From 85568a1a5e912c959226bdc851314d519e8a1cdf Mon Sep 17 00:00:00 2001 From: Marco Roth Date: Sat, 7 Nov 2026 22:45:34 -0800 Subject: [PATCH] Support source maps --- README.md | 41 +++++++++-- lib/lightningcss.rb | 4 +- lib/lightningcss/options.rb | 9 ++- lib/lightningcss/result.rb | 7 +- lib/lightningcss/transformer.rb | 8 +- rust/Cargo.lock | 1 + rust/Cargo.toml | 1 + rust/src/lib.rs | 77 +++++++++++++++++++- rust/src/options.rs | 5 ++ rust/tests/transform_test.rs | 37 +++++++++- sig/lightningcss.rbs | 8 +- sig/lightningcss/result.rbs | 6 +- sig/lightningcss/transformer.rbs | 16 ++-- test/lightningcss/options_test.rb | 4 +- test/lightningcss/source_map_test.rb | 105 +++++++++++++++++++++++++++ 15 files changed, 292 insertions(+), 37 deletions(-) create mode 100644 test/lightningcss/source_map_test.rb diff --git a/README.md b/README.md index 852f1ef..a3e36fa 100644 --- a/README.md +++ b/README.md @@ -144,6 +144,25 @@ LightningCSS.transform(".x:not(.y) { color: red }", scope: "[s]", minify: true). #=> ".x:not(.y)[s]{color:red}" ``` +#### Source maps + +Pass `source_map: true` and the result has a `map`, a JSON string. Give a `filename` too, since that is what the map names as its source. + +```ruby +result = LightningCSS.transform(".a { color: red }", filename: "main.css", source_map: true, minify: true) + +result.map +#=> "{\"version\":3,\"sourceRoot\":null,\"mappings\":\"AAAA\",\"sources\":[\"main.css\"],...}" +``` + +For CSS that was compiled from something else, pass that step's map as `input_source_map` and the result maps back to the original sources. A map it cannot read raises a `LightningCSS::OptionError`. + +```ruby +LightningCSS.transform(sass_output, filename: "main.css", source_map: true, input_source_map: sass_map) +``` + +`bundle` takes `source_map` as well, and adds every file it read to `sources` with its contents. `project_root` sets what the `sources` are relative to. A bundle reads many files, so it does not take a single `input_source_map`, and a style attribute has no source map. + #### Style attributes A style attribute is the list of declarations an element carries inline. It has no selectors and no at-rules around it, so it is its own grammar. @@ -280,14 +299,17 @@ It answers `call` as well, so it can be handed to anything expecting something c ### Options -| Option | Type | Description | -|------------------|----------------|----------------------------------------------------------------------------------------| -| `filename` | `String` | The name to use in errors and warnings. | -| `minify` | `bool` | Whether to print the result as small as it goes. | -| `error_recovery` | `bool` | Whether to carry on past a rule it cannot read. Off by default, so such a rule raises. | -| `targets` | `Hash` | The browsers being compiled for, each with the oldest version supported. | -| `css_modules` | `bool`, `Hash` | Whether to compile as a CSS module, and how. | -| `scope` | `String` | A selector fragment to narrow every rule by. | +| Option | Type | Description | +|--------------------|----------------|----------------------------------------------------------------------------------------| +| `filename` | `String` | The name to use in errors and warnings. | +| `minify` | `bool` | Whether to print the result as small as it goes. | +| `error_recovery` | `bool` | Whether to carry on past a rule it cannot read. Off by default, so such a rule raises. | +| `targets` | `Hash` | The browsers being compiled for, each with the oldest version supported. | +| `css_modules` | `bool`, `Hash` | Whether to compile as a CSS module, and how. | +| `scope` | `String` | A selector fragment to narrow every rule by. | +| `source_map` | `bool` | Whether to generate a source map. Off by default. | +| `input_source_map` | `String` | A source map as JSON to chain through, such as one from Sass. Needs `source_map`. | +| `project_root` | `String` | What the `sources` of a source map are relative to. | An option nobody reads is refused: @@ -312,6 +334,9 @@ result.to_s result.exports #=> nil +result.map +#=> nil + result.warnings #=> [] diff --git a/lib/lightningcss.rb b/lib/lightningcss.rb index f07274a..c618f5f 100644 --- a/lib/lightningcss.rb +++ b/lib/lightningcss.rb @@ -42,7 +42,7 @@ # set of them to reuse across many stylesheets. # module LightningCSS - #: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result + #: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Result def self.transform(code, **options) Result.from_json(Backend.transform(code.to_s, Options.serialize(options))) end @@ -54,7 +54,7 @@ def self.parse(code, **options) ParseResult.from_json(Backend.parse(code.to_s, serialized), code.to_s) end - #: (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result + #: (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?project_root: String?) -> LightningCSS::Result def self.bundle(path, **options) serialized = Options.serialize(options, Options::BUNDLE, "a bundle") diff --git a/lib/lightningcss/options.rb b/lib/lightningcss/options.rb index 91533b8..f9bcb6a 100644 --- a/lib/lightningcss/options.rb +++ b/lib/lightningcss/options.rb @@ -16,7 +16,10 @@ class Options :error_recovery, :targets, :css_modules, - :scope + :scope, + :source_map, + :input_source_map, + :project_root ].freeze #: Array[Symbol] STYLE_ATTRIBUTE = [ @@ -36,7 +39,9 @@ class Options :error_recovery, :targets, :css_modules, - :scope + :scope, + :source_map, + :project_root ].freeze #: Array[Symbol] attr_reader :to_h #: Hash[Symbol, untyped] diff --git a/lib/lightningcss/result.rb b/lib/lightningcss/result.rb index efcf3bf..6620608 100644 --- a/lib/lightningcss/result.rb +++ b/lib/lightningcss/result.rb @@ -13,6 +13,7 @@ module LightningCSS class Result attr_reader :code #: String attr_reader :exports #: Hash[String, String]? + attr_reader :map #: String? attr_reader :warnings #: Array[LightningCSS::Warning] #: (String) -> LightningCSS::Result @@ -22,14 +23,16 @@ def self.from_json(payload) new( code: parsed.fetch("code"), exports: parsed["exports"], + map: parsed["map"], warnings: parsed.fetch("warnings").map { |warning| Warning.from_hash(warning) } ) end - #: (code: String, warnings: Array[LightningCSS::Warning], ?exports: Hash[String, String]?) -> void - def initialize(code:, warnings:, exports: nil) + #: (code: String, warnings: Array[LightningCSS::Warning], ?exports: Hash[String, String]?, ?map: String?) -> void + def initialize(code:, warnings:, exports: nil, map: nil) @code = code @exports = exports + @map = map @warnings = warnings.freeze freeze diff --git a/lib/lightningcss/transformer.rb b/lib/lightningcss/transformer.rb index 3363381..4e5b2ac 100644 --- a/lib/lightningcss/transformer.rb +++ b/lib/lightningcss/transformer.rb @@ -14,14 +14,14 @@ module LightningCSS class Transformer attr_reader :options #: Hash[Symbol, untyped] - #: (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> void + #: (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> void def initialize(**options) @options = options.transform_keys(&:to_sym).freeze freeze end - #: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result + #: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Result def transform(code, **overrides) LightningCSS.transform(code, **options, **overrides) end @@ -33,7 +33,7 @@ def parse(code, **overrides) LightningCSS.parse(code, **options.slice(*Options::PARSE), **overrides) end - #: (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result + #: (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?project_root: String?) -> LightningCSS::Result def bundle(path, **overrides) LightningCSS.bundle(path, **options, **overrides) end @@ -48,7 +48,7 @@ def minify(code, **overrides) transform(code, **overrides, minify: true).code end - #: (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Transformer + #: (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Transformer def with(**overrides) self.class.new(**options, **overrides) end diff --git a/rust/Cargo.lock b/rust/Cargo.lock index f9be8ba..53fb11f 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -536,6 +536,7 @@ version = "0.0.0" dependencies = [ "cbindgen", "lightningcss", + "parcel_sourcemap", "serde", "serde_json", ] diff --git a/rust/Cargo.toml b/rust/Cargo.toml index ba7a92a..3b5795b 100644 --- a/rust/Cargo.toml +++ b/rust/Cargo.toml @@ -16,6 +16,7 @@ crate-type = ["cdylib", "staticlib", "rlib"] [dependencies] lightningcss = { version = "=1.0.0-alpha.72", features = ["visitor", "serde"] } +parcel_sourcemap = { version = "2.1", features = ["json"] } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/rust/src/lib.rs b/rust/src/lib.rs index 8421dea..a120e12 100644 --- a/rust/src/lib.rs +++ b/rust/src/lib.rs @@ -20,6 +20,7 @@ use std::sync::{Arc, RwLock}; use lightningcss::bundler::{BundleErrorKind, Bundler, FileProvider}; use lightningcss::stylesheet::{MinifyOptions, ParserOptions, PrinterOptions, StyleAttribute, StyleSheet}; use lightningcss::visitor::Visit; +use parcel_sourcemap::SourceMap; use crate::options::{Diagnostic, ParseResult, TransformOptions, TransformResult}; use crate::scope::Scoper; @@ -146,8 +147,49 @@ fn parse_source<'i>(code: &'i str, options: &TransformOptions) -> Result Result, Failure> { + let Some(json) = &options.input_source_map else { + return Ok(None); + }; + + if !options.source_map { + return Err(Failure::option("input_source_map needs source_map: true")); + } + + SourceMap::from_json("/", json) + .map(Some) + .map_err(|error| Failure::option(format!("Invalid input source map: {error}"))) +} + +fn new_source_map(options: &TransformOptions) -> Option { + options + .source_map + .then(|| SourceMap::new(options.project_root.as_deref().unwrap_or("/"))) +} + +fn serialize_source_map( + source_map: Option, + input_source_map: Option, +) -> Result, Failure> { + let Some(mut source_map) = source_map else { + return Ok(None); + }; + + if let Some(mut input_source_map) = input_source_map { + source_map + .extends(&mut input_source_map) + .map_err(|error| Failure::option(format!("Invalid input source map: {error}")))?; + } + + source_map + .to_json(None) + .map(Some) + .map_err(|error| Failure::internal(format!("Failed to serialize source map: {error}"))) +} + fn transform_source(code: &str, options: &TransformOptions) -> Result { let filename = options.filename.clone().unwrap_or_default(); + let input_source_map = read_input_source_map(options)?; let css_modules = match &options.css_modules { Some(modules) => Some(modules.to_config().map_err(Failure::option)?), None => None, @@ -183,17 +225,28 @@ fn transform_source(code: &str, options: &TransformOptions) -> Result Result Result Result Result>, pub css_modules: Option, pub scope: Option, + pub source_map: bool, + pub input_source_map: Option, + pub project_root: Option, } #[derive(Debug, Deserialize)] @@ -166,6 +169,8 @@ pub struct TransformResult { pub code: String, #[serde(skip_serializing_if = "Option::is_none")] pub exports: Option>, + #[serde(skip_serializing_if = "Option::is_none")] + pub map: Option, pub warnings: Vec, } diff --git a/rust/tests/transform_test.rs b/rust/tests/transform_test.rs index 6ff7baf..a909610 100644 --- a/rust/tests/transform_test.rs +++ b/rust/tests/transform_test.rs @@ -153,13 +153,48 @@ fn transform_answers_where_it_could_not_read_as_json() { ); } +#[test] +fn transform_answers_a_source_map_when_asked() { + let answer = call( + lightningcss_transform, + ".a {\n user-select: none;\n}\n\n.b {\n color: red;\n}\n", + r#"{"filename":"main.css","source_map":true,"minify":true}"#, + ) + .unwrap(); + let parsed: serde_json::Value = serde_json::from_str(&answer).unwrap(); + let map: serde_json::Value = serde_json::from_str(parsed["map"].as_str().unwrap()).unwrap(); + + assert_eq!(map["mappings"], "AAAA,oBAIA"); + assert_eq!(map["sources"], serde_json::json!(["main.css"])); +} + +#[test] +fn transform_leaves_the_source_map_out_when_not_asked() { + let answer = call(lightningcss_transform, ".a{}", "{}").unwrap(); + let parsed: serde_json::Value = serde_json::from_str(&answer).unwrap(); + + assert!(parsed.get("map").is_none()); +} + +#[test] +fn transform_refuses_an_input_source_map_it_cannot_read() { + assert_eq!( + code_of( + lightningcss_transform, + ".a{}", + r#"{"source_map":true,"input_source_map":"nope"}"# + ), + LightningCssErrorCode::Option + ); +} + #[test] fn transform_refuses_an_option_it_does_not_read() { let answer = call(lightningcss_transform, ".a {}", r#"{"nonsense":true}"#); assert_eq!( answer, - Err("Invalid options: unknown field `nonsense`, expected one of `filename`, `minify`, `error_recovery`, `targets`, `css_modules`, `scope` at line 1 column 11".to_string()) + Err("Invalid options: unknown field `nonsense`, expected one of `filename`, `minify`, `error_recovery`, `targets`, `css_modules`, `scope`, `source_map`, `input_source_map`, `project_root` at line 1 column 11".to_string()) ); } diff --git a/sig/lightningcss.rbs b/sig/lightningcss.rbs index 4eab55b..998e904 100644 --- a/sig/lightningcss.rbs +++ b/sig/lightningcss.rbs @@ -19,14 +19,14 @@ # `LightningCSS::Options` is what the options are read by, and `LightningCSS::Transformer` holds a # set of them to reuse across many stylesheets. module LightningCSS - # : (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result - def self.transform: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result + # : (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Result + def self.transform: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Result # : (String, ?filename: String?, ?error_recovery: bool) -> LightningCSS::ParseResult def self.parse: (String, ?filename: String?, ?error_recovery: bool) -> LightningCSS::ParseResult - # : (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result - def self.bundle: (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result + # : (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?project_root: String?) -> LightningCSS::Result + def self.bundle: (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?project_root: String?) -> LightningCSS::Result # : (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?) -> LightningCSS::Result def self.transform_style_attribute: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?) -> LightningCSS::Result diff --git a/sig/lightningcss/result.rbs b/sig/lightningcss/result.rbs index caa5787..2af7d67 100644 --- a/sig/lightningcss/result.rbs +++ b/sig/lightningcss/result.rbs @@ -14,13 +14,15 @@ module LightningCSS attr_reader exports: Hash[String, String]? + attr_reader map: String? + attr_reader warnings: Array[LightningCSS::Warning] # : (String) -> LightningCSS::Result def self.from_json: (String) -> LightningCSS::Result - # : (code: String, warnings: Array[LightningCSS::Warning], ?exports: Hash[String, String]?) -> void - def initialize: (code: String, warnings: Array[LightningCSS::Warning], ?exports: Hash[String, String]?) -> void + # : (code: String, warnings: Array[LightningCSS::Warning], ?exports: Hash[String, String]?, ?map: String?) -> void + def initialize: (code: String, warnings: Array[LightningCSS::Warning], ?exports: Hash[String, String]?, ?map: String?) -> void # : () -> bool def warnings?: () -> bool diff --git a/sig/lightningcss/transformer.rbs b/sig/lightningcss/transformer.rbs index ddab338..d64b838 100644 --- a/sig/lightningcss/transformer.rbs +++ b/sig/lightningcss/transformer.rbs @@ -13,19 +13,19 @@ module LightningCSS class Transformer attr_reader options: Hash[Symbol, untyped] - # : (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> void - def initialize: (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> void + # : (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> void + def initialize: (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> void - # : (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result - def transform: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result + # : (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Result + def transform: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Result alias call transform # : (String, ?filename: String?, ?error_recovery: bool) -> LightningCSS::ParseResult def parse: (String, ?filename: String?, ?error_recovery: bool) -> LightningCSS::ParseResult - # : (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result - def bundle: (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Result + # : (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?project_root: String?) -> LightningCSS::Result + def bundle: (String, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?project_root: String?) -> LightningCSS::Result # : (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?) -> LightningCSS::Result def transform_style_attribute: (String, ?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?) -> LightningCSS::Result @@ -33,8 +33,8 @@ module LightningCSS # : (String, ?filename: String?, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> String def minify: (String, ?filename: String?, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> String - # : (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Transformer - def with: (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?) -> LightningCSS::Transformer + # : (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Transformer + def with: (?filename: String?, ?minify: bool, ?error_recovery: bool, ?targets: browsers?, ?css_modules: css_modules?, ?scope: String?, ?source_map: bool, ?input_source_map: String?, ?project_root: String?) -> LightningCSS::Transformer # : () -> String def inspect: () -> String diff --git a/test/lightningcss/options_test.rb b/test/lightningcss/options_test.rb index 0da3c9a..0b2e212 100644 --- a/test/lightningcss/options_test.rb +++ b/test/lightningcss/options_test.rb @@ -45,7 +45,7 @@ class OptionsTest < Minitest::Spec end test "knows what the native library reads" do - assert_equal [:filename, :minify, :error_recovery, :targets, :css_modules, :scope], Options::KNOWN + assert_equal [:filename, :minify, :error_recovery, :targets, :css_modules, :scope, :source_map, :input_source_map, :project_root], Options::KNOWN end test "takes what it is allowed to read as an argument, so no option name can collide with it" do @@ -74,7 +74,7 @@ class OptionsTest < Minitest::Spec end test "knows what a bundle reads" do - assert_equal [:minify, :error_recovery, :targets, :css_modules, :scope], Options::BUNDLE + assert_equal [:minify, :error_recovery, :targets, :css_modules, :scope, :source_map, :project_root], Options::BUNDLE end test "refuses an option that has nothing to act on" do diff --git a/test/lightningcss/source_map_test.rb b/test/lightningcss/source_map_test.rb new file mode 100644 index 0000000..77dc8b8 --- /dev/null +++ b/test/lightningcss/source_map_test.rb @@ -0,0 +1,105 @@ +# frozen_string_literal: true + +require "test_helper" + +module LightningCSS + class SourceMapTest < Minitest::Spec + CSS = ".a {\n user-select: none;\n}\n\n.b {\n color: red;\n}\n" + SCSS = "$c: red;\n.a { user-select: none; }\n.b { color: $c; }\n" + ENTRY = File.expand_path("../fixtures/bundle/entry.css", __dir__) + ROOT = File.expand_path("../fixtures/bundle", __dir__) + + INPUT = JSON.generate( + version: 3, + file: "main.css", + sources: ["app.scss"], + names: [], + sourcesContent: [SCSS], + mappings: "AACA;EAAI;;;AACJ;EAAI" + ) + + def map_of(css = CSS, **) + JSON.parse(LightningCSS.transform(css, filename: "main.css", source_map: true, minify: true, **).map) + end + + test "has no map when it was not asked for one" do + assert_nil LightningCSS.transform(CSS, filename: "main.css").map + end + + test "answers a map as a JSON string" do + assert_instance_of String, LightningCSS.transform(CSS, filename: "main.css", source_map: true).map + end + + test "maps the output back to the stylesheet it was given" do + map = map_of + + assert_equal 3, map["version"] + assert_equal "AAAA,oBAIA", map["mappings"] + assert_equal ["main.css"], map["sources"] + assert_equal [CSS], map["sourcesContent"] + end + + test "chains through an input source map" do + map = map_of(input_source_map: INPUT) + + assert_equal "ACCA,oBACA", map["mappings"] + assert_equal ["main.css", "app.scss"], map["sources"] + assert_equal [CSS, SCSS], map["sourcesContent"] + end + + test "writes sources relative to the project root" do + map = JSON.parse(LightningCSS.transform(CSS, filename: "/app/css/main.css", source_map: true, project_root: "/app").map) + + assert_equal ["css/main.css"], map["sources"] + end + + test "raises an option error for an input source map that is not JSON" do + error = assert_raises(OptionError) { LightningCSS.transform(CSS, source_map: true, input_source_map: "nope") } + + assert_match(/\AInvalid input source map: /, error.message) + end + + test "raises an option error for an input source map with broken mappings" do + input = JSON.generate(version: 3, sources: [], names: [], mappings: "!!!") + error = assert_raises(OptionError) { LightningCSS.transform(CSS, source_map: true, input_source_map: input) } + + assert_match(/\AInvalid input source map: /, error.message) + end + + test "raises an option error for an input source map it was not asked to chain" do + error = assert_raises(OptionError) { LightningCSS.transform(CSS, input_source_map: INPUT) } + + assert_equal "input_source_map needs source_map: true", error.message + end + + test "adds every file a bundle read to its sources, with its contents" do + map = JSON.parse(LightningCSS.bundle(ENTRY, source_map: true, project_root: ROOT).map) + contents = map["sources"].zip(map["sourcesContent"]).to_h + + assert_equal ["colors.css", "entry.css", "nested/layout.css"], contents.keys.sort + contents.each { |source, content| assert_equal File.read(File.join(ROOT, source)), content } + end + + test "has no map for a bundle that was not asked for one" do + assert_nil LightningCSS.bundle(ENTRY).map + end + + test "refuses an input source map for a bundle" do + error = assert_raises(OptionError) { LightningCSS.bundle(ENTRY, source_map: true, input_source_map: INPUT) } + + assert_equal "input_source_map is not an option for a bundle", error.message + end + + test "refuses a source map for a style attribute" do + error = assert_raises(OptionError) { LightningCSS.transform_style_attribute("color: red", source_map: true) } + + assert_equal "source_map is not an option for a style attribute", error.message + end + + test "a transformer carries its source map options" do + map = JSON.parse(Transformer.new(filename: "main.css", source_map: true).transform(CSS).map) + + assert_equal ["main.css"], map["sources"] + end + end +end