Skip to content
Open
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
11 changes: 11 additions & 0 deletions .changepacks/changepack_log_vanilla_extract_css_utils.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"changes": {
"bindings/devup-ui-wasm/package.json": "Patch",
"bindings/devup-ui-binding/package.json": "Patch",
"packages/plugin-utils/package.json": "Patch",
"packages/eslint-plugin/package.json": "Patch",
"packages/react/package.json": "Patch"
},
"note": "`@vanilla-extract/css-utils` is aliased by default and its `calc` compiles to the strings the package builds (`calc.add/subtract/multiply/divide/negate`, chained `calc(x)` with `.toString()` or template interpolation, nested operations only parenthesized). A `.css.ts` stylesheet evaluates it without a module resolver, so its operands may be anything the stylesheet computes; elsewhere each call is written as its string and its operands must be literals, module-level `const`s holding a literal or other `calc` results. `@devup-ui/react/compat/vanilla-extract-css-utils` types it, and css-utils-literal-only reads its calls as the build does. New build errors: a `calc` operand outside a stylesheet the build cannot read, a `calc` read without being called, a `calc(x)` used as a value without `.toString()` (also in a stylesheet), an export other than `calc`, and a namespace import, `require()` or re-export of the package outside a stylesheet. Set `importAliases: { '@vanilla-extract/css-utils': false }` to keep the package",
"date": "2026-11-15T00:00:00.000Z"
}
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,21 @@ They are not evaluated by the ordinary-module extraction path.

Moving those calls into a `.css.ts` file — where vanilla-extract wants them anyway — removes the dependency.

## `@vanilla-extract/css-utils`

`calc` builds the same strings `@vanilla-extract/css-utils` does, so the package need not be installed. `calc.add`, `calc.subtract`, `calc.multiply`, `calc.divide` and `calc.negate` give a string; `calc(x)` gives an expression whose `add`, `subtract`, `multiply`, `divide` and `negate` chain, and which is a CSS value once `.toString()` is called or it is interpolated in a template. As in the package, an operand that is itself a `calc` is only parenthesized:

```ts
import { calc } from '@vanilla-extract/css-utils'

calc.add('100%', '-4px') // 'calc(100% + -4px)'
calc.negate('4px') // 'calc(4px * -1)'
calc('10px').add('5px').multiply(2).toString() // 'calc((10px + 5px) * 2)'
calc.add(calc.multiply('2px', 3), '1px') // 'calc((2px * 3) + 1px)'
```

A `.css.ts` stylesheet evaluates `calc`, so its operands can be anything the stylesheet computes, such as `vars.space.md` or a `createVar()`. Any other module is not evaluated: each `calc` there is written as the string it gives, so its operands must be literals, module-level `const`s holding a literal, or other `calc` results. Anything else is a build error at the operand, as is a `calc` read without being called, a `calc(x)` used as a value without `.toString()`, a namespace or default import, and a `require()` or re-export of the package. To use the package itself, set `importAliases: { '@vanilla-extract/css-utils': false }`.

## Namespace imports

A namespace stands for many named exports whose Devup UI counterparts are renamed (`style` → `css`), which a namespace access cannot express, so it is left alone:
Expand Down
13 changes: 13 additions & 0 deletions libs/extractor/src/import_alias_visit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -729,7 +729,19 @@ pub fn transform_import_aliases_with_edits<'a>(

// Collect import transformations
let mut transformations: Vec<(usize, usize, String)> = Vec::new();
// One analysis for the whole pass: building it sets the AST's symbol and
// reference IDs, which every later reader resolves against this table
let mut scoping = None;
if !redirect_every_name && crate::vanilla_extract_calc::reads(code, import_aliases) {
let built = scoping.insert(
SemanticBuilder::new()
.build(&program)
.semantic
.into_scoping(),
);
transformations
.extend(crate::vanilla_extract_calc::compile(&program, built, false).replacements);
}
let may_take_css = CssProp::of(import_aliases, code, false) != CssProp::Off;
let mut symbol = |local: &BindingIdentifier<'_>| {
scoping.get_or_insert_with(|| {
Expand Down Expand Up @@ -797,6 +809,7 @@ pub fn transform_import_aliases_with_edits<'a>(
format!("\"{runtime}\""),
));
} else if let Some(alias) = import_aliases.get(source_value)
&& source_value != crate::vanilla_extract_calc::CSS_UTILS
&& !import_decl.import_kind.is_type()
{
let span = import_decl.span;
Expand Down
6 changes: 6 additions & 0 deletions libs/extractor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,7 @@ mod util_type;
mod utils;
mod vanilla_extract;
pub use vanilla_extract::ExtractorCaches;
mod vanilla_extract_calc;
#[cfg(test)]
mod vanilla_extract_theme_import_tests;
mod visit;
Expand Down Expand Up @@ -514,6 +515,11 @@ fn extract_source(
filename,
&option.import_aliases,
));
errors.extend(vanilla_extract_calc::errors(
code,
filename,
&option.import_aliases,
));
if evaluated.is_none() && !errors.is_empty() {
return Err(located_errors(filename, code, &[], errors).into());
}
Expand Down
13 changes: 13 additions & 0 deletions libs/extractor/src/module_loader.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use rustc_hash::{FxHashMap, FxHashSet};

