Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 33 additions & 8 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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:

Expand All @@ -312,6 +334,9 @@ result.to_s
result.exports
#=> nil

result.map
#=> nil

result.warnings
#=> []

Expand Down
4 changes: 2 additions & 2 deletions lib/lightningcss.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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")

Expand Down
9 changes: 7 additions & 2 deletions lib/lightningcss/options.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
Expand All @@ -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]
Expand Down
7 changes: 5 additions & 2 deletions lib/lightningcss/result.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
8 changes: 4 additions & 4 deletions lib/lightningcss/transformer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand Down
1 change: 1 addition & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions rust/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Expand Down
77 changes: 75 additions & 2 deletions rust/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -146,8 +147,49 @@ fn parse_source<'i>(code: &'i str, options: &TransformOptions) -> Result<ParseRe
Ok(ParseResult { stylesheet, warnings })
}

fn read_input_source_map(options: &TransformOptions) -> Result<Option<SourceMap>, 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<SourceMap> {
options
.source_map
.then(|| SourceMap::new(options.project_root.as_deref().unwrap_or("/")))
}

fn serialize_source_map(
source_map: Option<SourceMap>,
input_source_map: Option<SourceMap>,
) -> Result<Option<String>, 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<TransformResult, Failure> {
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,
Expand Down Expand Up @@ -183,17 +225,28 @@ fn transform_source(code: &str, options: &TransformOptions) -> Result<TransformR
})
.map_err(|error| Failure::internal(format!("Failed to minify: {error}")))?;

let mut source_map = new_source_map(options);

if let Some(source_map) = &mut source_map {
source_map.add_source(&filename);
source_map
.set_source_content(0, code)
.map_err(|error| Failure::internal(format!("Failed to add source: {error}")))?;
}

let printed = stylesheet
.to_css(PrinterOptions {
minify: options.minify,
source_map: None,
project_root: None,
source_map: source_map.as_mut(),
project_root: options.project_root.as_deref(),
targets,
analyze_dependencies: None,
pseudo_classes: None,
})
.map_err(|error| Failure::internal(format!("Failed to print: {error}")))?;

let map = serialize_source_map(source_map, input_source_map)?;

let exports = printed.exports.map(|exports| {
exports
.into_iter()
Expand All @@ -209,6 +262,7 @@ fn transform_source(code: &str, options: &TransformOptions) -> Result<TransformR
Ok(TransformResult {
code: printed.code,
exports,
map,
warnings,
})
}
Expand Down Expand Up @@ -255,14 +309,31 @@ fn bundle_source(path: &str, options: &TransformOptions) -> Result<TransformResu
})
.map_err(|error| Failure::internal(format!("Failed to minify: {error}")))?;

let mut source_map = new_source_map(options);

if let Some(source_map) = &mut source_map {
for source in &stylesheet.sources {
let content = std::fs::read_to_string(source).map_err(|error| Failure::bundle(format!("{source}: {error}")))?;
let index = source_map.add_source(source);

source_map
.set_source_content(index as usize, &content)
.map_err(|error| Failure::internal(format!("Failed to add source: {error}")))?;
}
}

let printed = stylesheet
.to_css(PrinterOptions {
minify: options.minify,
source_map: source_map.as_mut(),
project_root: options.project_root.as_deref(),
targets,
..PrinterOptions::default()
})
.map_err(|error| Failure::internal(format!("Failed to print: {error}")))?;

let map = serialize_source_map(source_map, None)?;

let exports = printed.exports.map(|exports| {
exports
.into_iter()
Expand All @@ -278,6 +349,7 @@ fn bundle_source(path: &str, options: &TransformOptions) -> Result<TransformResu
Ok(TransformResult {
code: printed.code,
exports,
map,
warnings,
})
}
Expand Down Expand Up @@ -310,6 +382,7 @@ fn transform_attribute(code: &str, options: &TransformOptions) -> Result<Transfo
Ok(TransformResult {
code: printed.code,
exports: None,
map: None,
warnings: Vec::new(),
})
}
Expand Down
5 changes: 5 additions & 0 deletions rust/src/options.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,9 @@ pub struct TransformOptions {
pub targets: Option<HashMap<String, Version>>,
pub css_modules: Option<CssModulesOptions>,
pub scope: Option<String>,
pub source_map: bool,
pub input_source_map: Option<String>,
pub project_root: Option<String>,
}

#[derive(Debug, Deserialize)]
Expand Down Expand Up @@ -166,6 +169,8 @@ pub struct TransformResult {
pub code: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub exports: Option<HashMap<String, String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub map: Option<String>,
pub warnings: Vec<Diagnostic>,
}

Expand Down
37 changes: 36 additions & 1 deletion rust/tests/transform_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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())
);
}

Expand Down
Loading
Loading