use crate::{ExtractOption, ModuleResolver, utils::is_vanilla_extract_file};

pub(crate) mod css_utils;
mod import_bindings;
pub(crate) mod operations;
mod retained_css;
Expand All @@ -24,6 +25,7 @@ mod script;
mod tests;
mod validate;

use css_utils::{CSS_UTILS, CSS_UTILS_BINDING, CSS_UTILS_MODULE};
use import_bindings::{BindingSource, ImportBindings};
use retained_css::{CssImport, RetainedCss};
pub(crate) use script::{Body, Origin, SCRIPT_PATH, Script, Unit};
Expand Down Expand Up @@ -153,6 +155,9 @@ pub(crate) struct ModuleLoader<'r> {
/// What the stylesheet imports for its side effects, and the stylesheets it
/// imports, which emit their own styles: its output keeps importing them
pub kept_imports: Vec<String>,
/// Whether the stylesheet loads `@vanilla-extract/css-utils`, which it
/// evaluates as written here
css_utils: bool,
}

impl<'r> ModuleLoader<'r> {
Expand Down Expand Up @@ -185,6 +190,7 @@ impl<'r> ModuleLoader<'r> {
css_bindings: FxHashMap::default(),
dependencies: BTreeSet::new(),
kept_imports: Vec::new(),
css_utils: false,
}
}

Expand All @@ -207,6 +213,9 @@ impl<'r> ModuleLoader<'r> {
/// stylesheet
pub(crate) fn script(&self, entry: &ModuleScript) -> Script {
let mut script = Script::default();
if self.css_utils {
script.generated(CSS_UTILS_MODULE);
}
for definition in &self.definitions {
match definition {
Definition::Generated(text) => script.generated(text),
Expand All @@ -228,6 +237,10 @@ impl<'r> ModuleLoader<'r> {

/// The name of the exports object of `specifier` imported by `importer`
fn load(&mut self, specifier: &str, importer: &str, direct: bool) -> Result<String, LoadError> {
if specifier == CSS_UTILS && self.option.import_aliases.contains_key(CSS_UTILS) {
self.css_utils = true;
return Ok(CSS_UTILS_BINDING.to_string());
}
let resolver = self.resolver.ok_or(LoadError::NoResolver)?;
let module = resolver(specifier, importer).ok_or(LoadError::Unresolved)?;
if retained_css::is_css(&module.path) {
Expand Down
34 changes: 34 additions & 0 deletions libs/extractor/src/module_loader/css_utils.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
//! `@vanilla-extract/css-utils`, which a stylesheet evaluates as the package
//! itself would: its `calc` builds the same strings, without a resolver

/// The package's specifier
pub(crate) const CSS_UTILS: &str = "@vanilla-extract/css-utils";

/// The object the package's exports are bound to while a stylesheet runs
pub(super) const CSS_UTILS_BINDING: &str = "__vanilla_extract_css_utils__";

/// What the error a `calc(x)` written as a CSS value throws says
pub(crate) const CHAIN_VALUE: &str = "of '@vanilla-extract/css-utils' builds an expression";

/// The package's `calc`, as `@vanilla-extract/css-utils` 0.1 writes it: the
/// operands of each operation are joined by the operator, every `calc` in
/// them dropped, so a nested operation is only parenthesized
pub(super) const CSS_UTILS_MODULE: &str = r#"const __vanilla_extract_css_utils__ = (() => {
const toExpression = (operator, ...operands) => operands.map((operand) => "".concat(operand)).join(" ".concat(operator, " ")).replace(/calc/g, "");
const add = (...operands) => "calc(".concat(toExpression("+", ...operands), ")");
const subtract = (...operands) => "calc(".concat(toExpression("-", ...operands), ")");
const multiply = (...operands) => "calc(".concat(toExpression("*", ...operands), ")");
const divide = (...operands) => "calc(".concat(toExpression("/", ...operands), ")");
const negate = (x) => multiply(x, -1);
const calc = Object.assign((x) => ({
add: (...operands) => calc(add(x, ...operands)),
subtract: (...operands) => calc(subtract(x, ...operands)),
multiply: (...operands) => calc(multiply(x, ...operands)),
divide: (...operands) => calc(divide(x, ...operands)),
negate: () => calc(negate(x)),
toString: () => x.toString(),
toJSON: () => { throw new TypeError("`calc(x)` of '@vanilla-extract/css-utils' builds an expression, which is a CSS value only once `.toString()` is called or it is interpolated in a template"); },
}), { add, subtract, multiply, divide, negate });
return Object.freeze({ calc });
})();
"#;
3 changes: 3 additions & 0 deletions libs/extractor/src/module_loader/script/explain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,9 @@ fn fix(cause: &str) -> String {
"declare or import `{name}` before this code reads it; it is not available when the stylesheet is evaluated at build time"
);
}
if cause.contains(crate::module_loader::css_utils::CHAIN_VALUE) {
return "call `.toString()` on it, as `calc(x).multiply(2).toString()`, or interpolate it in a template".to_string();
}
if cause.starts_with("SyntaxError") {
return "correct the syntax at this location".to_string();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
source: libs/extractor/src/vanilla_extract_calc_tests.rs
expression: message
---
theme.css.ts:3:23: JS execution error: TypeError: `calc(x)` of '@vanilla-extract/css-utils' builds an expression, which is a CSS value only once `.toString()` is called or it is interpolated in a template. Fix: call `.toString()` on it, as `calc(x).multiply(2).toString()`, or interpolate it in a template
at stringify (native)
at style (native)
at <main> (theme.css.ts:3:23)
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
---
source: libs/extractor/src/vanilla_extract_calc_tests.rs
expression: "format!(\"{compiled:#?}\")"
---
Ok(
(
"import \"@devup-ui/react/devup-ui-0.css\";\nexport const a = \"a-a a-b\";\n;\nexport const theme = \"theme-0-1\";\nexport const vars = { \"space\": { \"md\": \"var(--space-md-0-2)\" } };\n",
[
"calc((var(--space-md-0-2) * 2) + (var(--var-0-0) * -1))",
],
),
)
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
source: libs/extractor/src/vanilla_extract_calc_tests.rs
expression: "format!(\"{compiled:#?}\")"
---
Ok(
(
"import type { Unused } from \"@vanilla-extract/css-utils\";\nexport const gap: typeof calc = \"calc(1px + 2px)\" as never;\nexport const half = `calc(100% / 2) - 1px`;\n",
[],
),
)
58 changes: 43 additions & 15 deletions libs/extractor/src/style_values/absence.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use super::StyleValues;
use crate::utils::unwrap_syntax_only;
use oxc_allocator::{Allocator, CloneIn};
use oxc_ast::ast::{Expression, IdentifierReference, Program};
use oxc_ast_visit::Visit;
use oxc_semantic::{Scoping, SemanticBuilder};
Expand Down Expand Up @@ -37,25 +38,32 @@ impl StyleValues<'_> {
if !program.source_text.contains("undefined") {
return;
}
let temporary;
let scoping: &Scoping = if let Some(scoping) = &self.scoping {
scoping
} else {
temporary = SemanticBuilder::new()
.build(program)
.semantic
.into_scoping();
&temporary
};
let mut references = AbsenceReferences {
scoping,
spans: FxHashSet::default(),
self.absent_references = match &self.scoping {
Some(scoping) => absent_references(scoping, program),
None => absent_in_copy(program),
};
references.visit_program(program);
self.absent_references = references.spans;
}
}

fn absent_references(scoping: &Scoping, program: &Program<'_>) -> FxHashSet<Span> {
let mut references = AbsenceReferences {
scoping,
spans: FxHashSet::default(),
};
references.visit_program(program);
references.spans
}

/// The proof for a program the visit reads with no analysis: built on a copy,
/// since analysing the program itself would give it IDs no table of the visit
/// resolves
fn absent_in_copy(program: &Program<'_>) -> FxHashSet<Span> {
let allocator = Allocator::default();
let copy = program.clone_in(&allocator);
let scoping = SemanticBuilder::new().build(&copy).semantic.into_scoping();
absent_references(&scoping, &copy)
}

struct AbsenceReferences<'s> {
scoping: &'s Scoping,
spans: FxHashSet<Span>,
Expand Down Expand Up @@ -155,6 +163,26 @@ mod tests {
assert!(!values.is_unbound_undefined(&statement.expression));
}

#[test]
fn recording_without_scoping_leaves_the_program_without_ids() {
// Given a program the visit reads with no semantic analysis.
let arena = Allocator::default();
let parsed = Parser::new(&arena, "undefined;", SourceType::tsx()).parse();
let mut values = StyleValues::default();
// When the absence proof is recorded.
values.record_absence(&parsed.program);
// Then the proof holds while the program keeps no reference ID, which
// the visit's empty table could not resolve.
let Statement::ExpressionStatement(statement) = &parsed.program.body[0] else {
panic!("expected expression");
};
let Expression::Identifier(identifier) = &statement.expression else {
panic!("expected identifier");
};
assert_eq!(identifier.reference_id.get(), None);
assert!(values.is_unbound_undefined(&statement.expression));
}

#[test]
fn recording_requires_reference_metadata_when_scoping_is_supplied() {
// Given real scoping whose authored reference ID was cleared before recording.
Expand Down
Loading
Loading