Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(theme): add ordered environmental adaptations (#5543)

Xinzi Zhou62bf723ed89d
diff --git a/.changeset/theme-adaptations.md b/.changeset/theme-adaptations.md
new file mode 100644
index 0000000000..32638cd71a
--- /dev/null
+++ b/.changeset/theme-adaptations.md
@@ -0,0 +1,65 @@
+---
+'@astryxdesign/core': minor
+'@astryxdesign/cli': minor
+---
+
+[breaking] Add ordered environmental adaptations to `defineTheme`
+
+Themes can now opt into CSS-first token, theme-local token, and component
+changes for named viewport widths, primary-pointer precision, contrast
+preference, and motion preference:
+
+```ts
+defineTheme({
+ name: 'acme',
+ adaptations: {
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [
+ {
+ when: {width: {from: 'lg', below: 'xl'}, pointer: 'coarse'},
+ value: {tokens: {'--size-element-md': '44px'}},
+ },
+ ],
+ },
+});
+```
+
+Condition fields are ANDed. `width.from` is inclusive, `width.below` is
+exclusive, and rules cascade in declaration order so later matching writes win.
+Theme extension preserves the effective breakpoint map and inherited rule order;
+static builds retain the metadata needed for source-equivalent extension.
+
+`AppShell` now accepts `xl` and `2xl` for `mobileNav.breakpoint` and resolves all
+five names through the nearest Theme. Mobile mode now uses the documented
+exclusive boundary (`width < breakpoint`), so an AppShell exactly at the named
+point renders the wider layout instead of the mobile layout.
+
+`defineTheme` now validates the token values authored inside an adaptation rule,
+rejecting non-string scalars and arrays with a length other than two instead of
+emitting them. Root and on-media token input keeps its existing acceptance
+unchanged, so themes that pass values through casts or spreads keep building. It
+also validates the combined portable and theme-local token graph for every
+reachable set of matching
+adaptation rules, rejecting cycles before CSS is emitted. Component writes in a
+rule use the same target, axis, value-domain, and extension validation as root
+`components`; a rule may not be the only place a custom value is enrolled,
+because generated type augmentation is unconditional.
+
+`astryx theme build` treats the adaptation generator as a core capability rather
+than a baseline requirement, so a theme with no adaptation intent still builds
+against an older installed `@astryxdesign/core` and emits the same CSS as before.
+A theme that does carry adaptation intent — valid rules, a custom
+`widthBreakpoints` map, or present-but-malformed adaptation metadata — fails
+against such a core before any output is written, with `ERR_CORE_INCOMPATIBLE`
+naming the missing `generateAdaptationCSS` export. A complete default width map
+with no rules asks for nothing and still builds. Where an older core's
+`defineTheme` drops adaptations while resolving, the build records each raw
+`defineTheme()` input and associates it with the theme it produced, so only the
+selected theme's lineage decides. An unobservable selected ancestor (including a
+CommonJS source package whose ESM core namespace cannot be wrapped) fails closed;
+an unused adaptive theme elsewhere in the import graph does not affect a plain
+build. The same capture preserves raw typography, color, radius, and motion axis
+metadata in old-core-built artifacts, allowing later current-core children to
+resolve partial adaptation axes exactly as if they extended the source theme.
+
+@imdreamrunner
diff --git a/docs/architecture/public-component-api.md b/docs/architecture/public-component-api.md
index 72a132710e..c08ed6066b 100644
--- a/docs/architecture/public-component-api.md
+++ b/docs/architecture/public-component-api.md
@@ -24,7 +24,13 @@ verified_by:
packages/core/src/docPropLiterals.test.ts,
packages/core/src/docPropReferences.test.ts,
]
-deciding_specs: [spec:AST-002/DEC-1, spec:AST-005/DEC-1]
+deciding_specs:
+ [
+ spec:AST-002/DEC-1,
+ spec:AST-005/DEC-1,
+ spec:AST-012/DEC-1,
+ spec:AST-012/DEC-2,
+ ]
---
# Public component API
@@ -103,6 +109,9 @@ guidance owns the process used to propose and test APIs.
and every public behavior change follows the result and disposition defined by
`architecture:knowledge-contracts`. Tests, a Changeset, or a generated manifest
are evidence; none can settle an absent or contradictory contract.
+- **INV14 — Shared breakpoint names keep one meaning.** Components that accept a
+ theme width point use `sm`/`md`/`lg`/`xl`/`2xl` from the active Theme. A
+ `below` boundary is exclusive, so equality belongs to the wider side.
This record applies to stable public packages. Lab components are not stable
public promises until promotion.
@@ -132,6 +141,9 @@ public promises until promotion.
theming/component records.
- A released breaking change includes the compatibility decision and migration
evidence required by the release process.
+- A component exposing a named theme width point uses the fixed vocabulary and
+ exclusive upper-edge behavior from `spec:AST-012`; it does not maintain a
+ parallel hardcoded breakpoint table.
- Changes to a family-owned API update the family contract rather than copying
its rule into this record or every component.
- A component that accepts or derives a navigation destination follows
@@ -152,6 +164,8 @@ public promises until promotion.
component cannot derive.
- `spec:AST-005/DEC-1` — every Astryx-owned navigation exit follows one
destination-safety decision.
+- `spec:AST-012/DEC-1` and `spec:AST-012/DEC-2` — components reuse the fixed
+ theme width names and inclusive-`from`/exclusive-`below` edge meanings.
Transition Action sequencing and pending behavior belong to their component or
family contract. This record links that owner once it is current; it does not
@@ -166,8 +180,9 @@ copy the component matrix.
| INV3, INV4 | Historical API review benchmark and `spec:AST-002` evidence | A prop combines unrelated axes or exposes a derivable implementation choice |
| INV5, INV6, INV7 | BaseProps/passthrough lint and representative runtime tests | Consumer ARIA/data/style/events are dropped, clobber component semantics, or fail to compose |
| INV9 | Published-surface, Changeset, migration, and public-type checks | A released API changes without explicit compatibility evidence |
-| INV12, INV13 | Generated declaration/export/behavior inventory plus canonical-owner mapping | A reachable supporting type or behavior is called internal, or mechanical evidence is treated as permission to accept it |
| INV11 | Public-API admission review plus owning theming/component tests | A public semantic custom property exposes derivable or unsupported implementation detail |
+| INV12, INV13 | Generated declaration/export/behavior inventory plus canonical-owner mapping | A reachable supporting type or behavior is called internal, or mechanical evidence is treated as permission to accept it |
+| INV14 | `AppShell.test.tsx` | A component hardcodes a divergent point or treats equality as below |
| Consumer-doc projection | `docPropReferences.test.ts` and `docPropLiterals.test.ts` | Docs name a nonexistent prop or omit public literal choices |
Known verification gaps:
diff --git a/docs/architecture/theme-application.md b/docs/architecture/theme-application.md
index 6a971469b6..58c779b7a9 100644
--- a/docs/architecture/theme-application.md
+++ b/docs/architecture/theme-application.md
@@ -15,6 +15,7 @@ applies_to:
packages/core/src/theme/MediaTheme.tsx,
packages/core/src/theme/useTheme.ts,
packages/core/src/theme/themeRegistry.ts,
+ packages/core/src/AppShell/AppShell.tsx,
]
verified_by:
[
@@ -22,8 +23,9 @@ verified_by:
packages/core/src/theme/MediaTheme.dom.test.tsx,
packages/core/src/theme/useTheme.test.tsx,
packages/core/src/theme/themeRegistry.test.ts,
+ packages/core/src/AppShell/AppShell.test.tsx,
]
-deciding_specs: []
+deciding_specs: [spec:AST-012/DEC-1]
---
# Theme application
@@ -71,6 +73,11 @@ that needs a nested theme must keep that provider context in the same React tree
off. Compiled theme CSS uses that marker to switch surface tokens while keeping
the parent theme's component rules.
+`AppShell` uses the same provider/root-fallback identity path to resolve named
+mobile-navigation width points. The nearest Theme wins; without provider context
+it follows the registered root theme, and without an active theme it uses the
+standard width map.
+
## Boundaries and invariants
- **INV1 — The nearest provider wins.** Children read the closest Theme context
@@ -97,6 +104,10 @@ the parent theme's component rules.
- **INV9 — Application does not change compiled rules.** The provider may mount,
share, and remove compiler output. It must not create different theme-to-CSS
behavior from the build path.
+- **INV10 — Named responsive consumers share Theme metadata.** AppShell resolves
+ `sm`/`md`/`lg`/`xl`/`2xl` from the nearest active theme through the same root
+ fallback as other no-provider consumers. Its mobile side is strictly below the
+ point; equality belongs to the wider layout.
This record does not own theme authoring, token definitions, compiler output, or
which component parts are public theme targets.
@@ -123,11 +134,12 @@ which component parts are public theme targets.
detached consumers. Its observation and subscription logic stays
single-owned; extracting another module is not part of this contract.
- `MediaTheme.tsx` owns local light/dark surface context.
+- `AppShell.tsx` consumes the nearest effective width map for mobile navigation.
- `architecture:theme-compilation` owns the CSS that Theme mounts.
## Deciding specs
-None. This record captures the approved Theme provider and hook behavior.
+- `spec:AST-012/DEC-1` owns the fixed width-point vocabulary AppShell consumes.
## Verification
@@ -138,3 +150,4 @@ None. This record captures the approved Theme provider and hook behavior.
| INV6, INV7 | `useTheme.test.tsx` | Provider consumers observe the DOM, fallback observers leak, or system mode resolves incorrectly |
| INV8 | `MediaTheme.dom.test.tsx` | Surface mode replaces the theme, loses parent component rules, or remounts children |
| INV9 | Runtime/build compiler comparison | Provider-mounted CSS differs from built CSS for the same theme |
+| INV10 | `AppShell.test.tsx` | A named point ignores the nearest theme or treats equality as mobile |
diff --git a/docs/architecture/theme-authoring-contract.md b/docs/architecture/theme-authoring-contract.md
index 6b0469d311..944dce52ab 100644
--- a/docs/architecture/theme-authoring-contract.md
+++ b/docs/architecture/theme-authoring-contract.md
@@ -12,6 +12,7 @@ owners: [cixzhang, imdreamrunner]
applies_to:
[
packages/core/src/theme/defineTheme.ts,
+ packages/core/src/theme/themeAdaptations.ts,
packages/core/src/theme/syntax/defineSyntaxTheme.ts,
packages/core/src/theme/expandColorScale.ts,
packages/core/src/theme/expandTypeScale.ts,
@@ -26,6 +27,7 @@ applies_to:
verified_by:
[
packages/core/src/theme/defineTheme.test.ts,
+ packages/core/src/theme/themeAdaptations.test.ts,
packages/core/src/theme/syntax/serverSafeSyntax.test.ts,
packages/core/src/theme/expandColorScale.test.ts,
packages/core/src/theme/expandTypeScale.test.ts,
@@ -41,6 +43,10 @@ deciding_specs:
spec:AST-006/DEC-3,
spec:AST-006/DEC-4,
spec:AST-006/DEC-6,
+ spec:AST-012/DEC-1,
+ spec:AST-012/DEC-2,
+ spec:AST-012/DEC-3,
+ spec:AST-012/DEC-4,
spec:AST-017/DEC-1,
]
---
@@ -66,8 +72,9 @@ source configuration independently.
- optional theme-family-local token declarations;
- component target/style-key overrides;
- icon and indicator registries;
-- syntax tokens; and
-- `onDark` / `onLight` surface overrides.
+- syntax tokens;
+- `onDark` / `onLight` surface overrides; and
+- ordered environmental `adaptations` with a fixed named width map.
`defineTheme` resolves that input into a flat `DefinedTheme`. An extended theme
contains the resolved values it inherits, so a build does not need the base
@@ -108,17 +115,23 @@ style key, and CSS property rather than replacing the entire inherited target.
- **INV8 — Local-token enrollment is explicit and closed.** Supplying
`localTokens`, or extending an exact enrolled base, produces a flattened local
declaration map plus ownership and lineage metadata. Enrolled themes validate
- exact namespaces, case-insensitive `var()` references, cycles, and collisions
- with `tokens`; unenrolled themes retain their legacy behavior.
+ exact namespaces, case-insensitive `var()` references, cycles—including cycles
+ reachable only after co-matching adaptation rules cascade—and collisions with
+ `tokens`; unenrolled themes retain their legacy behavior.
- **INV9 — Authoring and output are separate systems.** This record owns the
normalized theme definition. The shared compiler owns turning it into styles;
runtime and build own using or saving that output.
-- **INV10 — `defineTheme` validates only what it constructs.** It owns theme
+- **INV10 — Adaptations are ordered normalized intent.** Every effective theme
+ retains its complete `sm`/`md`/`lg`/`xl`/`2xl` width map, generative-axis
+ metadata, and inherited-then-local `{when, value}` rule order. Rules re-resolve
+ against a child theme's effective root metadata; they do not mutate root token
+ reads or introduce identity, registries, media surfaces, or new local names.
+- **INV11 — `defineTheme` validates only what it constructs.** It owns theme
creation and normalization. It may reject malformed input that affects normalized
theme behavior or generated values as a construction precondition. Authoring or
reference data used only for validation stays outside `DefineThemeInput` and
`DefinedTheme`.
-- **INV11 — Theme `define*` helpers construct theme values.** They transform,
+- **INV12 — Theme `define*` helpers construct theme values.** They transform,
derive, or normalize input into a durable typed theme value used by a current
supported consumer; validating and returning the exact input unchanged is
insufficient.
@@ -167,6 +180,9 @@ public surface belongs to
and on-media composition; no layer invents its own merge rule.
- A new generated scale states which semantic tokens it may produce and confirms
explicit token overrides still win.
+- An adaptation change preserves the fixed condition vocabulary, inclusive
+ `from`/exclusive `below` width edges, authored rule order, root-only local-name
+ enrollment, and source/built extension parity.
- Authoring fields unavailable to the runtime-only path remain prohibited.
Build/CLI metadata without a normalized-theme effect may exist only for a named
current supported reader, stays outside `DefineThemeInput` and `DefinedTheme`,
@@ -177,6 +193,8 @@ public surface belongs to
- `packages/core/src/theme/defineTheme.ts` owns the public input, normalized IR,
orchestration, and extension behavior.
+- `themeAdaptations.ts` owns the fixed breakpoint/condition vocabulary,
+ validation, inherited rule ordering, axis completion, and concrete rule writes.
- `syntax/defineSyntaxTheme.ts` constructs syntax themes before `defineTheme`
adopts their tokens.
- `expandColorScale.ts`, `expandTypeScale.ts`, `expandRadiusScale.ts`, and
@@ -192,10 +210,10 @@ public surface belongs to
AST-006 decisions 1–4 and 6 establish the shipped theme-local authoring shape,
exact naming and inheritance rules, enrolled-only validation, and shared value
-contract. The remaining authoring and normalization architecture predates that
-spec and remains unchanged. AST-017 decision 1 owns released compatibility
-classification and migration; this record identifies only the theme/Core trigger
-that enters that path.
+contract. AST-012 decisions 1–4 establish the fixed width map, named closed
+conditions, ordered rule cascade, and source/built adaptation metadata parity.
+AST-017 decision 1 owns released compatibility classification and migration; this
+record identifies only the theme/Core trigger that enters that path.
## Verification
@@ -206,7 +224,8 @@ that enters that path.
| INV6 | component merge tests across base/generated/explicit rules | Restating one property drops inherited component styles |
| INV7 | `onMediaTokens.test.ts` and generated surface-rule tests | A child loses inherited surface customization or surface precedence changes |
| INV8 | `defineTheme.test.ts` and CLI source/built inheritance tests | Enrollment, validation, or lineage differs across runtime and static authoring paths |
-| INV10 | `DefineThemeInput`/output diff plus runtime/build fixtures | Validation-only data enters the normalized theme, or productive input loses construction validation |
-| INV11 | Core theme export diff, constructed-value evidence, and current-consumer callsite | A theme `define*` helper only checks input and returns that exact input unchanged |
+| INV10 | `themeAdaptations.test.ts` and CLI build fixtures | Width metadata, rule order, or child re-resolution diverges across source and built themes |
+| INV11 | `DefineThemeInput`/output diff plus runtime/build fixtures | Validation-only data enters the normalized theme, or productive input loses construction validation |
+| INV12 | Core theme export diff, constructed-value evidence, and current-consumer callsite | A theme `define*` helper only checks input and returns that exact input unchanged |
| Theme/Core compatibility | Maintained theme source/build against the minimum Core in its currently supported peer/dependency range | A theme update silently requires newer in-range Core or bypasses the `spec:AST-017` path |
| Authoring projection | `scripts/check-theme-template.test.mjs` | A supported authoring concept is missing or misstated in the template |
diff --git a/docs/architecture/theme-compilation.md b/docs/architecture/theme-compilation.md
index d3a2bdfd44..6aca6e276b 100644
--- a/docs/architecture/theme-compilation.md
+++ b/docs/architecture/theme-compilation.md
@@ -12,19 +12,30 @@ owners: [cixzhang, imdreamrunner]
applies_to:
[
packages/core/src/theme/generateThemeRules.ts,
+ packages/core/src/theme/themeAdaptations.ts,
packages/core/src/theme/derivedVarRegistry.ts,
packages/core/src/theme/Theme.tsx,
packages/cli/api/theme/build/build.mjs,
+ packages/cli/api/theme/build/core-interception.mjs,
packages/build/,
]
verified_by:
[
packages/core/src/theme/generateThemeRules.test.ts,
+ packages/core/src/theme/themeAdaptations.test.ts,
packages/core/src/theme/derivedVarRegistry.test.ts,
packages/cli/api/theme/build/build.test.mjs,
packages/cli/api/theme/build/build.public-component-vars.test.mjs,
+ packages/cli/api/theme/build/build.adaptation-core-compat.test.mjs,
+ packages/cli/api/theme/build/build.packed-old-core.test.mjs,
+ ]
+deciding_specs:
+ [
+ spec:AST-006/DEC-2,
+ spec:AST-006/DEC-4,
+ spec:AST-012/DEC-3,
+ spec:AST-012/DEC-4,
]
-deciding_specs: [spec:AST-006/DEC-2, spec:AST-006/DEC-4]
---
# Theme compilation
@@ -48,13 +59,17 @@ The current web compiler works like this:
1. `generateThemeRules` turns portable tokens, theme-local tokens, and component
overrides into CSS rules.
-2. The same code adds state rules, media-surface rules, scopes, and layers.
-3. The `Theme` provider mounts those rules when a theme was not built ahead of
+2. Ordered adaptation rules compile to separate media blocks after root rules.
+ Blocks preserve author order and are never merged or value-diffed; media-surface
+ overrides compile after them.
+3. The same code adds state rules, media-surface rules, scopes, and layers.
+4. The `Theme` provider mounts those rules when a theme was not built ahead of
time.
-4. The CLI saves those rules into CSS and packages the related JavaScript and
+5. The CLI saves those rules into CSS and packages the related JavaScript and
types.
-5. A built theme preserves local-token ownership and lineage metadata and is
- marked so the provider does not compile or inject it again.
+6. A built theme preserves local-token ownership, effective width points,
+ generative-axis metadata, and normalized ordered rules, and is marked so the
+ provider does not compile or inject it again.
For top-level declarations in base component target rules, the compiler preserves
generic CSS properties as written. When a guaranteed property needs to reach
@@ -106,6 +121,10 @@ Platform-specific details stay inside that compiler.
emits the normalized `localTokens` map beside portable declarations without
rewriting names or values. Runtime and static output use the same rules, and
invalid enrolled input is rejected before either path writes partial CSS.
+- **INV12 — Adaptation order is observable.** Root declarations emit first,
+ adaptation blocks remain separate in authored order, and media-surface
+ overrides emit last. Duplicate conditions and later root-restoring writes are
+ preserved exactly; runtime and static output use the same blocks.
This record does not own:
@@ -135,6 +154,33 @@ This record does not own:
- Changing scope or layer output tests both source and distribution builds.
- Changing local-token emission or packaging verifies exact-name runtime/static
parity, atomic failure, and preservation of built-theme lineage metadata.
+- Changing adaptation output verifies authored block order, duplicate conditions,
+ root-restoring writes, media-surface precedence, derived component lowering,
+ and source/built extension parity.
+- The CLI and core version independently, so a CLI that compiles adaptations
+ against a core that does not is a supported pairing rather than a broken
+ install. That pairing is bounded to the adaptation capability, not a general
+ compatibility scheme for arbitrary older cores: a theme with no adaptation
+ intent builds and emits the same CSS it always did, while valid rules, a custom
+ width map, and present-but-malformed adaptation metadata all count as intent
+ and fail with `ERR_CORE_INCOMPATIBLE` before any output is generated. A
+ complete default width map with no rules is a no-op on both paths, because that
+ is what core writes onto every resolved theme and every shipped built theme.
+ Neither path may emit CSS with adaptation rules missing. Intent is read from
+ resolved metadata when available; because a core that predates adaptations
+ erases it, the build also records each raw `defineTheme()` input and associates
+ it with the theme it produced. Only the selected theme's lineage decides, so an
+ unused adaptive theme elsewhere in the graph does not fail a plain build. If
+ that selected lineage contains an unobserved source package — whether the
+ async fallback bypassed interception or CommonJS reached a core namespace that
+ could not be wrapped — the build fails closed. Built package artifacts remain
+ observable through their retained metadata. Captured raw typography, color,
+ radius, and motion metadata is also retained when the old core omits `__axes`,
+ so a current-core child extending the artifact resolves partial adaptation
+ axes exactly as it would from source. Generated CSS is identical across the
+ two cores for a theme with no adaptation intent; generated JavaScript and
+ `@generated` provenance may differ because they record resolved metadata and
+ the core version, so `--check` can legitimately report drift after an upgrade.
- Adding a platform compiler names the shared concepts it supports and tests
that they keep the same meaning. Unsupported concepts fail clearly instead of
disappearing.
@@ -152,15 +198,23 @@ This record does not own:
implementation variables.
- `packages/cli/api/theme/build/build.mjs` saves and packages compiled CSS. Its
private-variable diagnostic is currently non-blocking; rejecting that input is
- a named conformance gap, not existing enforcement.
+ a named conformance gap, not existing enforcement. It also owns the
+ adaptation-capability check for the installed core: baseline generation is
+ required, and `generateAdaptationCSS` is demanded by valid or malformed
+ adaptation intent in authored, resolved, or built input.
+ `core-interception.mjs` owns capturing authored input and its generative axes:
+ it hands the loading theme a core whose `defineTheme` is wrapped to record each
+ raw input against the theme it returned, and reports loader paths it could not
+ cover so erased intent never passes as clean.
- Future platform compilers consume the same `DefinedTheme` behind this boundary.
## Deciding specs
AST-006 decisions 2 and 4 establish exact local-token output and atomic shared
-validation for enrolled themes. The system owner separately selected one
-definition with platform-specific outputs and the guaranteed, best-effort,
-public-semantic, and private implementation tiers.
+validation for enrolled themes. AST-012 decisions 3 and 4 establish ordered
+adaptation blocks and source/built metadata parity. The system owner separately
+selected one definition with platform-specific outputs and the guaranteed,
+best-effort, public-semantic, and private implementation tiers.
## Verification
@@ -173,6 +227,7 @@ public-semantic, and private implementation tiers.
| INV8 | Component target metadata and compatibility review | Successful generic emission is treated as a guaranteed public behavior |
| INV9, INV10 | Platform compiler tests when another compiler ships | CSS details enter shared authoring, or shared theme intent silently disappears |
| INV11 | `defineTheme.test.ts` and `build.test.mjs` local-token fixtures | Runtime/static output rewrites a local name, disagrees, or leaves partial output after failure |
+| INV12 | `themeAdaptations.test.ts` and CLI adaptation build fixtures | Rule blocks merge/reorder/drop, surfaces lose precedence, or runtime/static CSS diverges |
| Built themes | Theme and CLI build tests | Runtime recompiles a built theme, or built output omits canonical rules |
## Known conformance and verification gaps
@@ -187,13 +242,13 @@ behavior does not yet conform and must not be treated as enforcement:
it. Runtime `defineTheme` has no equivalent validation and accepts them. The
follow-up must reject direct private variables recursively before CSS
generation across both paths and prove runtime/static parity.
-- **Pseudo and media-surface component overrides bypass derived expansion.**
- Top-level, non-pseudo base declarations use `derivedVarRegistry`, including
- `replaces` and container expansion. Base pseudo declarations and
- `onDark.components` / `onLight.components` declarations currently serialize
- properties directly. The follow-up must use one component-declaration lowering
- path for base, pseudo, and media-surface rules, with parity fixtures for a
- normal mapping, `replaces`, and container padding.
+- **Nested pseudo component declarations bypass derived expansion.** Top-level
+ component declarations at the root, in adaptations, and under
+ `onDark.components` / `onLight.components` use `derivedVarRegistry`, including
+ `replaces` and container expansion. Nested pseudo declarations on those
+ surfaces still serialize properties directly. The follow-up must route nested
+ pseudos through the same component-declaration lowering path, with parity
+ fixtures for a normal mapping, `replaces`, and container padding.
- **Guaranteed-property coverage is not machine-complete.** The shared catalog is
normative, but the component-doc schema has no per-target
`guaranteedProperties` declarations. CI therefore cannot prove that a target
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 1c0c3f5a76..1ddaf09f39 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -138,54 +138,55 @@ if (isError(result)) {
<!-- BEGIN GENERATED: error-codes -->
-| Code | Meaning |
-| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
-| `ERR_UNKNOWN` | Fallback for any error without a more specific code. |
-| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |
-| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a command group was not recognized (e.g. `astryx theme bogus`). |
-| `ERR_INVALID_OPTION` | An unknown flag/option was passed (Commander `unknownOption`). |
-| `ERR_INVALID_ARGUMENT` | An option/argument had a value Commander's parser rejected. |
-| `ERR_MISSING_ARGUMENT` | A required positional argument was omitted (Commander `missingArgument`). |
-| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (en, zh, dense). |
-| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (full, compact, brief). |
-| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |
-| `ERR_CORE_NOT_FOUND` | `@astryxdesign/core` could not be located (not installed / not in a monorepo). |
-| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |
-| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |
-| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |
-| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |
-| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |
-| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |
-| `ERR_AMBIGUOUS_TEMPLATE` | A template id matched more than one template (narrow with --type/--package). |
-| `ERR_AMBIGUOUS_COMPONENT` | A component name is owned by more than one package (narrow with --package). |
-| `ERR_UNKNOWN_THEME` | No theme matched the requested slug (theme add). |
-| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name (discover). |
-| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to agent-docs/init. |
-| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |
-| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |
-| `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |
-| `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |
-| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |
-| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |
-| `ERR_NO_SOURCE` | No source file could be located for the requested component/template. |
-| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |
-| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |
-| `ERR_FILE_EXISTS` | Refused to overwrite an existing file in non-interactive mode. |
-| `ERR_PATH_TRAVERSAL` | A path escaped its allowed root, or a name contained traversal markers. |
-| `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |
-| `ERR_THEME_INVALID` | A theme definition was missing a required property (e.g. `name`). |
-| `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a defineTheme result. |
-| `ERR_PALETTE_GENERATION` | A palette generation request or one of its constraints was invalid. |
-| `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |
-| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |
-| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |
-| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |
-| `ERR_UNKNOWN_POST` | No blog post matched the requested slug in the feed. |
-| `ERR_FETCH_FAILED` | A network fetch (RSS feed or post text) failed. |
-| `ERR_LAYOUT_PARSE` | A layout expression failed to parse (syntax error, with line/col). |
-| `ERR_LAYOUT_INVALID` | A layout expression parsed but failed validation (unknown component/prop/enum/block). |
-| `ERR_UNCLASSIFIED_EXIT` | Recorded in the debug log, never printed: a command exited non-zero without going through cliError/jsonError, so no stable code was available. |
-| `ERR_SIGNAL_TERMINATED` | Recorded in the debug log, never printed: the process was ended by a signal (Ctrl-C, SIGTERM) before the command reached a terminal path. |
+| Code | Meaning |
+| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `ERR_UNKNOWN` | Fallback for any error without a more specific code. |
+| `ERR_UNKNOWN_COMMAND` | A top-level command name was not recognized (e.g. `astryx bogus`). |
+| `ERR_UNKNOWN_SUBCOMMAND` | A subcommand under a command group was not recognized (e.g. `astryx theme bogus`). |
+| `ERR_INVALID_OPTION` | An unknown flag/option was passed (Commander `unknownOption`). |
+| `ERR_INVALID_ARGUMENT` | An option/argument had a value Commander's parser rejected. |
+| `ERR_MISSING_ARGUMENT` | A required positional argument was omitted (Commander `missingArgument`). |
+| `ERR_INVALID_LANG` | `--lang` was given a value outside its choices (en, zh, dense). |
+| `ERR_INVALID_DETAIL` | `--detail` was given a value outside its choices (full, compact, brief). |
+| `ERR_NODE_VERSION` | The running Node.js version is below the supported minimum. |
+| `ERR_CORE_NOT_FOUND` | `@astryxdesign/core` could not be located (not installed / not in a monorepo). |
+| `ERR_CORE_INCOMPATIBLE` | The installed `@astryxdesign/core` loaded but is too old for this input — it lacks a capability the CLI must call to emit correct output (upgrade core). |
+| `ERR_UNKNOWN_COMPONENT` | No component matched the requested name. |
+| `ERR_UNKNOWN_HOOK` | No hook matched the requested name. |
+| `ERR_UNKNOWN_TOPIC` | No docs topic matched the requested name. |
+| `ERR_UNKNOWN_SECTION` | A docs topic exists but the requested section within it does not. |
+| `ERR_UNKNOWN_CATEGORY` | A `--category` filter value did not match any known category. |
+| `ERR_UNKNOWN_TEMPLATE` | No template matched the requested name. |
+| `ERR_AMBIGUOUS_TEMPLATE` | A template id matched more than one template (narrow with --type/--package). |
+| `ERR_AMBIGUOUS_COMPONENT` | A component name is owned by more than one package (narrow with --package). |
+| `ERR_UNKNOWN_THEME` | No theme matched the requested slug (theme add). |
+| `ERR_UNKNOWN_PACKAGE` | No package matched the requested name (discover). |
+| `ERR_UNKNOWN_AGENT` | An unrecognized `--agent` value was passed to agent-docs/init. |
+| `ERR_UNKNOWN_FEATURE` | An unrecognized `--features` value was passed to init. |
+| `ERR_UNKNOWN_CODEMOD` | A `--codemod` value did not match any registered codemod (upgrade). |
+| `ERR_CODEMOD_FAILED` | One or more codemods failed during an upgrade run. |
+| `ERR_NOT_FOUND` | A generic discover/lookup query matched nothing in any package. |
+| `ERR_NO_DOC` | A component exists but has no typed `.doc.mjs` file. |
+| `ERR_NO_SHOWCASE` | No showcase exists for the requested component. |
+| `ERR_NO_SOURCE` | No source file could be located for the requested component/template. |
+| `ERR_INVALID_DOC` | A component's docs failed validation (malformed `.doc.mjs`). |
+| `ERR_FILE_NOT_FOUND` | A required input file did not exist. |
+| `ERR_FILE_EXISTS` | Refused to overwrite an existing file in non-interactive mode. |
+| `ERR_PATH_TRAVERSAL` | A path escaped its allowed root, or a name contained traversal markers. |
+| `ERR_WRITE_FAILED` | Writing output files failed (and was rolled back). |
+| `ERR_THEME_INVALID` | A theme definition was missing a required property (e.g. `name`). |
+| `ERR_THEME_LOAD` | A theme file could not be loaded / parsed into a defineTheme result. |
+| `ERR_PALETTE_GENERATION` | A palette generation request or one of its constraints was invalid. |
+| `ERR_VERSION_DETECT` | The current `@astryxdesign/core` version could not be detected. |
+| `ERR_INVALID_VERSION` | A `--from`/`--to` value was not a valid semver string. |
+| `ERR_DEP_MISSING` | A required external dependency (e.g. jscodeshift) is missing. |
+| `ERR_GH_CLI` | GitHub CLI (`gh`) is not installed or not authenticated. |
+| `ERR_UNKNOWN_POST` | No blog post matched the requested slug in the feed. |
+| `ERR_FETCH_FAILED` | A network fetch (RSS feed or post text) failed. |
+| `ERR_LAYOUT_PARSE` | A layout expression failed to parse (syntax error, with line/col). |
+| `ERR_LAYOUT_INVALID` | A layout expression parsed but failed validation (unknown component/prop/enum/block). |
+| `ERR_UNCLASSIFIED_EXIT` | Recorded in the debug log, never printed: a command exited non-zero without going through cliError/jsonError, so no stable code was available. |
+| `ERR_SIGNAL_TERMINATED` | Recorded in the debug log, never printed: the process was ended by a signal (Ctrl-C, SIGTERM) before the command reached a terminal path. |
<!-- END GENERATED: error-codes -->
<!-- Generated by scripts/generate-cli-readme.mjs from the error-codes EnumDoc (== ERROR_CODES). Run `pnpm -F @astryxdesign/cli readme`. -->
diff --git a/packages/cli/api/theme/build/build.adaptation-core-compat.test.mjs b/packages/cli/api/theme/build/build.adaptation-core-compat.test.mjs
new file mode 100644
index 0000000000..b8a01a8ff3
--- /dev/null
+++ b/packages/cli/api/theme/build/build.adaptation-core-compat.test.mjs
@@ -0,0 +1,394 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `theme build` against a core that predates ordered adaptations.
+ *
+ * The CLI and @astryxdesign/core are independently versioned optional peers
+ * (`"@astryxdesign/core": "*"`), so a newer CLI routinely runs against an older
+ * published core. Adaptations are a core CAPABILITY — `generateAdaptationCSS`
+ * — and requiring it unconditionally broke every theme build on such a pairing,
+ * adaptation or not.
+ *
+ * The contract these tests hold:
+ * - a theme with no adaptation intent builds against the older core, unchanged;
+ * - a theme that HAS adaptation intent — valid rules, a custom width map, or
+ * present-but-malformed metadata the old resolver would erase — fails before
+ * anything is generated or written with ERR_CORE_INCOMPATIBLE;
+ * - every shape a theme arrives in is recognized: raw `adaptations` input, a
+ * resolved `__adaptationRules`, a built module's `__adaptations`, and a
+ * source file whose adaptations the older resolver erased on the way in;
+ * - a source that cannot be observed completely fails clearly rather than
+ * building on an assumption;
+ * - raw generative-axis metadata survives an old-core build for a later
+ * current-core child's source-equivalent extension.
+ *
+ * The capability is removed with vi.mock and the resolver is made
+ * adaptation/axis-blind so unit cases exercise the same erased-input boundary
+ * without installing another package. `build.packed-old-core.test.mjs` covers
+ * the resolution-level pairing with a real package layout and separate process.
+ */
+
+import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+
+vi.mock('@astryxdesign/core/theme', async importActual => {
+ const actual = /** @type {Record<string, any>} */ (await importActual());
+ const {generateAdaptationCSS: _dropped, ...withoutAdaptations} = actual;
+
+ /** Model the published old core: it resolves ordinary theme values but drops
+ * every adaptation field and retained generative-axis metadata. */
+ const blind = value => {
+ if (!value || typeof value !== 'object') return value;
+ const {
+ adaptations: _adaptations,
+ __adaptations: _normalized,
+ __adaptationRules: _rules,
+ __axes: _axes,
+ ...rest
+ } = value;
+ if (rest.extends) rest.extends = blind(rest.extends);
+ return rest;
+ };
+
+ return {
+ ...withoutAdaptations,
+ defineTheme(input) {
+ return blind(actual.defineTheme(blind(input)));
+ },
+ };
+});
+
+const {themeBuild} = await import('./build.mjs');
+
+/** The message any old-core adaptation failure must carry. */
+const UPGRADE_MESSAGE = /does not export `generateAdaptationCSS`/;
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-old-core-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/**
+ * @param {string} name
+ * @param {string} source
+ * @returns {string} the file name, relative to tmpDir
+ */
+function writeTheme(name, source) {
+ fs.writeFileSync(path.join(tmpDir, `${name}.mjs`), source);
+ return `${name}.mjs`;
+}
+
+/** @param {string} name */
+function outputs(name) {
+ return ['css', 'js', 'd.ts', 'variants.d.ts'].map(ext =>
+ path.join(tmpDir, `${name}.${ext}`),
+ );
+}
+
+/** @param {string} name */
+function wroteNothing(name) {
+ return outputs(name).every(file => !fs.existsSync(file));
+}
+
+describe('theme build without core adaptation support', () => {
+ it('builds a theme that declares no adaptations', async () => {
+ const file = writeTheme(
+ 'plain',
+ `export default {
+ name: 'plain',
+ tokens: {'--color-background': '#fff'},
+ components: {button: {base: {borderRadius: '4px'}}},
+ };\n`,
+ );
+
+ const receipt = await themeBuild(file, {}, {cwd: tmpDir});
+
+ expect(receipt?.type).toBe('theme.build');
+ const css = fs.readFileSync(path.join(tmpDir, 'plain.css'), 'utf8');
+ expect(css).toContain('--color-background: #fff;');
+ expect(css).toContain('border-radius: 4px;');
+ });
+
+ it('builds a theme whose normalized adaptations carry no rules', async () => {
+ // What core's resolver puts on EVERY theme, and what every shipped built
+ // theme carries: the field is present, the rule list is empty, the width
+ // map is the complete default one. That combination asks for nothing.
+ const file = writeTheme(
+ 'normalized-empty',
+ `export default {
+ name: 'normalized-empty',
+ tokens: {'--color-background': '#fff'},
+ __adaptations: {
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [],
+ },
+ };\n`,
+ );
+
+ const receipt = await themeBuild(file, {}, {cwd: tmpDir});
+
+ expect(receipt?.type).toBe('theme.build');
+ expect(fs.existsSync(path.join(tmpDir, 'normalized-empty.css'))).toBe(true);
+ });
+
+ it('builds source that declares only the complete default adaptation map', async () => {
+ const file = writeTheme(
+ 'raw-default-map',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+ export default defineTheme({
+ name: 'raw-default-map',
+ tokens: {'--color-background': '#fff'},
+ adaptations: {
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [],
+ },
+ });\n`,
+ );
+
+ const receipt = await themeBuild(file, {}, {cwd: tmpDir});
+
+ expect(receipt?.type).toBe('theme.build');
+ expect(fs.existsSync(path.join(tmpDir, 'raw-default-map.css'))).toBe(true);
+ });
+
+ it.each([
+ ['a string rule list', 'rules-string', `{rules: 'invalid'}`],
+ ['a null rule list', 'rules-null', `{rules: null}`],
+ ['an object rule list', 'rules-object', `{rules: {invalid: true}}`],
+ ['an array breakpoint map', 'points-array', `{widthBreakpoints: []}`],
+ ['a null breakpoint map', 'points-null', `{widthBreakpoints: null}`],
+ ])(
+ 'rejects malformed adaptations with %s',
+ async (_label, name, adaptations) => {
+ const file = writeTheme(
+ name,
+ `export default {
+ name: '${name}',
+ tokens: {'--color-background': '#fff'},
+ adaptations: ${adaptations},
+ };\n`,
+ );
+
+ await expect(themeBuild(file, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_CORE_INCOMPATIBLE',
+ });
+ expect(wroteNothing(name)).toBe(true);
+ },
+ );
+
+ it('rejects a CUSTOM width map even with no rules', async () => {
+ // Emits no CSS, so nothing looks lost — but the map is preserved in built
+ // metadata, resolves `AppShell`'s `mobileNav.breakpoint` names, and is
+ // inherited through `extends`. An older core keeps none of that, so the
+ // theme would build and then behave differently wherever those points are
+ // read. This is the one intent case with no CSS behind it.
+ const file = writeTheme(
+ 'breakpoints-only',
+ `export default {
+ name: 'breakpoints-only',
+ tokens: {'--color-background': '#fff'},
+ __adaptations: {
+ widthBreakpoints: {sm: 600, md: 900, lg: 1200, xl: 1500, '2xl': 1800},
+ rules: [],
+ },
+ };\n`,
+ );
+
+ await expect(themeBuild(file, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_CORE_INCOMPATIBLE',
+ });
+ expect(wroteNothing('breakpoints-only')).toBe(true);
+ });
+
+ it('rejects a partial width map, even one matching the defaults', async () => {
+ // Core merges a partial map over the defaults; the override is real and
+ // inheritable regardless of the values it happens to name.
+ const file = writeTheme(
+ 'one-point',
+ `export default {
+ name: 'one-point',
+ tokens: {'--color-background': '#fff'},
+ adaptations: {widthBreakpoints: {md: 768}, rules: []},
+ };\n`,
+ );
+
+ await expect(themeBuild(file, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_CORE_INCOMPATIBLE',
+ });
+ });
+
+ it('rejects raw `adaptations` input, writing nothing', async () => {
+ const file = writeTheme(
+ 'raw',
+ `export default {
+ name: 'raw',
+ tokens: {'--color-background': '#fff'},
+ adaptations: {
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [
+ {when: {pointer: 'coarse'}, value: {tokens: {'--size-element-md': '44px'}}},
+ ],
+ },
+ };\n`,
+ );
+
+ await expect(themeBuild(file, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_CORE_INCOMPATIBLE',
+ message: expect.stringMatching(UPGRADE_MESSAGE),
+ });
+ expect(wroteNothing('raw')).toBe(true);
+ });
+
+ it('rejects a resolved theme carrying `__adaptationRules`', async () => {
+ const file = writeTheme(
+ 'resolved',
+ `export default {
+ name: 'resolved',
+ tokens: {'--color-background': '#fff'},
+ __adaptationRules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--size-element-md': '44px'}},
+ },
+ ],
+ };\n`,
+ );
+
+ await expect(themeBuild(file, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_CORE_INCOMPATIBLE',
+ });
+ expect(wroteNothing('resolved')).toBe(true);
+ });
+
+ it('rejects a built module read back as `__adaptations` with rules', async () => {
+ // The shape `generateBuiltModule` emits — the base an `extends` chain reads.
+ const file = writeTheme(
+ 'built-base',
+ `export default {
+ name: 'built-base',
+ __built: true,
+ tokens: {'--color-background': '#fff'},
+ __adaptations: {
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [
+ {when: {contrast: 'more'}, value: {tokens: {'--color-border': '#000'}}},
+ ],
+ },
+ };\n`,
+ );
+
+ await expect(themeBuild(file, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_CORE_INCOMPATIBLE',
+ });
+ expect(wroteNothing('built-base')).toBe(true);
+ });
+
+ it('rejects a source whose adaptations the old resolver erased', async () => {
+ // The dangerous pairing: this core's `defineTheme` builds its result field
+ // by field and drops `adaptations`, so the object the build ends up
+ // holding carries no trace of them. Interception records the raw input as
+ // the call happens, which is the only remaining witness — without it this
+ // ships CSS with every adaptation rule silently missing.
+ const file = writeTheme(
+ 'erased',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+ export default defineTheme({
+ name: 'erased',
+ tokens: {'--color-background': '#fff'},
+ adaptations: {
+ rules: [
+ {when: {motion: 'reduce'}, value: {tokens: {'--motion-fast': '0ms'}}},
+ ],
+ },
+ });\n`,
+ );
+
+ await expect(themeBuild(file, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_CORE_INCOMPATIBLE',
+ });
+ expect(wroteNothing('erased')).toBe(true);
+ });
+
+ it('sees adaptations a factory hands to defineTheme', async () => {
+ // No static analysis could follow this reliably; interception does not
+ // have to — the call happens, so the input is recorded.
+ const file = writeTheme(
+ 'factory',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+ const layer = (...parts) => parts.reduce((a, p) => ({...a, ...p}), {});
+ const build = cfg => defineTheme(layer({name: 'factory', tokens: {}}, cfg));
+ export default [build({adaptations: {rules: [{when: {pointer: 'coarse'}, value: {}}]}})].at(-1);\n`,
+ );
+
+ await expect(themeBuild(file, {}, {cwd: tmpDir})).rejects.toMatchObject({
+ code: 'ERR_CORE_INCOMPATIBLE',
+ });
+ expect(wroteNothing('factory')).toBe(true);
+ });
+
+ it('does not fail a plain theme for an adaptive sibling in the same module', async () => {
+ // Both themes are defined in one module; only the selected one's lineage
+ // decides. Failing here would be the false positive that makes the guard
+ // unusable.
+ const file = writeTheme(
+ 'siblings',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+ export const unused = defineTheme({
+ name: 'unused',
+ tokens: {},
+ adaptations: {rules: [{when: {pointer: 'coarse'}, value: {}}]},
+ });
+ export default defineTheme({
+ name: 'siblings',
+ tokens: {'--color-background': '#fff'},
+ });\n`,
+ );
+
+ const receipt = await themeBuild(file, {}, {cwd: tmpDir});
+
+ expect(receipt?.type).toBe('theme.build');
+ });
+
+ it('builds a theme whose only mention of adaptations is comments and strings', async () => {
+ // A text search would fail this theme; watching the actual call cannot.
+ const file = writeTheme(
+ 'commented',
+ `/**
+ * No adaptations yet. One day maybe:
+ * adaptations: {rules: [{when: {pointer: 'coarse'}, value: {}}]}
+ */
+ // adaptations: {widthBreakpoints: {sm: 600}, rules: []},
+ export default {
+ name: 'commented',
+ tokens: {'--color-background': '#fff'},
+ /* adaptations: {rules: []}, */
+ };\n`,
+ );
+
+ const receipt = await themeBuild(file, {}, {cwd: tmpDir});
+
+ expect(receipt?.type).toBe('theme.build');
+ });
+
+ it('fails the same way in --check mode, before reporting drift', async () => {
+ const file = writeTheme(
+ 'checked',
+ `export default {
+ name: 'checked',
+ tokens: {'--color-background': '#fff'},
+ adaptations: {
+ rules: [{when: {pointer: 'coarse'}, value: {tokens: {'--size-element-md': '44px'}}}],
+ },
+ };\n`,
+ );
+
+ await expect(
+ themeBuild(file, {check: true}, {cwd: tmpDir}),
+ ).rejects.toMatchObject({code: 'ERR_CORE_INCOMPATIBLE'});
+ });
+});
diff --git a/packages/cli/api/theme/build/build.adaptation-enrollment.test.mjs b/packages/cli/api/theme/build/build.adaptation-enrollment.test.mjs
new file mode 100644
index 0000000000..c3afbf67cb
--- /dev/null
+++ b/packages/cli/api/theme/build/build.adaptation-enrollment.test.mjs
@@ -0,0 +1,215 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Root and adaptation component-value validation are the SAME check.
+ *
+ * AST-012/DEC-5: component writes in an adaptation rule use the same target,
+ * axis, value-domain and extension validation as root `components`. The single
+ * thing adaptations add is that a value whose validity comes from THEME
+ * ENROLLMENT may not be enrolled conditionally — generated module augmentation
+ * is unconditional, so a value existing only under a media condition would
+ * widen a component's public type from a conditional surface.
+ *
+ * Everything else carries: built-ins are independently valid, and an
+ * unresolved shared result (a closed literal-union axis with no augmentation
+ * point, or a domain the docs cannot enumerate) reaches adaptations unchanged.
+ * The spec explicitly rejects adaptation-specific resolvers, allowlists and
+ * unresolved-domain exceptions.
+ *
+ * Each case is therefore PAIRED: the same `component:prop:value` is put on the
+ * root and in a rule, and the two outcomes are asserted together. A test that
+ * only checked the adaptation side could not tell parity from coincidence.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {themeBuild} from './build.mjs';
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-enrollment-'));
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/** Build a theme whose ROOT declares `component[key]`. */
+async function buildWithRootValue(name, component, key) {
+ const file = `${name}.mjs`;
+ fs.writeFileSync(
+ path.join(tmpDir, file),
+ `export default {
+ name: '${name}',
+ tokens: {'--color-background-body': '#fff'},
+ components: {'${component}': {'${key}': {color: 'red'}}},
+ };\n`,
+ );
+ return themeBuild(file, {}, {cwd: tmpDir});
+}
+
+/** Build a theme whose value appears ONLY inside an adaptation rule. */
+async function buildWithRuleOnlyValue(name, component, key) {
+ const file = `${name}.mjs`;
+ fs.writeFileSync(
+ path.join(tmpDir, file),
+ `export default {
+ name: '${name}',
+ tokens: {'--color-background-body': '#fff'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {components: {'${component}': {'${key}': {color: 'red'}}}},
+ },
+ ],
+ },
+ };\n`,
+ );
+ return themeBuild(file, {}, {cwd: tmpDir});
+}
+
+/** Did the build emit type augmentation — i.e. was the value enrollment-dependent? */
+function emittedAugmentation(receipt) {
+ return Boolean(receipt?.data?.outputs?.variantsDts);
+}
+
+describe('values the root accepts without enrollment are accepted rule-only', () => {
+ it.each([
+ ['a built-in value', 'button', 'variant:primary'],
+ // Button `size` is a closed literal union with no `ButtonSizeMap`, so the
+ // root has no augmentation point to widen and passes the value through.
+ // DEC-5 requires an adaptation to carry that same shared result.
+ ['a closed non-augmentable axis', 'button', 'size:jumbo'],
+ // A target whose prop domain the docs cannot enumerate — the unresolved
+ // case. It must NOT be an adaptation-specific exception; it is simply
+ // whatever root does.
+ ['an unresolved domain', 'avatar-group', 'size:not-a-real-avatar-size'],
+ ])('accepts %s on both surfaces', async (_label, component, key) => {
+ const rootReceipt = await buildWithRootValue('root-ok', component, key);
+ expect(rootReceipt?.type).toBe('theme.build');
+ // The root accepts it WITHOUT generating augmentation. That proves the
+ // shared root path does not classify it as enrollment-dependent; for an
+ // unresolved domain, acceptance is not evidence that the value is valid.
+ expect(emittedAugmentation(rootReceipt)).toBe(false);
+
+ const ruleReceipt = await buildWithRuleOnlyValue('rule-ok', component, key);
+ expect(ruleReceipt?.type).toBe('theme.build');
+ });
+});
+
+describe('enrollment-dependent values may not be enrolled by a rule', () => {
+ const COMPONENT = 'button';
+ const KEY = 'variant:brandy';
+
+ it('the root enrolls it and generates augmentation', async () => {
+ const receipt = await buildWithRootValue('root-custom', COMPONENT, KEY);
+
+ expect(receipt?.type).toBe('theme.build');
+ expect(emittedAugmentation(receipt)).toBe(true);
+ const variants = fs.readFileSync(
+ path.join(tmpDir, 'root-custom.variants.d.ts'),
+ 'utf8',
+ );
+ expect(variants).toContain('ButtonVariantMap');
+ expect(variants).toContain("'brandy': true;");
+ });
+
+ it('a rule-only value is rejected', async () => {
+ await expect(
+ buildWithRuleOnlyValue('rule-custom', COMPONENT, KEY),
+ ).rejects.toMatchObject({
+ code: 'ERR_THEME_INVALID',
+ message: expect.stringMatching(/enrolls the custom value/),
+ });
+ });
+
+ it('is accepted in a rule once the root declares it', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'both.mjs'),
+ `export default {
+ name: 'both',
+ tokens: {'--color-background-body': '#fff'},
+ components: {button: {'variant:brandy': {color: 'red'}}},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {components: {button: {'variant:brandy': {color: 'blue'}}}},
+ },
+ ],
+ },
+ };\n`,
+ );
+
+ const receipt = await themeBuild('both.mjs', {}, {cwd: tmpDir});
+
+ expect(receipt?.type).toBe('theme.build');
+ // Enrolled once, at the root, and the augmentation stays unconditional.
+ expect(emittedAugmentation(receipt)).toBe(true);
+ const css = fs.readFileSync(path.join(tmpDir, 'both.css'), 'utf8');
+ expect(css).toContain('pointer: coarse');
+ });
+});
+
+describe('the enrollment rule is the only difference', () => {
+ it('rejects a rule-only custom value while accepting its unresolved sibling', async () => {
+ // One theme, one rule, two values: the enrollment-dependent one fails and
+ // the unresolved one does not contribute an error. Proves the check keys
+ // on classification, not on "absent from root".
+ fs.writeFileSync(
+ path.join(tmpDir, 'mixed.mjs'),
+ `export default {
+ name: 'mixed',
+ tokens: {'--color-background-body': '#fff'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ button: {'size:jumbo': {color: 'red'}, 'variant:brandy': {color: 'blue'}},
+ },
+ },
+ },
+ ],
+ },
+ };\n`,
+ );
+
+ await expect(themeBuild('mixed.mjs', {}, {cwd: tmpDir})).rejects.toThrow(
+ /variant:brandy/,
+ );
+ await expect(
+ themeBuild('mixed.mjs', {}, {cwd: tmpDir}),
+ ).rejects.not.toThrow(/size:jumbo/);
+ });
+
+ it('accepts a rule that only restyles built-ins on many axes', async () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'builtins.mjs'),
+ `export default {
+ name: 'builtins',
+ tokens: {'--color-background-body': '#fff'},
+ adaptations: {
+ rules: [
+ {
+ when: {width: {below: 'md'}},
+ value: {
+ components: {
+ button: {'variant:secondary': {padding: '8px'}, base: {gap: '4px'}},
+ },
+ },
+ },
+ ],
+ },
+ };\n`,
+ );
+
+ const receipt = await themeBuild('builtins.mjs', {}, {cwd: tmpDir});
+
+ expect(receipt?.type).toBe('theme.build');
+ expect(emittedAugmentation(receipt)).toBe(false);
+ });
+});
diff --git a/packages/cli/api/theme/build/build.mjs b/packages/cli/api/theme/build/build.mjs
index 3718fae0a8..c7e2d6fdfe 100644
--- a/packages/cli/api/theme/build/build.mjs
+++ b/packages/cli/api/theme/build/build.mjs
@@ -19,6 +19,15 @@
* (silent by default), so the CLI keeps its exact output while a programmatic
* caller stays quiet.
*
+ * The installed `@astryxdesign/core` is an independently versioned optional
+ * peer, so it can be older than the CLI. A theme that uses only baseline
+ * features builds against such a core unchanged; a theme that needs ordered
+ * adaptations (which need core's `generateAdaptationCSS`) fails early with
+ * ERR_CORE_INCOMPATIBLE rather than emitting CSS with those rules quietly
+ * missing. That check is scoped to the adaptation capability — it is not a
+ * general compatibility scheme for every export an arbitrary older core might
+ * lack.
+ *
* With `{check: true}`, it compiles the same outputs in memory but writes
* nothing: it compares each generated file against what is on disk (ignoring
* only the volatile `@generated` `Command:` line) and returns a
@@ -30,7 +39,7 @@
import * as fs from 'node:fs';
import * as path from 'node:path';
-import {pathToFileURL, fileURLToPath} from 'node:url';
+import {fileURLToPath} from 'node:url';
import {createJiti} from 'jiti';
import {getCliInvocation} from '../../../foundation/env/package-manager.mjs';
import {CLI_ROOT, findCoreDir} from '../../../foundation/fs/paths.mjs';
@@ -48,6 +57,7 @@ import {
targetsByKey,
} from '../../../foundation/discovery/theming-targets.mjs';
import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';
+import {interceptCore} from './core-interception.mjs';
// Import shared theme processing from core. `astryx theme build` MUST produce the
// exact same CSS as the `<Theme>` runtime, so it has exactly one generation
@@ -56,17 +66,51 @@ import {collectUnloadedFonts, formatFontLoadingHelp} from './font-warning.mjs';
// action). A built, resolvable `@astryxdesign/core` is a hard requirement.
// A built, resolvable `@astryxdesign/core` is a hard requirement. These are
// populated from a dynamic import (a runtime boundary), so `any` is intentional.
+//
+// The CLI and core are independently versioned optional peers, so this import
+// can succeed against a core OLDER than the CLI. Only the exports every theme
+// build needs are REQUIRED (`defineTheme`, `generateThemeRulesSplit`).
+// `generateAdaptationCSS` (ordered environmental adaptations) is treated as a
+// capability instead, required only by a theme that actually uses it:
+// requiring it unconditionally made every theme build — adaptations or not —
+// fail against an older published core. This is a targeted allowance for that
+// one capability, not a general scheme; the other two optional reads below
+// (`generateOnMediaCSS`, `dataTokenDefaults`) both exist in every core that
+// ships adaptations' predecessor surface.
/** @type {any} */ let _defineTheme = null;
/** @type {any} */ let _generateThemeRulesSplit = null;
/** @type {any} */ let _generateOnMediaCSS = null;
+/** @type {any} */ let _generateAdaptationCSS = null;
/** @type {any} */ let _dataTokenDefaults = null;
+/**
+ * The whole `@astryxdesign/core/theme` namespace. A theme file handed a
+ * wrapped core must still get every export the installed one has, including
+ * ones this file never names — so interception spreads this rather than
+ * rebuilding a core from the handful of functions below.
+ */
+/** @type {any} */ let _coreThemeModule = null;
+/**
+ * The `@astryxdesign/core` ROOT namespace, imported separately because it
+ * exports far more than the theme subpath. Interception must hand a theme file
+ * that imports a component from the root the root's own exports, not the theme
+ * namespace wearing its name.
+ */
+/** @type {any} */ let _coreRootModule = null;
/** @type {any} */ let _coreImportError = null;
try {
const coreTheme = await import('@astryxdesign/core/theme');
+ _coreThemeModule = coreTheme;
_defineTheme = coreTheme.defineTheme;
_generateThemeRulesSplit = coreTheme.generateThemeRulesSplit;
_generateOnMediaCSS = coreTheme.generateOnMediaCSS;
+ _generateAdaptationCSS = coreTheme.generateAdaptationCSS;
_dataTokenDefaults = coreTheme.dataTokenDefaults;
+ try {
+ _coreRootModule = await import('@astryxdesign/core');
+ } catch {
+ // A core without a usable root entry still builds themes; interception
+ // falls back to the theme namespace for the root specifier.
+ }
} catch (e) {
// Capture the reason so the theme action can surface a precise, actionable
// error. We don't throw here: this module is imported eagerly by the CLI
@@ -201,90 +245,135 @@ function toPascalCase(name) {
.join('');
}
+/** @type {Promise<Record<string, Record<string, string[]>>> | null} */
+let _knownValuesIndexPromise = null;
+
/**
- * Load known built-in values for a component's visual props from its .doc.mjs file.
- * Parses the type string (e.g. "'info' | 'warning' | 'error' | 'success'") to extract values.
- * Returns a map of { propName: string[] } for props that are visual (listed in theming targets).
- * @param {string} componentName
- * @returns {Promise<Record<string, string[]>>}
+ * Build one target-keyed index of built-in visual-prop values from every core
+ * component doc. A rendered target often lives in a sibling doc (for example,
+ * `astryx-heading` is documented by Text/Heading.doc.mjs), so directory-name
+ * guessing is not a valid lookup strategy.
*/
-async function loadKnownValues(componentName) {
- // Resolve core src relative to the CLI package, not cwd (which may be a theme package)
- const cliDir = path.dirname(fileURLToPath(import.meta.url));
- const coreSrc = path.resolve(cliDir, '../../../../core/src');
- if (!fs.existsSync(coreSrc)) return {};
- // Map component name to directory (e.g. 'banner' → 'Banner',
- // 'dropdown-menu' → 'DropdownMenu'). Theme keys use the rendered class
- // token, which hyphenates multi-word names, so strip non-letters from BOTH
- // sides before comparing.
- const dirs = fs
- .readdirSync(coreSrc, {withFileTypes: true})
- .filter(d => d.isDirectory())
- .map(d => d.name);
- const target = componentName.toLowerCase().replace(/[^a-z]/g, '');
- const dir = dirs.find(d => d.toLowerCase().replace(/[^a-z]/g, '') === target);
- if (!dir) return {};
-
- const docPath = path.join(coreSrc, dir, `${dir}.doc.mjs`);
- if (!fs.existsSync(docPath)) return {};
+async function loadKnownValuesIndex() {
+ const coreRoot = resolveCoreRoot();
+ const coreSrc = coreRoot ? path.join(coreRoot, 'src') : null;
+ if (!coreSrc || !fs.existsSync(coreSrc)) return {};
- try {
- const docModule = await import(pathToFileURL(docPath).href);
- const doc = docModule.docs;
- if (!doc?.theming?.targets) return {};
-
- // Collect all props — from doc.props or doc.components[].props
- const allProps = [];
- if (doc.props) allProps.push(...doc.props);
- if (doc.components) {
- for (const comp of doc.components) {
- if (comp.props) allProps.push(...comp.props);
+ /** @type {any[]} */
+ const docs = [];
+ /** @param {string} dir */
+ async function scan(dir) {
+ for (const entry of fs.readdirSync(dir, {withFileTypes: true})) {
+ const full = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ if (entry.name !== 'node_modules' && entry.name !== '__tests__') {
+ await scan(full);
+ }
+ continue;
}
- }
- if (allProps.length === 0) return {};
-
- // Collect visual prop names from theming targets
- /** @type {Set<string>} */
- const visualProps = new Set();
- for (const target of doc.theming.targets) {
- if (target.visualProps) {
- for (const vp of target.visualProps) visualProps.add(vp);
+ if (!entry.name.endsWith('.doc.mjs')) continue;
+ try {
+ docs.push(await loadComponentDoc(full));
+ } catch {
+ // One malformed or optional doc must not erase validation for the rest.
}
}
+ }
+ await scan(coreSrc);
- // Extract values from prop type strings
- /** @type {Record<string, string[]>} */
+ /** @param {string} value */
+ const targetName = value =>
+ value
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
+ .replace(/\s+/g, '-')
+ .toLowerCase();
+ /**
+ * @param {any[]} props
+ * @returns {Record<string, Set<string>>}
+ */
+ const valuesFromProps = props => {
+ /** @type {Record<string, Set<string>>} */
const result = {};
- for (const prop of allProps) {
- if (!visualProps.has(prop.name)) continue;
- if (!prop.type || typeof prop.type !== 'string') continue;
-
- // Parse union type: "'info' | 'warning' | 'error' | 'success'" → ['info', 'warning', 'error', 'success']
- const matches = prop.type.match(/'([^']+)'/g);
- if (matches) {
- result[prop.name] = matches.map((/** @type {string} */ m) =>
- m.replace(/'/g, ''),
- );
+ for (const prop of props ?? []) {
+ if (typeof prop?.name !== 'string' || typeof prop?.type !== 'string') {
+ continue;
}
+ /** @type {Set<string>} */
+ const values = new Set();
+ for (const match of prop.type.match(/'([^']+)'/g) ?? []) {
+ values.add(match.slice(1, -1));
+ }
+ for (const part of prop.type
+ .split('|')
+ .map((/** @type {string} */ value) => value.trim())) {
+ if (/^-?\d+(?:\.\d+)?$/.test(part)) values.add(part);
+ }
+ if (values.size > 0) result[prop.name] = values;
}
return result;
- } catch {
- return {};
+ };
+
+ /** @type {Record<string, Record<string, Set<string>>>} */
+ const valuesByOwner = {};
+ for (const doc of docs) {
+ if (typeof doc?.name === 'string') {
+ valuesByOwner[targetName(doc.name)] = valuesFromProps(doc.props);
+ }
+ for (const component of /** @type {any[]} */ (doc?.components ?? [])) {
+ if (typeof component?.name === 'string') {
+ valuesByOwner[targetName(component.name)] = valuesFromProps(
+ component.props,
+ );
+ }
+ }
}
+
+ /** @type {Record<string, Record<string, Set<string>>>} */
+ const collected = {};
+ for (const doc of docs) {
+ const localValues = valuesFromProps([
+ ...(doc?.props ?? []),
+ ...(doc?.components ?? []).flatMap(
+ (/** @type {any} */ component) => component?.props ?? [],
+ ),
+ ]);
+ for (const target of doc?.theming?.targets ?? []) {
+ if (typeof target?.className !== 'string') continue;
+ const componentName = target.className.replace(/^astryx-/, '');
+ const ownerValues = valuesByOwner[componentName] ?? {};
+ if (!collected[componentName]) collected[componentName] = {};
+ for (const prop of target.visualProps ?? []) {
+ if (!collected[componentName][prop]) {
+ collected[componentName][prop] = new Set();
+ }
+ for (const value of [
+ ...(localValues[prop] ?? []),
+ ...(ownerValues[prop] ?? []),
+ ]) {
+ collected[componentName][prop].add(value);
+ }
+ }
+ }
+ }
+
+ return Object.fromEntries(
+ Object.entries(collected).map(([component, props]) => [
+ component,
+ Object.fromEntries(
+ Object.entries(props).map(([prop, values]) => [prop, [...values]]),
+ ),
+ ]),
+ );
}
-// Cache for loaded known values
-/** @type {Map<string, Record<string, string[]>>} */
-const _knownValuesCache = new Map();
/**
* @param {string} componentName
* @returns {Promise<Record<string, string[]>>}
*/
async function getKnownValues(componentName) {
- if (!_knownValuesCache.has(componentName)) {
- _knownValuesCache.set(componentName, await loadKnownValues(componentName));
- }
- return _knownValuesCache.get(componentName) ?? {};
+ _knownValuesIndexPromise ??= loadKnownValuesIndex();
+ const index = await _knownValuesIndexPromise;
+ return index[componentName] ?? {};
}
/**
@@ -479,6 +568,426 @@ function componentHasAugmentableInterface(pascalName, interfaceName) {
return re.test(decl);
}
+/**
+ * Adaptation values from resolved runtime rules, raw input, or normalized built
+ * metadata. Built modules intentionally omit `__adaptationRules`, so every CLI
+ * diagnostic that reads rule intent must also understand `__adaptations`.
+ *
+ * @param {Record<string, any>} themeDef
+ * @returns {Record<string, any>[]}
+ */
+function adaptationRuleValues(themeDef) {
+ if (Array.isArray(themeDef.__adaptationRules)) {
+ return themeDef.__adaptationRules;
+ }
+ const rules = themeDef.adaptations?.rules ?? themeDef.__adaptations?.rules;
+ if (!Array.isArray(rules)) return [];
+ return rules.map((/** @type {any} */ rule) => rule?.value).filter(Boolean);
+}
+
+const ADAPTATION_METADATA_KEYS = new Set(['widthBreakpoints', 'rules']);
+const WIDTH_BREAKPOINT_NAMES = ['sm', 'md', 'lg', 'xl', '2xl'];
+
+/** @param {unknown} value @returns {value is Record<string, any>} */
+function isRecord(value) {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+/**
+ * A malformed adaptations block is intent too: an old core erases it before it
+ * can be validated, so treating only valid non-empty arrays/maps as intent
+ * would turn author errors into successful, incomplete builds.
+ *
+ * @param {unknown} adaptations
+ * @returns {boolean}
+ */
+function adaptationMetadataHasIntent(adaptations) {
+ if (adaptations === undefined) return false;
+ if (!isRecord(adaptations)) return true;
+ if (
+ Object.keys(adaptations).some(key => !ADAPTATION_METADATA_KEYS.has(key))
+ ) {
+ return true;
+ }
+
+ if (adaptations.rules !== undefined) {
+ if (!Array.isArray(adaptations.rules)) return true;
+ if (adaptations.rules.length > 0) return true;
+ }
+
+ if (adaptations.widthBreakpoints !== undefined) {
+ if (hasMalformedWidthBreakpoints(adaptations.widthBreakpoints)) return true;
+ if (hasCustomWidthBreakpoints(adaptations.widthBreakpoints)) return true;
+ }
+ return false;
+}
+
+/**
+ * Does this theme carry ordered-adaptation intent the installed core must be
+ * able to compile or validate?
+ *
+ * A theme reaches the build in three shapes and this has to see all of them:
+ * raw `adaptations`, resolved `__adaptationRules`, and a built module's
+ * `__adaptations`. Any rule, custom width map, or malformed present metadata is
+ * intent. Malformed data matters because an old core erases it before its
+ * current-core validation can run; accepting it would turn an author error into
+ * a successful incomplete build.
+ *
+ * The complete default width map with an empty rule list is the one no-op: core
+ * writes that shape onto every resolved theme and every shipped built theme.
+ *
+ * @param {any} themeDef
+ * @returns {boolean}
+ */
+function hasAdaptationIntent(themeDef) {
+ if (!themeDef || typeof themeDef !== 'object') return false;
+
+ if (themeDef.__adaptationRules !== undefined) {
+ if (!Array.isArray(themeDef.__adaptationRules)) return true;
+ if (themeDef.__adaptationRules.length > 0) return true;
+ }
+
+ return (
+ adaptationMetadataHasIntent(themeDef.adaptations) ||
+ adaptationMetadataHasIntent(themeDef.__adaptations)
+ );
+}
+
+/**
+ * The default viewport-width tier start points, in CSS px. A theme whose
+ * effective map is exactly this asked for nothing.
+ * SYNC: packages/core/src/theme/themeAdaptations.ts (DEFAULT_WIDTH_BREAKPOINTS)
+ */
+const DEFAULT_WIDTH_BREAKPOINTS = Object.freeze({
+ sm: 640,
+ md: 768,
+ lg: 1024,
+ xl: 1280,
+ '2xl': 1536,
+});
+
+/**
+ * @param {unknown} widthBreakpoints
+ * @returns {boolean}
+ */
+function hasMalformedWidthBreakpoints(widthBreakpoints) {
+ if (!isRecord(widthBreakpoints)) return true;
+ const names = Object.keys(widthBreakpoints);
+ if (names.some(name => !WIDTH_BREAKPOINT_NAMES.includes(name))) return true;
+ for (const name of names) {
+ const point = widthBreakpoints[name];
+ if (typeof point !== 'number' || !Number.isFinite(point) || point <= 0) {
+ return true;
+ }
+ }
+
+ const effective = /** @type {Record<string, number>} */ ({
+ ...DEFAULT_WIDTH_BREAKPOINTS,
+ ...widthBreakpoints,
+ });
+ for (let index = 1; index < WIDTH_BREAKPOINT_NAMES.length; index++) {
+ if (
+ effective[WIDTH_BREAKPOINT_NAMES[index]] <=
+ effective[WIDTH_BREAKPOINT_NAMES[index - 1]]
+ ) {
+ return true;
+ }
+ }
+ return false;
+}
+
+/**
+ * @param {unknown} widthBreakpoints
+ * @returns {boolean}
+ */
+function hasCustomWidthBreakpoints(widthBreakpoints) {
+ if (!widthBreakpoints || typeof widthBreakpoints !== 'object') return false;
+ const points = /** @type {Record<string, number>} */ (widthBreakpoints);
+ const defaults = /** @type {Record<string, number>} */ (
+ DEFAULT_WIDTH_BREAKPOINTS
+ );
+ const names = Object.keys(points);
+ if (names.length === 0) return false;
+ // Any point that differs from the default is custom. So is a PARTIAL map:
+ // core merges it over the defaults, which is a real, inheritable override
+ // even when every value it names happens to match. A COMPLETE map equal to
+ // the defaults asks for nothing — which is exactly what core writes onto
+ // every theme it resolves, and what every shipped built theme carries.
+ if (names.some(name => points[name] !== defaults[name])) return true;
+ return names.length !== Object.keys(defaults).length;
+}
+
+/**
+ * Fail when a theme needs ordered adaptations and the installed core cannot
+ * compile them.
+ *
+ * The CLI and core are optional peers on independent release trains, so a
+ * newer CLI routinely runs against an older published core. Adaptations are a
+ * capability of core's generator: without `generateAdaptationCSS` the build
+ * could still emit token and component CSS, and every adaptation rule would
+ * vanish from the output with no signal. That is the one outcome this must
+ * never produce — so it stops before anything is generated or written, names
+ * the missing capability, and says what to do about it.
+ *
+ * `lineage` is the selected theme's own ancestry — the raw inputs it and its
+ * bases were resolved from, captured as the file loaded (core-interception).
+ * An older core's `defineTheme()` drops `adaptations` while resolving, so the
+ * resolved object alone cannot answer; the raw input can. Scoping to lineage
+ * is what keeps an unrelated adaptive theme in the same module from failing a
+ * plain theme's build.
+ *
+ * `unobserved`, when non-empty, lists lineage members the recorder never saw
+ * because one or more loader paths could not be intercepted. `degradation`
+ * names those gaps: top-level await forced the async loader, or a CommonJS
+ * source dependency could reach a frozen/non-configurable core namespace.
+ * Those members cannot be proven clean, and unproven must not build.
+ *
+ * Silent for a theme with no adaptation intent and fully observed lineage:
+ * those build against an older core exactly as they always did.
+ *
+ * @param {any} themeDef - Raw or resolved theme; both shapes are understood.
+ * @param {{coreVersion?: string, lineage?: any[], unobserved?: any[], degradation?: {topLevelAwait?: boolean, commonJs?: boolean}}} [context]
+ * @returns {void}
+ */
+function assertAdaptationCapability(
+ themeDef,
+ {coreVersion, lineage, unobserved, degradation} = {},
+) {
+ if (_generateAdaptationCSS) return;
+ // A core that could not be imported at all is ERR_CORE_NOT_FOUND's story —
+ // "upgrade core" would be the wrong advice for "core is missing".
+ if (!_defineTheme || !_generateThemeRulesSplit) return;
+
+ const candidates = lineage?.length ? lineage : [themeDef];
+ const installed =
+ coreVersion && coreVersion !== 'unknown'
+ ? `@astryxdesign/core@${coreVersion}`
+ : 'the installed @astryxdesign/core';
+
+ if (candidates.some(hasAdaptationIntent)) {
+ throw new AstryxError(
+ `This theme declares ordered adaptations, but ${installed} does not ` +
+ 'export `generateAdaptationCSS` from @astryxdesign/core/theme, so ' +
+ 'its adaptation rules cannot be compiled. Building without them ' +
+ 'would silently drop every adaptation rule from the generated CSS. ' +
+ 'Upgrade @astryxdesign/core to a version that supports theme ' +
+ 'adaptations, or remove `adaptations` from this theme.',
+ undefined,
+ ERROR_CODES.ERR_CORE_INCOMPATIBLE,
+ );
+ }
+
+ if (!unobserved?.length) return;
+
+ // These lineage members carry neither a capture marker nor their own
+ // `__adaptations`: they were never observed, this core would have erased any
+ // adaptations they had, and nothing here can tell whether they had any.
+ // Unproven is not clean.
+ const named = unobserved
+ .map(value => (typeof value?.name === 'string' ? `"${value.name}"` : null))
+ .filter(Boolean);
+ const gaps = [
+ degradation?.topLevelAwait
+ ? 'top-level await forced the fallback loader for installed packages'
+ : null,
+ degradation?.commonJs
+ ? 'a CommonJS source dependency reached a frozen or non-configurable core namespace'
+ : null,
+ ].filter(Boolean);
+ throw new AstryxError(
+ `${installed} cannot compile ordered adaptations, and whether ${
+ named.length > 0 ? named.join(', ') : 'part of this theme'
+ } uses adaptations could not be observed${
+ gaps.length > 0 ? ` because ${gaps.join(' and ')}` : ''
+ }. This core erases adaptations while resolving, so building could emit ` +
+ 'CSS with adaptation rules silently missing. Upgrade ' +
+ '@astryxdesign/core to a version that supports theme adaptations, or ' +
+ 'use a built theme artifact that retains adaptation metadata.',
+ undefined,
+ ERROR_CODES.ERR_CORE_INCOMPATIBLE,
+ );
+}
+
+/**
+ * Every `[component, rules]` pair a theme may emit, including ordered
+ * adaptation rules. Validators, private-variable checks, and notices must see
+ * rule-only values even though variant augmentation is root-owned.
+ *
+ * @param {Record<string, any>} themeDef
+ * @returns {[string, Record<string, any>][]}
+ */
+function themedComponentEntries(themeDef) {
+ const maps = [
+ themeDef.components,
+ ...adaptationRuleValues(themeDef).map(
+ (/** @type {any} */ value) => value.components,
+ ),
+ ];
+
+ /** @type {[string, Record<string, any>][]} */
+ const entries = [];
+ for (const map of maps) {
+ if (map) entries.push(...Object.entries(map));
+ }
+ return entries;
+}
+
+/**
+ * Root component entries are the only surface allowed to introduce variants.
+ * @param {Record<string, any>} themeDef
+ * @returns {[string, Record<string, any>][]}
+ */
+function rootComponentEntries(themeDef) {
+ return themeDef.components ? Object.entries(themeDef.components) : [];
+}
+
+/**
+ * Component entries written only by adaptation rules.
+ * @param {Record<string, any>} themeDef
+ * @returns {[string, Record<string, any>][]}
+ */
+function adaptationComponentEntries(themeDef) {
+ const maps = adaptationRuleValues(themeDef).map(
+ (/** @type {any} */ value) => value.components,
+ );
+ return maps.flatMap((/** @type {any} */ map) =>
+ map ? Object.entries(map) : [],
+ );
+}
+
+/**
+ * How one `prop:value` pair on a component target is classified — the single
+ * vocabulary both the root and adaptation paths reason in.
+ *
+ * - `builtin` — the value is in the component doc's enumerated domain. Valid
+ * on its own; no theme has to declare anything for it.
+ * - `enrollment` — the value is not built in AND core exposes an augmentable
+ * `*Map` interface for the prop, so the value becomes valid only because a
+ * theme enrolls it (the build generates module augmentation for it).
+ * - `unresolved` — anything else: a closed literal-union axis with no
+ * augmentation point (Button `size`), or a domain the docs cannot enumerate.
+ * Root emits no augmentation and accepts it as pass-through.
+ *
+ * SYNC: packages/cli/api/theme/build/build.mjs (generateVariantDeclarationsAsync,
+ * validateAdaptationEnrollment)
+ *
+ * @typedef {'builtin' | 'enrollment' | 'unresolved'} ComponentValueClass
+ */
+
+/**
+ * Classify a component visual-prop value.
+ *
+ * This is the ONE place that decides what a value is, so the root and
+ * adaptation paths cannot drift: per AST-012/DEC-5 an adaptation uses the same
+ * target, axis, value-domain and extension validation as root `components`,
+ * and adds only the rule that enrollment-dependent values may not be enrolled
+ * conditionally. An unresolved result carries into adaptations unchanged, and
+ * tightening root validation tightens adaptations automatically.
+ *
+ * @param {string} component - Rendered target token (without `astryx-`).
+ * @param {string} prop
+ * @param {string} value
+ * @returns {Promise<ComponentValueClass>}
+ */
+async function classifyComponentValue(component, prop, value) {
+ const known = await getKnownValues(component);
+ const knownForProp = known[prop];
+ if (knownForProp && knownForProp.includes(value)) {
+ return 'builtin';
+ }
+
+ const propPascal = prop.charAt(0).toUpperCase() + prop.slice(1);
+ const target = (await resolveAugmentationTargetCandidates(component)).find(
+ candidate =>
+ componentHasAugmentableInterface(
+ candidate.moduleName,
+ `${candidate.interfacePrefix}${propPascal}Map`,
+ ),
+ );
+ return target ? 'enrollment' : 'unresolved';
+}
+
+/**
+ * Every `prop:value` pair a component override key names. A key is `base`, a
+ * bare state name, or `+`-joined `prop:value` pairs.
+ *
+ * @param {string} key
+ * @returns {{prop: string, value: string, pair: string}[]}
+ */
+function componentValuePairs(key) {
+ if (key === 'base') return [];
+ /** @type {{prop: string, value: string, pair: string}[]} */
+ const pairs = [];
+ for (const pair of key.split('+')) {
+ const colon = pair.indexOf(':');
+ if (colon === -1) continue;
+ pairs.push({
+ prop: pair.slice(0, colon),
+ value: pair.slice(colon + 1),
+ pair,
+ });
+ }
+ return pairs;
+}
+
+/**
+ * Reject values whose validity depends on THEME ENROLLMENT when only an
+ * adaptation rule enrolls them.
+ *
+ * Per AST-012/DEC-5 this is the single thing adaptations add to root
+ * validation. Everything else — which targets and axes exist, which values a
+ * domain admits — is the root path's judgement, reached through the shared
+ * classifier, so there is no adaptation-specific resolver, allowlist or
+ * unresolved-domain exception here:
+ *
+ * - `builtin` values are independently valid and need no root declaration;
+ * - `unresolved` values carry root's shared result unchanged (accepting one
+ * does not make the axis extensible — the conditional-API invariant still
+ * governs it, and tightening root tightens this automatically);
+ * - `enrollment` values are the exception: generated module augmentation is
+ * unconditional, so a value that exists only under a media condition would
+ * widen a component's public type from a conditional surface. Those must
+ * appear on the effective root `components` surface first.
+ *
+ * @param {Record<string, any>} themeDef
+ * @returns {Promise<string[]>}
+ */
+async function validateAdaptationEnrollment(themeDef) {
+ const adaptationEntries = adaptationComponentEntries(themeDef);
+ if (adaptationEntries.length === 0) {
+ return [];
+ }
+
+ /** @type {Set<string>} */
+ const rootValues = new Set();
+ for (const [component, rules] of rootComponentEntries(themeDef)) {
+ for (const key of Object.keys(rules)) {
+ for (const {pair} of componentValuePairs(key)) {
+ rootValues.add(`${component}:${pair}`);
+ }
+ }
+ }
+
+ /** @type {string[]} */
+ const errors = [];
+ for (const [component, rules] of adaptationEntries) {
+ for (const key of Object.keys(rules)) {
+ for (const {prop, value, pair} of componentValuePairs(key)) {
+ if (rootValues.has(`${component}:${pair}`)) continue;
+ const valueClass = await classifyComponentValue(component, prop, value);
+ if (valueClass !== 'enrollment') continue;
+ errors.push(
+ `Adaptation rule enrolls the custom value "${component}.${prop}:${value}". ` +
+ 'A value that is valid only because a theme enrolls it generates ' +
+ 'unconditional type augmentation, so it must be declared on the root ' +
+ 'theme first; a rule may then restyle it under a condition.',
+ );
+ }
+ }
+ }
+ return [...new Set(errors)];
+}
+
/**
* Generate TypeScript declaration content with module augmentation for custom
* component prop values found in the theme's `components` keys. Reads known
@@ -503,27 +1012,24 @@ async function generateVariantDeclarationsAsync(themeDef) {
return null;
}
- // Collect custom values: { component: { prop: [value, ...] } }
+ // Collect enrollment-dependent values: { component: { prop: [value, ...] } }
+ // Classification is shared with the adaptation check, so "what is a custom
+ // value" has exactly one definition (AST-012/DEC-5).
/** @type {Record<string, Record<string, Set<string>>>} */
const customValues = {};
for (const {components} of componentLayers) {
for (const [component, rules] of Object.entries(components)) {
- const knownForComponent = await getKnownValues(component);
-
for (const key of Object.keys(rules)) {
- if (key === 'base') continue;
-
- const pairs = key.split('+');
- for (const pair of pairs) {
- const colonIdx = pair.indexOf(':');
- if (colonIdx === -1) continue;
- const prop = pair.slice(0, colonIdx);
- const value = pair.slice(colonIdx + 1);
-
- // Skip known built-in values
- const knownForProp = knownForComponent[prop];
- if (knownForProp && knownForProp.includes(value)) continue;
+ for (const {prop, value} of componentValuePairs(key)) {
+ // Built-ins need no augmentation; unresolved axes have no
+ // augmentation point to widen, and are passed through untouched.
+ const valueClass = await classifyComponentValue(
+ component,
+ prop,
+ value,
+ );
+ if (valueClass !== 'enrollment') continue;
if (!customValues[component]) customValues[component] = {};
if (!customValues[component][prop])
@@ -556,11 +1062,12 @@ async function generateVariantDeclarationsAsync(themeDef) {
),
);
- // Only augment interfaces that actually exist as an extension point in
- // core. Props backed by closed literal-union types (e.g. Button `size`,
- // Heading `type`/`level`) have no `*Map` interface — a `declare module`
- // block against a non-existent interface just creates a new, unused
- // interface and never extends the component's prop union, so skip it.
+ // Resolve the augmentation point again to name it. Classification has
+ // already established that one exists (that is what `enrollment` means),
+ // so this is a lookup, not a filter — but a target that somehow fails to
+ // resolve here must not emit a `declare module` block against a
+ // non-existent interface, which would create a dead sibling interface
+ // rather than widening the component's prop union.
if (!target) continue;
const modulePath = `@astryxdesign/core/${target.moduleName}`;
@@ -630,26 +1137,95 @@ const THEME_MODULE_EXTENSIONS = [
'.json',
];
+/**
+ * Errors that mean "the synchronous loader cannot evaluate this module", as
+ * opposed to "this module is broken". Only the former may fall back to the
+ * async path: a genuine author error (a throw, a missing import, a real syntax
+ * error) must surface as itself, and must never be quietly downgraded into a
+ * load whose interception no longer reaches installed packages.
+ *
+ * Top-level await is the case that exists in practice — the sync path compiles
+ * the module as a CommonJS function body, where `await` is a SyntaxError with
+ * this exact V8 wording.
+ *
+ * @param {unknown} error
+ * @returns {boolean}
+ */
+function isSyncLoaderLimitation(error) {
+ if (!(error instanceof SyntaxError)) return false;
+ return /await is only valid in async function/i.test(error.message);
+}
+
/**
* Import a theme module using jiti and find the defineTheme() result.
- * Returns the resolved DefinedTheme object.
+ * Returns the resolved DefinedTheme object, plus whether interception was
+ * degraded on the way.
+ *
+ * When `interception` is given, the theme file — and everything it imports, at
+ * any depth — is handed that wrapped core instead of resolving its own, so
+ * each theme defined anywhere in the graph is associated with the raw input it
+ * came from. That is the only way to see an `adaptations` block an older core
+ * erases while resolving. It costs no extra execution: the theme is loaded
+ * exactly once, on whichever path succeeds.
+ *
+ * Interception forces jiti's SYNCHRONOUS path. jiti only hands a module's
+ * imports back to itself when it transpiles that module, and it skips
+ * transpiling an ESM file under `import()` — so an installed package whose
+ * SOURCE calls `defineTheme` would resolve its own real core and erase the
+ * author's adaptations unobserved. The sync path transpiles it, so the wrapped
+ * core reaches inside installed packages too.
+ *
+ * A module the sync path cannot evaluate at all (top-level await) still has to
+ * load, so it falls back to the async import — but that fallback is DEGRADED:
+ * package sources on that path resolve their own core again. The caller is
+ * told, and treats anything it could not observe as unproven rather than
+ * assuming it is clean.
+ *
* @param {string} filePath
- * @returns {Promise<any>}
+ * @param {import('./core-interception.mjs').CoreInterception} [interception]
+ * @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
*/
-async function importThemeModule(filePath) {
+async function importThemeModule(filePath, interception) {
const jiti = createJiti(import.meta.url, {
moduleCache: false,
jsx: true,
extensions: THEME_MODULE_EXTENSIONS,
+ ...(interception ? {virtualModules: interception.modules} : {}),
});
- const mod = await jiti.import(filePath, {default: true});
+ /** @type {any} */
+ let mod;
+ const degraded = {topLevelAwait: false, commonJs: false};
+ if (interception) {
+ // The CommonJS patch covers `.cjs` package source, which jiti always
+ // loads natively; the sync path covers everything else inside packages.
+ // A frozen require(esm) namespace cannot be patched, so retain that gap and
+ // let the selected lineage decide whether it matters.
+ const commonJsPatch = interception.patchCommonJs(filePath);
+ degraded.commonJs = !commonJsPatch.covered;
+ try {
+ try {
+ mod = jiti(filePath);
+ } catch (error) {
+ // Only a sync-loader limitation may fall back. Anything else is the
+ // theme's own failure and belongs to the caller unchanged.
+ if (!isSyncLoaderLimitation(error)) throw error;
+ degraded.topLevelAwait = true;
+ mod = await jiti.import(filePath, {default: true});
+ }
+ } finally {
+ commonJsPatch.undo();
+ }
+ } else {
+ mod = await jiti.import(filePath, {default: true});
+ }
- if (isThemeObject(mod)) return mod;
+ if (isThemeObject(mod)) return {theme: mod, degraded};
if (mod && typeof mod === 'object') {
+ if (isThemeObject(mod.default)) return {theme: mod.default, degraded};
for (const value of Object.values(mod)) {
- if (isThemeObject(value)) return value;
+ if (isThemeObject(value)) return {theme: value, degraded};
}
}
@@ -676,15 +1252,24 @@ function isThemeObject(value) {
/**
* Extract the theme definition from a JS/TS file.
* Tries jiti first (full TS support), falls back to regex+eval.
+ *
+ * The legacy fallback needs no interception: it evaluates the `defineTheme()`
+ * ARGUMENT, so what it returns is raw authored input with `adaptations` still
+ * on it — nothing has erased anything yet. It is therefore never degraded.
+ *
* @param {string} filePath
- * @returns {Promise<any>}
+ * @param {import('./core-interception.mjs').CoreInterception} [interception]
+ * @returns {Promise<{theme: any, degraded: {topLevelAwait: boolean, commonJs: boolean}}>}
*/
-async function extractThemeDefinition(filePath) {
+async function extractThemeDefinition(filePath, interception) {
try {
- return await importThemeModule(filePath);
+ return await importThemeModule(filePath, interception);
} catch (jitiError) {
try {
- return extractThemeDefinitionLegacy(filePath);
+ return {
+ theme: extractThemeDefinitionLegacy(filePath),
+ degraded: {topLevelAwait: false, commonJs: false},
+ };
} catch {
const je = /** @type {Error} */ (jitiError);
throw new Error(
@@ -826,10 +1411,12 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
* there is nothing to emit.
* @param {string} field
* @param {unknown} value
+ * @param {boolean} [includeEmpty]
* @returns {string}
*/
- const serializeField = (field, value) => {
- if (!value || Object.keys(value).length === 0) return '';
+ const serializeField = (field, value, includeEmpty = false) => {
+ if (value == null || (!includeEmpty && Object.keys(value).length === 0))
+ return '';
const body = JSON.stringify(value, null, 2)
.split('\n')
.map((line, i) => (i === 0 ? line : ' ' + line))
@@ -837,6 +1424,9 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
return ` ${field}: ${body},\n`;
};
+ // Everything a theme that `extends` this built one has to be able to read
+ // back. A field missing here is silently lost by the extending theme.
+ // SYNC: packages/core/src/theme/defineTheme.ts (DefinedTheme)
const inheritableFields =
(themeDef.__localTokenLineage !== undefined
? ` localTokens: ${JSON.stringify(themeDef.localTokens ?? {}, null, 2)
@@ -855,7 +1445,9 @@ function generateBuiltModule(themeDef, iconInfo, iconsSpecifier) {
: '') +
serializeField('components', themeDef.components) +
serializeField('__onDark', themeDef.__onDark) +
- serializeField('__onLight', themeDef.__onLight);
+ serializeField('__onLight', themeDef.__onLight) +
+ serializeField('__adaptations', themeDef.__adaptations) +
+ serializeField('__axes', themeDef.__axes ?? {}, true);
return `${iconImport}/**
* ${themeDef.name} theme — built by \`${getCliInvocation()} theme build\`
@@ -949,12 +1541,13 @@ async function getKnownComponents() {
async function validateComponentOverrides(themeDef) {
/** @type {string[]} */
const warnings = [];
- if (!themeDef.components) return warnings;
+ const componentEntries = themedComponentEntries(themeDef);
+ if (componentEntries.length === 0) return warnings;
const knownComponents = await getKnownComponents();
if (knownComponents == null) return warnings;
- for (const [component, rules] of Object.entries(themeDef.components)) {
+ for (const [component, rules] of componentEntries) {
// Check component name
if (!(component in knownComponents)) {
const similar = Object.keys(knownComponents)
@@ -1005,7 +1598,7 @@ async function validateComponentOverrides(themeDef) {
}
}
- return warnings;
+ return [...new Set(warnings)];
}
/**
@@ -1021,23 +1614,33 @@ async function validateComponentOverrides(themeDef) {
function validatePrivateVars(themeDef) {
/** @type {string[]} */
const errors = [];
- if (!themeDef.components) return errors;
- for (const [component, rules] of Object.entries(themeDef.components)) {
+ for (const [component, rules] of themedComponentEntries(themeDef)) {
for (const [key, styles] of Object.entries(rules)) {
- for (const prop of Object.keys(styles)) {
- if (typeof prop === 'string' && prop.startsWith('--_')) {
- errors.push(
- `Component "${component}" (${key}) sets private var "${prop}". ` +
- `Private vars (--_*) are internal — use standard CSS properties ` +
- `(e.g. borderRadius, padding) instead. The pipeline expands them automatically.`,
- );
+ /**
+ * @param {unknown} value
+ * @param {string[]} [path]
+ */
+ const visit = (value, path = []) => {
+ if (!value || typeof value !== 'object' || Array.isArray(value)) return;
+ for (const [prop, nested] of Object.entries(value)) {
+ if (prop.startsWith('--_')) {
+ errors.push(
+ `Component "${component}" (${[key, ...path].join(' ')}) sets private var "${prop}". ` +
+ `Private vars (--_*) are internal — use standard CSS properties ` +
+ `(e.g. borderRadius, padding) instead. The pipeline expands them automatically.`,
+ );
+ }
+ visit(nested, [...path, prop]);
}
- }
+ };
+ visit(styles);
}
}
- return errors;
+ // One entry per distinct message: a component declared both at the root and
+ // in one or more adaptations would otherwise report the same problem twice.
+ return [...new Set(errors)];
}
const BUILTIN_HEADING_TYPES = new Set(['display-1', 'display-2', 'display-3']);
@@ -1223,15 +1826,45 @@ export async function themeBuild(
logger.log(`\nBuilding theme from ${path.relative(cwd, filePath)}...`);
+ // When the installed core cannot compile adaptations, watch its
+ // `defineTheme` as the theme loads: that core erases `adaptations` while
+ // resolving, so the raw input captured here is the only remaining witness
+ // to what the author wrote. Costs no extra execution — the theme is loaded
+ // once either way — and a core that CAN compile them needs none of it.
+ const interception = _generateAdaptationCSS
+ ? undefined
+ : interceptCore(_coreThemeModule, _coreRootModule);
+
// Extract theme definition
let themeDef;
+ /** Paths through the load that interception could not fully observe. */
+ let loadDegradation;
try {
- themeDef = await extractThemeDefinition(filePath);
+ const loaded = await extractThemeDefinition(filePath, interception);
+ themeDef = loaded.theme;
+ loadDegradation = loaded.degraded;
} catch (e) {
const err = /** @type {Error} */ (e);
throw new AstryxError(err.message, undefined, ERROR_CODES.ERR_THEME_LOAD);
}
+ // The marker is scoped to that isolated load: drop it before the theme
+ // reaches anything that reads or writes it. (Symbol keys are invisible to
+ // JSON.stringify and Object.keys, so it could not reach output regardless.)
+ // Both reads happen BEFORE the strip, which is what removes the evidence.
+ const adaptationLineage = interception
+ ? interception.lineageOf(themeDef)
+ : undefined;
+ const capturedGenerativeAxes = interception
+ ? interception.capturedAxesOf(themeDef)
+ : undefined;
+ const hasCoverageGap = Boolean(
+ loadDegradation?.topLevelAwait || loadDegradation?.commonJs,
+ );
+ const unobservedLineage =
+ interception && hasCoverageGap ? interception.unobservedIn(themeDef) : [];
+ if (interception) interception.strip(themeDef);
+
if (!themeDef.name) {
throw new AstryxError(
'Theme must have a name property.',
@@ -1293,6 +1926,8 @@ export async function themeBuild(
// `astryx theme build` and the `<Theme>` runtime MUST emit identical CSS, so
// there is exactly one generation path: @astryxdesign/core/theme. If core could not
// be imported, fail hard rather than silently producing divergent output.
+ // Only the baseline exports every theme build needs are required here;
+ // capability exports are checked against what the theme actually asks for.
if (!_defineTheme || !_generateThemeRulesSplit) {
throw new AstryxError(
'Could not load @astryxdesign/core/theme — `astryx theme build` requires a ' +
@@ -1307,6 +1942,19 @@ export async function themeBuild(
);
}
+ // An adaptation theme against a core that cannot compile adaptations stops
+ // here — before any CSS is generated and long before anything is written.
+ // Checked against the SELECTED theme's own lineage: the raw inputs it and
+ // its bases were resolved from, so an unrelated adaptive theme elsewhere in
+ // the import graph cannot fail this build.
+ const coreVersionForCapability = readPkgVersion(findCoreDir(cwd));
+ assertAdaptationCapability(themeDef, {
+ coreVersion: coreVersionForCapability,
+ lineage: adaptationLineage,
+ unobserved: unobservedLineage,
+ degradation: loadDegradation,
+ });
+
let css;
let resolvedTheme;
{
@@ -1316,6 +1964,11 @@ export async function themeBuild(
// theme has none of them — and hand the WHOLE object over: picking fields
// by name is how `extends` (and `color`, and `syntax`) used to be dropped
// on the way in.
+ // Fields that only ever appear on RAW defineTheme() input, never on an
+ // already-resolved theme. Their presence is how the build tells the two
+ // apart and decides to run defineTheme() itself. A field missing from this
+ // list is dropped without a word, so every new input field belongs here.
+ // SYNC: packages/core/src/theme/defineTheme.ts (DefineThemeInput)
const INPUT_ONLY_FIELDS = [
'extends',
'typography',
@@ -1325,15 +1978,62 @@ export async function themeBuild(
'syntax',
'onDark',
'onLight',
+ 'adaptations',
];
const needsResolution =
INPUT_ONLY_FIELDS.some(field => themeDef[field] !== undefined) ||
('localTokens' in themeDef && themeDef.__localTokenLineage === undefined);
if (needsResolution) {
- resolvedTheme = _defineTheme({...themeDef});
+ try {
+ resolvedTheme = _defineTheme({...themeDef});
+ } catch (error) {
+ const message =
+ error instanceof Error
+ ? error.message
+ : 'Theme normalization failed.';
+ throw new AstryxError(
+ message,
+ undefined,
+ ERROR_CODES.ERR_THEME_INVALID,
+ );
+ }
} else {
resolvedTheme = themeDef;
}
+
+ // Cores that predate adaptations can still resolve typography, color,
+ // radius, and motion into root tokens, but they do not retain the raw axis
+ // inputs. Keep the effective metadata captured from the same defineTheme
+ // lineage so a later current-core child can complete a partial adaptation
+ // axis exactly as it would when extending the source theme.
+ if (
+ resolvedTheme.__axes === undefined &&
+ capturedGenerativeAxes &&
+ Object.keys(capturedGenerativeAxes).length > 0
+ ) {
+ resolvedTheme = {...resolvedTheme, __axes: capturedGenerativeAxes};
+ }
+
+ // Re-check after resolution: `extends` can pull adaptation rules in from a
+ // base the entry file never mentions, and a resolver that understands them
+ // surfaces them here.
+ assertAdaptationCapability(resolvedTheme, {
+ coreVersion: coreVersionForCapability,
+ lineage: adaptationLineage,
+ unobserved: unobservedLineage,
+ degradation: loadDegradation,
+ });
+
+ const adaptationEnrollmentErrors =
+ await validateAdaptationEnrollment(resolvedTheme);
+ if (adaptationEnrollmentErrors.length > 0) {
+ throw new AstryxError(
+ adaptationEnrollmentErrors.join('\n'),
+ undefined,
+ ERROR_CODES.ERR_THEME_INVALID,
+ );
+ }
+
const scopeSelector = themeScopeStart(themeDef.name);
const scopeTo = THEME_SCOPE_TO;
@@ -1349,26 +2049,57 @@ export async function themeBuild(
`@layer reset {\n@scope (${scopeSelector}) to (${scopeTo}) {\n${proseInner}\n}\n}`,
);
}
- if (component.length > 0) {
- const componentInner = component.join('\n\n');
- const componentScope = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
- // #3658: also emit attribute-specific rules so <Theme mode> can override color-scheme.
- // Decided from the theme's own values, not the generated CSS: that CSS
- // also carries the data-token defaults, which are light-dark() pairs, so
- // a substring check on it would fire for every theme.
- const themeOwnValues = JSON.stringify([
- resolvedTheme.tokens ?? {},
- resolvedTheme.localTokens ?? {},
- resolvedTheme.components ?? {},
- ]);
- const colorSchemeDecl = themeOwnValues.includes('light-dark(')
+ // Ordered adaptation rules use the same generator as the runtime path.
+ // An older core has no such generator; a theme that needs one never
+ // reaches this line (assertAdaptationCapability above), so the empty
+ // result here belongs to a theme with no adaptation rules to emit.
+ let adaptationCss;
+ try {
+ adaptationCss = _generateAdaptationCSS
+ ? _generateAdaptationCSS(resolvedTheme)
+ : {component: '', prose: ''};
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : 'Theme normalization failed.';
+ throw new AstryxError(message, undefined, ERROR_CODES.ERR_THEME_INVALID);
+ }
+ const componentInner = component.join('\n\n');
+ const componentScope =
+ component.length > 0
+ ? `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`
+ : '';
+
+ // #3658: also emit attribute-specific rules so <Theme mode> can override
+ // color-scheme. Inspect root and rule-owned values, not generated CSS, which
+ // also carries theme-independent data-token defaults with light-dark().
+ const themeOwnValues = JSON.stringify([
+ resolvedTheme.tokens ?? {},
+ resolvedTheme.localTokens ?? {},
+ resolvedTheme.components ?? {},
+ ...(resolvedTheme.__adaptationRules ?? []).flatMap(
+ (
+ /** @type {{tokens?: Record<string, string>, localTokens?: Record<string, string>, components?: object}} */ rule,
+ ) => [rule.tokens ?? {}, rule.localTokens ?? {}, rule.components ?? {}],
+ ),
+ ]);
+ const colorSchemeDecl =
+ themeOwnValues.includes('light-dark(') ||
+ adaptationCss.component.includes('light-dark(')
? ' :root { color-scheme: light dark; }\n html[data-theme="light"] { color-scheme: light; }\n html[data-theme="dark"] { color-scheme: dark; }\n\n'
: '';
+ if (colorSchemeDecl || componentScope) {
cssParts.push(
`@layer astryx-theme {\n${colorSchemeDecl}${componentScope}\n}`,
);
}
- // On-media rules (MediaTheme dark/light surface overrides)
+ if (adaptationCss.prose) {
+ cssParts.push(`@layer reset {\n${adaptationCss.prose}\n}`);
+ }
+ if (adaptationCss.component) {
+ cssParts.push(`@layer astryx-theme {\n${adaptationCss.component}\n}`);
+ }
+ // Media-surface rules come last so onDark/onLight win over matching
+ // adaptations on the same resolved leaf.
if (_generateOnMediaCSS) {
const onMediaCss = _generateOnMediaCSS(resolvedTheme);
if (onMediaCss) {
@@ -1605,7 +2336,16 @@ Or with a <link> tag:
// theme with a webfont, including a perfect one, and as a warning it made
// every such build read as defective (it also put the shipped template
// permanently in violation of its own "compiles with no warnings" guard).
- const unloadedFonts = collectUnloadedFonts(resolvedTheme);
+ // Adaptation rules are resolved theme writes in their own right, so a family
+ // named only inside one needs the same notice as one named at the root.
+ const unloadedFonts = [
+ ...new Set([
+ ...collectUnloadedFonts(resolvedTheme),
+ ...adaptationRuleValues(resolvedTheme).flatMap(
+ (/** @type {any} */ value) => collectUnloadedFonts(value),
+ ),
+ ]),
+ ];
for (const family of unloadedFonts) {
const msg = `Font "${family}" is named by this theme but not loaded — add a <link> or @font-face in your app (recipe: astryx docs typography)`;
noticeMessages.push(msg);
diff --git a/packages/cli/api/theme/build/build.packed-old-core.test.mjs b/packages/cli/api/theme/build/build.packed-old-core.test.mjs
new file mode 100644
index 0000000000..e3513b768a
--- /dev/null
+++ b/packages/cli/api/theme/build/build.packed-old-core.test.mjs
@@ -0,0 +1,1478 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file `theme build` from a PACKED CLI resolving a genuinely older core.
+ *
+ * The unit-level sibling (build.adaptation-core-compat.test.mjs) drives
+ * `themeBuild()` directly. This one reproduces the pairing a consumer actually
+ * has: the CLI's published file set installed under
+ * `node_modules/@astryxdesign/cli`, next to a `node_modules/@astryxdesign/core`
+ * that behaves like the published 0.5.4. Nothing is mocked; the CLI binary runs
+ * in its own process and resolves core the way Node does, which is the layer
+ * the regression lived in (`astryx theme build` failed with ERR_CORE_NOT_FOUND
+ * for every theme, adaptations or not).
+ *
+ * The old core is adaptation-BLIND, not "the current core minus one export".
+ * Its `defineTheme` does what 0.5.4's did: it never reads `adaptations`, and
+ * the theme it returns carries no adaptation metadata at all. That is what
+ * makes the source analysis load-bearing — the resolved object is silent about
+ * adaptations the author wrote, so a build that trusted it would emit CSS with
+ * every rule missing. Its `./theme` entry exports exactly 0.5.4's surface,
+ * which really does include `generateOnMediaCSS` and `dataTokenDefaults`; the
+ * only capability it lacks is `generateAdaptationCSS`.
+ *
+ * On outputs: the CSS is compared with old and current cores, and must match.
+ * The generated JS module is NOT: a current core resolves normalized
+ * `__adaptations` metadata onto every theme and the module serializes it, so a
+ * plain theme's `.js` legitimately differs between the two. That drift is
+ * asserted rather than wished away — it is also why `theme build --check`
+ * against outputs committed with a current core reports drift on an older one.
+ */
+
+import {afterAll, beforeAll, describe, expect, it} from 'vitest';
+import {execFileSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const REPO_ROOT = path.resolve(HERE, '../../../../..');
+const CLI_PKG = path.join(REPO_ROOT, 'packages/cli');
+const CORE_DIST = path.join(REPO_ROOT, 'packages/core/dist');
+const CORE_THEME_ENTRY = path.join(CORE_DIST, 'theme/index.js');
+
+/** The CLI's published file set (packages/cli package.json `files`). */
+const PACKED_DIRS = ['clients', 'api', 'assets', 'authoring', 'foundation'];
+/** Runtime dependencies the packed CLI resolves from its install root. */
+const RUNTIME_DEPS = ['commander', 'jiti', 'jscodeshift', 'zod'];
+
+const OLD_CORE_VERSION = '0.5.4';
+const CURRENT_CORE_VERSION = '0.6.0';
+const TSC_BIN = path.join(REPO_ROOT, 'node_modules/typescript/bin/tsc');
+
+/**
+ * A core that predates ordered adaptations.
+ *
+ * `defineTheme` is adaptation-blind on both sides: `adaptations` never reaches
+ * the resolver, and no adaptation metadata comes back out — including through
+ * `extends`, which is how 0.5.4 behaved for a base theme it did not understand.
+ * It also predates retained `__axes` metadata: generative axes still produce
+ * root tokens, but the resolved theme does not expose the inputs for a later
+ * current-core child to complete a partial adaptation axis from. Everything
+ * else is the real generator, so a CSS difference between this core and a
+ * current one can only come from the CLI's own branching.
+ *
+ * The export list is 0.5.4's `./theme` surface. `generateOnMediaCSS` and
+ * `dataTokenDefaults` are on it deliberately: they exist in 0.5.4, and
+ * pretending otherwise would test a core that never shipped.
+ */
+const OLD_CORE_THEME_MODULE = `import {defineTheme as resolveTheme} from ${JSON.stringify(
+ CORE_THEME_ENTRY,
+)};
+
+export {
+ generateThemeCSS,
+ generateThemeRules,
+ generateThemeRulesSplit,
+ generateOnMediaCSS,
+ isDefinedTheme,
+ tokenDefaults,
+ dataTokenDefaults,
+} from ${JSON.stringify(CORE_THEME_ENTRY)};
+
+/** Strip every adaptation field and retained axis metadata; this core has no concept of them. */
+function blind(value) {
+ if (!value || typeof value !== 'object') return value;
+ const {adaptations, __adaptations, __adaptationRules, __axes, ...rest} = value;
+ if (rest.extends) rest.extends = blind(rest.extends);
+ return rest;
+}
+
+export function defineTheme(input) {
+ return blind(resolveTheme(blind(input)));
+}
+`;
+
+/** A current core: the whole surface, adaptations included. */
+const CURRENT_CORE_THEME_MODULE = `export * from ${JSON.stringify(
+ CORE_THEME_ENTRY,
+)};\n`;
+
+let root;
+let consumer;
+let corePkg;
+
+/**
+ * Mirror a directory as a tree of symlinks to its entries, so the fixture can
+ * replace ONE file of a large built package without copying the rest.
+ * @param {string} from
+ * @param {string} to
+ * @param {string[]} [except] - entry names to skip
+ */
+function linkEntries(from, to, except = []) {
+ fs.mkdirSync(to, {recursive: true});
+ for (const entry of fs.readdirSync(from)) {
+ if (except.includes(entry)) continue;
+ fs.symlinkSync(path.join(from, entry), path.join(to, entry));
+ }
+}
+
+/**
+ * Install one of the two cores under the fixture's `node_modules`. The version
+ * moves with the surface so generated provenance headers differ exactly as
+ * they would between two real releases.
+ * @param {'old' | 'current'} surface
+ */
+function useCore(surface) {
+ const old = surface === 'old';
+ fs.writeFileSync(
+ path.join(corePkg, 'package.json'),
+ `${JSON.stringify(
+ {
+ name: '@astryxdesign/core',
+ version: old ? OLD_CORE_VERSION : CURRENT_CORE_VERSION,
+ type: 'module',
+ exports: {
+ '.': './dist/index.js',
+ './theme': './dist/theme/index.js',
+ './*': './dist/*/index.js',
+ },
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ fs.writeFileSync(
+ path.join(corePkg, 'dist/theme/index.js'),
+ old ? OLD_CORE_THEME_MODULE : CURRENT_CORE_THEME_MODULE,
+ );
+}
+
+/**
+ * Install a theme package under the fixture's `node_modules`, shaped like a
+ * published Astryx theme: a `./built` subpath exporting the module
+ * `generateBuiltModule` writes.
+ * @param {string} name - Package name.
+ * @param {string} exportName - The theme's export name.
+ * @param {string} adaptationsLiteral - The `__adaptations` object source.
+ * @param {{esmOnly?: boolean}} [options] - `esmOnly` publishes an `exports`
+ * map with only an `import` condition, which `require` resolution rejects.
+ */
+function installThemePackage(
+ name,
+ exportName,
+ adaptationsLiteral,
+ options = {},
+) {
+ const pkgRoot = path.join(root, 'node_modules', name);
+ fs.mkdirSync(path.join(pkgRoot, 'dist'), {recursive: true});
+ const builtFile = options.esmOnly ? 'built.mjs' : 'built.js';
+ fs.writeFileSync(
+ path.join(pkgRoot, 'package.json'),
+ `${JSON.stringify(
+ {
+ name,
+ version: '0.5.4',
+ type: 'module',
+ ...(options.esmOnly
+ ? {exports: {'./built': {import: `./dist/${builtFile}`}}}
+ : {
+ main: './dist/source.js',
+ exports: {
+ '.': './dist/source.js',
+ './built': './dist/built.js',
+ },
+ }),
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkgRoot, 'dist', builtFile),
+ `export const ${exportName} = {
+ name: '${exportName}',
+ __built: true,
+ tokens: {'--color-surface': '#eee'},
+ __adaptations: ${adaptationsLiteral},
+};
+`,
+ );
+ if (!options.esmOnly) {
+ fs.writeFileSync(
+ path.join(pkgRoot, 'dist/source.js'),
+ `export {${exportName}} from './built.js';\n`,
+ );
+ }
+}
+
+/**
+ * Install a package whose SOURCE calls `defineTheme` at load time, rather than
+ * shipping a built object literal. Its core import must resolve to the wrapped
+ * one for its author's adaptations to be observable at all.
+ * @param {string} name
+ * @param {string} exportName
+ * @param {string} adaptationsSource - Source for the `adaptations:` entry, or ''.
+ * @param {{cjs?: boolean, tla?: boolean}} [options]
+ */
+function installSourcePackage(
+ name,
+ exportName,
+ adaptationsSource,
+ options = {},
+) {
+ const pkgRoot = path.join(root, 'node_modules', name);
+ fs.mkdirSync(path.join(pkgRoot, 'src'), {recursive: true});
+ const entry = options.cjs ? 'src/index.cjs' : 'src/index.mjs';
+ fs.writeFileSync(
+ path.join(pkgRoot, 'package.json'),
+ `${JSON.stringify(
+ {
+ name,
+ version: '0.5.4',
+ ...(options.cjs ? {} : {type: 'module'}),
+ main: `./${entry}`,
+ exports: {'.': `./${entry}`},
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+ fs.writeFileSync(
+ path.join(pkgRoot, entry),
+ options.cjs
+ ? `const {defineTheme} = require('@astryxdesign/core/theme');
+exports.${exportName} = defineTheme({
+ name: '${exportName}',
+ tokens: {'--color-surface': '#eee'},
+ ${adaptationsSource}
+});
+`
+ : `import {defineTheme} from '@astryxdesign/core/theme';
+${options.tla ? `const surface = await Promise.resolve('#eee');\n` : ''}export const ${exportName} = defineTheme({
+ name: '${exportName}',
+ tokens: {'--color-surface': ${options.tla ? 'surface' : "'#eee'"}},
+ ${adaptationsSource}
+});
+`,
+ );
+}
+
+/**
+ * @param {string} themeFile
+ * @param {string[]} [extraArgs]
+ * @returns {{status: number, envelope: any}}
+ */
+function buildTheme(themeFile, extraArgs = []) {
+ const bin = path.join(
+ root,
+ 'node_modules/@astryxdesign/cli/clients/cli/bin/astryx.mjs',
+ );
+ try {
+ const stdout = execFileSync(
+ process.execPath,
+ [bin, 'theme', 'build', themeFile, ...extraArgs, '--json'],
+ {cwd: consumer, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']},
+ );
+ return {status: 0, envelope: JSON.parse(stdout)};
+ } catch (error) {
+ const e = /** @type {any} */ (error);
+ return {status: e.status ?? 1, envelope: JSON.parse(String(e.stdout))};
+ }
+}
+
+/**
+ * Generated content with only its leading `@generated` provenance header
+ * removed. Split on the FIRST close marker: a generated JS module has a second
+ * block comment of its own, and cutting at every marker would compare nothing
+ * but that comment.
+ */
+function bodyOf(file) {
+ const content = fs.readFileSync(path.join(consumer, file), 'utf8');
+ const end = content.indexOf('*/\n');
+ return end === -1 ? content : content.slice(end + 3);
+}
+
+/** @param {string} name @param {string} source */
+function theme(name, source) {
+ fs.writeFileSync(path.join(consumer, name), source);
+ return name;
+}
+
+/** @param {string} base */
+function outputsExist(base) {
+ return ['css', 'js', 'd.ts'].some(ext =>
+ fs.existsSync(path.join(consumer, `${base}.${ext}`)),
+ );
+}
+
+/** Type-check the shipped template against 0.5.4's pre-adaptation input. */
+function typecheckShippedTemplateAgainstCore054() {
+ const fixture = path.join(consumer, 'template-core-0.5.4');
+ fs.rmSync(fixture, {recursive: true, force: true});
+ fs.mkdirSync(fixture, {recursive: true});
+
+ const template = fs
+ .readFileSync(path.join(CLI_PKG, 'assets/theme.template.ts'), 'utf8')
+ .replace("from '@astryxdesign/core/theme';", "from './core-0.5.4.js';");
+ fs.writeFileSync(path.join(fixture, 'theme.template.ts'), template);
+
+ // Core 0.5.4's DefineThemeInput field set, with each field retaining its real
+ // type from Core. Keeping the keys explicit prevents a future Core field from
+ // making this compatibility fixture silently more permissive.
+ fs.writeFileSync(
+ path.join(fixture, 'core-0.5.4.d.ts'),
+ `import type {
+ DefineThemeInput as CurrentDefineThemeInput,
+ DefinedTheme,
+} from '@astryxdesign/core/theme';
+export type DefineThemeInput = Pick<
+ CurrentDefineThemeInput,
+ | 'name'
+ | 'extends'
+ | 'typography'
+ | 'motion'
+ | 'radius'
+ | 'color'
+ | 'tokens'
+ | 'localTokens'
+ | 'components'
+ | 'icons'
+ | 'indicators'
+ | 'syntax'
+ | 'onDark'
+ | 'onLight'
+>;
+export declare function defineTheme(input: DefineThemeInput): DefinedTheme;
+`,
+ );
+ fs.writeFileSync(
+ path.join(fixture, 'tsconfig.json'),
+ `${JSON.stringify(
+ {
+ compilerOptions: {
+ target: 'ES2022',
+ module: 'ESNext',
+ moduleResolution: 'Bundler',
+ strict: true,
+ skipLibCheck: true,
+ noEmit: true,
+ },
+ include: ['theme.template.ts', 'core-0.5.4.d.ts'],
+ },
+ null,
+ 2,
+ )}\n`,
+ );
+
+ try {
+ execFileSync(
+ process.execPath,
+ [TSC_BIN, '--project', path.join(fixture, 'tsconfig.json')],
+ {cwd: fixture, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe']},
+ );
+ return {ok: true, output: ''};
+ } catch (error) {
+ const e = /** @type {any} */ (error);
+ return {ok: false, output: `${e.stdout ?? ''}${e.stderr ?? ''}`};
+ }
+}
+
+const ADAPTATIONS = `{
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [
+ {when: {pointer: 'coarse'}, value: {tokens: {'--size-element-md': '44px'}}},
+ ],
+ }`;
+
+const MALFORMED_ADAPTATIONS = [
+ ['rules-string', `{rules: 'invalid'}`],
+ ['rules-null', `{rules: null}`],
+ ['rules-object', `{rules: {invalid: true}}`],
+ ['points-array', `{widthBreakpoints: []}`],
+ ['points-null', `{widthBreakpoints: null}`],
+];
+
+beforeAll(() => {
+ // The `node` project's globalSetup builds core before any worker forks; a
+ // missing dist here means that contract broke, not that this test is
+ // optional.
+ expect(
+ fs.existsSync(CORE_THEME_ENTRY),
+ 'packages/core must be built before this suite (vitest.global-setup.node.mjs)',
+ ).toBe(true);
+
+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-packed-old-core-'));
+ consumer = path.join(root, 'app');
+ fs.mkdirSync(consumer, {recursive: true});
+ const modules = path.join(root, 'node_modules');
+
+ // The packed CLI, as published.
+ const cli = path.join(modules, '@astryxdesign/cli');
+ fs.mkdirSync(cli, {recursive: true});
+ for (const dir of PACKED_DIRS) {
+ fs.cpSync(path.join(CLI_PKG, dir), path.join(cli, dir), {recursive: true});
+ }
+ fs.mkdirSync(path.join(cli, 'scripts'), {recursive: true});
+ fs.copyFileSync(
+ path.join(CLI_PKG, 'scripts/postinstall.mjs'),
+ path.join(cli, 'scripts/postinstall.mjs'),
+ );
+ fs.copyFileSync(
+ path.join(CLI_PKG, 'package.json'),
+ path.join(cli, 'package.json'),
+ );
+
+ // Its runtime dependencies, resolved from the install root like a real one.
+ for (const dep of RUNTIME_DEPS) {
+ const resolved = fs.realpathSync(path.join(REPO_ROOT, 'node_modules', dep));
+ fs.symlinkSync(resolved, path.join(modules, dep));
+ }
+
+ // The installed core. Real built implementations behind a swappable
+ // `./theme` entry; component docs live in `src` in the published package
+ // too, and the theme build reads them to validate component overrides.
+ corePkg = path.join(modules, '@astryxdesign/core');
+ fs.mkdirSync(corePkg, {recursive: true});
+ fs.symlinkSync(
+ path.join(REPO_ROOT, 'packages/core/src'),
+ path.join(corePkg, 'src'),
+ );
+ linkEntries(CORE_DIST, path.join(corePkg, 'dist'), ['theme']);
+ linkEntries(path.join(CORE_DIST, 'theme'), path.join(corePkg, 'dist/theme'), [
+ 'index.js',
+ ]);
+ useCore('old');
+
+ // Two installed theme packages, shaped like a published one: a `./built`
+ // subpath exporting a built theme module. The plain one carries the default
+ // no-op width map every shipped built theme has; the adaptive one carries
+ // rules. Both are resolved by bare specifier, from the consumer's file.
+ installThemePackage(
+ '@fixture/theme-plain',
+ 'plainPackageTheme',
+ `{widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536}, rules: []}`,
+ );
+ installThemePackage(
+ '@fixture/theme-adaptive',
+ 'adaptivePackageTheme',
+ `{
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [{when: {contrast: 'more'}, value: {tokens: {'--color-border': '#000'}}}],
+ }`,
+ );
+ // ESM-only `exports` maps: `require` resolution throws
+ // ERR_PACKAGE_PATH_NOT_EXPORTED on these, the loader resolves them fine.
+ installThemePackage(
+ '@fixture/theme-esm',
+ 'esmAdaptiveTheme',
+ `{widthBreakpoints: {sm: 600, md: 900, lg: 1200, xl: 1500, '2xl': 1800}, rules: []}`,
+ {esmOnly: true},
+ );
+ installThemePackage(
+ '@fixture/theme-esm-plain',
+ 'esmPlainTheme',
+ `{widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536}, rules: []}`,
+ {esmOnly: true},
+ );
+ // A CommonJS package artifact.
+ const cjsRoot = path.join(root, 'node_modules/@fixture/theme-cjs');
+ fs.mkdirSync(cjsRoot, {recursive: true});
+ fs.writeFileSync(
+ path.join(cjsRoot, 'package.json'),
+ `${JSON.stringify({name: '@fixture/theme-cjs', version: '0.5.4', main: './index.js'}, null, 2)}\n`,
+ );
+ fs.writeFileSync(
+ path.join(cjsRoot, 'index.js'),
+ `exports.cjsPackageTheme = {
+ name: 'cjs-base',
+ __built: true,
+ tokens: {'--color-surface': '#eee'},
+ __adaptations: {widthBreakpoints: {sm: 600, md: 900, lg: 1200, xl: 1500, '2xl': 1800}, rules: []},
+};
+`,
+ );
+
+ theme(
+ 'plain.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const plainTheme = defineTheme({
+ name: 'plain',
+ tokens: {'--color-background': '#fff'},
+ components: {button: {base: {borderRadius: '4px'}}},
+});
+`,
+ );
+ theme(
+ 'adaptive.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const adaptiveTheme = defineTheme({
+ name: 'adaptive',
+ tokens: {'--color-background': '#fff'},
+ adaptations: ${ADAPTATIONS},
+});
+`,
+ );
+ theme(
+ 'shorthand.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const adaptations = ${ADAPTATIONS};
+export const shorthandTheme = defineTheme({
+ name: 'shorthand',
+ tokens: {'--color-background': '#fff'},
+ adaptations,
+});
+`,
+ );
+ theme(
+ 'shared-config.ts',
+ `export const sharedConfig = {adaptations: ${ADAPTATIONS}};\n`,
+ );
+ theme(
+ 'spread.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {sharedConfig} from './shared-config';
+export const spreadTheme = defineTheme({
+ name: 'spread',
+ tokens: {'--color-background': '#fff'},
+ ...sharedConfig,
+});
+`,
+ );
+ theme(
+ 'adaptive-base.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const adaptiveBase = defineTheme({
+ name: 'adaptive-base',
+ tokens: {'--color-background': '#fff'},
+ adaptations: ${ADAPTATIONS},
+});
+`,
+ );
+ theme(
+ 'extending.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {adaptiveBase} from './adaptive-base';
+export const extendingTheme = defineTheme({
+ name: 'extending',
+ tokens: {'--color-accent': '#09f'},
+ extends: adaptiveBase,
+});
+`,
+ );
+ // Zero rules, but a CUSTOM width map: no CSS, yet real semantics an older
+ // core drops (built metadata, AppShell breakpoint names, extends).
+ theme(
+ 'breakpoints-only.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const breakpointsOnlyTheme = defineTheme({
+ name: 'breakpoints-only',
+ tokens: {'--color-background': '#fff'},
+ adaptations: {
+ widthBreakpoints: {sm: 600, md: 900, lg: 1200, xl: 1500, '2xl': 1800},
+ rules: [],
+ },
+});
+`,
+ );
+ theme(
+ 'no-op-adaptations.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const noOpAdaptationsTheme = defineTheme({
+ name: 'no-op-adaptations',
+ tokens: {'--color-background': '#fff'},
+ adaptations: {
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [],
+ },
+});
+`,
+ );
+ for (const [name, adaptations] of MALFORMED_ADAPTATIONS) {
+ theme(
+ `malformed-${name}.ts`,
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const malformedTheme = defineTheme({
+ name: 'malformed-${name}',
+ tokens: {'--color-background': '#fff'},
+ adaptations: ${adaptations},
+});
+`,
+ );
+ }
+ // Extends a real INSTALLED theme package whose built artifact carries only
+ // the default no-op width map — the documented pattern, and what every
+ // shipped theme's `/built` subpath actually looks like. Must keep building.
+ theme(
+ 'extends-package.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {plainPackageTheme} from '@fixture/theme-plain/built';
+export const extendsPackageTheme = defineTheme({
+ name: 'extends-package',
+ tokens: {'--color-accent': '#09f'},
+ extends: plainPackageTheme,
+});
+`,
+ );
+ // Same shape, but the installed package's built artifact carries rules.
+ theme(
+ 'extends-adaptive-package.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {adaptivePackageTheme} from '@fixture/theme-adaptive/built';
+export const extendsAdaptivePackageTheme = defineTheme({
+ name: 'extends-adaptive-package',
+ tokens: {'--color-accent': '#09f'},
+ extends: adaptivePackageTheme,
+});
+`,
+ );
+ // Negative control: the word is everywhere, the declaration is nowhere.
+ theme(
+ 'commented.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+/**
+ * No adaptations here. A future revision might add:
+ * adaptations: {rules: [{when: {pointer: 'coarse'}, value: {}}]}
+ */
+// adaptations: {widthBreakpoints: {sm: 600}, rules: []},
+const note = 'adaptations: none';
+export const commentedTheme = defineTheme({
+ name: 'commented',
+ tokens: {'--color-background': '#fff'},
+ components: {button: {base: {borderRadius: '4px'}}},
+ /* adaptations: {rules: [{when: {pointer: 'coarse'}, value: {}}]}, */
+});
+export {note};
+`,
+ );
+ // Re-export barrel — the shape every shipped theme's `src/source.ts` has.
+ theme(
+ 'reexported-theme.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const reexportedTheme = defineTheme({
+ name: 'reexport',
+ tokens: {'--color-background': '#fff'},
+ adaptations: ${ADAPTATIONS},
+});
+`,
+ );
+ theme('reexport.ts', `export {reexportedTheme} from './reexported-theme';\n`);
+ theme(
+ 'plain-reexported-theme.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const plainReexportedTheme = defineTheme({
+ name: 'plain-reexport',
+ tokens: {'--color-background': '#fff'},
+ components: {button: {base: {borderRadius: '4px'}}},
+});
+`,
+ );
+ theme(
+ 'plain-reexport.ts',
+ `export {plainReexportedTheme} from './plain-reexported-theme';\n`,
+ );
+ theme(
+ 'star-reexported-theme.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const starReexportedTheme = defineTheme({
+ name: 'star-reexport',
+ tokens: {'--color-background': '#fff'},
+ adaptations: ${ADAPTATIONS},
+});
+`,
+ );
+ theme('star-reexport.ts', `export * from './star-reexported-theme';\n`);
+ // Local factory wrapper.
+ theme(
+ 'factory.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const makeTheme = input => defineTheme({...input, tokens: {'--color-background': '#fff'}});
+export const factoryTheme = makeTheme({name: 'factory', adaptations: ${ADAPTATIONS}});
+`,
+ );
+ theme(
+ 'plain-factory.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const makeTheme = input => defineTheme({...input, tokens: {'--color-background': '#fff'}});
+export const plainFactoryTheme = makeTheme({name: 'plain-factory'});
+`,
+ );
+ // A theme whose only export the analysis cannot read at all.
+ theme(
+ 'unreadable.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const build = () => defineTheme({name: 'unreadable', tokens: {}, adaptations: ${ADAPTATIONS}});
+export const unreadableTheme = [build()][0];
+`,
+ );
+ // Extends an ESM-only installed package: `require` cannot resolve its
+ // `exports` map, the loader can.
+ theme(
+ 'extends-esm-package.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {esmAdaptiveTheme} from '@fixture/theme-esm/built';
+export const extendsEsmTheme = defineTheme({
+ name: 'extends-esm-package',
+ tokens: {'--color-accent': '#09f'},
+ extends: esmAdaptiveTheme,
+});
+`,
+ );
+ theme(
+ 'extends-esm-plain-package.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {esmPlainTheme} from '@fixture/theme-esm-plain/built';
+export const extendsEsmPlainTheme = defineTheme({
+ name: 'extends-esm-plain-package',
+ tokens: {'--color-accent': '#09f'},
+ extends: esmPlainTheme,
+});
+`,
+ );
+ // A runtime BRANCH decides whether adaptations are used. No static reading
+ // of the source can answer this; watching the call does.
+ theme(
+ 'branch.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const wanted = ['a', 'daptive'].join('') === 'adaptive';
+export const branchTheme = defineTheme({
+ name: 'branch',
+ tokens: {'--color-background': '#fff'},
+ ...(wanted ? {adaptations: ${ADAPTATIONS}} : {}),
+});
+`,
+ );
+ theme(
+ 'branch-plain.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const wanted = ['a', 'daptive'].join('') === 'nope';
+export const branchPlainTheme = defineTheme({
+ name: 'branch-plain',
+ tokens: {'--color-background': '#fff'},
+ ...(wanted ? {adaptations: ${ADAPTATIONS}} : {}),
+});
+`,
+ );
+ // Object-SPREAD of a base theme rather than `extends:` — the case a WeakMap
+ // alone would lose, since a spread makes a brand-new object.
+ theme(
+ 'spread-base.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {adaptiveBase} from './adaptive-base';
+export const spreadBaseTheme = defineTheme({
+ ...adaptiveBase,
+ name: 'spread-base',
+});
+`,
+ );
+ theme(
+ 'plain-base.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const plainBase = defineTheme({
+ name: 'plain-base',
+ tokens: {'--color-background': '#fff'},
+});
+`,
+ );
+ theme(
+ 'spread-plain-base.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {plainBase} from './plain-base';
+export const spreadPlainBaseTheme = defineTheme({
+ ...plainBase,
+ name: 'spread-plain-base',
+});
+`,
+ );
+ // Direct `extends` of a raw object literal, no import at all.
+ theme(
+ 'direct-extends.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const directExtendsTheme = defineTheme({
+ name: 'direct-extends',
+ tokens: {'--color-accent': '#09f'},
+ extends: {name: 'inline-base', tokens: {}, adaptations: ${ADAPTATIONS}},
+});
+`,
+ );
+ // Imported from the package ROOT rather than the `/theme` subpath.
+ theme(
+ 'root-import.ts',
+ `import {defineTheme} from '@astryxdesign/core';
+export const rootImportTheme = defineTheme({
+ name: 'root-import',
+ tokens: {'--color-background': '#fff'},
+ adaptations: ${ADAPTATIONS},
+});
+`,
+ );
+ theme(
+ 'root-import-plain.ts',
+ `import {defineTheme} from '@astryxdesign/core';
+export const rootImportPlainTheme = defineTheme({
+ name: 'root-import-plain',
+ tokens: {'--color-background': '#fff'},
+});
+`,
+ );
+ // A CommonJS installed base package.
+ theme(
+ 'extends-cjs-package.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {cjsPackageTheme} from '@fixture/theme-cjs';
+export const extendsCjsTheme = defineTheme({
+ name: 'extends-cjs-package',
+ tokens: {'--color-accent': '#09f'},
+ extends: cjsPackageTheme,
+});
+`,
+ );
+ // An adaptive theme sitting UNUSED beside the selected plain one. Only the
+ // selected theme's lineage may decide; this must build.
+ theme(
+ 'unused-sibling.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const unusedAdaptive = defineTheme({
+ name: 'unused-adaptive',
+ tokens: {},
+ adaptations: ${ADAPTATIONS},
+});
+export default defineTheme({
+ name: 'unused-sibling',
+ tokens: {'--color-background': '#fff'},
+ components: {button: {base: {borderRadius: '4px'}}},
+});
+`,
+ );
+ // Same, one module away: the import graph carries an adaptive theme the
+ // selected one never uses.
+ theme(
+ 'unused-imported.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {adaptiveBase} from './adaptive-base';
+export const unusedImportedTheme = defineTheme({
+ name: 'unused-imported',
+ tokens: {'--color-background': String(typeof adaptiveBase === 'object' ? '#fff' : '#000')},
+});
+`,
+ );
+ // Installed packages whose SOURCE calls defineTheme at runtime, rather than
+ // shipping a built object literal. Their `defineTheme` must be the wrapped
+ // one — a package resolving its own real core would erase the author's
+ // adaptations where nothing can see it.
+ installSourcePackage(
+ '@fixture/theme-src-adaptive',
+ 'srcAdaptiveTheme',
+ `adaptations: {
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [{when: {pointer: 'coarse'}, value: {tokens: {'--size-element-md': '44px'}}}],
+ },`,
+ );
+ installSourcePackage('@fixture/theme-src-plain', 'srcPlainTheme', '');
+ installSourcePackage(
+ '@fixture/theme-src-cjs-adaptive',
+ 'srcCjsAdaptiveTheme',
+ `adaptations: {
+ widthBreakpoints: {sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536},
+ rules: [{when: {motion: 'reduce'}, value: {tokens: {'--motion-fast': '0ms'}}}],
+ },`,
+ {cjs: true},
+ );
+
+ theme(
+ 'extends-src-package.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {srcAdaptiveTheme} from '@fixture/theme-src-adaptive';
+export const extendsSrcTheme = defineTheme({
+ name: 'extends-src-package',
+ tokens: {'--color-accent': '#09f'},
+ extends: srcAdaptiveTheme,
+});
+`,
+ );
+ theme(
+ 'extends-src-plain-package.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {srcPlainTheme} from '@fixture/theme-src-plain';
+export const extendsSrcPlainTheme = defineTheme({
+ name: 'extends-src-plain-package',
+ tokens: {'--color-accent': '#09f'},
+ extends: srcPlainTheme,
+});
+`,
+ );
+ theme(
+ 'extends-src-cjs-package.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {srcCjsAdaptiveTheme} from '@fixture/theme-src-cjs-adaptive';
+export const extendsSrcCjsTheme = defineTheme({
+ name: 'extends-src-cjs-package',
+ tokens: {'--color-accent': '#09f'},
+ extends: srcCjsAdaptiveTheme,
+});
+`,
+ );
+ // Imports a NON-theme export from the package root. Mapping the root to the
+ // theme namespace would delete it and break this build.
+ theme(
+ 'root-only-export.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {Button} from '@astryxdesign/core';
+export const rootOnlyExportTheme = defineTheme({
+ name: 'root-only-export',
+ tokens: {'--color-background': typeof Button === 'undefined' ? 'MISSING' : '#fff'},
+});
+`,
+ );
+
+ // A source theme with every generative axis and no adaptation intent. An old
+ // core resolves its tokens but retains no `__axes`; the packed CLI must carry
+ // the captured authoring metadata into the built artifact so a current-core
+ // child can complete a partial adaptation axis source-equivalently.
+ theme(
+ 'axis-base.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+export const axisBase = defineTheme({
+ name: 'axis-base',
+ typography: {scale: {base: 15, ratio: 1.2}},
+ color: {accent: '#0064E0', neutralStyle: 'warm', contrast: 'high'},
+ radius: {base: 6, multiplier: 1},
+ motion: {fast: 120, medium: 300, slow: 700, ratio: 0.75},
+});
+`,
+ );
+ theme(
+ 'axis-roundtrip-child.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {axisBaseTheme} from './axis-base.js';
+export const axisRoundTripChild = defineTheme({
+ name: 'axis-child',
+ extends: axisBaseTheme,
+ adaptations: {
+ rules: [{when: {pointer: 'coarse'}, value: {radius: {multiplier: 2}}}],
+ },
+});
+`,
+ );
+ theme(
+ 'axis-source-child.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {axisBase} from './axis-base.ts';
+export const axisSourceChild = defineTheme({
+ name: 'axis-child',
+ extends: axisBase,
+ adaptations: {
+ rules: [{when: {pointer: 'coarse'}, value: {radius: {multiplier: 2}}}],
+ },
+});
+`,
+ );
+
+ // ── Top-level await: forces the DEGRADED load path ────────────────────
+ // The sync loader cannot evaluate TLA, so the load falls back to the async
+ // import. The entry's own `defineTheme` still routes through the wrapped
+ // core there, so a self-contained theme stays fully observed and must build.
+ // What the async path loses is TRANSPILING installed packages, so a package
+ // SOURCE on that path resolves its own core and escapes observation.
+ theme(
+ 'tla-entry.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const accent = await Promise.resolve('#09f');
+export const tlaEntryTheme = defineTheme({
+ name: 'tla-entry',
+ tokens: {'--color-accent': accent},
+ components: {button: {base: {borderRadius: '4px'}}},
+});
+`,
+ );
+ theme(
+ 'tla-entry-adaptive.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const accent = await Promise.resolve('#09f');
+export const tlaEntryAdaptiveTheme = defineTheme({
+ name: 'tla-entry-adaptive',
+ tokens: {'--color-accent': accent},
+ adaptations: ${ADAPTATIONS},
+});
+`,
+ );
+ theme(
+ 'tla-sibling-helper.mjs',
+ `export const accent = await Promise.resolve('#09f');\n`,
+ );
+ theme(
+ 'tla-sibling.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {accent} from './tla-sibling-helper.mjs';
+export const tlaSiblingTheme = defineTheme({
+ name: 'tla-sibling',
+ tokens: {'--color-accent': accent},
+ components: {button: {base: {borderRadius: '4px'}}},
+});
+`,
+ );
+ theme(
+ 'tla-sibling-base.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {accent} from './tla-sibling-helper.mjs';
+export const tlaSiblingBase = defineTheme({
+ name: 'tla-sibling-base-inner',
+ tokens: {'--color-surface': accent},
+ adaptations: ${ADAPTATIONS},
+});
+`,
+ );
+ theme(
+ 'tla-sibling-adaptive.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {tlaSiblingBase} from './tla-sibling-base';
+export const tlaSiblingAdaptiveTheme = defineTheme({
+ name: 'tla-sibling-adaptive',
+ tokens: {'--color-accent': '#09f'},
+ extends: tlaSiblingBase,
+});
+`,
+ );
+ // The genuinely escaped case: a TLA theme extending an installed package's
+ // SOURCE, which the async path never transpiles, so its own core resolves
+ // unwrapped and this core erases its adaptations unobserved.
+ theme(
+ 'tla-dependency.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+import {srcPlainTheme} from '@fixture/theme-src-plain';
+const accent = await Promise.resolve('#09f');
+export const tlaDependencyTheme = defineTheme({
+ name: 'tla-dependency',
+ tokens: {'--color-accent': accent},
+ extends: srcPlainTheme,
+});
+`,
+ );
+ // TLA with nothing unobservable in the lineage: degraded, but every member
+ // is either recorded or carries its own metadata, so it must still build.
+ theme(
+ 'tla-self-contained.ts',
+ `import {defineTheme} from '@astryxdesign/core/theme';
+const accent = await Promise.resolve('#09f');
+export const tlaSelfContainedTheme = defineTheme({
+ name: 'tla-self-contained',
+ tokens: {'--color-accent': accent},
+});
+`,
+ );
+ // A genuine author error must surface AS ITSELF, never be downgraded to the
+ // async path — which would also execute the module's side effects twice.
+ theme(
+ 'author-throws.ts',
+ `import * as fs from 'node:fs';
+import {defineTheme} from '@astryxdesign/core/theme';
+fs.appendFileSync(new URL('./author-throws.log', import.meta.url), 'x');
+export const authorThrowsTheme = defineTheme({
+ name: 'author-throws',
+ tokens: {'--color-background': (() => { throw new Error('deliberate author bug'); })()},
+});
+`,
+ );
+}, 120_000);
+
+afterAll(() => {
+ if (root) fs.rmSync(root, {recursive: true, force: true});
+});
+
+describe('packed CLI against a core that predates adaptations', () => {
+ beforeAll(() => useCore('old'));
+
+ it('builds a non-adaptation theme', () => {
+ const {status, envelope} = buildTheme('plain.ts');
+
+ expect({status, error: envelope.error}).toEqual({
+ status: 0,
+ error: undefined,
+ });
+ expect(envelope.type).toBe('theme.build');
+ const css = fs.readFileSync(path.join(consumer, 'plain.css'), 'utf8');
+ expect(css).toContain('--color-background: #fff;');
+ expect(css).toContain('border-radius: 4px;');
+ expect(css).toContain(`Core: @astryxdesign/core@${OLD_CORE_VERSION}`);
+ });
+
+ it('keeps the shipped template type-compatible with Core 0.5.4', () => {
+ const template = fs.readFileSync(
+ path.join(CLI_PKG, 'assets/theme.template.ts'),
+ 'utf8',
+ );
+ expect(template).not.toMatch(/^\s{2}adaptations:/m);
+ expect(template).toMatch(/^\s{2}\/\/ adaptations: \{/m);
+
+ const result = typecheckShippedTemplateAgainstCore054();
+ expect(
+ result.ok,
+ `Core 0.5.4 rejected the shipped theme template:\n${result.output}`,
+ ).toBe(true);
+ });
+
+ it('builds a theme that only talks about adaptations in comments and strings', () => {
+ const {status, envelope} = buildTheme('commented.ts');
+
+ expect({status, error: envelope.error}).toEqual({
+ status: 0,
+ error: undefined,
+ });
+ expect(
+ fs.readFileSync(path.join(consumer, 'commented.css'), 'utf8'),
+ ).toContain('border-radius: 4px;');
+ });
+
+ it('builds a theme extending an installed theme package with no adaptation intent', () => {
+ // The documented pattern — `extends` a shipped theme's `/built` subpath.
+ // Its `__adaptations` is the default no-op map, so the bare specifier must
+ // resolve and the theme must build, not become an unresolved guess.
+ const {status, envelope} = buildTheme('extends-package.ts');
+
+ expect({status, error: envelope.error}).toEqual({
+ status: 0,
+ error: undefined,
+ });
+ expect(
+ fs.readFileSync(path.join(consumer, 'extends-package.css'), 'utf8'),
+ ).toContain('--color-accent: #09f;');
+ });
+
+ it.each([
+ ['a raw complete default adaptation map', 'no-op-adaptations'],
+ ['a plain re-export barrel', 'plain-reexport'],
+ ['a plain local factory', 'plain-factory'],
+ ['an ESM-only package base with no intent', 'extends-esm-plain-package'],
+ ['a runtime branch that skips adaptations', 'branch-plain'],
+ ['a spread of a plain base theme', 'spread-plain-base'],
+ ['a root `@astryxdesign/core` import', 'root-import-plain'],
+ ['an unused adaptive sibling in the same module', 'unused-sibling'],
+ ['an unused adaptive theme one module away', 'unused-imported'],
+ [
+ 'a package whose SOURCE defines a plain theme',
+ 'extends-src-plain-package',
+ ],
+ ])('builds a theme reaching the loader through %s', (_label, base) => {
+ const {status, envelope} = buildTheme(`${base}.ts`);
+
+ expect({status, error: envelope.error}).toEqual({
+ status: 0,
+ error: undefined,
+ });
+ expect(fs.existsSync(path.join(consumer, `${base}.css`))).toBe(true);
+ });
+
+ it('preserves exports that only the package ROOT has', () => {
+ // The wrapped root must be the root namespace, not the theme namespace
+ // wearing its name — a theme importing a component from
+ // `@astryxdesign/core` would otherwise get `undefined`.
+ const {status, envelope} = buildTheme('root-only-export.ts');
+
+ expect({status, error: envelope.error}).toEqual({
+ status: 0,
+ error: undefined,
+ });
+ const css = fs.readFileSync(
+ path.join(consumer, 'root-only-export.css'),
+ 'utf8',
+ );
+ expect(css).not.toContain('MISSING');
+ expect(css).toContain('--color-background: #fff;');
+ });
+
+ it.each([
+ ['in the entry file', 'tla-entry'],
+ ['in a relative sibling module', 'tla-sibling'],
+ ['with no package base at all', 'tla-self-contained'],
+ ])(
+ 'builds a plain theme when top-level await %s forces the fallback path',
+ (_label, base) => {
+ // Degraded, but not blind: the entry's own `defineTheme` still routes
+ // through the wrapped core on the async path, so the whole lineage was
+ // observed and there is nothing unproven. Failing these would make the
+ // guard fire on ordinary correct themes.
+ const {status, envelope} = buildTheme(`${base}.ts`);
+
+ expect({status, error: envelope.error}).toEqual({
+ status: 0,
+ error: undefined,
+ });
+ expect(fs.existsSync(path.join(consumer, `${base}.css`))).toBe(true);
+ },
+ );
+
+ it.each([
+ ['declared in the entry file', 'tla-entry-adaptive'],
+ ['inherited from a relative base', 'tla-sibling-adaptive'],
+ ])('still detects adaptations %s under top-level await', (_label, base) => {
+ // Degrading the load must not lose real intent: these are observed, and
+ // their captured raw input still carries the author's `adaptations`.
+ const {status, envelope} = buildTheme(`${base}.ts`);
+
+ expect(status).toBe(1);
+ expect(envelope.code).toBe('ERR_CORE_INCOMPATIBLE');
+ expect(envelope.error).toContain('generateAdaptationCSS');
+ expect(outputsExist(base)).toBe(false);
+ });
+
+ it('refuses a package base that escaped observation on the fallback path', () => {
+ // The one genuinely unprovable shape: the async path does not transpile
+ // installed packages, so this base's own `defineTheme` is the real one.
+ // This core erases adaptations while resolving, so whether it had any is
+ // unknowable — and unproven must not build.
+ const {status, envelope} = buildTheme('tla-dependency.ts');
+
+ expect(status).toBe(1);
+ expect(envelope.code).toBe('ERR_CORE_INCOMPATIBLE');
+ expect(envelope.error).toMatch(/could not be observed/);
+ expect(envelope.error).toMatch(/top-level await/);
+ expect(envelope.error).toContain('srcPlainTheme');
+ expect(outputsExist('tla-dependency')).toBe(false);
+ });
+
+ it('surfaces a genuine author error without executing the theme twice', () => {
+ // The narrow fallback exists for sync-loader limitations only. An author's
+ // own exception must reach them as itself — never be swallowed into a
+ // second, weaker load, which would also re-run every side effect the
+ // module had already performed.
+ const log = path.join(consumer, 'author-throws.log');
+ fs.rmSync(log, {force: true});
+
+ const {status, envelope} = buildTheme('author-throws.ts');
+
+ expect(status).toBe(1);
+ expect(envelope.code).toBe('ERR_THEME_LOAD');
+ expect(envelope.error).toContain('deliberate author bug');
+ // One 'x' per execution of the theme module.
+ expect(fs.readFileSync(log, 'utf8')).toBe('x');
+ });
+
+ it('never serializes the lineage marker into generated output', () => {
+ buildTheme('unused-sibling.ts');
+
+ for (const ext of ['css', 'js', 'd.ts']) {
+ const content = fs.readFileSync(
+ path.join(consumer, `unused-sibling.${ext}`),
+ 'utf8',
+ );
+ expect(content).not.toContain('astryx.theme.lineage');
+ expect(content).not.toContain('Symbol');
+ }
+ });
+
+ it.each(MALFORMED_ADAPTATIONS)(
+ 'refuses malformed adaptation metadata in %s',
+ name => {
+ const base = `malformed-${name}`;
+ const {status, envelope} = buildTheme(`${base}.ts`);
+
+ expect(status).toBe(1);
+ expect(envelope.code).toBe('ERR_CORE_INCOMPATIBLE');
+ expect(outputsExist(base)).toBe(false);
+ },
+ );
+
+ it('refuses a CommonJS source package when its core namespace cannot be wrapped', () => {
+ const base = 'extends-src-cjs-package';
+ const {status, envelope} = buildTheme(`${base}.ts`);
+
+ expect(status).toBe(1);
+ expect(envelope.code).toBe('ERR_CORE_INCOMPATIBLE');
+ expect(envelope.error).toMatch(/could not be observed/i);
+ expect(envelope.error).toMatch(/CommonJS/i);
+ expect(outputsExist(base)).toBe(false);
+ });
+
+ it.each([
+ ['a direct `adaptations` property', 'adaptive'],
+ ['the object shorthand', 'shorthand'],
+ ['a spread of an imported config', 'spread'],
+ ['an `extends` base that declares them', 'extending'],
+ ['a custom width map with no rules', 'breakpoints-only'],
+ [
+ 'an installed theme package that declares them',
+ 'extends-adaptive-package',
+ ],
+ ['an `export {x} from` re-export barrel', 'reexport'],
+ ['an `export * from` barrel', 'star-reexport'],
+ ['a local factory wrapper', 'factory'],
+ ['an ESM-only installed package', 'extends-esm-package'],
+ ['a runtime branch that adds them', 'branch'],
+ ['an object spread of an adaptive base', 'spread-base'],
+ ['a direct `extends` of a raw object', 'direct-extends'],
+ ['a root `@astryxdesign/core` import', 'root-import'],
+ ['a CommonJS installed package base', 'extends-cjs-package'],
+ ['a package whose SOURCE calls defineTheme', 'extends-src-package'],
+ ])('refuses a theme declaring adaptations via %s', (_label, base) => {
+ const {status, envelope} = buildTheme(`${base}.ts`);
+
+ expect(status).toBe(1);
+ expect(envelope.code).toBe('ERR_CORE_INCOMPATIBLE');
+ expect(envelope.error).toContain('generateAdaptationCSS');
+ expect(outputsExist(base)).toBe(false);
+ });
+
+ it('refuses a theme whose export shape it could never have read statically', () => {
+ // The loader builds this file happily, and no source analysis could
+ // attribute its export. Interception does not have to: the call happened,
+ // so the raw input was recorded.
+ const {status, envelope} = buildTheme('unreadable.ts');
+
+ expect(status).toBe(1);
+ expect(envelope.code).toBe('ERR_CORE_INCOMPATIBLE');
+ expect(envelope.error).toContain('generateAdaptationCSS');
+ expect(outputsExist('unreadable')).toBe(false);
+ });
+
+ it('fails --check the same way, without reporting drift instead', () => {
+ const {status, envelope} = buildTheme('adaptive.ts', ['--check']);
+
+ expect(status).toBe(1);
+ expect(envelope.code).toBe('ERR_CORE_INCOMPATIBLE');
+ });
+});
+
+describe('the same themes once core supports adaptations', () => {
+ beforeAll(() => useCore('current'));
+
+ it.each([
+ 'adaptive',
+ 'shorthand',
+ 'spread',
+ 'extending',
+ 'breakpoints-only',
+ 'extends-package',
+ 'extends-adaptive-package',
+ 'reexport',
+ 'star-reexport',
+ 'factory',
+ 'unreadable',
+ 'extends-esm-package',
+ 'branch',
+ 'spread-base',
+ 'direct-extends',
+ 'root-import',
+ 'extends-cjs-package',
+ 'no-op-adaptations',
+ 'extends-src-package',
+ 'extends-src-plain-package',
+ 'extends-src-cjs-package',
+ 'root-only-export',
+ 'tla-entry',
+ 'tla-entry-adaptive',
+ 'tla-sibling',
+ 'tla-sibling-adaptive',
+ 'tla-dependency',
+ 'tla-self-contained',
+ ])('builds %s', base => {
+ const {status, envelope} = buildTheme(`${base}.ts`);
+
+ expect({status, error: envelope.error}).toEqual({
+ status: 0,
+ error: undefined,
+ });
+ // Also pins each fixture's theme NAME to its file name, which is what
+ // makes the "wrote nothing" assertions under the older core meaningful:
+ // outputs are named after the theme, so a drifting name would quietly
+ // turn those checks vacuous.
+ expect(fs.existsSync(path.join(consumer, `${base}.css`))).toBe(true);
+ });
+
+ it('emits adaptation CSS from a CommonJS source package', () => {
+ buildTheme('extends-src-cjs-package.ts');
+
+ const css = fs.readFileSync(
+ path.join(consumer, 'extends-src-cjs-package.css'),
+ 'utf8',
+ );
+ expect(css).toContain('prefers-reduced-motion: reduce');
+ expect(css).toContain('--motion-fast: 0ms;');
+ });
+
+ it('emits the adaptation CSS the older core could not', () => {
+ buildTheme('adaptive.ts');
+
+ const css = fs.readFileSync(path.join(consumer, 'adaptive.css'), 'utf8');
+ expect(css).toContain('pointer: coarse');
+ expect(css).toContain('--size-element-md: 44px;');
+ });
+});
+
+describe('old-Core generative-axis round trip', () => {
+ it('preserves raw axes for a current-Core child with a partial radius adaptation', () => {
+ useCore('old');
+ const baseBuild = buildTheme('axis-base.ts');
+ expect({status: baseBuild.status, error: baseBuild.envelope.error}).toEqual(
+ {
+ status: 0,
+ error: undefined,
+ },
+ );
+ const builtBase = bodyOf('axis-base.js');
+ expect(builtBase).toContain('__axes');
+ expect(builtBase).toContain('"typography"');
+ expect(builtBase).toContain('"color"');
+ expect(builtBase).toContain('"radius"');
+ expect(builtBase).toContain('"motion"');
+ expect(builtBase).toContain('"base": 6');
+
+ useCore('current');
+ const roundTripBuild = buildTheme('axis-roundtrip-child.ts');
+ expect({
+ status: roundTripBuild.status,
+ error: roundTripBuild.envelope.error,
+ }).toEqual({status: 0, error: undefined});
+ const roundTripCss = bodyOf('axis-child.css');
+
+ const sourceBuild = buildTheme('axis-source-child.ts');
+ expect({
+ status: sourceBuild.status,
+ error: sourceBuild.envelope.error,
+ }).toEqual({
+ status: 0,
+ error: undefined,
+ });
+ expect(roundTripCss).toBe(bodyOf('axis-child.css'));
+ expect(roundTripCss).toContain('--radius-inner: 12px;');
+ expect(roundTripCss).toContain('--radius-container: 36px;');
+ });
+});
+
+describe('output parity across the two cores', () => {
+ it('emits identical CSS for a theme with no adaptations', () => {
+ useCore('old');
+ buildTheme('plain.ts');
+ const oldCss = bodyOf('plain.css');
+
+ useCore('current');
+ buildTheme('plain.ts');
+
+ // Bodies only: the `@generated` header records the core version, which
+ // differs between two releases by design.
+ expect(oldCss).toBe(bodyOf('plain.css'));
+ });
+
+ it('emits a JS module that differs only by resolved adaptation metadata', () => {
+ // Documented drift, not a defect: a current core normalizes `__adaptations`
+ // onto every theme and the built module serializes it for `extends`. An
+ // older core has no such metadata to serialize. This is why `--check`
+ // against outputs committed with a current core reports JS drift on an
+ // older one — the CSS is still identical.
+ useCore('old');
+ buildTheme('plain.ts');
+ const oldJs = bodyOf('plain.js');
+
+ useCore('current');
+ buildTheme('plain.ts');
+ const currentJs = bodyOf('plain.js');
+
+ expect(oldJs).not.toBe(currentJs);
+ expect(oldJs).not.toContain('__adaptations');
+ expect(currentJs).toContain('__adaptations');
+ // Nothing else moved: strip the metadata block and they agree.
+ expect(
+ currentJs.replace(/ {2}__adaptations: \{[\s\S]*?\n {2}\},\n/, ''),
+ ).toBe(oldJs);
+ });
+});
diff --git a/packages/cli/api/theme/build/core-interception.mjs b/packages/cli/api/theme/build/core-interception.mjs
new file mode 100644
index 0000000000..93ad68068a
--- /dev/null
+++ b/packages/cli/api/theme/build/core-interception.mjs
@@ -0,0 +1,486 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Capture a theme's authored adaptation input as the theme file loads.
+ *
+ * `astryx theme build` resolves a theme by calling the INSTALLED core's
+ * `defineTheme()`. A core that predates ordered adaptations builds its result
+ * field by field and drops `adaptations` on the way in, so by the time the
+ * build holds a theme object, the author's rules are gone without a trace —
+ * and building anyway would emit CSS with every adaptation rule silently
+ * missing.
+ *
+ * Rather than re-deriving the author's intent from the source (which means
+ * following factories, barrels, spreads and package resolution — an incomplete
+ * JS interpreter, and a bug farm), this watches the real thing happen. The
+ * theme is already loaded through jiti; jiti's `virtualModules` lets us hand
+ * the theme file a `@astryxdesign/core/theme` whose `defineTheme` is the
+ * installed one wrapped in a recorder. Every call — in the theme file, in a
+ * relative base, in an installed package, at any depth — hands us the raw
+ * input before the old resolver can erase it. The JS engine does the
+ * evaluating; we only observe.
+ *
+ * ## Lineage, not a pile of calls
+ *
+ * A module can define several themes, and only one of them is the theme being
+ * built. Failing a build because SOME theme in the import graph uses
+ * adaptations would be wrong — an unused adaptive theme sitting in the same
+ * file must not fail its plain sibling. So each returned theme is associated
+ * with the input it came from, and capability detection walks only the
+ * selected theme's own lineage:
+ *
+ * - a WeakMap keyed by the returned object, for themes handled by reference;
+ * - an enumerable Symbol on the returned object, because a theme is routinely
+ * OBJECT-SPREAD (`{...base, name: 'child'}`) and a spread copies enumerable
+ * symbol keys while a WeakMap entry does not survive it.
+ *
+ * The Symbol is scoped to one isolated load and stripped before the theme
+ * reaches any output path. It cannot leak into a generated file regardless:
+ * `JSON.stringify`, `Object.keys` and `Object.entries` all ignore symbol keys.
+ *
+ * Used only when the installed core cannot compile adaptations. A core that
+ * can reports them on the resolved theme itself, which needs none of this.
+ *
+ * ## Reach, and its one edge
+ *
+ * jiti hands a module's imports back to itself only when it TRANSPILES that
+ * module, so the load runs through jiti's synchronous path (see
+ * `importThemeModule`), which transpiles installed ESM packages too — a
+ * package whose source calls `defineTheme` is observed like any other module.
+ * `patchCommonJs` covers `.cjs` source, which jiti always loads natively, by
+ * wrapping the core's own CommonJS exports object for the duration of the
+ * load.
+ *
+ * One combination stays out of reach: a `.cjs` package source resolving an
+ * ESM-ONLY core. Node's `require(esm)` hands it a frozen/non-configurable module
+ * namespace, which cannot be patched in place. `patchCommonJs` reports that
+ * coverage gap; if the selected theme's lineage then contains an unobserved
+ * member, the build fails closed rather than assuming erased adaptations were
+ * absent. A package's BUILT artifact remains supported because it carries
+ * `__adaptations` as observable plain data.
+ *
+ * The same capture also retains raw typography, color, radius, and motion axes.
+ * Older cores resolve those inputs into tokens but do not expose `__axes`; the
+ * CLI reconstructs the effective metadata with current core's merge semantics
+ * so a later current-core child can extend the built artifact source-equivalently.
+ *
+ * SYNC: packages/cli/api/theme/build/build.mjs (importThemeModule)
+ */
+
+import {createRequire} from 'node:module';
+
+/**
+ * Marks a theme object with the raw input it was resolved from. Enumerable on
+ * purpose — an object spread must carry it — and a Symbol on purpose, so it is
+ * invisible to every serialization path the build uses.
+ */
+export const THEME_LINEAGE = Symbol.for('astryx.theme.lineage');
+
+/**
+ * @typedef {object} ThemeLineage
+ * @property {any} input - The raw `defineTheme()` argument.
+ * @property {any} result - What the installed core returned for it.
+ */
+
+/**
+ * A recorder for one isolated theme load.
+ *
+ * @typedef {object} CoreInterception
+ * @property {Record<string, unknown>} modules - `virtualModules` for jiti.
+ * @property {(theme: any) => any[]} lineageOf - Every raw input that fed a
+ * theme, following its own `extends` chain and spread provenance.
+ * @property {(theme: any) => any[]} unobservedIn - Lineage members this
+ * recorder never saw and that carry no adaptation metadata; ask before
+ * `strip`.
+ * @property {(theme: any) => Record<string, any> | undefined} capturedAxesOf -
+ * Effective generative-axis metadata reconstructed from captured raw inputs.
+ * @property {(theme: any) => void} strip - Remove the marker from a theme and
+ * its reachable bases, before it is used to generate anything.
+ * @property {(fromFile: string) => {covered: boolean, undo: () => void}} patchCommonJs -
+ * Cover the one path `virtualModules` cannot reach and report whether every
+ * resolvable CommonJS core namespace could be wrapped.
+ */
+
+/**
+ * Was this theme produced by a `defineTheme()` call the recorder saw?
+ * Must be asked BEFORE `strip` — that is what removes the evidence.
+ *
+ * @param {any} value
+ * @param {WeakMap<object, ThemeLineage>} byReference
+ * @returns {boolean}
+ */
+function wasObserved(value, byReference) {
+ if (!value || typeof value !== 'object') return false;
+ return byReference.has(value) || value[THEME_LINEAGE] !== undefined;
+}
+
+const GENERATIVE_AXIS_KEYS = ['typography', 'color', 'radius', 'motion'];
+
+/**
+ * Merge generative axes exactly as current core does. The CLI needs this small
+ * compatibility copy because the installed core being observed predates both
+ * the public adaptation compiler and retained `__axes` metadata.
+ *
+ * SYNC: packages/core/src/theme/themeAdaptations.ts
+ * (resolveThemeGenerativeAxes, mergeRole)
+ *
+ * @param {Record<string, any> | undefined} inherited
+ * @param {Record<string, any>} own
+ * @returns {Record<string, any>}
+ */
+function mergeGenerativeAxes(inherited, own) {
+ /** @param {any} root @param {any} next */
+ const mergeRole = (root, next) => {
+ if (!root) return next;
+ if (!next) return root;
+ return {
+ ...root,
+ ...next,
+ weights:
+ root.weights || next.weights
+ ? {...root.weights, ...next.weights}
+ : undefined,
+ };
+ };
+
+ const inheritedTypography = inherited?.typography;
+ const ownTypography = own.typography;
+ /** @param {any} inheritedRole @param {any} ownRole @param {boolean} [followsOwnBody] */
+ const resolveFamily = (inheritedRole, ownRole, followsOwnBody = false) => {
+ const merged = mergeRole(inheritedRole, ownRole);
+ if (!merged) return undefined;
+ if (ownRole?.family) {
+ return {
+ ...merged,
+ family: ownRole.family,
+ fallbacks: ownRole.fallbacks,
+ };
+ }
+ if (followsOwnBody) {
+ return {...merged, family: undefined, fallbacks: undefined};
+ }
+ return {
+ ...merged,
+ family: inheritedRole?.family,
+ fallbacks: inheritedRole?.fallbacks,
+ };
+ };
+
+ let body = resolveFamily(inheritedTypography?.body, ownTypography?.body);
+ let heading = resolveFamily(
+ inheritedTypography?.heading,
+ ownTypography?.heading,
+ Boolean(ownTypography?.body?.family && !ownTypography?.heading?.family),
+ );
+ let code = resolveFamily(inheritedTypography?.code, ownTypography?.code);
+ const weightOwner = ownTypography?.scale
+ ? ownTypography
+ : inheritedTypography?.scale
+ ? inheritedTypography
+ : undefined;
+ /** @param {any} role @param {any} owner */
+ const applyWeights = (role, owner) =>
+ role
+ ? {...role, weight: owner?.weight, weights: owner?.weights}
+ : undefined;
+ body = applyWeights(body, weightOwner?.body);
+ heading = applyWeights(heading, weightOwner?.heading);
+ code = applyWeights(code, weightOwner?.code);
+
+ const typography =
+ inheritedTypography || ownTypography
+ ? {
+ ...inheritedTypography,
+ ...ownTypography,
+ scale: ownTypography?.scale ?? inheritedTypography?.scale,
+ body,
+ heading,
+ code,
+ }
+ : undefined;
+ const color = own.color ?? inherited?.color;
+ const radius = own.radius
+ ? {...inherited?.radius, ...own.radius}
+ : inherited?.radius;
+ const motion = own.motion
+ ? {...inherited?.motion, ...own.motion}
+ : inherited?.motion;
+
+ return {
+ ...(typography ? {typography} : {}),
+ ...(color ? {color} : {}),
+ ...(radius ? {radius} : {}),
+ ...(motion ? {motion} : {}),
+ };
+}
+
+/**
+ * Wrap an installed core module so every `defineTheme()` call records the raw
+ * input against the theme it produced.
+ *
+ * Both entry points a theme can import core through are wrapped, each from its
+ * OWN namespace: `@astryxdesign/core/theme` keeps the theme namespace, and the
+ * package root keeps the root namespace, which exports far more (components,
+ * hooks) than the theme subpath. Mapping the root at the theme namespace would
+ * silently delete every one of those exports from a theme file that imports a
+ * component. Every real export is preserved on each; one function is wrapped.
+ *
+ * A core that already compiles adaptations should never be wrapped — it
+ * reports its own — but wrapping is harmless if it is.
+ *
+ * @param {any} coreThemeModule - The installed `@astryxdesign/core/theme` namespace.
+ * @param {any} [coreRootModule] - The installed `@astryxdesign/core` namespace.
+ * @returns {CoreInterception}
+ */
+export function interceptCore(coreThemeModule, coreRootModule) {
+ /** @type {WeakMap<object, ThemeLineage>} */
+ const byReference = new WeakMap();
+
+ /** @param {any} value @param {ThemeLineage} lineage */
+ const mark = (value, lineage) => {
+ if (!value || typeof value !== 'object') return;
+ byReference.set(value, lineage);
+ try {
+ // Enumerable so a spread of this theme carries it; configurable so it
+ // can be removed again before the theme is used for output.
+ Object.defineProperty(value, THEME_LINEAGE, {
+ value: lineage,
+ enumerable: true,
+ configurable: true,
+ writable: true,
+ });
+ } catch {
+ // A frozen or sealed theme keeps the WeakMap association only.
+ }
+ };
+
+ /** @param {any} value @returns {ThemeLineage | undefined} */
+ const lineageFor = value => {
+ if (!value || typeof value !== 'object') return undefined;
+ return byReference.get(value) ?? value[THEME_LINEAGE];
+ };
+
+ /**
+ * One namespace, spread so exports this file does not know about still
+ * reach the theme file, with `defineTheme` (if present) wrapped.
+ * @param {any} namespace
+ * @returns {any}
+ */
+ const wrapNamespace = namespace => {
+ if (!namespace) return namespace;
+ const real = namespace.defineTheme;
+ if (typeof real !== 'function') return {...namespace};
+ return {
+ ...namespace,
+ /** @param {any} input */
+ defineTheme(input) {
+ const result = real.call(namespace, input);
+ mark(result, {input, result});
+ return result;
+ },
+ };
+ };
+
+ return {
+ modules: {
+ '@astryxdesign/core/theme': wrapNamespace(coreThemeModule),
+ // Falls back to the theme namespace only when the root could not be
+ // imported at all; a partial root is better than none, and a core
+ // missing its own root entry is already broken.
+ '@astryxdesign/core': wrapNamespace(coreRootModule ?? coreThemeModule),
+ },
+
+ lineageOf(theme) {
+ /** @type {any[]} */
+ const inputs = [];
+ /** @type {Set<any>} */
+ const seen = new Set();
+ /** @type {any[]} */
+ const queue = [theme];
+
+ while (queue.length > 0) {
+ const value = queue.pop();
+ if (!value || typeof value !== 'object' || seen.has(value)) continue;
+ seen.add(value);
+
+ // The theme itself is evidence: a built module or a plain object
+ // literal carries its adaptation metadata directly, having never gone
+ // through `defineTheme` at all.
+ inputs.push(value);
+
+ const lineage = lineageFor(value);
+ if (lineage) {
+ // The raw input is where an erased `adaptations` still lives, and
+ // its own `extends` is the next link in the chain.
+ if (lineage.input && typeof lineage.input === 'object') {
+ queue.push(lineage.input);
+ }
+ }
+ if (value.extends) queue.push(value.extends);
+ }
+ return inputs;
+ },
+
+ unobservedIn(theme) {
+ // Lineage members this recorder never saw AND that carry no adaptation
+ // metadata of their own. On a degraded load these are exactly the
+ // themes whose adaptations, if any, were erased unobserved. Must be
+ // called before `strip`.
+ //
+ // A RAW INPUT reached through an observed result is itself evidence —
+ // it is the very object the recorder captured, and only the result
+ // carries the marker. Counting it as unobserved would fail every
+ // degraded build, including themes whose whole lineage was seen.
+ /** @type {Set<any>} */
+ const observedInputs = new Set();
+ for (const value of this.lineageOf(theme)) {
+ const lineage = lineageFor(value);
+ if (lineage?.input && typeof lineage.input === 'object') {
+ observedInputs.add(lineage.input);
+ }
+ }
+
+ return this.lineageOf(theme).filter(
+ value =>
+ value &&
+ typeof value === 'object' &&
+ !wasObserved(value, byReference) &&
+ !observedInputs.has(value) &&
+ value.adaptations === undefined &&
+ value.__adaptations === undefined &&
+ value.__adaptationRules === undefined,
+ );
+ },
+
+ capturedAxesOf(theme) {
+ /** @type {Set<any>} */
+ const seen = new Set();
+
+ /** @param {any} value @returns {Record<string, any> | undefined} */
+ const visit = value => {
+ if (!value || typeof value !== 'object' || seen.has(value)) {
+ return undefined;
+ }
+ seen.add(value);
+
+ // A built/current theme already carries the effective metadata. An
+ // empty object is meaningful: it proves there are no inherited axes.
+ if (value.__axes !== undefined) {
+ return value.__axes &&
+ typeof value.__axes === 'object' &&
+ !Array.isArray(value.__axes)
+ ? value.__axes
+ : undefined;
+ }
+
+ const lineage = lineageFor(value);
+ const input =
+ lineage?.input && typeof lineage.input === 'object'
+ ? lineage.input
+ : value;
+ const inherited = visit(input.extends);
+ /** @type {Record<string, any>} */
+ const own = {};
+ for (const key of GENERATIVE_AXIS_KEYS) {
+ if (input[key] !== undefined) own[key] = input[key];
+ }
+ if (!inherited && Object.keys(own).length === 0) return undefined;
+ return mergeGenerativeAxes(inherited, own);
+ };
+
+ return visit(theme);
+ },
+
+ strip(theme) {
+ /** @type {Set<any>} */
+ const seen = new Set();
+ /** @type {any[]} */
+ const queue = [theme];
+ while (queue.length > 0) {
+ const value = queue.pop();
+ if (!value || typeof value !== 'object' || seen.has(value)) continue;
+ seen.add(value);
+ const lineage = lineageFor(value);
+ if (Object.hasOwn(value, THEME_LINEAGE)) {
+ try {
+ delete value[THEME_LINEAGE];
+ } catch {
+ // Best effort: a non-configurable marker is still invisible to
+ // JSON.stringify / Object.keys, so it cannot reach output.
+ }
+ }
+ if (lineage?.input && typeof lineage.input === 'object') {
+ queue.push(lineage.input);
+ }
+ if (value.extends) queue.push(value.extends);
+ }
+ },
+
+ patchCommonJs(fromFile) {
+ // jiti hands a module's imports back to itself only when it transpiles
+ // that module, and it never transpiles a `.cjs` file — so a package
+ // whose source is `.cjs` requires the real core natively and
+ // `virtualModules` never sees it. Patch mutable CommonJS exports in place;
+ // when require(esm) returns a non-configurable module namespace, report
+ // the coverage gap so the caller can reject any selected lineage member
+ // whose adaptation intent could not be observed.
+ /** @type {Array<() => void>} */
+ const undo = [];
+ let covered = true;
+ for (const specifier of [
+ '@astryxdesign/core/theme',
+ '@astryxdesign/core',
+ ]) {
+ /** @type {any} */
+ let cjs;
+ try {
+ cjs = createRequire(fromFile)(specifier);
+ } catch {
+ // A specifier that CommonJS cannot resolve cannot be used by a `.cjs`
+ // source dependency either, so it creates no unobserved path.
+ continue;
+ }
+
+ const real = cjs?.defineTheme;
+ if (typeof real !== 'function') continue;
+ const descriptor = Object.getOwnPropertyDescriptor(cjs, 'defineTheme');
+ if (!descriptor || !(descriptor.writable || descriptor.configurable)) {
+ covered = false;
+ continue;
+ }
+
+ try {
+ Object.defineProperty(cjs, 'defineTheme', {
+ ...descriptor,
+ value: /** @param {any} input */ input => {
+ const result = real.call(cjs, input);
+ mark(result, {input, result});
+ return result;
+ },
+ });
+ undo.push(() =>
+ Object.defineProperty(cjs, 'defineTheme', descriptor),
+ );
+ } catch {
+ // ESM namespace exotic objects may report a writable descriptor but
+ // still reject redefinition. This is a real coverage failure, not an
+ // absent CommonJS entry: a `.cjs` dependency can call the function
+ // while the recorder cannot wrap it.
+ covered = false;
+ }
+ }
+ return {
+ covered,
+ undo() {
+ for (const restore of undo.reverse()) {
+ try {
+ restore();
+ } catch {
+ /* best effort */
+ }
+ }
+ },
+ };
+ },
+ };
+}
diff --git a/packages/cli/api/theme/build/font-warning.mjs b/packages/cli/api/theme/build/font-warning.mjs
index afbf0894b4..1e3948f2d1 100644
--- a/packages/cli/api/theme/build/font-warning.mjs
+++ b/packages/cli/api/theme/build/font-warning.mjs
@@ -8,15 +8,16 @@
* fallback typeface on every machine whose app never loads it, and no step
* says so. These helpers close that gap at build time.
*
- * `collectUnloadedFonts` inspects a RESOLVED theme (raw typography configs
- * are already collapsed into `--font-family-*` tokens by the time the build
- * sees the theme, so tokens + component-override `fontFamily` values are the
- * complete font surface on both load paths) and returns the families that
+ * `collectUnloadedFonts` inspects a resolved theme or serialized adaptation
+ * value. Resolved values use `--font-family-*` tokens and component
+ * `fontFamily` properties; serialized adaptation values may also retain their
+ * typography role configs. It returns the families that
* are neither CSS generics nor known preinstalled system fonts. Unrecognized
* names are assumed to be webfonts on purpose: a missed warning hides the
* bug, a spurious one costs a glance.
*
- * @input A resolved theme object ({tokens, components}) from build.mjs.
+ * @input A resolved theme or serialized adaptation value ({tokens, components,
+ * typography}).
* @output Ordered, case-insensitively deduped family names, and the human
* help snippet (<link> pair + @font-face) printed after the install
* instructions.
@@ -132,7 +133,7 @@ function splitFamilies(value) {
* minus generics, CSS-wide keywords, `var()` references, and known system
* families. Source order, first-seen casing, deduped case-insensitively.
*
- * @param {{tokens?: Record<string, string>, components?: object}} resolvedTheme
+ * @param {{tokens?: Record<string, string>, components?: object, typography?: {body?: {family?: string, fallbacks?: string}, heading?: {family?: string, fallbacks?: string}, code?: {family?: string, fallbacks?: string}}}} resolvedTheme
* @returns {string[]}
*/
export function collectUnloadedFonts(resolvedTheme) {
@@ -156,6 +157,25 @@ export function collectUnloadedFonts(resolvedTheme) {
if (token.startsWith('--font-family-')) consider(value);
}
+ // Built modules retain normalized adaptation intent instead of resolved rule
+ // layers. Those rule values still carry authored role families here. A
+ // fallback without a family is inert in core's buildFontFamily().
+ const body = resolvedTheme?.typography?.body;
+ if (body?.family) {
+ consider(body.family);
+ consider(body.fallbacks);
+ }
+ const heading = resolvedTheme?.typography?.heading;
+ if (heading?.family) {
+ consider(heading.family);
+ consider(heading.fallbacks);
+ }
+ const code = resolvedTheme?.typography?.code;
+ if (code?.family) {
+ consider(code.family);
+ consider(code.fallbacks);
+ }
+
// Component overrides are plain CSS maps of unknown depth (style keys,
// nested at-rule blocks) — walk them and pick up every fontFamily.
/** @param {unknown} node */
diff --git a/packages/cli/api/theme/build/font-warning.test.mjs b/packages/cli/api/theme/build/font-warning.test.mjs
index 280fcef9b6..424004f5a0 100644
--- a/packages/cli/api/theme/build/font-warning.test.mjs
+++ b/packages/cli/api/theme/build/font-warning.test.mjs
@@ -118,6 +118,28 @@ describe('collectUnloadedFonts', () => {
).toEqual(['Orbitron', 'Bungee']);
});
+ it('collects families from serialized adaptation typography', () => {
+ expect(
+ collectUnloadedFonts({
+ typography: {
+ body: {family: 'Revision Webfont', fallbacks: 'sans-serif'},
+ heading: {family: 'Display Face', fallbacks: 'Georgia, serif'},
+ },
+ }),
+ ).toEqual(['Revision Webfont', 'Display Face']);
+ });
+
+ it('ignores serialized fallbacks that have no family', () => {
+ expect(
+ collectUnloadedFonts({
+ typography: {
+ body: {fallbacks: 'Phantom Serif'},
+ heading: {family: 'Display Face', fallbacks: 'Georgia, serif'},
+ },
+ }),
+ ).toEqual(['Display Face']);
+ });
+
it('matches known system families case-insensitively', () => {
expect(
collectUnloadedFonts({
diff --git a/packages/cli/api/theme/themeBuild.doc.mjs b/packages/cli/api/theme/themeBuild.doc.mjs
index e5adec2fe2..354ab1c975 100644
--- a/packages/cli/api/theme/themeBuild.doc.mjs
+++ b/packages/cli/api/theme/themeBuild.doc.mjs
@@ -96,6 +96,10 @@ export const doc = {
code: 'ERR_CORE_NOT_FOUND',
when: '@astryxdesign/core/theme cannot be imported; a built, resolvable @astryxdesign/core is required',
},
+ {
+ code: 'ERR_CORE_INCOMPATIBLE',
+ when: 'the selected theme carries ordered-adaptation intent but the installed @astryxdesign/core does not export generateAdaptationCSS (upgrade core)',
+ },
{
code: 'ERR_WRITE_FAILED',
when: 'writing the outputs fails (staged temp files are rolled back)',
diff --git a/packages/cli/assets/docs/theme.doc.dense.mjs b/packages/cli/assets/docs/theme.doc.dense.mjs
index 7a2f83a0c1..4aef03af86 100644
--- a/packages/cli/assets/docs/theme.doc.dense.mjs
+++ b/packages/cli/assets/docs/theme.doc.dense.mjs
@@ -5,17 +5,154 @@
export const docsDense = {
description: 'Theme provider, custom themes, light/dark, component overrides',
sections: [
- { section: 'Quick Start', title: 'Quick Start', content: [null, null, null, null, { type: 'prose', text: 'default import = runtime injection. /built import = pre-compiled CSS (pair with theme.css).' }] },
- { section: 'Available Themes', title: 'Themes', content: [null, null, { type: 'prose', text: 'published: neutral (start here), butter, chocolate, gothic (dark-only), matcha, stone, y2k. @astryxdesign/theme-{name} = source (runtime). @astryxdesign/theme-{name}/built = optimized (+ theme.css).' }] },
- { section: 'Theme Props', title: 'Props', content: [null] },
- { section: 'Creating a Custom Theme', title: 'Custom Theme', content: [{ type: 'prose', text: '`theme list` + `theme add <slug>` to start from a shipped theme, or defineTheme from scratch. only override tokens that differ.' }, null, { type: 'prose', text: '`astryx theme template` writes theme.template.ts: every defineTheme field + token families + override syntax, annotated, with the CLI command that prints each reference.' }] },
- { section: 'defineTheme', title: 'defineTheme', content: [{ type: 'prose', text: 'scale configs (color, typography, radius, motion) + explicit token overrides + component overrides. color derives full palette from accent via HCT; accent = hex or [light, dark] tuple (per-scheme palettes). tokens overrides win token-by-token; --color-on-accent stays baked from color.accent, so prefer a tuple accent over overriding --color-accent.' }, null, null] },
- { section: 'Component Style Overrides', title: 'Component Overrides', content: [{ type: 'prose', text: 'components field uses semantic component keys + style keys (base, variant:value, stateName), not raw selectors. for external CSS, prefer data-* selectors from `astryx docs styling`. write standard CSS (borderRadius, padding) — pipeline expands to internal vars. public vars (--button-focus-offset etc) set directly. private vars (--_*) cannot be set — use CSS properties. run `astryx theme targets [Name]` to enumerate every themeable key (--json for lint), `astryx component <Name>` for one component.' }, null, null, null, null] },
- { section: 'Custom Variants', title: 'Custom Variants', content: [{ type: 'prose', text: 'any unknown prop:value in components becomes a new variant. astryx theme build generates TS augmentations. works on any extensible prop axis (variant, status, etc).' }, null, null, null, null] },
- { section: 'Building Themes for Production', title: 'Build for Production', content: [{ type: 'prose', text: 'astryx theme build compiles defineTheme to static CSS. outputs .css + .js (__built:true) + .d.ts.' }, null, null, null, null] },
- { section: 'Runtime vs Built Themes', title: 'Runtime vs Built', content: [{ type: 'prose', text: 'runtime: useInsertionEffect injects styles client-side. built: static CSS on first paint. USE /built + theme.css FOR SSR.' }, null, null, null] },
- { section: 'Light/Dark Mode', title: 'Light/Dark', content: [{ type: 'prose', text: 'light-dark() in token values via [light, dark] tuples. mode=system follows OS.' }, null, null] },
- { section: 'Nesting Themes', title: 'Nesting', content: [{ type: 'prose', text: 'wrap sections in separate <Theme> providers' }, null] },
- { section: 'useTheme Hook', title: 'useTheme', content: [null, { type: 'prose', text: 'read-only. manage state at app level.' }] },
+ {
+ section: 'Quick Start',
+ title: 'Quick Start',
+ content: [
+ null,
+ null,
+ null,
+ null,
+ {
+ type: 'prose',
+ text: 'default import = runtime injection. /built import = pre-compiled CSS (pair with theme.css).',
+ },
+ ],
+ },
+ {
+ section: 'Available Themes',
+ title: 'Themes',
+ content: [
+ null,
+ null,
+ {
+ type: 'prose',
+ text: 'published: neutral (start here), butter, chocolate, gothic (dark-only), matcha, stone, y2k. @astryxdesign/theme-{name} = source (runtime). @astryxdesign/theme-{name}/built = optimized (+ theme.css).',
+ },
+ ],
+ },
+ {section: 'Theme Props', title: 'Props', content: [null]},
+ {
+ section: 'Creating a Custom Theme',
+ title: 'Custom Theme',
+ content: [
+ {
+ type: 'prose',
+ text: '`theme list` + `theme add <slug>` to start from a shipped theme, or defineTheme from scratch. only override tokens that differ.',
+ },
+ null,
+ {
+ type: 'prose',
+ text: '`astryx theme template` writes theme.template.ts: every defineTheme field + token families + override syntax, annotated, with the CLI command that prints each reference.',
+ },
+ ],
+ },
+ {
+ section: 'defineTheme',
+ title: 'defineTheme',
+ content: [
+ {
+ type: 'prose',
+ text: 'scale configs (color, typography, radius, motion) + explicit token overrides + component overrides. color derives full palette from accent via HCT; accent = hex or [light, dark] tuple (per-scheme palettes). tokens overrides win token-by-token; --color-on-accent stays baked from color.accent, so prefer a tuple accent over overriding --color-accent.',
+ },
+ null,
+ null,
+ ],
+ },
+ {
+ section: 'Theme Adaptations',
+ title: 'Adaptations',
+ content: [
+ {
+ type: 'prose',
+ text: 'adaptations = ordered {when,value} rules over width/pointer/contrast/motion. widthBreakpoints fixed sm|md|lg|xl|2xl defaults 640|768|1024|1280|1536; map alone emits no CSS. width.from inclusive, width.below exclusive; condition fields AND. root first, then matching rules in authored order (later writes win), then onDark/onLight. rules can write typography/color/radius/motion/tokens/localTokens/components; local names belong on root. Component writes validate exactly like root components (same targets/axes/domains); only difference: a rule cannot be the sole enroller of a custom value (type augmentation is unconditional) — declare it on root, then restyle. Built-ins need no root declaration. Co-matching token/localToken writes are validated together; any reachable var() cycle fails. extends inherits breakpoints + ordered rules, appends child rules, re-resolves against child axes. CSS-only; use built themes for SSR first paint.',
+ },
+ null,
+ null,
+ ],
+ },
+ {
+ section: 'Component Style Overrides',
+ title: 'Component Overrides',
+ content: [
+ {
+ type: 'prose',
+ text: 'components field uses semantic component keys + style keys (base, variant:value, stateName), not raw selectors. for external CSS, prefer data-* selectors from `astryx docs styling`. write standard CSS (borderRadius, padding) — pipeline expands to internal vars. public vars (--button-focus-offset etc) set directly. private vars (--_*) cannot be set — use CSS properties. run `astryx theme targets [Name]` to enumerate every themeable key (--json for lint), `astryx component <Name>` for one component.',
+ },
+ null,
+ null,
+ null,
+ null,
+ ],
+ },
+ {
+ section: 'Custom Variants',
+ title: 'Custom Variants',
+ content: [
+ {
+ type: 'prose',
+ text: 'any unknown prop:value in components becomes a new variant. astryx theme build generates TS augmentations. works on any extensible prop axis (variant, status, etc).',
+ },
+ null,
+ null,
+ null,
+ null,
+ ],
+ },
+ {
+ section: 'Building Themes for Production',
+ title: 'Build for Production',
+ content: [
+ {
+ type: 'prose',
+ text: 'astryx theme build compiles defineTheme to static CSS. outputs .css + .js (__built:true) + .d.ts.',
+ },
+ null,
+ null,
+ null,
+ null,
+ ],
+ },
+ {
+ section: 'Runtime vs Built Themes',
+ title: 'Runtime vs Built',
+ content: [
+ {
+ type: 'prose',
+ text: 'runtime: useInsertionEffect injects styles client-side. built: static CSS on first paint. USE /built + theme.css FOR SSR.',
+ },
+ null,
+ null,
+ null,
+ ],
+ },
+ {
+ section: 'Light/Dark Mode',
+ title: 'Light/Dark',
+ content: [
+ {
+ type: 'prose',
+ text: 'light-dark() in token values via [light, dark] tuples. mode=system follows OS.',
+ },
+ null,
+ null,
+ ],
+ },
+ {
+ section: 'Nesting Themes',
+ title: 'Nesting',
+ content: [
+ {type: 'prose', text: 'wrap sections in separate <Theme> providers'},
+ null,
+ ],
+ },
+ {
+ section: 'useTheme Hook',
+ title: 'useTheme',
+ content: [
+ null,
+ {type: 'prose', text: 'read-only. manage state at app level.'},
+ ],
+ },
],
};
diff --git a/packages/cli/assets/docs/theme.doc.mjs b/packages/cli/assets/docs/theme.doc.mjs
index e964534765..62be7d16f6 100644
--- a/packages/cli/assets/docs/theme.doc.mjs
+++ b/packages/cli/assets/docs/theme.doc.mjs
@@ -12,7 +12,7 @@ export const docs = {
sections: [
{
title: 'Quick Start',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'code',
@@ -63,7 +63,7 @@ function App() {
},
{
title: 'Available Themes',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -118,7 +118,7 @@ function App() {
},
{
title: 'Theme Props',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'table',
@@ -138,7 +138,7 @@ function App() {
},
{
title: 'Creating a Custom Theme',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -158,7 +158,7 @@ function App() {
},
{
title: 'defineTheme',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -231,7 +231,7 @@ const myTheme = defineTheme({
},
{
title: 'Extending a Theme',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -258,23 +258,126 @@ const brandTheme = defineTheme({
type: 'table',
headers: ['Field', 'Merge behavior'],
rows: [
- ['tokens', 'Base tokens are copied first, then child tokens override on top.'],
- ['components', 'Deep-merged: child component rules override matching keys from the base.'],
- ['icons', 'Shallow-merged: child icons override matching names from the base.'],
- ['indicators', 'Shallow-merged: child indicators override matching names from the base.'],
- ['onDark, onLight', "Deep-merged per surface: the base's resolved surface first, then the child's overrides."],
- ['typography, motion, radius, color', 'Child config replaces base entirely (these are scale inputs, not additive).'],
+ [
+ 'tokens',
+ 'Base tokens are copied first, then child tokens override on top.',
+ ],
+ [
+ 'components',
+ 'Deep-merged: child component rules override matching keys from the base.',
+ ],
+ [
+ 'icons',
+ 'Shallow-merged: child icons override matching names from the base.',
+ ],
+ [
+ 'indicators',
+ 'Shallow-merged: child indicators override matching names from the base.',
+ ],
+ [
+ 'onDark, onLight',
+ "Deep-merged per surface: the base's resolved surface first, then the child's overrides.",
+ ],
+ [
+ 'typography, motion, radius, color',
+ 'Child config replaces base entirely (these are scale inputs, not additive).',
+ ],
+ [
+ 'adaptations',
+ 'Width-breakpoint overrides merge by fixed name. Inherited ordered rules keep their relative order; child rules append and re-resolve against the child root axes.',
+ ],
],
},
{
type: 'prose',
- text: 'Inheritance is resolved when the theme is defined, so an extended theme is flat: `astryx theme build` emits one self-contained stylesheet holding everything the child inherited, and the base theme\'s CSS does not need to be loaded next to it. A base that is not a theme (most often an import that missed) is a build error rather than a theme that silently inherits nothing.',
+ text: "Inheritance is resolved when the theme is defined, so an extended theme is flat: `astryx theme build` emits one self-contained stylesheet holding everything the child inherited, and the base theme's CSS does not need to be loaded next to it. A base that is not a theme (most often an import that missed) is a build error rather than a theme that silently inherits nothing.",
+ },
+ ],
+ },
+ {
+ title: 'Theme Adaptations',
+ category: 'guide',
+ content: [
+ {
+ type: 'prose',
+ text: 'Use `adaptations` for opt-in token, theme-local token, and component changes under viewport width, primary-pointer precision, contrast preference, or motion preference. Conditions in one `when` are ANDed. Rules are ordinary ordered objects, and later matching writes win.',
+ },
+ {
+ type: 'code',
+ lang: 'tsx',
+ label: 'Width and pointer adaptations',
+ code: `const acmeTheme = defineTheme({
+ name: 'acme',
+ adaptations: {
+ widthBreakpoints: {
+ sm: 640,
+ md: 768,
+ lg: 1024,
+ xl: 1280,
+ '2xl': 1536,
+ },
+ rules: [
+ {
+ when: {width: {below: 'md'}},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ tokens: {
+ '--size-element-sm': '36px',
+ '--size-element-md': '40px',
+ '--size-element-lg': '44px',
+ },
+ },
+ },
+ {
+ when: {
+ width: {from: 'lg', below: 'xl'},
+ pointer: 'coarse',
+ contrast: 'more',
+ },
+ value: {components: {card: {base: {borderWidth: '2px'}}}},
+ },
+ ],
+ },
+});`,
+ },
+ {
+ type: 'table',
+ headers: ['Condition', 'Values'],
+ rows: [
+ ['width.from / width.below', 'sm | md | lg | xl | 2xl'],
+ ['pointer', 'coarse | fine'],
+ ['contrast', 'more | less | no-preference'],
+ ['motion', 'reduce | no-preference'],
+ ],
+ },
+ {
+ type: 'prose',
+ text: '`widthBreakpoints` are fixed named start points. Defaults are 640 / 768 / 1024 / 1280 / 1536 CSS pixels. `from` includes its point; `below` excludes it. Breakpoint configuration alone emits no CSS.',
+ },
+ {
+ type: 'prose',
+ text: '**Precedence follows rule order.** Root theme values apply first, then every matching rule in declaration order. A later rule may deliberately restore a root value. `onDark` and `onLight` media-surface overrides apply after adaptations and win on the same leaf.',
+ },
+ {
+ type: 'prose',
+ text: "`extends` preserves the base rule order and appends child rules. Inherited conditions use the child's effective breakpoint map, and partial generative axes complete from the child root metadata. An empty child rule is a no-op, not a removal operator.",
+ },
+ {
+ type: 'prose',
+ text: 'A rule may replace a theme-local token only when the exact name is already enrolled by root `localTokens` or an enrolled base. Component writes in a rule are validated exactly like root `components` — same targets, axes, and value domains. The one addition is that a rule may not be the only place a custom value is enrolled: a value that is valid only because a theme enrolls it generates unconditional type augmentation, so declare it on the root theme first and let rules restyle it. Built-in values need no root declaration. When rules can match together, their ordered portable and local token writes are validated as one effective graph; any reachable cycle fails before CSS is emitted.',
+ },
+ {
+ type: 'prose',
+ text: 'Adaptations compile to CSS media queries with no resize listener or styling rerender. Runtime and `astryx theme build` use the same compiler, but only a built theme is present at first paint in an SSR app.',
},
],
},
{
title: 'Component Style Overrides',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -307,7 +410,7 @@ const brandTheme = defineTheme({
},
{
type: 'prose',
- text: 'Run `astryx theme targets` for every themeable key in the system (`astryx theme targets <Name>` to scope it, `--json` to lint a theme against it), and `astryx component <Name>` for one component\'s theming targets, public CSS variables, and which standard CSS properties are supported.',
+ text: "Run `astryx theme targets` for every themeable key in the system (`astryx theme targets <Name>` to scope it, `--json` to lint a theme against it), and `astryx component <Name>` for one component's theming targets, public CSS variables, and which standard CSS properties are supported.",
},
{
type: 'list',
@@ -328,11 +431,11 @@ const brandTheme = defineTheme({
},
{
title: 'Custom Variants',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
- text: 'Themes can add new prop values to any component. Any `prop:value` key where the value isn\'t a built-in gets treated as a new variant. Use `astryx theme build` to generate TypeScript augmentations for type safety.',
+ text: "Themes can add new prop values to any component. Any `prop:value` key where the value isn't a built-in gets treated as a new variant. Use `astryx theme build` to generate TypeScript augmentations for type safety.",
},
{
type: 'code',
@@ -371,13 +474,13 @@ const brandTheme = defineTheme({
},
{
type: 'prose',
- text: 'Custom variants only work when the theme that defines them is active. The component\'s variant map is extended via module augmentation, with no changes to the component source needed.',
+ text: "Custom variants only work when the theme that defines them is active. The component's variant map is extended via module augmentation, with no changes to the component source needed.",
},
],
},
{
title: 'Building Themes for Production',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -411,7 +514,7 @@ const brandTheme = defineTheme({
],
[
'ocean.variants.d.ts',
- '(Optional) Module augmentations for custom component prop values found in the theme\'s component overrides',
+ "(Optional) Module augmentations for custom component prop values found in the theme's component overrides",
],
],
},
@@ -432,13 +535,13 @@ import './themes/ocean.css';
},
{
type: 'prose',
- text: 'The build also warns when the theme names font families it does not load (webfonts like Fraunces) and prints the `<link>`/`@font-face` to add. The built CSS only sets font-family, so loading the font files stays the app\'s job. See `astryx docs typography` for the full recipe.',
+ text: "The build also warns when the theme names font families it does not load (webfonts like Fraunces) and prints the `<link>`/`@font-face` to add. The built CSS only sets font-family, so loading the font files stays the app's job. See `astryx docs typography` for the full recipe.",
},
],
},
{
title: 'Runtime vs Built Themes',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -450,13 +553,13 @@ import './themes/ocean.css';
rows: [
[
'Import (published theme)',
- "@astryxdesign/theme-{name}",
- "@astryxdesign/theme-{name}/built + theme.css",
+ '@astryxdesign/theme-{name}',
+ '@astryxdesign/theme-{name}/built + theme.css',
],
[
'Import (custom theme)',
'defineTheme() directly',
- "Built .js + .css from `astryx theme build`",
+ 'Built .js + .css from `astryx theme build`',
],
[
'How it works',
@@ -494,14 +597,14 @@ import './themes/ocean.css';
style: 'dont',
items: [
'Use runtime themes in production SSR apps; component overrides will flash on hydration.',
- 'Import /built without the CSS file; component overrides won\'t apply.',
+ "Import /built without the CSS file; component overrides won't apply.",
],
},
],
},
{
title: 'Light/Dark Mode',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -530,7 +633,7 @@ import './themes/ocean.css';
},
{
title: 'Nesting Themes',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -556,7 +659,7 @@ import './themes/ocean.css';
},
{
title: 'Token Utilities',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
@@ -599,7 +702,7 @@ const chartTheme = {
},
{
title: 'useTheme Hook',
- category: 'guide',
+ category: 'guide',
content: [
{
type: 'prose',
diff --git a/packages/cli/assets/theme.template.ts b/packages/cli/assets/theme.template.ts
index 4215ef4c17..03b9b40ba7 100644
--- a/packages/cli/assets/theme.template.ts
+++ b/packages/cli/assets/theme.template.ts
@@ -327,4 +327,61 @@ export const myTheme = defineTheme({
*/
// onDark: {tokens: {'--color-accent': '#90CAF9'}, components: {button: {'variant:ghost': {borderWidth: '1px'}}}},
// onLight: {tokens: {'--color-accent': '#0B5FCC'}},
+
+ // ───────────────────────────────────────────────────────────────────────
+ // Theme adaptations
+ // ───────────────────────────────────────────────────────────────────────
+
+ /**
+ * Opt-in values for reviewed environmental conditions. Width points use the
+ * fixed names `sm`, `md`, `lg`, `xl`, and `2xl`; overriding the map alone
+ * emits no CSS. Fields inside `when` are ANDed, and matching rules cascade in
+ * authored order so later writes win.
+ *
+ * `from` includes its point; `below` excludes it. The other supported axes
+ * are primary-pointer precision, contrast preference, and motion preference.
+ * Component writes in a rule are validated exactly like root `components`.
+ * The one addition: a custom value that is valid only because a theme
+ * enrolls it must be declared at the root first, since generated type
+ * augmentation is unconditional; a rule may then restyle it.
+ */
+ // Adaptations are opt-in. Uncomment and edit the example below when the
+ // theme needs environmental values.
+ // adaptations: {
+ // widthBreakpoints: {
+ // sm: 640,
+ // md: 768,
+ // lg: 1024,
+ // xl: 1280,
+ // '2xl': 1536,
+ // },
+ // rules: [
+ // {
+ // // Narrow at every pointer precision.
+ // when: {width: {below: 'md'}},
+ // value: {tokens: {'--spacing-4': '12px'}},
+ // },
+ // {
+ // // Taller controls under a finger or stylus at every width.
+ // when: {pointer: 'coarse'},
+ // value: {
+ // tokens: {
+ // '--size-element-sm': '36px',
+ // '--size-element-md': '40px',
+ // '--size-element-lg': '44px',
+ // },
+ // },
+ // },
+ // // Combined conditions are peers, not nested syntax:
+ // // {
+ // // when: {
+ // // width: {from: 'lg', below: 'xl'},
+ // // pointer: 'coarse',
+ // // contrast: 'more',
+ // // motion: 'reduce',
+ // // },
+ // // value: {components: {card: {base: {borderWidth: '2px'}}}},
+ // // },
+ // ],
+ // },
});
diff --git a/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs b/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs
new file mode 100644
index 0000000000..5f16d5f21b
--- /dev/null
+++ b/packages/cli/clients/cli/commands/build-theme.adaptations.test.mjs
@@ -0,0 +1,560 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file Ensures `astryx theme build` preserves AST-012 adaptation semantics.
+ * Runtime and static output share core's compiler; this suite guards the CLI
+ * loading, diagnostics, serialization, and extension boundaries around it.
+ */
+
+import {afterEach, beforeAll, beforeEach, describe, expect, it} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {pathToFileURL} from 'node:url';
+import {ensureCoreBuilt} from './ensure-core-built.mjs';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+function writeTheme(dir, name, inputSource) {
+ fs.mkdirSync(dir, {recursive: true});
+ const file = path.join(dir, `${name}.mjs`);
+ fs.writeFileSync(
+ file,
+ `import {defineTheme} from '@astryxdesign/core/theme';\n` +
+ `export default defineTheme(${inputSource});\n`,
+ );
+ return file;
+}
+
+function writePlainTheme(dir, name, inputSource) {
+ fs.mkdirSync(dir, {recursive: true});
+ const file = path.join(dir, `${name}.mjs`);
+ fs.writeFileSync(file, `export default ${inputSource};\n`);
+ return file;
+}
+
+async function build(project, themeFile) {
+ return runCli(['theme', 'build', path.relative(project, themeFile)], project);
+}
+
+beforeAll(() => {
+ ensureCoreBuilt();
+}, 200_000);
+
+let tmpDir;
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(
+ path.join(os.tmpdir(), 'astryx-build-theme-adaptations-'),
+ );
+});
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+describe('theme build adaptations', () => {
+ it('emits ordered closed conditions after root values', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(
+ themesDir,
+ 'ordered',
+ `{
+ name: 'ordered',
+ tokens: {'--spacing-4': '16px'},
+ adaptations: {
+ widthBreakpoints: {md: 800, lg: 1100},
+ rules: [
+ {
+ when: {width: {from: 'md', below: 'lg'}, pointer: 'coarse'},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ {
+ when: {contrast: 'more', motion: 'reduce'},
+ value: {tokens: {'--spacing-4': '20px'}},
+ },
+ ],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).toBe(0);
+
+ const css = fs.readFileSync(path.join(themesDir, 'ordered.css'), 'utf-8');
+ expect(css).toContain(
+ '@media (width >= 800px) and (width < 1100px) and (pointer: coarse)',
+ );
+ expect(css).toContain(
+ '@media (prefers-contrast: more) and (prefers-reduced-motion: reduce)',
+ );
+ expect(css.indexOf('--spacing-4: 16px')).toBeLessThan(
+ css.indexOf('--spacing-4: 12px'),
+ );
+ expect(css.indexOf('--spacing-4: 12px')).toBeLessThan(
+ css.indexOf('--spacing-4: 20px'),
+ );
+ });
+
+ it('resolves a plain object whose only input-only field is adaptations', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writePlainTheme(
+ themesDir,
+ 'plain-adaptive',
+ `{
+ name: 'plain-adaptive',
+ adaptations: {
+ rules: [{
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--color-accent': ['#111111', '#eeeeee']}},
+ }],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).toBe(0);
+
+ const css = fs.readFileSync(
+ path.join(themesDir, 'plain-adaptive.css'),
+ 'utf-8',
+ );
+ expect(css).toContain('@media (pointer: coarse)');
+ expect(css).toContain('light-dark(#111111, #eeeeee)');
+ expect(css).not.toContain('#111111,#eeeeee');
+ });
+
+ it('emits the color-scheme guard for a tuple declared only in a rule', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(
+ themesDir,
+ 'rule-tuple',
+ `{
+ name: 'rule-tuple',
+ adaptations: {
+ rules: [{
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--color-accent': ['#0077B6', '#48CAE4']}},
+ }],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).toBe(0);
+
+ const css = fs.readFileSync(
+ path.join(themesDir, 'rule-tuple.css'),
+ 'utf-8',
+ );
+ expect(css).toContain(':root { color-scheme: light dark; }');
+ expect(css).toContain('html[data-theme="light"] { color-scheme: light; }');
+ expect(css).toContain('html[data-theme="dark"] { color-scheme: dark; }');
+ });
+
+ it('keeps media-surface overrides after adaptation rules', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(
+ themesDir,
+ 'surface-order',
+ `{
+ name: 'surface-order',
+ tokens: {'--color-background-body': '#ffffff'},
+ adaptations: {
+ rules: [{
+ when: {contrast: 'more'},
+ value: {tokens: {'--color-background-body': '#eeeeee'}},
+ }],
+ },
+ onDark: {tokens: {'--color-background-body': '#111111'}},
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).toBe(0);
+
+ const css = fs.readFileSync(
+ path.join(themesDir, 'surface-order.css'),
+ 'utf-8',
+ );
+ expect(css.indexOf('#eeeeee')).toBeLessThan(css.lastIndexOf('#111111'));
+ expect(css.lastIndexOf('[data-astryx-media="dark"]')).toBeGreaterThan(
+ css.indexOf('@media (prefers-contrast: more)'),
+ );
+ });
+
+ it('serializes normalized intent and axes, not resolved rule CSS', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(
+ themesDir,
+ 'built-base',
+ `{
+ name: 'built-base',
+ typography: {scale: {base: 14, ratio: 1.25}},
+ adaptations: {
+ widthBreakpoints: {sm: 700},
+ rules: [{
+ when: {width: {below: 'sm'}},
+ value: {
+ typography: {
+ scale: {base: 16},
+ body: {family: 'Revision Webfont'},
+ },
+ tokens: {'--color-accent': ['#111111', '#eeeeee']},
+ },
+ }],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).toBe(0);
+
+ const jsPath = path.join(themesDir, 'built-base.js');
+ const js = fs.readFileSync(jsPath, 'utf-8');
+ expect(js).toContain('__adaptations');
+ expect(js).toContain('__axes');
+ expect(js).not.toContain('__adaptationRules');
+ expect(js).not.toContain('@media');
+ expect(
+ Buffer.byteLength(js.slice(js.indexOf('__adaptations'))),
+ ).toBeLessThan(1_500);
+
+ const {builtBaseTheme} = await import(
+ `${pathToFileURL(jsPath).href}?test=${Date.now()}`
+ );
+ const {defineTheme} = await import('@astryxdesign/core/theme');
+ const child = defineTheme({
+ name: 'built-child',
+ extends: builtBaseTheme,
+ adaptations: {widthBreakpoints: {sm: 720}},
+ });
+ expect(child.__adaptationRules?.[0].query).toBe('(width < 720px)');
+ expect(child.__adaptationRules?.[0].tokens['--font-size-lg']).toBe(
+ '1.25rem',
+ );
+
+ const rebuildDir = path.join(project, 'rebuild');
+ fs.mkdirSync(rebuildDir, {recursive: true});
+ const rebuiltInput = path.join(rebuildDir, 'rebuilt.mjs');
+ fs.writeFileSync(
+ rebuiltInput,
+ `export {builtBaseTheme as default} from '../themes/built-base.js';\n`,
+ );
+ const rebuilt = await build(project, rebuiltInput);
+ expect(rebuilt.code).toBe(0);
+ const rebuiltCss = fs.readFileSync(
+ path.join(rebuildDir, 'built-base.css'),
+ 'utf-8',
+ );
+ expect(rebuiltCss).toContain('@media (width < 700px)');
+ expect(rebuiltCss).toContain('--font-size-lg: 1.25rem');
+ expect(rebuiltCss).toContain('light-dark(#111111, #eeeeee)');
+ expect(rebuiltCss).toContain(':root { color-scheme: light dark; }');
+ expect(`${rebuilt.stdout}${rebuilt.stderr}`).toContain(
+ 'Font "Revision Webfont" is named by this theme but not loaded',
+ );
+ });
+
+ it('retains the effective width map even when no rules emit CSS', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(
+ themesDir,
+ 'points-only',
+ `{
+ name: 'points-only',
+ tokens: {'--spacing-4': '18px'},
+ adaptations: {widthBreakpoints: {xl: 1400}},
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).toBe(0);
+
+ const css = fs.readFileSync(
+ path.join(themesDir, 'points-only.css'),
+ 'utf-8',
+ );
+ const js = fs.readFileSync(path.join(themesDir, 'points-only.js'), 'utf-8');
+ expect(css).not.toContain('@media');
+ expect(js).toMatch(/"xl": 1400/);
+ expect(js).toContain('__adaptations');
+ });
+
+ it('allows an existing built-in visual value inside a rule', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(
+ themesDir,
+ 'builtin-variant',
+ `{
+ name: 'builtin-variant',
+ adaptations: {
+ rules: [{
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ button: {'variant:secondary': {borderWidth: '3px'}},
+ heading: {'level:1': {letterSpacing: '-0.01em'}},
+ },
+ },
+ }],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).toBe(0);
+ const css = fs.readFileSync(
+ path.join(themesDir, 'builtin-variant.css'),
+ 'utf-8',
+ );
+ expect(css).toContain('border-width: 3px');
+ expect(css).toContain('letter-spacing: -0.01em');
+ });
+
+ it('warns rather than hard-failing unknown rule targets and axes', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(
+ themesDir,
+ 'unknown-rule-axis',
+ `{
+ name: 'unknown-rule-axis',
+ adaptations: {
+ rules: [{
+ when: {pointer: 'coarse'},
+ value: {
+ components: {table: {'density:compact': {borderWidth: '3px'}}},
+ },
+ }],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).toBe(0);
+ expect(`${result.stdout}${result.stderr}`).toContain(
+ 'Unknown prop "density" on component "table"',
+ );
+ expect(
+ fs.readFileSync(path.join(themesDir, 'unknown-rule-axis.css'), 'utf-8'),
+ ).toContain('border-width: 3px');
+ });
+
+ it('rejects a rule that is the only place a custom value is enrolled', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const badFile = writeTheme(
+ themesDir,
+ 'rule-only-variant',
+ `{
+ name: 'rule-only-variant',
+ adaptations: {
+ rules: [{
+ when: {pointer: 'coarse'},
+ value: {
+ components: {button: {'variant:brandy': {borderWidth: '3px'}}},
+ },
+ }],
+ },
+ }`,
+ );
+
+ const bad = await build(project, badFile);
+ expect(bad.code).not.toBe(0);
+ expect(`${bad.stdout}${bad.stderr}`).toContain(
+ 'enrolls the custom value "button.variant:brandy"',
+ );
+ expect(fs.existsSync(path.join(themesDir, 'rule-only-variant.css'))).toBe(
+ false,
+ );
+
+ const goodFile = writeTheme(
+ themesDir,
+ 'root-variant',
+ `{
+ name: 'root-variant',
+ components: {button: {'variant:brandy': {borderWidth: '1px'}}},
+ adaptations: {
+ rules: [{
+ when: {pointer: 'coarse'},
+ value: {
+ components: {button: {'variant:brandy': {borderWidth: '3px'}}},
+ },
+ }],
+ },
+ }`,
+ );
+
+ const good = await build(project, goodFile);
+ expect(good.code).toBe(0);
+ expect(
+ fs.readFileSync(
+ path.join(themesDir, 'root-variant.variants.d.ts'),
+ 'utf-8',
+ ),
+ ).toContain('brandy');
+ });
+
+ it('validates private variables declared only in a rule', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writeTheme(
+ themesDir,
+ 'rule-private',
+ `{
+ name: 'rule-private',
+ adaptations: {
+ rules: [{
+ when: {pointer: 'coarse'},
+ value: {
+ components: {button: {base: {'--_button-pad': '3px'}}},
+ },
+ }],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(`${result.stdout}${result.stderr}`).toContain('private var');
+ });
+
+ it('rejects cycles across co-matching rules before writing output', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const a = '--astryx-theme-overlap-build-a';
+ const b = '--astryx-theme-overlap-build-b';
+ const themeFile = writePlainTheme(
+ themesDir,
+ 'overlap-build',
+ `{
+ name: 'overlap-build',
+ localTokens: {'${a}': '1px', '${b}': '2px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {'${a}': 'var(${b})'}},
+ },
+ {
+ when: {contrast: 'more'},
+ value: {localTokens: {'${b}': 'var(${a})'}},
+ },
+ ],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).not.toBe(0);
+ expect(`${result.stdout}${result.stderr}`).toMatch(
+ /overlapping rules \[0, 1\].*cycle detected/i,
+ );
+ expect(fs.existsSync(path.join(themesDir, 'overlap-build.css'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(themesDir, 'overlap-build.js'))).toBe(false);
+ });
+
+ it('reports invalid serialized adaptation metadata as ERR_THEME_INVALID', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writePlainTheme(
+ themesDir,
+ 'stale-built',
+ `{
+ name: 'stale-built',
+ __built: true,
+ tokens: {'--spacing-4': '16px'},
+ __adaptations: {
+ widthBreakpoints: {
+ sm: 640, md: 768, lg: 1024, xl: 1280, '2xl': 1536,
+ },
+ rules: [{
+ when: {pointer: 'sideways'},
+ value: {tokens: {'--spacing-4': '12px'}},
+ }],
+ },
+ __axes: {},
+ }`,
+ );
+
+ const result = await runCli(
+ ['theme', 'build', path.relative(project, themeFile), '--json'],
+ project,
+ );
+ expect(result.code).not.toBe(0);
+ expect(`${result.stdout}${result.stderr}`).toContain('ERR_THEME_INVALID');
+ expect(`${result.stdout}${result.stderr}`).toContain(
+ "when.pointer must be 'coarse' or 'fine'",
+ );
+ expect(fs.existsSync(path.join(themesDir, 'stale-built.css'))).toBe(false);
+ });
+
+ it('rejects invalid serialized breakpoint metadata with no rules', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writePlainTheme(
+ themesDir,
+ 'stale-built-points',
+ `{
+ name: 'stale-built-points',
+ __built: true,
+ tokens: {'--spacing-4': '16px'},
+ __adaptations: {
+ widthBreakpoints: {
+ sm: 640, md: 768, lg: 700, xl: 1280, '2xl': 1536,
+ },
+ rules: [],
+ },
+ __axes: {},
+ }`,
+ );
+
+ const result = await runCli(
+ ['theme', 'build', path.relative(project, themeFile), '--json'],
+ project,
+ );
+ expect(result.code).not.toBe(0);
+ expect(`${result.stdout}${result.stderr}`).toContain('ERR_THEME_INVALID');
+ expect(`${result.stdout}${result.stderr}`).toContain('strictly increasing');
+ expect(fs.existsSync(path.join(themesDir, 'stale-built-points.css'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(themesDir, 'stale-built-points.js'))).toBe(
+ false,
+ );
+ });
+
+ it('rejects invalid metadata before writing any output', async () => {
+ const project = path.join(tmpDir, 'project');
+ const themesDir = path.join(project, 'themes');
+ const themeFile = writePlainTheme(
+ themesDir,
+ 'invalid-range',
+ `{
+ name: 'invalid-range',
+ adaptations: {
+ rules: [{
+ when: {width: {from: 'xl', below: 'md'}},
+ value: {tokens: {'--spacing-4': '12px'}},
+ }],
+ },
+ }`,
+ );
+
+ const result = await build(project, themeFile);
+ expect(result.code).not.toBe(0);
+ expect(`${result.stdout}${result.stderr}`).toContain(
+ 'must resolve to `from < below`',
+ );
+ expect(fs.existsSync(path.join(themesDir, 'invalid-range.css'))).toBe(
+ false,
+ );
+ expect(fs.existsSync(path.join(themesDir, 'invalid-range.js'))).toBe(false);
+ });
+});
diff --git a/packages/cli/foundation/response/error-codes.d.ts b/packages/cli/foundation/response/error-codes.d.ts
index f2aec8735e..4186e1d027 100644
--- a/packages/cli/foundation/response/error-codes.d.ts
+++ b/packages/cli/foundation/response/error-codes.d.ts
@@ -19,6 +19,7 @@ export type ErrorCode =
| 'ERR_INVALID_DETAIL'
| 'ERR_NODE_VERSION'
| 'ERR_CORE_NOT_FOUND'
+ | 'ERR_CORE_INCOMPATIBLE'
| 'ERR_UNKNOWN_COMPONENT'
| 'ERR_UNKNOWN_HOOK'
| 'ERR_UNKNOWN_TOPIC'
diff --git a/packages/cli/foundation/response/error-codes.doc.mjs b/packages/cli/foundation/response/error-codes.doc.mjs
index bad2557b12..bcf908c164 100644
--- a/packages/cli/foundation/response/error-codes.doc.mjs
+++ b/packages/cli/foundation/response/error-codes.doc.mjs
@@ -70,6 +70,11 @@ export const doc = {
description:
'`@astryxdesign/core` could not be located (not installed / not in a monorepo).',
},
+ {
+ value: 'ERR_CORE_INCOMPATIBLE',
+ description:
+ 'The installed `@astryxdesign/core` loaded but is too old for this input — it lacks a capability the CLI must call to emit correct output (upgrade core).',
+ },
// "Unknown <subject>" lookups
{
diff --git a/packages/cli/foundation/response/error-codes.mjs b/packages/cli/foundation/response/error-codes.mjs
index 8057ee55cf..aabdc614fc 100644
--- a/packages/cli/foundation/response/error-codes.mjs
+++ b/packages/cli/foundation/response/error-codes.mjs
@@ -46,6 +46,7 @@
* | 'ERR_INVALID_DETAIL'
* | 'ERR_NODE_VERSION'
* | 'ERR_CORE_NOT_FOUND'
+ * | 'ERR_CORE_INCOMPATIBLE'
* | 'ERR_UNKNOWN_COMPONENT'
* | 'ERR_UNKNOWN_HOOK'
* | 'ERR_UNKNOWN_TOPIC'
@@ -59,7 +60,7 @@
* | 'ERR_UNKNOWN_AGENT'
* | 'ERR_UNKNOWN_FEATURE'
* | 'ERR_UNKNOWN_CODEMOD'
- | 'ERR_CODEMOD_FAILED'
+ * | 'ERR_CODEMOD_FAILED'
* | 'ERR_NOT_FOUND'
* | 'ERR_NO_DOC'
* | 'ERR_NO_SHOWCASE'
@@ -115,6 +116,12 @@ export const ERROR_CODES = Object.freeze({
ERR_NODE_VERSION: 'ERR_NODE_VERSION',
/** `@astryxdesign/core` could not be located (not installed / not in a monorepo). */
ERR_CORE_NOT_FOUND: 'ERR_CORE_NOT_FOUND',
+ /**
+ * The installed `@astryxdesign/core` was found and loaded, but it is too old
+ * for what this input needs: it does not expose a capability the CLI would
+ * have to call to produce correct output. Upgrading core is the fix.
+ */
+ ERR_CORE_INCOMPATIBLE: 'ERR_CORE_INCOMPATIBLE',
// ── "Unknown <subject>" lookups ──────────────────────────────────
/** No component matched the requested name. */
diff --git a/packages/core/src/AppShell/AppShell.doc.mjs b/packages/core/src/AppShell/AppShell.doc.mjs
index 81c496e54b..2a5b592458 100644
--- a/packages/core/src/AppShell/AppShell.doc.mjs
+++ b/packages/core/src/AppShell/AppShell.doc.mjs
@@ -7,27 +7,103 @@ export const docs = {
displayName: 'App Shell',
group: 'AppShell',
category: 'Layout',
- keywords: ["appshell","layout","scaffold","sidebar","sidenav","topnav","header","navigation","dashboard","shell","page","frame"],
+ keywords: [
+ 'appshell',
+ 'layout',
+ 'scaffold',
+ 'sidebar',
+ 'sidenav',
+ 'topnav',
+ 'header',
+ 'navigation',
+ 'dashboard',
+ 'shell',
+ 'page',
+ 'frame',
+ ],
usage: {
description:
'AppShell is the page shell for an application. It provides slots for top navigation, side navigation, banners, and main content. Use it as the root wrapper for every page. It handles responsive mobile navigation and skip-to-content automatically. Configure side nav collapse on SideNav with its collapsible prop.',
bestPractices: [
- {guidance: true, description: 'Choose the right height: use "fill" for dashboards with internal scrolling and "auto" for pages that grow with content.'},
- {guidance: true, description: 'Set `contentPadding` based on content type: 4 for forms and settings, 0 for tables and dashboards.'},
- {guidance: true, description: 'Give every nav slot an accessible name. AppShell renders TopNav and SideNav as separate navigation landmarks, and a screen reader lists them by name, so pass `label` to each one.'},
- {guidance: true, description: 'Start the page heading inside `children`. AppShell owns the skip link, the banner landmark and the main landmark, but it renders no heading, so the first heading in the content area is the page h1.'},
- {guidance: false, description: "Nest one AppShell inside another; it's the outermost layout frame."},
- {guidance: false, description: 'Use for sub-page layouts; use Layout for content areas within AppShell.'},
- {guidance: false, description: 'Add your own skip link or <main> element. AppShell already renders both, and a second main landmark makes the first ambiguous.'},
+ {
+ guidance: true,
+ description:
+ 'Choose the right height: use "fill" for dashboards with internal scrolling and "auto" for pages that grow with content.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set `contentPadding` based on content type: 4 for forms and settings, 0 for tables and dashboards.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Give every nav slot an accessible name. AppShell renders TopNav and SideNav as separate navigation landmarks, and a screen reader lists them by name, so pass `label` to each one.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Start the page heading inside `children`. AppShell owns the skip link, the banner landmark and the main landmark, but it renders no heading, so the first heading in the content area is the page h1.',
+ },
+ {
+ guidance: false,
+ description:
+ "Nest one AppShell inside another; it's the outermost layout frame.",
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for sub-page layouts; use Layout for content areas within AppShell.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Add your own skip link or <main> element. AppShell already renders both, and a second main landmark makes the first ambiguous.',
+ },
],
anatomy: [
- {name: 'Page shell', required: true, description: 'Outermost application frame that owns page-level navigation, responsive shell behavior, and the main content landmark.'},
- {name: 'Skip link', required: true, description: 'First focusable element on the page. Visually hidden until focused, then moves focus to the main content area.'},
- {name: 'Banner', required: false, description: 'The banner slot, for system-wide announcements. Renders above the top nav, inside the banner landmark.'},
- {name: 'Top navigation', required: false, description: 'The topNav slot, typically TopNav. Below the mobile breakpoint it becomes a compact bar carrying the nav toggle.'},
- {name: 'Side navigation', required: false, description: 'The sideNav slot, typically SideNav. Inline above the breakpoint, moved into the mobile drawer below it.'},
- {name: 'Main content', required: true, description: 'children, rendered in the main landmark. Scrolls internally when height is fill, and with the page when it is auto.'},
- {name: 'Mobile nav drawer', required: false, description: 'Generated below the breakpoint from the nav slots unless mobileNav disables or replaces it. A modal dialog: it traps focus and returns focus to the toggle on close.'},
+ {
+ name: 'Page shell',
+ required: true,
+ description:
+ 'Outermost application frame that owns page-level navigation, responsive shell behavior, and the main content landmark.',
+ },
+ {
+ name: 'Skip link',
+ required: true,
+ description:
+ 'First focusable element on the page. Visually hidden until focused, then moves focus to the main content area.',
+ },
+ {
+ name: 'Banner',
+ required: false,
+ description:
+ 'The banner slot, for system-wide announcements. Renders above the top nav, inside the banner landmark.',
+ },
+ {
+ name: 'Top navigation',
+ required: false,
+ description:
+ 'The topNav slot, typically TopNav. Below the mobile breakpoint it becomes a compact bar carrying the nav toggle.',
+ },
+ {
+ name: 'Side navigation',
+ required: false,
+ description:
+ 'The sideNav slot, typically SideNav. Inline above the breakpoint, moved into the mobile drawer below it.',
+ },
+ {
+ name: 'Main content',
+ required: true,
+ description:
+ 'children, rendered in the main landmark. Scrolls internally when height is fill, and with the page when it is auto.',
+ },
+ {
+ name: 'Mobile nav drawer',
+ required: false,
+ description:
+ 'Generated below the breakpoint from the nav slots unless mobileNav disables or replaces it. A modal dialog: it traps focus and returns focus to the toggle on close.',
+ },
],
},
props: [
@@ -65,7 +141,7 @@ export const docs = {
// coincidence. The legal values live in the description instead (#1645).
type: 'ReactNode',
description:
- "Mobile navigation configuration. Accepts false (disable), a config object (tune auto behavior), or ReactNode (full custom drawer). The config object is {hasToggle?: boolean, isOpen?: boolean, onOpenChange?: (isOpen: boolean) => void, content?: ReactNode, breakpoint?: 'sm' | 'md' | 'lg' | 'none', defaultIsMobile?: boolean}; breakpoint defaults to 'md'.",
+ "Mobile navigation configuration. Accepts false (disable), a config object (tune auto behavior), or ReactNode (full custom drawer). The config object is {hasToggle?: boolean, isOpen?: boolean, onOpenChange?: (isOpen: boolean) => void, content?: ReactNode, breakpoint?: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'none', defaultIsMobile?: boolean}; breakpoint defaults to 'md', resolves through the nearest Theme's widthBreakpoints, and switches to the wider layout at equality. 'none' is always non-mobile and ignores defaultIsMobile.",
slotElements: [{__element: 'MobileNav', props: {}}],
},
{
@@ -73,7 +149,12 @@ export const docs = {
type: 'ReactNode',
description:
'Banner slot for system-wide announcements, placed above the topNav.',
- slotElements: [{__element: 'Banner', props: {title: 'Info', status: 'info', container: 'section'}}],
+ slotElements: [
+ {
+ __element: 'Banner',
+ props: {title: 'Info', status: 'info', container: 'section'},
+ },
+ ],
},
{
name: 'height',
@@ -102,13 +183,19 @@ export const docs = {
contentPadding: 4,
topNav: {
__element: 'TopNav',
- props: {label: 'Navigation', heading: {__element: 'TopNavHeading', props: {heading: 'My App'}}},
+ props: {
+ label: 'Navigation',
+ heading: {__element: 'TopNavHeading', props: {heading: 'My App'}},
+ },
},
sideNav: {
__element: 'SideNav',
props: {},
children: [
- {__element: 'SideNavItem', props: {label: 'Dashboard', isSelected: true}},
+ {
+ __element: 'SideNavItem',
+ props: {label: 'Dashboard', isSelected: true},
+ },
{__element: 'SideNavItem', props: {label: 'Settings'}},
{__element: 'SideNavItem', props: {label: 'Help'}},
],
@@ -118,7 +205,11 @@ export const docs = {
props: {gap: 3},
children: [
{__element: 'Heading', props: {level: 2}, children: 'Dashboard'},
- {__element: 'Text', props: {type: 'body', color: 'secondary'}, children: 'Welcome back. Here is an overview of your workspace.'},
+ {
+ __element: 'Text',
+ props: {type: 'body', color: 'secondary'},
+ children: 'Welcome back. Here is an overview of your workspace.',
+ },
],
},
},
@@ -140,14 +231,34 @@ export const docsZh = {
description:
'AppShell is the page shell for an application. It provides slots for top navigation, side navigation, banners, and main content. Use it as the root wrapper for every page. It handles responsive mobile navigation and skip-to-content automatically. Configure side nav collapse on SideNav with its collapsible prop.',
bestPractices: [
- {guidance: true, description: 'Choose the right height: use "fill" for dashboards with internal scrolling and "auto" for pages that grow with content.'},
- {guidance: true, description: 'Set `contentPadding` based on content type: 4 for forms and settings, 0 for tables and dashboards.'},
- {guidance: false, description: "Nest one AppShell inside another; it's the outermost layout frame."},
- {guidance: false, description: 'Use for sub-page layouts; use Layout for content areas within AppShell.'},
+ {
+ guidance: true,
+ description:
+ 'Choose the right height: use "fill" for dashboards with internal scrolling and "auto" for pages that grow with content.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set `contentPadding` based on content type: 4 for forms and settings, 0 for tables and dashboards.',
+ },
+ {
+ guidance: false,
+ description:
+ "Nest one AppShell inside another; it's the outermost layout frame.",
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for sub-page layouts; use Layout for content areas within AppShell.',
+ },
],
},
props: [
- {name: 'children', type: 'ReactNode', description: '主内容区域,渲染在 <main> 元素内部。'},
+ {
+ name: 'children',
+ type: 'ReactNode',
+ description: '主内容区域,渲染在 <main> 元素内部。',
+ },
{
name: 'contentPadding',
type: '0 | 0.5 | 1 | 1.5 | 2 | 3 | 4 | 5 | 6 | 8 | 10',
@@ -155,10 +266,27 @@ export const docsZh = {
'主内容区域的内边距。根据页面主要内容模式设置:4(16px)适用于表单/设置/文本页面,0 适用于仪表盘/地图/表格。可通过 Section 覆盖个别区域。',
default: '0',
},
- {name: 'topNav', type: 'ReactNode', description: '顶部导航插槽,通常为 TopNav。'},
- {name: 'sideNav', type: 'ReactNode', description: '侧边导航插槽,通常为 SideNav。'},
- {name: 'mobileNav', type: 'ReactNode', description: "移动端导航配置。接受 false(禁用)、配置对象(调整自动行为)或 ReactNode(完全自定义抽屉)。配置对象为 {hasToggle?, isOpen?, onOpenChange?, content?, breakpoint?: 'sm' | 'md' | 'lg' | 'none', defaultIsMobile?};breakpoint 默认为 'md'。"},
- {name: 'banner', type: 'ReactNode', description: '横幅插槽,用于全局公告,放置在 topNav 上方。'},
+ {
+ name: 'topNav',
+ type: 'ReactNode',
+ description: '顶部导航插槽,通常为 TopNav。',
+ },
+ {
+ name: 'sideNav',
+ type: 'ReactNode',
+ description: '侧边导航插槽,通常为 SideNav。',
+ },
+ {
+ name: 'mobileNav',
+ type: 'ReactNode',
+ description:
+ "移动端导航配置。接受 false(禁用)、配置对象(调整自动行为)或 ReactNode(完全自定义抽屉)。配置对象为 {hasToggle?, isOpen?, onOpenChange?, content?, breakpoint?: 'sm' | 'md' | 'lg' | 'xl' | '2xl' | 'none', defaultIsMobile?};breakpoint 默认为 'md',从最近 Theme 的 widthBreakpoints 解析,并在等于断点时切换到较宽布局;'none' 始终使用非移动端布局并忽略 defaultIsMobile。",
+ },
+ {
+ name: 'banner',
+ type: 'ReactNode',
+ description: '横幅插槽,用于全局公告,放置在 topNav 上方。',
+ },
{
name: 'height',
type: "'fill' | 'auto'",
@@ -184,9 +312,7 @@ export const docsZh = {
targets: [
{
className: 'astryx-app-shell',
- visualProps: [
- 'variant',
- ],
+ visualProps: ['variant'],
},
{className: 'astryx-app-shell-header', visualProps: ['variant']},
{className: 'astryx-app-shell-sidenav', visualProps: ['variant']},
@@ -202,20 +328,49 @@ export const docsDense = {
description:
'AppShell is the page shell for an application. It provides slots for top navigation, side navigation, banners, and main content. Use it as the root wrapper for every page. It handles responsive mobile navigation and skip-to-content automatically. Configure side nav collapse on SideNav with its collapsible prop.',
bestPractices: [
- {guidance: true, description: 'Choose the right height: use "fill" for dashboards with internal scrolling and "auto" for pages that grow with content.'},
- {guidance: true, description: 'Set `contentPadding` based on content type: 4 for forms and settings, 0 for tables and dashboards.'},
- {guidance: true, description: 'Give every nav slot an accessible name: TopNav and SideNav are separate navigation landmarks, so pass `label` to each.'},
- {guidance: true, description: 'Start the page heading inside `children`: AppShell owns the skip link, banner, and main landmarks but renders no heading, so the first content heading is the page h1.'},
- {guidance: false, description: "Nest one AppShell inside another; it's the outermost layout frame."},
- {guidance: false, description: 'Use for sub-page layouts; use Layout for content areas within AppShell.'},
- {guidance: false, description: 'Add your own skip link or <main>; AppShell renders both, and a second main landmark makes the first ambiguous.'},
+ {
+ guidance: true,
+ description:
+ 'Choose the right height: use "fill" for dashboards with internal scrolling and "auto" for pages that grow with content.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Set `contentPadding` based on content type: 4 for forms and settings, 0 for tables and dashboards.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Give every nav slot an accessible name: TopNav and SideNav are separate navigation landmarks, so pass `label` to each.',
+ },
+ {
+ guidance: true,
+ description:
+ 'Start the page heading inside `children`: AppShell owns the skip link, banner, and main landmarks but renders no heading, so the first content heading is the page h1.',
+ },
+ {
+ guidance: false,
+ description:
+ "Nest one AppShell inside another; it's the outermost layout frame.",
+ },
+ {
+ guidance: false,
+ description:
+ 'Use for sub-page layouts; use Layout for content areas within AppShell.',
+ },
+ {
+ guidance: false,
+ description:
+ 'Add your own skip link or <main>; AppShell renders both, and a second main landmark makes the first ambiguous.',
+ },
],
},
propDescriptions: {
children: 'main content area, rendered inside <main>',
topNav: 'top nav slot, typically TopNav',
sideNav: 'side nav slot, typically SideNav',
- mobileNav: 'mobile nav config: false | MobileNavConfig | ReactNode',
+ mobileNav:
+ 'mobile nav config: false | ReactNode | config with theme-resolved sm|md|lg|xl|2xl|none breakpoint (exclusive upper edge); none is always non-mobile and ignores defaultIsMobile',
banner: 'slot for system-wide announcements above topNav',
height:
'fill=viewport 100dvh w/ independent scroll; auto=content-driven w/ sticky nav',
diff --git a/packages/core/src/AppShell/AppShell.test.tsx b/packages/core/src/AppShell/AppShell.test.tsx
index a73cad392b..bee1e3852f 100644
--- a/packages/core/src/AppShell/AppShell.test.tsx
+++ b/packages/core/src/AppShell/AppShell.test.tsx
@@ -2,8 +2,8 @@
/**
* @file AppShell.test.tsx
- * @input Uses vitest, @testing-library/react, AppShell component
- * @output Unit tests for AppShell component behavior
+ * @input Uses vitest, React server rendering, @testing-library/react, AppShell component
+ * @output Unit tests for AppShell client behavior and SSR breakpoint semantics
* @position Testing; validates AppShell.tsx implementation
*
* SYNC: When AppShell.tsx changes, update tests to match new behavior
@@ -18,7 +18,8 @@ import {
beforeEach,
afterEach,
} from 'vitest';
-import {render, screen, fireEvent} from '@testing-library/react';
+import {renderToString} from 'react-dom/server';
+import {act, render, screen, fireEvent} from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import {AppShell} from './AppShell';
import {InternationalizationProvider} from '../i18n';
@@ -26,6 +27,7 @@ import {MobileNav} from '../MobileNav';
import {SideNav, SideNavItem, SideNavSection} from '../SideNav';
import {TopNav, TopNavHeading, TopNavItem} from '../TopNav';
import {useAppShellMobile} from './AppShellMobileContext';
+import {Theme, defineTheme} from '../theme';
// jsdom doesn't implement showModal/close on <dialog>, so we mock them
beforeAll(() => {
@@ -109,6 +111,9 @@ beforeEach(() => {
afterEach(() => {
vi.restoreAllMocks();
+ act(() => {
+ document.documentElement.removeAttribute('data-astryx-theme');
+ });
});
describe('AppShell', () => {
@@ -296,15 +301,140 @@ describe('AppShell', () => {
// Responsive breakpoint
// ===========================================================================
- it('tracks breakpoint changes', () => {
+ it('uses the default named breakpoint with an exclusive upper edge', () => {
render(
<AppShell sideNav={<TestSideNav />} mobileNav={{breakpoint: 'md'}}>
<div>Content</div>
</AppShell>,
);
- // matchMedia should have been called for the breakpoint
- expect(window.matchMedia).toHaveBeenCalled();
+ expect(window.matchMedia).toHaveBeenCalledWith('(width < 768px)');
+ });
+
+ it('resolves all named points through the nearest Theme', () => {
+ const theme = {
+ ...defineTheme({
+ name: 'app-shell-points',
+ adaptations: {widthBreakpoints: {xl: 1400, '2xl': 1800}},
+ }),
+ __built: true as const,
+ };
+
+ render(
+ <Theme theme={theme}>
+ <AppShell sideNav={<TestSideNav />} mobileNav={{breakpoint: '2xl'}}>
+ <div>Content</div>
+ </AppShell>
+ </Theme>,
+ );
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(width < 1800px)');
+ });
+
+ it('uses the provider object when another theme shares its name', () => {
+ const outer = {
+ ...defineTheme({
+ name: 'same-name',
+ adaptations: {widthBreakpoints: {md: 700}},
+ }),
+ __built: true as const,
+ };
+ const inner = {
+ ...defineTheme({
+ name: 'same-name',
+ adaptations: {widthBreakpoints: {md: 900}},
+ }),
+ __built: true as const,
+ };
+
+ render(
+ <Theme theme={outer}>
+ <Theme theme={inner}>
+ <div>Nested</div>
+ </Theme>
+ <AppShell sideNav={<TestSideNav />} mobileNav={{breakpoint: 'md'}}>
+ <div>Content</div>
+ </AppShell>
+ </Theme>,
+ );
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(width < 700px)');
+ });
+
+ it('uses a built theme object from provider context', () => {
+ const builtTheme = {
+ ...defineTheme({
+ name: 'built-app-shell-points',
+ adaptations: {widthBreakpoints: {'2xl': 1700}},
+ }),
+ __built: true as const,
+ __adaptationRules: undefined,
+ };
+
+ render(
+ <Theme theme={builtTheme}>
+ <AppShell sideNav={<TestSideNav />} mobileNav={{breakpoint: '2xl'}}>
+ <div>Content</div>
+ </AppShell>
+ </Theme>,
+ );
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(width < 1700px)');
+ });
+
+ it('falls back per key when built metadata has a partial width map', () => {
+ const partialBuiltTheme = {
+ ...defineTheme({name: 'partial-built-app-shell-points'}),
+ __built: true as const,
+ __adaptations: {
+ widthBreakpoints: {md: 700},
+ rules: [],
+ },
+ } as unknown as ReturnType<typeof defineTheme>;
+
+ render(
+ <Theme theme={partialBuiltTheme}>
+ <AppShell sideNav={<TestSideNav />} mobileNav={{breakpoint: 'xl'}}>
+ <div>Content</div>
+ </AppShell>
+ </Theme>,
+ );
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(width < 1280px)');
+ });
+
+ it('follows the registered root theme without provider context', () => {
+ defineTheme({
+ name: 'root-app-shell-points',
+ adaptations: {widthBreakpoints: {lg: 1111}},
+ });
+ const originalGetAttribute = document.documentElement.getAttribute.bind(
+ document.documentElement,
+ );
+ vi.spyOn(document.documentElement, 'getAttribute').mockImplementation(
+ name =>
+ name === 'data-astryx-theme'
+ ? 'root-app-shell-points'
+ : originalGetAttribute(name),
+ );
+
+ render(
+ <AppShell sideNav={<TestSideNav />} mobileNav={{breakpoint: 'lg'}}>
+ <div>Content</div>
+ </AppShell>,
+ );
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(width < 1111px)');
+ });
+
+ it('supports the added xl breakpoint without a Theme provider', () => {
+ render(
+ <AppShell sideNav={<TestSideNav />} mobileNav={{breakpoint: 'xl'}}>
+ <div>Content</div>
+ </AppShell>,
+ );
+
+ expect(window.matchMedia).toHaveBeenCalledWith('(width < 1280px)');
});
it('does not enter mobile mode when mobileNav breakpoint is none', () => {
@@ -314,7 +444,7 @@ describe('AppShell', () => {
</AppShell>,
);
- // breakpoint 'none' uses (max-width: 0px) which never matches,
+ // breakpoint 'none' uses (width < 0px), which never matches,
// so sideNav stays inline and no mobile nav toggle appears
expect(screen.getByText('Nav')).toBeInTheDocument();
expect(
@@ -322,6 +452,23 @@ describe('AppShell', () => {
).not.toBeInTheDocument();
});
+ it('renders breakpoint none as non-mobile on the server regardless of the SSR hint', () => {
+ const host = document.createElement('div');
+ host.innerHTML = renderToString(
+ <AppShell
+ sideNav={<TestSideNav />}
+ mobileNav={{breakpoint: 'none', defaultIsMobile: true}}>
+ <div>Content</div>
+ </AppShell>,
+ );
+
+ expect(
+ host.querySelector(
+ '.astryx-app-shell > .astryx-layout .astryx-layout-panel',
+ ),
+ ).not.toBeNull();
+ });
+
// ===========================================================================
// Mobile overlay (default MobileNav wrapping sideNav)
// ===========================================================================
diff --git a/packages/core/src/AppShell/AppShell.tsx b/packages/core/src/AppShell/AppShell.tsx
index a85c954110..fd470489af 100644
--- a/packages/core/src/AppShell/AppShell.tsx
+++ b/packages/core/src/AppShell/AppShell.tsx
@@ -6,8 +6,8 @@ import React from 'react';
/**
* @file AppShell.tsx
- * @input Uses React, Layout, LayoutHeader, LayoutPanel, LayoutContent, StyleX
- * @output Exports AppShell component and AppShellProps type
+ * @input Uses React, Theme-resolved breakpoints, Layout, navigation slots, and StyleX
+ * @output Exports AppShell component and AppShellProps with SSR-safe mobile layout
* @position Page shell for an application — the top-level wrapper for any app.
* Composes Layout internally to provide header, sideNav, and main content areas.
* Use for any app that needs a top nav, side navigation, and scrollable content.
@@ -56,6 +56,11 @@ import {useMediaQuery} from '../hooks/useMediaQuery';
import {observeResize} from '../utils/sharedResizeObserver';
import {themeProps} from '../utils/themeProps';
import {useTranslator} from '../i18n';
+import {useThemeDefinition} from '../theme/useTheme';
+import {
+ DEFAULT_WIDTH_BREAKPOINTS,
+ type WidthBreakpointName,
+} from '../theme/themeAdaptations';
import type {AppShellVariantMap} from './index';
import {useMergedRefs} from '../hooks/useMergedRefs';
@@ -74,13 +79,6 @@ const ActivityWrapper = HasActivity
// Constants
// =============================================================================
-const BREAKPOINT_VALUES: Record<AppShellBreakpoint, number> = {
- sm: 640,
- md: 768,
- lg: 1024,
- none: 0,
-};
-
const MAIN_CONTENT_ID = 'astryx-app-shell-main';
// =============================================================================
@@ -88,13 +86,10 @@ const MAIN_CONTENT_ID = 'astryx-app-shell-main';
// =============================================================================
/**
- * SideNav breakpoint options.
- * - `sm`: 640px
- * - `md`: 768px
- * - `lg`: 1024px
- * - `none`: Never auto-collapse
+ * SideNav breakpoint options. Named points resolve through the nearest Theme;
+ * without an active theme they use Astryx's default width-breakpoint map.
*/
-export type AppShellBreakpoint = 'sm' | 'md' | 'lg' | 'none';
+export type AppShellBreakpoint = WidthBreakpointName | 'none';
/**
* Navigation background style:
@@ -141,7 +136,10 @@ export interface MobileNavConfig {
content?: ReactNode;
/**
- * Breakpoint below which mobile nav activates.
+ * Named Theme width point below which mobile nav activates. `sm`, `md`,
+ * `lg`, `xl`, and `2xl` resolve through the nearest Theme's effective
+ * `adaptations.widthBreakpoints`; equality belongs to the wider layout.
+ * Use `none` to disable automatic mobile mode.
* @default 'md'
*/
breakpoint?: AppShellBreakpoint;
@@ -149,7 +147,8 @@ export interface MobileNavConfig {
/**
* SSR hint: whether the initial render should assume mobile layout.
* Seeds the breakpoint state so the server-rendered HTML matches
- * the client on mobile devices, avoiding a layout flash.
+ * the client on mobile devices, avoiding a layout flash. Ignored when
+ * `breakpoint` is `none`, which is always non-mobile.
*
* Derive from the User-Agent header or a device-detection cookie
* in a server component, then pass down.
@@ -469,6 +468,7 @@ export function AppShell({
...rest
}: AppShellProps) {
const t = useTranslator();
+ const activeTheme = useThemeDefinition();
// =========================================================================
// Parse mobileNav prop — normalize to config, custom element, or disabled
// =========================================================================
@@ -504,13 +504,17 @@ export function AppShell({
// =========================================================================
// Mobile nav open state (controlled + uncontrolled)
// =========================================================================
+ const activeWidthBreakpoints = activeTheme?.__adaptations?.widthBreakpoints;
const breakpointQuery =
sideNavBreakpoint === 'none'
- ? '(max-width: 0px)'
- : `(max-width: ${BREAKPOINT_VALUES[sideNavBreakpoint]}px)`;
+ ? '(width < 0px)'
+ : `(width < ${
+ activeWidthBreakpoints?.[sideNavBreakpoint] ??
+ DEFAULT_WIDTH_BREAKPOINTS[sideNavBreakpoint]
+ }px)`;
const isBelowBreakpoint = useMediaQuery(
breakpointQuery,
- mobileNavConfig?.defaultIsMobile,
+ sideNavBreakpoint === 'none' ? false : mobileNavConfig?.defaultIsMobile,
);
const [uncontrolledMobileOpen, setUncontrolledMobileOpen] = useState(false);
const isMobileNavOpen = mobileNavConfig?.isOpen ?? uncontrolledMobileOpen;
diff --git a/packages/core/src/theme/defineTheme.ts b/packages/core/src/theme/defineTheme.ts
index 0e02addec8..bcfaac0207 100644
--- a/packages/core/src/theme/defineTheme.ts
+++ b/packages/core/src/theme/defineTheme.ts
@@ -13,7 +13,7 @@
* - A [light, dark] tuple: converted to light-dark(light, dark)
*
* @example
- * ```tsx
+ * ```
* const oceanTheme = defineTheme({
* name: 'ocean',
* tokens: {
@@ -47,7 +47,7 @@ type ThemeIconOverrides = Partial<
Record<IconName | NamespacedIconName, ReactNode>
>;
import type {IndicatorRegistry} from '../Indicator/types';
-import type {TypographyConfig, FontWeight} from './types';
+import type {TypographyConfig} from './types';
import {
resolveOnMedia,
type OnMediaOverrides,
@@ -68,20 +68,24 @@ import {
fontWeightDefaults,
typeScaleDefaults,
} from './tokens.stylex';
+import type {MotionScaleConfig} from './expandMotionScale';
+import type {RadiusScaleConfig} from './expandRadiusScale';
+import type {ColorScaleConfig} from './expandColorScale';
+import {resolveThemeValues, type ThemeValuesInput} from './resolveThemeValues';
import {
- expandTypeScale,
- generateTypeScaleComponents,
- type TypeScaleConfig,
-} from './expandTypeScale';
-import {expandMotionScale, type MotionScaleConfig} from './expandMotionScale';
-import {expandRadiusScale, type RadiusScaleConfig} from './expandRadiusScale';
-import {expandColorScale, type ColorScaleConfig} from './expandColorScale';
+ normalizeThemeAdaptations,
+ resolveThemeAdaptationRules,
+ resolveThemeGenerativeAxes,
+ type NormalizedThemeAdaptations,
+ type ResolvedThemeAdaptationRule,
+ type ThemeAdaptations,
+ type ThemeGenerativeAxes,
+} from './themeAdaptations';
import type {DomainTokenName} from './domainTokens';
import {domainTokenDefaults} from './domainTokens';
import type {SyntaxThemeDefinition} from './syntax';
import {registerTheme} from './themeRegistry';
-import {deepMergeComponents} from './mergeComponents';
import {resolveLocalTokenContract} from './localTokens';
// =============================================================================
@@ -154,7 +158,7 @@ export type StyleOverrides = Record<string, string | Record<string, string>>;
* to override interaction states without CSS custom property escape hatches.
*
* @example
- * ```tsx
+ * ```
* components: {
* button: {
* base: { fontWeight: '600' },
@@ -194,7 +198,7 @@ export interface DefineThemeInput {
* (e.g. icons, accent color) without re-specifying the full theme.
*
* @example
- * ```tsx
+ * ```
* import {neutralTheme} from '@astryxdesign/theme-neutral';
*
* const myTheme = defineTheme({
@@ -216,7 +220,7 @@ export interface DefineThemeInput {
* @import for your fonts before rendering the theme.
*
* @example
- * ```tsx
+ * ```
* typography: {
* scale: { base: 14, ratio: 1.2 },
* body: { family: 'Geist', fallbacks: '-apple-system, sans-serif' },
@@ -254,7 +258,7 @@ export interface DefineThemeInput {
* Explicit `tokens` overrides take precedence over radius-generated values.
*
* @example
- * ```tsx
+ * ```
* radius: { base: 4, multiplier: 1 }
*
* // Sharp/brutalist — all radii become 0
@@ -321,7 +325,7 @@ export interface DefineThemeInput {
* and generate TypeScript module augmentations for type-safe extensibility.
*
* @example
- * ```tsx
+ * ```
* components: {
* button: {
* base: { fontWeight: '600' },
@@ -356,7 +360,7 @@ export interface DefineThemeInput {
* per-region (or per-instance) by wrapping in SyntaxTheme.
*
* @example
- * ```tsx
+ * ```
* import {dracula} from '@astryxdesign/core/theme/syntax';
* defineTheme({ name: 'my-theme', syntax: dracula, ... })
* ```
@@ -372,7 +376,7 @@ export interface DefineThemeInput {
* background.
*
* @example
- * ```tsx
+ * ```
* onDark: {
* tokens: { '--color-accent': '#90CAF9' },
* components: {
@@ -387,6 +391,33 @@ export interface DefineThemeInput {
* but for the inverse case (e.g. dark-mode page with a light popover).
*/
onLight?: OnMediaOverrides;
+ /**
+ * Ordered environment-conditioned token and component adaptations.
+ *
+ * Width points use the fixed names `sm`, `md`, `lg`, `xl`, and `2xl` and
+ * default to 640, 768, 1024, 1280, and 1536 CSS pixels. Breakpoint
+ * configuration alone emits no CSS. Rules are emitted in declaration order;
+ * fields inside `when` are ANDed and later matching writes win.
+ *
+ * @example
+ * ```
+ * adaptations: {
+ * widthBreakpoints: {lg: 1024, xl: 1280},
+ * rules: [
+ * {
+ * when: {
+ * width: {from: 'lg', below: 'xl'},
+ * pointer: 'coarse',
+ * },
+ * value: {
+ * tokens: {'--size-element-md': '44px'},
+ * },
+ * },
+ * ],
+ * }
+ * ```
+ */
+ adaptations?: ThemeAdaptations;
}
/** A defined theme — ready to pass to <Theme> */
@@ -428,8 +459,24 @@ export interface DefinedTheme {
* @internal
*/
__onLight?: ResolvedOnMedia;
+ /**
+ * Effective breakpoint map and ordered normalized rule inputs retained for
+ * source-equivalent extension, including from a built theme.
+ * @internal
+ */
+ __adaptations?: NormalizedThemeAdaptations;
+ /** Concrete ordered rule writes used by the runtime CSS compiler. @internal */
+ __adaptationRules?: ResolvedThemeAdaptationRule[];
+ /** Effective root generative-axis metadata used to resolve child rules. @internal */
+ __axes?: ThemeGenerativeAxes;
}
+/** A theme produced by the current defineTheme implementation. */
+export type ResolvedDefinedTheme = DefinedTheme & {
+ __adaptations: NormalizedThemeAdaptations;
+ __axes: ThemeGenerativeAxes;
+};
+
// =============================================================================
// All defaults merged into a single flat map
// =============================================================================
@@ -456,50 +503,6 @@ export const tokenDefaults: Record<string, string> = {
// defineTheme
// =============================================================================
-/**
- * Resolve a token value to a CSS string.
- * - String values pass through as-is
- * - [light, dark] tuples become light-dark(light, dark)
- */
-function resolveTokenValue(value: TokenValue): string {
- if (Array.isArray(value)) {
- return `light-dark(${value[0]}, ${value[1]})`;
- }
- return value;
-}
-
-/**
- * Resolve a FontWeight name to a var() reference.
- * Named weights map to var(--font-weight-*); raw values pass through.
- */
-function resolveFontWeight(weight: FontWeight): string {
- const named: Record<string, string> = {
- normal: 'var(--font-weight-normal)',
- medium: 'var(--font-weight-medium)',
- semibold: 'var(--font-weight-semibold)',
- bold: 'var(--font-weight-bold)',
- };
- return named[weight] ?? weight;
-}
-
-/**
- * Build the full CSS font-family value from family + fallbacks.
- * Quotes the family name if it contains spaces.
- */
-function buildFontFamily(
- family?: string,
- fallbacks?: string,
-): string | undefined {
- if (!family) {
- return undefined;
- }
- const quoted = family.includes(' ') ? `"${family}"` : family;
- if (fallbacks) {
- return `${quoted}, ${fallbacks}`;
- }
- return quoted;
-}
-
/**
* Describe a rejected `extends` value for the error message — enough to tell a
* missed import (`undefined`) from a module namespace or a plain object.
@@ -528,10 +531,8 @@ function describeBadBase(value: unknown): string {
* that are merged into the token map. Explicit `tokens` entries take
* precedence over generated values.
*/
-export function defineTheme(input: DefineThemeInput): DefinedTheme {
- const tokens: Record<string, string> = {};
-
- // 0. Pre-seed from base theme when `extends` is provided (lowest precedence).
+export function defineTheme(input: DefineThemeInput): ResolvedDefinedTheme {
+ // Pre-seed from the base theme when `extends` is provided (lowest precedence).
// A base that is not a theme is refused rather than ignored: `extends` used
// to inherit nothing when its value was undefined, which is what a named
// import silently resolving to the wrong module hands over, and the theme
@@ -545,142 +546,34 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
);
}
const base = input.extends;
- if (base) {
- for (const [key, value] of Object.entries(base.tokens)) {
- tokens[key] = value;
- }
- }
-
- // Build typeScale config from typography if present
- const typo = input.typography;
- let typeScaleConfig: TypeScaleConfig | undefined;
- if (typo?.scale) {
- // Collect weight overrides from typography roles
- const headingWeights: Partial<Record<1 | 2 | 3 | 4 | 5 | 6, string>> = {};
- const headingRole = typo.heading;
- if (headingRole?.weights) {
- for (const [level, w] of Object.entries(headingRole.weights)) {
- if (w) {
- headingWeights[Number(level) as 1 | 2 | 3 | 4 | 5 | 6] =
- resolveFontWeight(w);
- }
- }
- }
- // Default heading weight from role
- const defaultHeadingWeight = headingRole?.weight
- ? resolveFontWeight(headingRole.weight)
- : undefined;
- if (defaultHeadingWeight) {
- for (let i = 1; i <= 6; i++) {
- if (!(i in headingWeights)) {
- headingWeights[i as 1 | 2 | 3 | 4 | 5 | 6] = defaultHeadingWeight;
- }
- }
- }
-
- // Text weight overrides from roles
- const textWeights: Partial<Record<string, string>> = {};
- if (typo.body?.weight) {
- textWeights.body = resolveFontWeight(typo.body.weight);
- }
- if (typo.code?.weight) {
- textWeights.code = resolveFontWeight(typo.code.weight);
- }
-
- typeScaleConfig = {
- base: typo.scale.base,
- ratio: typo.scale.ratio,
- weights: {
- ...(Object.keys(headingWeights).length > 0
- ? {heading: headingWeights}
- : {}),
- ...(Object.keys(textWeights).length > 0 ? {text: textWeights} : {}),
- },
- };
- }
-
- // 1. Apply color-generated tokens (lowest precedence for colors)
- if (input.color) {
- const colorTokens = expandColorScale(input.color);
- for (const [key, value] of Object.entries(colorTokens)) {
- tokens[key] = value;
- }
- }
-
- // 1a. Apply typeScale-generated tokens (lowest precedence for type)
- if (typeScaleConfig) {
- const typeScaleTokens = expandTypeScale(typeScaleConfig);
- for (const [key, value] of Object.entries(typeScaleTokens)) {
- tokens[key] = value;
- }
- }
-
- // 1b. Apply radius-generated tokens (lowest precedence for radius)
- if (input.radius) {
- const radiusTokens = expandRadiusScale(input.radius);
- for (const [key, value] of Object.entries(radiusTokens)) {
- tokens[key] = value;
- }
- }
-
- // 1c. Apply motion-generated tokens (same precedence as typeScale)
- if (input.motion) {
- const motionTokens = expandMotionScale(input.motion);
- for (const [key, value] of Object.entries(motionTokens)) {
- tokens[key] = value;
- }
- }
-
- // 1d. Apply typography font family tokens
- if (typo) {
- // Heading inherits from body if not specified
- const bodyFamily = buildFontFamily(typo.body?.family, typo.body?.fallbacks);
- const headingFamily =
- buildFontFamily(typo.heading?.family, typo.heading?.fallbacks) ??
- bodyFamily;
- const codeFamily = buildFontFamily(typo.code?.family, typo.code?.fallbacks);
-
- if (bodyFamily) {
- tokens['--font-family-body'] = bodyFamily;
- }
- if (headingFamily) {
- tokens['--font-family-heading'] = headingFamily;
- }
- if (codeFamily) {
- tokens['--font-family-code'] = codeFamily;
- }
- }
-
- // 1e. Apply syntax theme tokens (before explicit overrides)
- if (input.syntax) {
- const syntaxMap = input.syntax.tokens;
- const prefix = '--color-syntax-';
- for (const [key, value] of Object.entries(syntaxMap)) {
- tokens[prefix + key] = value;
- }
- }
- // 2. Apply explicit token overrides (highest precedence — overwrites generated tokens)
- if (input.tokens) {
- for (const [key, value] of Object.entries(input.tokens)) {
- if (value !== undefined) {
- tokens[key] = resolveTokenValue(value);
- }
- }
- }
+ // The theme's own value axes and the resolved base an `extends` supplies.
+ // The same axis metadata is retained so adaptation rules can complete partial
+ // configs without approximating values from unrelated built-in defaults.
+ const ownValues: ThemeValuesInput = {
+ typography: input.typography,
+ color: input.color,
+ radius: input.radius,
+ motion: input.motion,
+ syntax: input.syntax,
+ tokens: input.tokens,
+ components: input.components,
+ };
+ const ownAxes: ThemeGenerativeAxes = {
+ typography: input.typography,
+ color: input.color,
+ radius: input.radius,
+ motion: input.motion,
+ };
+ const seed = base
+ ? {tokens: base.tokens, components: base.components}
+ : undefined;
- // 3. Generate component overrides: base (lowest) → typeScale → explicit (highest)
- let components = input.components;
- if (typeScaleConfig) {
- const generated = generateTypeScaleComponents(typeScaleConfig);
- components = deepMergeComponents(generated, input.components);
- }
- if (base?.components) {
- components = deepMergeComponents(base.components, components);
- }
+ const {tokens, components} = resolveThemeValues(ownValues, seed);
- // 4. Resolve on-media token overrides (base's resolved surface, then
- // defaults, then this theme's own overrides)
+ // On-media token overrides (base's resolved surface, then defaults, then
+ // this theme's own overrides). They compile after adaptations so the
+ // media-surface value stays more specific in the authored cascade.
const __onDark = resolveOnMedia('dark', input.onDark, base?.__onDark);
const __onLight = resolveOnMedia('light', input.onLight, base?.__onLight);
@@ -693,7 +586,24 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
__onLight,
);
- // 5. Merge icons — input icons override base icons
+ // Adaptations inherit their breakpoint map and ordered rules. Every rule is
+ // re-resolved against this theme's effective root axes, so a child can change
+ // the root scale while preserving the base rule's authored intent.
+ const __axes = resolveThemeGenerativeAxes(base?.__axes, ownAxes);
+ const __adaptations = normalizeThemeAdaptations(
+ input.name,
+ base?.__adaptations,
+ input.adaptations,
+ );
+ const __adaptationRules = resolveThemeAdaptationRules(
+ input.name,
+ __adaptations,
+ __axes,
+ tokens,
+ localTokenContract?.localTokens,
+ );
+
+ // Icons — input icons override base icons
const icons =
input.icons && base?.icons
? {...base.icons, ...input.icons}
@@ -706,7 +616,7 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
? {...base.indicators, ...input.indicators}
: (input.indicators ?? base?.indicators);
- const theme: DefinedTheme = {
+ const theme: ResolvedDefinedTheme = {
name: input.name,
tokens,
...(localTokenContract
@@ -725,6 +635,9 @@ export function defineTheme(input: DefineThemeInput): DefinedTheme {
: undefined,
__onDark,
__onLight,
+ __adaptations,
+ __adaptationRules,
+ __axes,
};
registerTheme(theme);
@@ -739,6 +652,7 @@ export {
generateThemeRules,
generateThemeRulesSplit,
generateOnMediaCSS,
+ generateAdaptationCSS,
generateThemeCSS,
type ThemeRulesSplit,
type ThemeCSSOutput,
diff --git a/packages/core/src/theme/generateThemeRules.test.ts b/packages/core/src/theme/generateThemeRules.test.ts
index 9ad017c21c..1094d2c8b7 100644
--- a/packages/core/src/theme/generateThemeRules.test.ts
+++ b/packages/core/src/theme/generateThemeRules.test.ts
@@ -2,20 +2,49 @@
/**
* @file generateThemeRules.test.ts
- * Tests that generateThemeRules produces correct, consistent CSS rules
- * for both runtime and build paths.
+ * Tests that shared root, adaptation, and media-surface lowering produces
+ * correct, consistently ordered CSS for both runtime and build paths.
*/
import {describe, it, expect} from 'vitest';
import {
dataTokenDefaults,
defineTheme,
+ generateAdaptationCSS,
generateThemeCSS,
generateOnMediaCSS,
generateThemeRules,
} from './index';
import {generateDataTokenDefaultsCSS} from './generateThemeRules';
+function topLevelCSSBlocks(css: string): string[] {
+ const blocks: string[] = [];
+ let depth = 0;
+ let start = -1;
+
+ for (let index = 0; index < css.length; index++) {
+ const character = css[index];
+ if (start === -1) {
+ if (/\s/.test(character)) {
+ continue;
+ }
+ start = index;
+ }
+
+ if (character === '{') {
+ depth++;
+ } else if (character === '}') {
+ depth--;
+ if (depth === 0) {
+ blocks.push(css.slice(start, index + 1));
+ start = -1;
+ }
+ }
+ }
+
+ return blocks;
+}
+
const defaultInput = {
name: 'default',
typography: {scale: {base: 14, ratio: 1.2}},
@@ -208,14 +237,15 @@ describe('generateThemeRules', () => {
// --- Prose rules ---
- it('includes prose heading rules with computed values', () => {
+ it('includes prose heading rules linked to semantic tokens', () => {
const h1Rule = rules.find(
r => r.trimStart().startsWith(':where(h1)') || r.includes(':where(h1)'),
);
expect(h1Rule).toBeDefined();
- // Prose rules use val() helper which resolves to the token value (now a var ref)
- expect(h1Rule).toContain('var(--font-size-2xl)');
- expect(h1Rule).toContain('var(--font-weight-semibold)');
+ // Keep prose linked to semantic variables so conditional token writes apply
+ // through CSS without duplicating these selectors inside every media rule.
+ expect(h1Rule).toContain('var(--text-heading-1-size)');
+ expect(h1Rule).toContain('var(--text-heading-1-weight)');
// Prose defaults intentionally carry NO block margins: reset.css zeroes
// raw element margins and the Markdown/Heading components own their spacing
// via StyleX (@layer astryx-base). Emitting margins here would re-introduce
@@ -224,12 +254,12 @@ describe('generateThemeRules', () => {
expect(h1Rule).not.toContain('margin-block-end');
});
- it('includes prose p rule with computed values', () => {
+ it('includes prose p rule linked to semantic tokens', () => {
const pRule = rules.find(
r => r.trimStart().startsWith(':where(p)') || r.includes(':where(p)'),
);
expect(pRule).toBeDefined();
- expect(pRule).toContain('var(--font-size-base)');
+ expect(pRule).toContain('var(--text-body-size)');
expect(pRule).toContain('font-family: var(--font-family-body)');
expect(pRule).toContain('var(--color-text-primary)');
// No margins on the prose paragraph default (see heading rule note).
@@ -355,12 +385,12 @@ describe('generateThemeRules with weight overrides', () => {
);
});
- it('reflects weight override in prose h3', () => {
+ it('keeps prose h3 linked to the semantic weight token', () => {
const h3Rule = rules.find(
r => r.trimStart().startsWith(':where(h3)') || r.includes(':where(h3)'),
);
expect(h3Rule).toBeDefined();
- expect(h3Rule).toContain('var(--font-weight-bold)');
+ expect(h3Rule).toContain('var(--text-heading-3-weight)');
});
});
@@ -513,6 +543,304 @@ describe('generateThemeRules with an explicit Heading weight prop', () => {
expect(boldIndex).toBeGreaterThan(typeIndex);
expect(css.slice(boldIndex)).toContain('font-weight: 900');
});
+
+ it('scopes Text color and size guards after each media-surface type rule', () => {
+ const themed = defineTheme({
+ name: 'media-text-prop-guards',
+ onDark: {
+ components: {
+ text: {'type:large': {color: '#fff', fontSize: '4rem'}},
+ },
+ },
+ onLight: {
+ components: {
+ text: {'type:body': {color: '#000', fontSize: '0.75rem'}},
+ },
+ },
+ });
+ const css = generateOnMediaCSS(themed);
+
+ for (const [surface, type] of [
+ ['dark', 'large'],
+ ['light', 'body'],
+ ] as const) {
+ const surfacePrefix = `:is([data-astryx-media="${surface}"])`;
+ const typeSelector = `${surfacePrefix} :is(.astryx-text.${type})`;
+ const colorSelector = `${surfacePrefix} :is(.astryx-text.primary)`;
+ const sizeSelector = `${surfacePrefix} :is(.astryx-text.sm)`;
+ const typeIndex = css.indexOf(typeSelector);
+
+ expect(typeIndex).toBeGreaterThanOrEqual(0);
+ expect(css).toContain(
+ `${colorSelector} { color: var(--color-text-primary); }`,
+ );
+ expect(css).toContain(
+ `${sizeSelector} { font-size: var(--font-size-sm); }`,
+ );
+ expect(css.indexOf(colorSelector)).toBeGreaterThan(typeIndex);
+ expect(css.indexOf(sizeSelector)).toBeGreaterThan(typeIndex);
+ }
+ });
+
+ it('keeps a coarse-only weight out of a later fine-only level block', () => {
+ const themed = defineTheme({
+ name: 'exclusive-adapted-heading-weight',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ heading: {'weight:bold': {fontWeight: '800'}},
+ },
+ },
+ },
+ {
+ when: {pointer: 'fine'},
+ value: {
+ components: {
+ heading: {'level:2': {fontWeight: '300'}},
+ },
+ },
+ },
+ ],
+ },
+ });
+ const blocks = topLevelCSSBlocks(generateAdaptationCSS(themed).component);
+ const fineBlock = blocks.find(block =>
+ block.startsWith('@media (pointer: fine)'),
+ );
+ const rootGuard = blocks.find(block => block.startsWith('@scope '));
+
+ expect(fineBlock).toContain('.astryx-heading.level-2');
+ expect(fineBlock).not.toContain('font-weight: 800');
+ expect(rootGuard).toContain(
+ '.astryx-heading.normal { font-weight: var(--font-weight-normal); }',
+ );
+ expect(rootGuard).toContain(
+ '.astryx-heading.medium { font-weight: var(--font-weight-medium); }',
+ );
+ expect(rootGuard).toContain(
+ '.astryx-heading.semibold { font-weight: var(--font-weight-semibold); }',
+ );
+ expect(rootGuard).toContain(
+ '.astryx-heading.bold { font-weight: var(--font-weight-bold); }',
+ );
+ expect(blocks.indexOf(rootGuard!)).toBeGreaterThan(
+ blocks.indexOf(fineBlock!),
+ );
+
+ const weight800Blocks = blocks.filter(block =>
+ block.includes('font-weight: 800'),
+ );
+ expect(weight800Blocks).toHaveLength(2);
+ expect(
+ weight800Blocks.every(block =>
+ block.startsWith('@media (pointer: coarse)'),
+ ),
+ ).toBe(true);
+ });
+
+ it('keeps a coarse weight above a later broad level only when coarse matches', () => {
+ const themed = defineTheme({
+ name: 'broad-adapted-heading-level',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ heading: {'weight:bold': {fontWeight: '800'}},
+ },
+ },
+ },
+ {
+ when: {contrast: 'more'},
+ value: {
+ components: {
+ heading: {'level:2': {fontWeight: '300'}},
+ },
+ },
+ },
+ ],
+ },
+ });
+ const blocks = topLevelCSSBlocks(generateAdaptationCSS(themed).component);
+ const broadLevelBlock = blocks.find(
+ block =>
+ block.startsWith('@media (prefers-contrast: more)') &&
+ block.includes('.astryx-heading.level-2'),
+ );
+ const rootGuard = blocks.find(block => block.startsWith('@scope '));
+ const coarseGuard = blocks
+ .filter(block => block.startsWith('@media (pointer: coarse)'))
+ .at(-1);
+
+ expect(broadLevelBlock).not.toContain('font-weight: 800');
+ expect(rootGuard).toContain(
+ '.astryx-heading.bold { font-weight: var(--font-weight-bold); }',
+ );
+ expect(coarseGuard).toContain('.astryx-heading.bold { font-weight: 800; }');
+ expect(blocks.indexOf(rootGuard!)).toBeGreaterThan(
+ blocks.indexOf(broadLevelBlock!),
+ );
+ expect(blocks.indexOf(coarseGuard!)).toBeGreaterThan(
+ blocks.indexOf(rootGuard!),
+ );
+ });
+
+ it('keeps authored order for two co-matching weight writes', () => {
+ const themed = defineTheme({
+ name: 'ordered-adapted-heading-weight',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ heading: {'weight:bold': {fontWeight: '800'}},
+ },
+ },
+ },
+ {
+ when: {contrast: 'more'},
+ value: {
+ components: {
+ heading: {'weight:bold': {fontWeight: '700'}},
+ },
+ },
+ },
+ ],
+ },
+ });
+ const blocks = topLevelCSSBlocks(generateAdaptationCSS(themed).component);
+ const rootGuard = blocks.find(block => block.startsWith('@scope '));
+ const coarseGuard = blocks
+ .filter(block => block.startsWith('@media (pointer: coarse)'))
+ .at(-1);
+ const contrastGuard = blocks
+ .filter(block => block.startsWith('@media (prefers-contrast: more)'))
+ .at(-1);
+
+ expect(coarseGuard).toContain('font-weight: 800');
+ expect(contrastGuard).toContain('font-weight: 700');
+ expect(blocks.indexOf(coarseGuard!)).toBeGreaterThan(
+ blocks.indexOf(rootGuard!),
+ );
+ expect(blocks.indexOf(contrastGuard!)).toBeGreaterThan(
+ blocks.indexOf(coarseGuard!),
+ );
+ });
+
+ it('uses a root-customized weight as the adaptation fallback', () => {
+ const themed = defineTheme({
+ name: 'root-customized-adapted-heading-weight',
+ components: {
+ heading: {'weight:bold': {fontWeight: '900'}},
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'fine'},
+ value: {
+ components: {
+ heading: {'level:2': {fontWeight: '300'}},
+ },
+ },
+ },
+ ],
+ },
+ });
+ const blocks = topLevelCSSBlocks(generateAdaptationCSS(themed).component);
+ const fineBlock = blocks.find(block =>
+ block.startsWith('@media (pointer: fine)'),
+ );
+ const rootGuard = blocks.find(block => block.startsWith('@scope '));
+
+ expect(fineBlock).toContain('.astryx-heading.level-2');
+ expect(rootGuard).toContain('.astryx-heading.bold { font-weight: 900; }');
+ expect(blocks.indexOf(rootGuard!)).toBeGreaterThan(
+ blocks.indexOf(fineBlock!),
+ );
+ });
+
+ it('keeps a single rule weight above its own later type write', () => {
+ const themed = defineTheme({
+ name: 'single-adapted-heading-weight',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ heading: {
+ 'weight:bold': {fontWeight: '800'},
+ 'type:hero': {fontWeight: '300'},
+ },
+ },
+ },
+ },
+ ],
+ },
+ });
+ const blocks = topLevelCSSBlocks(generateAdaptationCSS(themed).component);
+ const coarseBlocks = blocks.filter(block =>
+ block.startsWith('@media (pointer: coarse)'),
+ );
+ const rootGuard = blocks.find(block => block.startsWith('@scope '));
+
+ expect(coarseBlocks).toHaveLength(2);
+ expect(coarseBlocks[0]).toContain('.astryx-heading.hero');
+ expect(rootGuard).toContain(
+ '.astryx-heading.bold { font-weight: var(--font-weight-bold); }',
+ );
+ expect(coarseBlocks[1]).toContain(
+ '.astryx-heading.bold { font-weight: 800; }',
+ );
+ expect(blocks.at(-1)).toBe(coarseBlocks[1]);
+ });
+
+ it('keeps onDark and onLight weight guards after adaptation guards', () => {
+ const themed = defineTheme({
+ name: 'surface-adapted-heading-weight',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ heading: {'weight:bold': {fontWeight: '800'}},
+ },
+ },
+ },
+ ],
+ },
+ onDark: {
+ components: {
+ heading: {'weight:bold': {fontWeight: '700'}},
+ },
+ },
+ onLight: {
+ components: {
+ heading: {'weight:bold': {fontWeight: '600'}},
+ },
+ },
+ });
+ const css = generateThemeCSS(themed).component;
+
+ expect(css.lastIndexOf('font-weight: 800')).toBeLessThan(
+ css.lastIndexOf('font-weight: 700'),
+ );
+ expect(css.lastIndexOf('font-weight: 700')).toBeLessThan(
+ css.lastIndexOf('font-weight: 600'),
+ );
+ expect(css.slice(css.lastIndexOf('font-weight: 700') - 200)).toContain(
+ '[data-astryx-media="dark"]',
+ );
+ expect(css.slice(css.lastIndexOf('font-weight: 600') - 200)).toContain(
+ '[data-astryx-media="light"]',
+ );
+ });
});
// =============================================================================
@@ -711,6 +1039,50 @@ describe('derived var expansion', () => {
expect(rule).not.toContain('padding-inline: var(--eps-input-padding-x)');
});
+ it('lowers onDark and onLight text-area paddingInline to the adaptation leaf', () => {
+ const theme = defineTheme({
+ name: 'test-media-derived-text-area',
+ adaptations: {
+ rules: [
+ {
+ when: {contrast: 'more'},
+ value: {
+ components: {
+ 'text-area': {base: {paddingInline: '12px'}},
+ },
+ },
+ },
+ ],
+ },
+ onDark: {
+ components: {
+ 'text-area': {base: {paddingInline: '24px'}},
+ },
+ },
+ onLight: {
+ components: {
+ 'text-area': {base: {paddingInline: '20px'}},
+ },
+ },
+ });
+
+ const adaptationCss = generateAdaptationCSS(theme).component;
+ const surfaceCss = generateOnMediaCSS(theme);
+ expect(adaptationCss).toContain('--_textarea-inline-padding: 12px');
+ expect(surfaceCss).toContain('--_textarea-inline-padding: 24px');
+ expect(surfaceCss).toContain('--_textarea-inline-padding: 20px');
+ expect(surfaceCss).not.toContain('padding-inline: 24px');
+ expect(surfaceCss).not.toContain('padding-inline: 20px');
+
+ const combinedCss = generateThemeCSS(theme).component;
+ expect(
+ combinedCss.indexOf('--_textarea-inline-padding: 12px'),
+ ).toBeLessThan(combinedCss.lastIndexOf('--_textarea-inline-padding: 24px'));
+ expect(
+ combinedCss.indexOf('--_textarea-inline-padding: 12px'),
+ ).toBeLessThan(combinedCss.lastIndexOf('--_textarea-inline-padding: 20px'));
+ });
+
it('replaces progressbar-mark width/height with vars (no raw properties)', () => {
const theme = defineTheme({
name: 'test-derived-progressbar-mark',
diff --git a/packages/core/src/theme/generateThemeRules.ts b/packages/core/src/theme/generateThemeRules.ts
index 03eb1bf087..05f4f8e46d 100644
--- a/packages/core/src/theme/generateThemeRules.ts
+++ b/packages/core/src/theme/generateThemeRules.ts
@@ -3,7 +3,9 @@
/**
* @file Theme CSS generation utilities
*
- * Shared logic for generating CSS rules from a resolved theme definition.
+ * Shared logic for generating CSS rules from a resolved theme definition,
+ * including one component-leaf lowering path for root, adaptation, and
+ * media-surface values plus condition-correct Heading weight precedence guards.
* Used by both the runtime path (Theme injects <style>) and the build
* path (`astryx theme build` pre-compiles to CSS files).
*
@@ -15,7 +17,11 @@
* @position packages/core/src/theme/generateThemeRules.ts
*/
-import type {DefinedTheme} from './defineTheme';
+import type {ComponentStyleMap, DefinedTheme} from './defineTheme';
+import {
+ normalizeThemeAdaptations,
+ resolveThemeAdaptationRules,
+} from './themeAdaptations';
import {parseStyleKey} from '../utils/parseStyleKey';
import {getDerivedVars} from './derivedVarRegistry';
import {dataTokenDefaults} from './domainTokens/dataTokens';
@@ -47,6 +53,18 @@ function componentClassSelector(component: string, suffix: string): string {
return `.${classPrefix}-${component}${suffix}`;
}
+type MediaSurface = 'dark' | 'light';
+
+/** Scope a component selector to an inverted media surface when requested. */
+function componentSelector(
+ component: string,
+ suffix: string,
+ surface?: MediaSurface,
+): string {
+ const selector = componentClassSelector(component, suffix);
+ return surface ? `:is(${mediaSelector(surface)}) :is(${selector})` : selector;
+}
+
/**
* Guard appended to a themed `:hover` rule so it cannot match a disabled
* element.
@@ -279,6 +297,7 @@ function parsePadding(props: [string, string][]): ParsedPadding {
function expandContainerPadding(
component: string,
parsed: ParsedPadding,
+ resetInheritedSpecificity = false,
): [string, string][] {
const prefix = cssVar(`${component}-padding`);
const tokens: [string, string][] = [];
@@ -301,26 +320,47 @@ function expandContainerPadding(
if (allSame) {
tokens.push([prefix, effectiveInlineStart ?? '']);
- return tokens;
- }
-
- // Directional tokens
- if (parsed.inlineStart != null || parsed.inlineEnd != null) {
- // Asymmetric inline — emit start and end separately
- if (effectiveInlineStart != null) {
- tokens.push([`${prefix}-inline-start`, effectiveInlineStart]);
+ } else {
+ // Directional tokens
+ if (parsed.inlineStart != null || parsed.inlineEnd != null) {
+ // Asymmetric inline — emit start and end separately
+ if (effectiveInlineStart != null) {
+ tokens.push([`${prefix}-inline-start`, effectiveInlineStart]);
+ }
+ if (effectiveInlineEnd != null) {
+ tokens.push([`${prefix}-inline-end`, effectiveInlineEnd]);
+ }
+ } else if (parsed.inline != null) {
+ tokens.push([`${prefix}-inline`, parsed.inline]);
}
- if (effectiveInlineEnd != null) {
- tokens.push([`${prefix}-inline-end`, effectiveInlineEnd]);
+ if (parsed.blockStart != null) {
+ tokens.push([`${prefix}-block-start`, parsed.blockStart]);
+ }
+ if (parsed.blockEnd != null) {
+ tokens.push([`${prefix}-block-end`, parsed.blockEnd]);
}
- } else if (parsed.inline != null) {
- tokens.push([`${prefix}-inline`, parsed.inline]);
- }
- if (parsed.blockStart != null) {
- tokens.push([`${prefix}-block-start`, parsed.blockStart]);
}
- if (parsed.blockEnd != null) {
- tokens.push([`${prefix}-block-end`, parsed.blockEnd]);
+
+ if (resetInheritedSpecificity) {
+ const emitted = new Set(tokens.map(([name]) => name));
+ const moreSpecific = emitted.has(prefix)
+ ? [
+ `${prefix}-inline`,
+ `${prefix}-inline-start`,
+ `${prefix}-inline-end`,
+ `${prefix}-block-start`,
+ `${prefix}-block-end`,
+ ]
+ : emitted.has(`${prefix}-inline`)
+ ? [`${prefix}-inline-start`, `${prefix}-inline-end`]
+ : [];
+ for (const name of moreSpecific) {
+ if (!emitted.has(name)) {
+ // `initial` makes a custom property guaranteed-invalid so var() follows
+ // its fallback, clearing a more-specific declaration from a root rule.
+ tokens.push([name, 'initial']);
+ }
+ }
}
return tokens;
@@ -336,13 +376,31 @@ function expandContainerPadding(
* Returns an array of CSS rule strings — the shared format used by both
* the runtime path (useInsertionEffect) and the build path (astryx theme build).
*/
-export function generateThemeRules(theme: DefinedTheme): string[] {
+/**
+ * The parts of a theme that turn into CSS rules.
+ *
+ * Narrower than `DefinedTheme` on purpose: an adaptation rule is not a whole
+ * theme, and it calls this with only the values that rule writes. Typing the
+ * parameter as `DefinedTheme` would let a future field be read here and silently
+ * lost for every conditional rule, with no type error to catch it.
+ */
+export interface ThemeRuleSource {
+ /** Resolved portable token values. */
+ tokens: Record<string, string>;
+ /** Resolved theme-local token values. */
+ localTokens?: Record<string, string>;
+ /** Resolved component style overrides. */
+ components?: ComponentStyleMap;
+}
+
+export function generateThemeRules(theme: ThemeRuleSource): string[] {
const parts: string[] = [];
const tokens = theme.tokens;
- // Helper: resolve a token value — tokens always have computed values
- // since defineTheme runs expandTypeScale to produce them.
- const val = (key: string): string => tokens[key] || `var(${key})`;
+ // Bare prose rules reference semantic variables instead of baking the root
+ // value. That lets adaptation token writes take effect through CSS alone
+ // without duplicating prose selectors inside every media query.
+ const val = (key: string): string => `var(${key})`;
// 1. Token block — CSS custom properties on :scope
const tokenEntries = [
@@ -390,6 +448,17 @@ const HEADING_WEIGHT_TOKEN_MAP: Record<string, string> = {
bold: 'var(--font-weight-bold)',
};
+interface HeadingWeightOverrideOptions {
+ /** Scope selectors to one on-media surface. */
+ surface?: MediaSurface;
+ /** Effective root components used as the surface fallback. */
+ inheritedComponents?: Record<string, unknown>;
+ /** Emit all standard choices even when this component map has no Heading. */
+ forceAll?: boolean;
+ /** Emit only choices whose rule explicitly writes fontWeight. */
+ authoredOnly?: boolean;
+}
+
/**
* Re-emit Heading's explicit weight choices in the theme layer.
*
@@ -401,14 +470,23 @@ const HEADING_WEIGHT_TOKEN_MAP: Record<string, string> = {
function generateHeadingWeightOverrides(
components: Record<string, unknown>,
parts: string[],
- surface?: 'dark' | 'light',
- inheritedComponents?: Record<string, unknown>,
+ {
+ surface,
+ inheritedComponents,
+ forceAll = false,
+ authoredOnly = false,
+ }: HeadingWeightOverrideOptions = {},
): void {
const headingRules = components.heading;
- if (!headingRules || typeof headingRules !== 'object') {
+ const headingRuleMap =
+ headingRules &&
+ typeof headingRules === 'object' &&
+ !Array.isArray(headingRules)
+ ? (headingRules as Record<string, unknown>)
+ : undefined;
+ if (!headingRuleMap && !forceAll) {
return;
}
- const headingRuleMap = headingRules as Record<string, unknown>;
const inheritedHeadingRules = inheritedComponents?.heading;
const inheritedHeadingRuleMap =
inheritedHeadingRules && typeof inheritedHeadingRules === 'object'
@@ -419,15 +497,18 @@ function generateHeadingWeightOverrides(
HEADING_WEIGHT_TOKEN_MAP,
)) {
const styleKey = `weight:${weightName}`;
- const authoredWeight = getAuthoredHeadingWeight(headingRuleMap, styleKey);
+ const authoredWeight = headingRuleMap
+ ? getAuthoredHeadingWeight(headingRuleMap, styleKey)
+ : undefined;
+ if (authoredOnly && authoredWeight === undefined) {
+ continue;
+ }
const inheritedWeight = inheritedHeadingRuleMap
? getAuthoredHeadingWeight(inheritedHeadingRuleMap, styleKey)
: undefined;
const effectiveWeight = authoredWeight ?? inheritedWeight ?? weightValue;
- const suffix = parseStyleKey(`weight:${weightName}`);
- const selector = surface
- ? `:is(${mediaSelector(surface)}) :is(${componentClassSelector('heading', suffix)})`
- : componentClassSelector('heading', suffix);
+ const suffix = parseStyleKey(styleKey);
+ const selector = componentSelector('heading', suffix, surface);
parts.push(` ${selector} { font-weight: ${effectiveWeight}; }`);
}
}
@@ -444,11 +525,17 @@ function getAuthoredHeadingWeight(
return typeof fontWeight === 'string' ? fontWeight : undefined;
}
+/** Options shared by root, adaptation, and media-surface component lowering. */
+interface ComponentRuleOptions {
+ resetInheritedPaddingSpecificity?: boolean;
+ surface?: MediaSurface;
+}
+
/**
* Generate component override rules using the .astryx-* class selector
- * format. Runtime components also emit matching data-* prop reflections; the
- * theme CSS generator will move to data-attribute selectors in a later step.
- * Handles derived var expansion and container padding mapping.
+ * format. Runtime components also emit matching data-* prop reflections for
+ * external selector migrations. Handles derived var expansion and container
+ * padding mapping for every theme layer.
*/
function generateComponentRules(
components: Record<
@@ -456,6 +543,10 @@ function generateComponentRules(
Record<string, Record<string, string | Record<string, string>>>
>,
parts: string[],
+ {
+ resetInheritedPaddingSpecificity = false,
+ surface,
+ }: ComponentRuleOptions = {},
): void {
for (const [component, rules] of Object.entries(components)) {
for (const [key, styles] of Object.entries(rules)) {
@@ -465,7 +556,7 @@ function generateComponentRules(
}
const suffix = parseStyleKey(key);
- const baseSelector = componentClassSelector(component, suffix);
+ const baseSelector = componentSelector(component, suffix, surface);
// Separate regular properties from pseudo-class overrides
const props: [string, string][] = [];
@@ -534,7 +625,11 @@ function generateComponentRules(
([p]) => !CONTAINER_PADDING_PROPS.has(p),
);
const parsed = parsePadding(paddingProps);
- const containerTokens = expandContainerPadding(component, parsed);
+ const containerTokens = expandContainerPadding(
+ component,
+ parsed,
+ resetInheritedPaddingSpecificity,
+ );
finalProps = [...nonPaddingProps, ...containerTokens];
}
@@ -630,6 +725,7 @@ function generateProseRules(
function generateColorOverrides(
components: Record<string, unknown>,
parts: string[],
+ surface?: MediaSurface,
): void {
const TEXT_COLOR_MAP: Record<string, string> = {
primary: 'var(--color-text-primary)',
@@ -647,17 +743,17 @@ function generateColorOverrides(
for (const [colorName, colorValue] of Object.entries(TEXT_COLOR_MAP)) {
if (touchesText) {
parts.push(
- ` ${componentClassSelector('text', `.${colorName}`)} { color: ${colorValue}; }`,
+ ` ${componentSelector('text', `.${colorName}`, surface)} { color: ${colorValue}; }`,
);
}
if (touchesHeading) {
parts.push(
- ` ${componentClassSelector('heading', `.${colorName}`)} { color: ${colorValue}; }`,
+ ` ${componentSelector('heading', `.${colorName}`, surface)} { color: ${colorValue}; }`,
);
}
if (touchesLink) {
parts.push(
- ` ${componentClassSelector('link', `.${colorName}`)} { color: ${colorValue}; }`,
+ ` ${componentSelector('link', `.${colorName}`, surface)} { color: ${colorValue}; }`,
);
}
}
@@ -704,6 +800,7 @@ const TEXT_SIZE_TOKEN_MAP: Record<string, string> = {
function generateSizeOverrides(
components: Record<string, unknown>,
parts: string[],
+ surface?: MediaSurface,
): void {
if (!('text' in components)) {
return;
@@ -711,7 +808,7 @@ function generateSizeOverrides(
for (const [sizeName, sizeValue] of Object.entries(TEXT_SIZE_TOKEN_MAP)) {
const suffix = parseStyleKey(`size:${sizeName}`);
parts.push(
- ` ${componentClassSelector('text', suffix)} { font-size: ${sizeValue}; }`,
+ ` ${componentSelector('text', suffix, surface)} { font-size: ${sizeValue}; }`,
);
}
}
@@ -770,64 +867,23 @@ export function generateOnMediaCSS(theme: DefinedTheme): string {
parts.push(` ${mediaSelector(surface)} {\n${declarations}\n }`);
}
- // Component overrides
+ // Component overrides use the same lowering as root and adaptations so a
+ // surface writes the same derived leaf and can win by source order.
if (onMedia.components) {
- for (const [component, rules] of Object.entries(onMedia.components)) {
- for (const [key, styles] of Object.entries(
- rules as Record<
- string,
- Record<string, string | Record<string, string>>
- >,
- )) {
- const entries = Object.entries(styles);
- if (entries.length === 0) {
- continue;
- }
-
- const suffix = parseStyleKey(key);
- const baseSelector = `:is(${mediaSelector(surface)}) :is(${componentClassSelector(component, suffix)})`;
-
- const props: [string, string][] = [];
- const pseudos: [string, Record<string, string>][] = [];
-
- for (const [prop, value] of entries) {
- if (prop.startsWith(':') && typeof value === 'object') {
- pseudos.push([prop, value]);
- } else {
- props.push([prop, value as string]);
- }
- }
-
- if (props.length > 0) {
- const declarations = props
- .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
- .join('\n');
- parts.push(` ${baseSelector} {\n${declarations}\n }`);
- }
-
- for (const [pseudo, pseudoStyles] of pseudos) {
- const pseudoEntries = Object.entries(pseudoStyles);
- if (pseudoEntries.length > 0) {
- const declarations = pseudoEntries
- .map(([prop, value]) => ` ${toKebabCase(prop)}: ${value};`)
- .join('\n');
- parts.push(
- ` ${appendPseudoToSelectorList(baseSelector, pseudo)} {\n${declarations}\n }`,
- );
- }
- }
- }
- }
+ generateComponentRules(onMedia.components, parts, {
+ resetInheritedPaddingSpecificity: true,
+ surface,
+ });
+ generateColorOverrides(onMedia.components, parts, surface);
+ generateSizeOverrides(onMedia.components, parts, surface);
// Apply the effective explicit Heading weight after media-specific type
// rules. A surface-authored target wins, followed by the inherited main
// target and then the built-in token fallback.
- generateHeadingWeightOverrides(
- onMedia.components,
- parts,
+ generateHeadingWeightOverrides(onMedia.components, parts, {
surface,
- theme.components,
- );
+ inheritedComponents: theme.components,
+ });
}
}
@@ -839,6 +895,149 @@ export function generateOnMediaCSS(theme: DefinedTheme): string {
return `@scope (${scopeSelector}) to (${THEME_SCOPE_TO}) {\n${inner}\n}`;
}
+/** Generate only the declarations one adaptation rule writes. */
+function generateAdaptationRuleRules(rule: ThemeRuleSource): string[] {
+ const parts: string[] = [];
+ const tokenEntries = [
+ ...Object.entries(rule.tokens),
+ ...Object.entries(rule.localTokens ?? {}),
+ ];
+ if (tokenEntries.length > 0) {
+ const declarations = tokenEntries
+ .map(([prop, value]) => ` ${prop}: ${value};`)
+ .join('\n');
+ parts.push(` :scope {\n${declarations}\n }`);
+ }
+
+ if (rule.components) {
+ generateComponentRules(rule.components, parts, {
+ resetInheritedPaddingSpecificity: true,
+ });
+ generateColorOverrides(rule.components, parts);
+ generateSizeOverrides(rule.components, parts);
+ }
+ return parts;
+}
+
+function hasHeadingComponentRules(
+ components: Record<string, unknown> | undefined,
+): boolean {
+ const headingRules = components?.heading;
+ return (
+ headingRules !== null &&
+ typeof headingRules === 'object' &&
+ !Array.isArray(headingRules)
+ );
+}
+
+function generateAdaptationMediaBlock(
+ query: string,
+ parts: string[],
+ scopeSelector: string,
+): string {
+ return `@media ${query} {\n @scope (${scopeSelector}) to (${THEME_SCOPE_TO}) {\n${parts
+ .map(indentRule)
+ .join('\n\n')}\n }\n}`;
+}
+
+/**
+ * Generate CSS for a theme's ordered adaptation rules.
+ *
+ * Each authored rule stays a separate media block in declaration order. Blocks
+ * are never merged, reordered, or value-diffed: a later rule that deliberately
+ * writes a root value must remain present so it can override an earlier matching
+ * rule. Bare prose follows semantic variables, so token writes need no duplicate
+ * prose selectors here.
+ */
+export function generateAdaptationCSS(theme: DefinedTheme): ThemeCSSOutput {
+ // Built themes can reach this compiler without passing through defineTheme.
+ // Validate retained metadata even when it has no rules (and therefore emits
+ // no CSS): width points remain observable through AppShell and inheritance.
+ const normalizedAdaptations =
+ theme.__adaptations === undefined
+ ? undefined
+ : normalizeThemeAdaptations(theme.name, theme.__adaptations, undefined);
+ const rules =
+ theme.__adaptationRules ??
+ (normalizedAdaptations
+ ? resolveThemeAdaptationRules(
+ theme.name,
+ normalizedAdaptations,
+ theme.__axes ?? {},
+ theme.tokens,
+ theme.localTokens,
+ )
+ : undefined);
+ if (!rules || rules.length === 0) {
+ return {prose: '', component: ''};
+ }
+
+ const scopeSelector = themeScopeStart(theme.name);
+ const blocks: string[] = [];
+ const adaptsHeading = rules.some(rule =>
+ hasHeadingComponentRules(rule.components),
+ );
+
+ // Emit ordinary rule writes first, without inherited Heading weight
+ // fallbacks. Carrying an earlier weight into a later block makes that value
+ // active whenever the later condition matches, even if the earlier condition
+ // does not. Pairwise merging cannot repair that: multiple mutually exclusive
+ // earlier rules can each overlap one broad later rule.
+ for (const rule of rules) {
+ const parts = generateAdaptationRuleRules(rule);
+ if (parts.length === 0) {
+ continue;
+ }
+ blocks.push(generateAdaptationMediaBlock(rule.query, parts, scopeSelector));
+ }
+
+ if (adaptsHeading) {
+ // Put one unconditional effective-root guard after every ordinary
+ // adaptation block. It restores the public weight prop above every
+ // conditional type/level default without attributing any prior rule's
+ // value to a condition that did not author it.
+ const rootWeightParts: string[] = [];
+ generateHeadingWeightOverrides(theme.components ?? {}, rootWeightParts, {
+ forceAll: true,
+ });
+ blocks.push(
+ `@scope (${scopeSelector}) to (${THEME_SCOPE_TO}) {\n${rootWeightParts.join(
+ '\n\n',
+ )}\n}`,
+ );
+
+ // Reapply only explicitly authored conditional weight writes, preserving
+ // authored rule order so co-matching writes retain last-write-wins.
+ for (const rule of rules) {
+ const authoredWeightParts: string[] = [];
+ generateHeadingWeightOverrides(
+ rule.components ?? {},
+ authoredWeightParts,
+ {authoredOnly: true},
+ );
+ if (authoredWeightParts.length > 0) {
+ blocks.push(
+ generateAdaptationMediaBlock(
+ rule.query,
+ authoredWeightParts,
+ scopeSelector,
+ ),
+ );
+ }
+ }
+ }
+
+ return {prose: '', component: blocks.join('\n\n')};
+}
+
+/** Indent a generated rule one level further, for nesting inside `@media`. */
+function indentRule(rule: string): string {
+ return rule
+ .split('\n')
+ .map(line => (line.length > 0 ? ` ${line}` : line))
+ .join('\n');
+}
+
/**
* The `--color-data-*` defaults as one unscoped `:root` block.
*
@@ -896,6 +1095,15 @@ export function generateThemeCSS(theme: DefinedTheme): ThemeCSSOutput {
componentCss = `@scope (${scopeSelector}) to (${scopeTo}) {\n${componentInner}\n}`;
}
+ // Adaptations follow the root theme in authored order. Media-surface rules
+ // follow adaptations so onDark/onLight keep their specified precedence.
+ const adaptationCss = generateAdaptationCSS(theme);
+ if (adaptationCss.component) {
+ componentCss = componentCss
+ ? `${componentCss}\n\n${adaptationCss.component}`
+ : adaptationCss.component;
+ }
+
const onMediaCss = generateOnMediaCSS(theme);
if (onMediaCss) {
componentCss = componentCss
diff --git a/packages/core/src/theme/index.ts b/packages/core/src/theme/index.ts
index 5b59e3dee2..ca77a84775 100644
--- a/packages/core/src/theme/index.ts
+++ b/packages/core/src/theme/index.ts
@@ -22,6 +22,7 @@ export {
defineTheme,
generateThemeCSS,
generateOnMediaCSS,
+ generateAdaptationCSS,
generateThemeRules,
generateThemeRulesSplit,
type ThemeCSSOutput,
@@ -38,6 +39,7 @@ export {
export type {
DefineThemeInput,
DefinedTheme,
+ ResolvedDefinedTheme,
CoreTokenName,
TokenName,
TokenValue,
@@ -45,6 +47,22 @@ export type {
StyleOverrides,
} from './defineTheme';
+// Ordered environment-conditioned theme adaptations
+export {
+ DEFAULT_WIDTH_BREAKPOINTS,
+ WIDTH_BREAKPOINT_NAMES,
+} from './themeAdaptations';
+export type {
+ WidthBreakpointName,
+ WidthBreakpoints,
+ ThemeAdaptations,
+ ThemeAdaptationCondition,
+ ThemeAdaptationWidthCondition,
+ ThemeAdaptationRule,
+ ThemeAdaptationValue,
+ ThemeAdaptationTypographyConfig,
+} from './themeAdaptations';
+
export type {
SyntaxTokenName,
DomainTokenName,
diff --git a/packages/core/src/theme/localTokens.ts b/packages/core/src/theme/localTokens.ts
index 397fa080bb..41ee0f57ce 100644
--- a/packages/core/src/theme/localTokens.ts
+++ b/packages/core/src/theme/localTokens.ts
@@ -1,5 +1,13 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
+/**
+ * @file localTokens.ts
+ * @input Root and adaptation theme-local token declarations and references
+ * @output Validated enrollment metadata plus normalized conditional writes
+ * @position Theme-local namespace owner; final adaptation-cycle validation is
+ * performed after the reachable ordered cascade is assembled.
+ */
+
import type {ComponentStyleMap, DefinedTheme, TokenValue} from './defineTheme';
import type {ResolvedOnMedia} from './onMediaTokens';
@@ -8,6 +16,11 @@ const THEME_NAME_PATTERN = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
const LOCAL_TOKEN_SUFFIX_PATTERN = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
const CSS_VAR_PATTERN = /var\(\s*(--[^,\s)]+)/gi;
+/** Whether a custom-property name belongs to Astryx's reserved local namespace. */
+export function isReservedThemeLocalTokenName(name: string): boolean {
+ return name.startsWith(LOCAL_TOKEN_PREFIX);
+}
+
export interface ResolvedLocalTokenContract {
localTokens: Record<string, string>;
owners: Record<string, string>;
@@ -43,7 +56,10 @@ function resolveTokenValue(value: TokenValue, path: string): string {
);
}
-function collectLocalReferences(value: unknown, refs: Set<string>): void {
+function collectCustomPropertyReferences(
+ value: unknown,
+ refs: Set<string>,
+): void {
if (typeof value === 'string') {
CSS_VAR_PATTERN.lastIndex = 0;
for (
@@ -51,58 +67,144 @@ function collectLocalReferences(value: unknown, refs: Set<string>): void {
match;
match = CSS_VAR_PATTERN.exec(value)
) {
- const name = match[1];
- if (name.startsWith(LOCAL_TOKEN_PREFIX)) {
- refs.add(name);
- }
+ refs.add(match[1]);
}
return;
}
if (Array.isArray(value)) {
for (const item of value) {
- collectLocalReferences(item, refs);
+ collectCustomPropertyReferences(item, refs);
}
return;
}
if (value && typeof value === 'object') {
for (const nested of Object.values(value)) {
- collectLocalReferences(nested, refs);
+ collectCustomPropertyReferences(nested, refs);
}
}
}
-function assertNoLocalTokenCycles(localTokens: Record<string, string>): void {
+function collectLocalReferences(value: unknown, refs: Set<string>): void {
+ const customProperties = new Set<string>();
+ collectCustomPropertyReferences(value, customProperties);
+ for (const name of customProperties) {
+ if (isReservedThemeLocalTokenName(name)) {
+ refs.add(name);
+ }
+ }
+}
+
+export function assertNoTokenCycles(
+ tokenValues: Record<string, string>,
+ context?: string,
+ relevantNames?: ReadonlySet<string>,
+): void {
const dependencies = new Map<string, string[]>();
- for (const [name, value] of Object.entries(localTokens)) {
+ for (const [name, value] of Object.entries(tokenValues)) {
const refs = new Set<string>();
- collectLocalReferences(value, refs);
+ collectCustomPropertyReferences(value, refs);
dependencies.set(
name,
- [...refs].filter(reference => hasOwn(localTokens, reference)),
+ [...refs].filter(reference => hasOwn(tokenValues, reference)),
);
}
- const visiting = new Set<string>();
- const visited = new Set<string>();
- const visit = (name: string, path: string[]): void => {
- if (visiting.has(name)) {
- const start = path.indexOf(name);
- const cycle = [...path.slice(start), name].join(' -> ');
- throw new Error(`Theme-local token cycle detected: ${cycle}.`);
+ const findCyclePath = (
+ start: string,
+ component: ReadonlySet<string>,
+ ): string[] => {
+ const path = [start];
+ const onPath = new Set(path);
+ const search = (name: string): boolean => {
+ for (const dependency of dependencies.get(name) ?? []) {
+ if (!component.has(dependency)) {
+ continue;
+ }
+ if (dependency === start) {
+ path.push(start);
+ return true;
+ }
+ if (onPath.has(dependency)) {
+ continue;
+ }
+ path.push(dependency);
+ onPath.add(dependency);
+ if (search(dependency)) {
+ return true;
+ }
+ onPath.delete(dependency);
+ path.pop();
+ }
+ return false;
+ };
+ search(start);
+ return path;
+ };
+
+ let nextIndex = 0;
+ const indexes = new Map<string, number>();
+ const lowlinks = new Map<string, number>();
+ const stack: string[] = [];
+ const onStack = new Set<string>();
+
+ const visit = (name: string): void => {
+ const index = nextIndex++;
+ indexes.set(name, index);
+ lowlinks.set(name, index);
+ stack.push(name);
+ onStack.add(name);
+
+ for (const dependency of dependencies.get(name) ?? []) {
+ if (!indexes.has(dependency)) {
+ visit(dependency);
+ lowlinks.set(
+ name,
+ Math.min(lowlinks.get(name) ?? index, lowlinks.get(dependency) ?? 0),
+ );
+ } else if (onStack.has(dependency)) {
+ lowlinks.set(
+ name,
+ Math.min(lowlinks.get(name) ?? index, indexes.get(dependency) ?? 0),
+ );
+ }
}
- if (visited.has(name)) {
+
+ if (lowlinks.get(name) !== index) {
return;
}
- visiting.add(name);
- for (const dependency of dependencies.get(name) ?? []) {
- visit(dependency, [...path, name]);
+
+ const component: string[] = [];
+ let member: string;
+ do {
+ member = stack.pop() ?? name;
+ onStack.delete(member);
+ component.push(member);
+ } while (member !== name);
+
+ const hasCycle =
+ component.length > 1 ||
+ (dependencies.get(component[0]) ?? []).includes(component[0]);
+ if (
+ !hasCycle ||
+ (relevantNames &&
+ !component.some(componentName => relevantNames.has(componentName)))
+ ) {
+ return;
}
- visiting.delete(name);
- visited.add(name);
+
+ const start =
+ component.find(componentName => relevantNames?.has(componentName)) ??
+ component[0];
+ const cycle = findCyclePath(start, new Set(component)).join(' -> ');
+ throw new Error(
+ `${context ? `${context}: ` : ''}Theme token cycle detected: ${cycle}.`,
+ );
};
- for (const name of Object.keys(localTokens)) {
- visit(name, []);
+ for (const name of Object.keys(tokenValues)) {
+ if (!indexes.has(name)) {
+ visit(name);
+ }
}
}
@@ -262,7 +364,7 @@ export function resolveLocalTokenContract(
}
assertDeclaredReferences(localTokens, components, onDark, onLight);
- assertNoLocalTokenCycles(localTokens);
+ assertNoTokenCycles(localTokens, `defineTheme("${input.name}").localTokens`);
return {
localTokens,
@@ -270,3 +372,66 @@ export function resolveLocalTokenContract(
lineage: [...(base?.__localTokenLineage ?? []), input.name],
};
}
+
+/**
+ * Resolve theme-local values written by one adaptation rule.
+ *
+ * Adaptations may replace names already enrolled by the root theme lineage, but
+ * they never enroll names of their own. This validates one rule's references;
+ * cycle validation waits until all co-matching writes have cascaded in order.
+ */
+export function resolveAdaptationLocalTokens(
+ themeName: string,
+ ruleIndex: number,
+ declarations: Record<string, TokenValue> | undefined,
+ rootLocalTokens: Record<string, string> | undefined,
+ tokens: Record<string, string>,
+ components: ComponentStyleMap | undefined,
+): Record<string, string> | undefined {
+ const path = `defineTheme("${themeName}").adaptations.rules[${ruleIndex}].value.localTokens`;
+ if (declarations === undefined) {
+ const refs = new Set<string>();
+ collectLocalReferences(tokens, refs);
+ collectLocalReferences(components, refs);
+ for (const reference of refs) {
+ if (!rootLocalTokens || !hasOwn(rootLocalTokens, reference)) {
+ throw new Error(
+ `${path}: theme-local token reference "${reference}" has no declaration in the enrolled root theme lineage.`,
+ );
+ }
+ }
+ return undefined;
+ }
+ if (
+ declarations === null ||
+ typeof declarations !== 'object' ||
+ Array.isArray(declarations)
+ ) {
+ throw new Error(`${path} must be a token map.`);
+ }
+
+ const resolved: Record<string, string> = {};
+ for (const [name, value] of Object.entries(declarations)) {
+ if (!rootLocalTokens || !hasOwn(rootLocalTokens, name)) {
+ throw new Error(
+ `${path}["${name}"] cannot enroll a theme-local token. Declare it in the root theme or an exact enrolled base first.`,
+ );
+ }
+ resolved[name] = resolveTokenValue(value, `${path}["${name}"]`);
+ }
+
+ const effective = {...rootLocalTokens, ...resolved};
+ const refs = new Set<string>();
+ collectLocalReferences(resolved, refs);
+ collectLocalReferences(tokens, refs);
+ collectLocalReferences(components, refs);
+ for (const reference of refs) {
+ if (!hasOwn(effective, reference)) {
+ throw new Error(
+ `${path}: theme-local token reference "${reference}" has no declaration in the enrolled root theme lineage.`,
+ );
+ }
+ }
+
+ return Object.keys(resolved).length > 0 ? resolved : undefined;
+}
diff --git a/packages/core/src/theme/resolveThemeValues.ts b/packages/core/src/theme/resolveThemeValues.ts
new file mode 100644
index 0000000000..acf306994a
--- /dev/null
+++ b/packages/core/src/theme/resolveThemeValues.ts
@@ -0,0 +1,338 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file resolveThemeValues.ts
+ * @input The value-bearing axes of a theme input (typography, color, radius,
+ * motion, syntax, tokens, components) and an optional resolved seed
+ * @output A resolved token map and component style map
+ * @position Theme system core; consumed by defineTheme and themeAdaptations
+ *
+ * One resolution pipeline, shared by every layer that turns declarative theme
+ * axes into concrete values. `defineTheme` runs its top-level input over an
+ * optional base seed. An adaptation rule completes partial axes from root
+ * metadata first, then runs its own value without a seed to obtain exactly the
+ * leaves that rule writes.
+ *
+ * Precedence inside one resolved layer, lowest to highest: seed → color → type
+ * scale → radius → motion → font families → syntax → explicit `tokens`.
+ * Ordered rule-vs-root and rule-vs-rule precedence is owned by
+ * `themeAdaptations` and CSS source order, outside this value resolver.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/theme/defineTheme.ts (its only other caller)
+ * - /packages/core/src/theme/themeAdaptations.ts
+ */
+
+import type {ComponentStyleMap, TokenName, TokenValue} from './defineTheme';
+import type {TypographyConfig, FontWeight} from './types';
+import type {SyntaxThemeDefinition} from './syntax';
+import {
+ expandTypeScale,
+ generateTypeScaleComponents,
+ type TypeScaleConfig,
+} from './expandTypeScale';
+import {expandMotionScale, type MotionScaleConfig} from './expandMotionScale';
+import {expandRadiusScale, type RadiusScaleConfig} from './expandRadiusScale';
+import {expandColorScale, type ColorScaleConfig} from './expandColorScale';
+import {deepMergeComponents} from './mergeComponents';
+
+// =============================================================================
+// Types
+// =============================================================================
+
+/**
+ * The value-bearing axes of a theme — everything that resolves to tokens or
+ * component styles. Deliberately excludes identity (`name`), inheritance
+ * (`extends`), the registries (`icons`, `indicators`), the surface overrides
+ * (`onDark`/`onLight`) and the tiers themselves: none of those participate in
+ * value resolution.
+ */
+export interface ThemeValuesInput {
+ /** Typography — fonts, scale, and weights. */
+ typography?: TypographyConfig;
+ /** Color scale configuration. */
+ color?: ColorScaleConfig;
+ /** Radius scale configuration. */
+ radius?: RadiusScaleConfig;
+ /** Motion scale configuration. */
+ motion?: MotionScaleConfig;
+ /** Syntax highlighting theme. */
+ syntax?: SyntaxThemeDefinition;
+ /** Explicit token overrides — highest precedence. */
+ tokens?: Partial<Record<TokenName, TokenValue>>;
+ /** Component style overrides. */
+ components?: ComponentStyleMap;
+}
+
+/** Already-resolved values to start from — the lowest precedence layer. */
+export interface ThemeValuesSeed {
+ /** Resolved token values. */
+ tokens?: Record<string, string>;
+ /** Resolved component styles. */
+ components?: ComponentStyleMap;
+}
+
+/** The resolved output of one theme layer. */
+export interface ResolvedThemeValues {
+ /** Resolved token CSS values. */
+ tokens: Record<string, string>;
+ /** Resolved component style overrides, if any. */
+ components?: ComponentStyleMap;
+}
+
+// =============================================================================
+// Value helpers
+// =============================================================================
+
+/**
+ * Resolve a token value to a CSS string.
+ * - String values pass through as-is
+ * - [light, dark] tuples become light-dark(light, dark)
+ *
+ * `strict` decides what happens to anything else, and the split is a
+ * compatibility boundary rather than a preference:
+ *
+ * - LENIENT (default) is the behavior `defineTheme` has always had. `TokenValue`
+ * is a compile-time contract only, and themes reach this function through
+ * casts, broad spreads, generated objects and plain JavaScript, so values
+ * outside the type genuinely do arrive. Historically a two-element array
+ * became `light-dark()` and everything else passed through untouched;
+ * rejecting those now would break themes that build today and have nothing
+ * to do with adaptations.
+ * - STRICT is for values authored inside an adaptation rule. That surface is
+ * new, so there is no established acceptance to preserve, and a malformed
+ * value there is worth catching before it reaches CSS.
+ *
+ * SYNC: packages/core/src/theme/themeAdaptations.ts (strict resolution)
+ */
+export function resolveTokenValue(
+ value: TokenValue,
+ {strict = false}: {strict?: boolean} = {},
+): string {
+ if (typeof value === 'string') {
+ return value;
+ }
+ if (
+ Array.isArray(value) &&
+ value.length === 2 &&
+ typeof value[0] === 'string' &&
+ typeof value[1] === 'string'
+ ) {
+ return `light-dark(${value[0]}, ${value[1]})`;
+ }
+ if (strict) {
+ throw new Error(
+ 'Theme token values must be CSS strings or [light, dark] string tuples.',
+ );
+ }
+ // The legacy path, preserved verbatim: any array is read as a light/dark
+ // pair, and a non-string scalar is emitted as it always was. TypeScript has
+ // narrowed `value` to `never` by here — by the declared type these cannot
+ // exist, and that mismatch with runtime is exactly why this path stays.
+ if (Array.isArray(value)) {
+ return `light-dark(${value[0]}, ${value[1]})`;
+ }
+ return value;
+}
+
+/**
+ * Resolve a FontWeight name to a var() reference.
+ * Named weights map to var(--font-weight-*); raw values pass through.
+ */
+export function resolveFontWeight(weight: FontWeight): string {
+ const named: Record<string, string> = {
+ normal: 'var(--font-weight-normal)',
+ medium: 'var(--font-weight-medium)',
+ semibold: 'var(--font-weight-semibold)',
+ bold: 'var(--font-weight-bold)',
+ };
+ return named[weight] ?? weight;
+}
+
+/**
+ * Build the full CSS font-family value from family + fallbacks.
+ * Quotes the family name if it contains spaces.
+ */
+export function buildFontFamily(
+ family?: string,
+ fallbacks?: string,
+): string | undefined {
+ if (!family) {
+ return undefined;
+ }
+ const quoted = family.includes(' ') ? `"${family}"` : family;
+ if (fallbacks) {
+ return `${quoted}, ${fallbacks}`;
+ }
+ return quoted;
+}
+
+// =============================================================================
+// Axis builders
+// =============================================================================
+
+/**
+ * Build the type-scale config from a typography config, collecting the weight
+ * overrides its roles imply.
+ *
+ * Returns undefined when the config declares no scale — font families and
+ * weights alone do not produce one.
+ */
+export function buildTypeScaleConfig(
+ typo: TypographyConfig,
+): TypeScaleConfig | undefined {
+ if (!typo.scale) {
+ return undefined;
+ }
+
+ // Collect weight overrides from typography roles
+ const headingWeights: Partial<Record<1 | 2 | 3 | 4 | 5 | 6, string>> = {};
+ const headingRole = typo.heading;
+ if (headingRole?.weights) {
+ for (const [level, w] of Object.entries(headingRole.weights)) {
+ if (w) {
+ headingWeights[Number(level) as 1 | 2 | 3 | 4 | 5 | 6] =
+ resolveFontWeight(w);
+ }
+ }
+ }
+ // Default heading weight from role
+ const defaultHeadingWeight = headingRole?.weight
+ ? resolveFontWeight(headingRole.weight)
+ : undefined;
+ if (defaultHeadingWeight) {
+ for (let i = 1; i <= 6; i++) {
+ if (!(i in headingWeights)) {
+ headingWeights[i as 1 | 2 | 3 | 4 | 5 | 6] = defaultHeadingWeight;
+ }
+ }
+ }
+
+ // Text weight overrides from roles
+ const textWeights: Partial<Record<string, string>> = {};
+ if (typo.body?.weight) {
+ textWeights.body = resolveFontWeight(typo.body.weight);
+ }
+ if (typo.code?.weight) {
+ textWeights.code = resolveFontWeight(typo.code.weight);
+ }
+
+ return {
+ base: typo.scale.base,
+ ratio: typo.scale.ratio,
+ weights: {
+ ...(Object.keys(headingWeights).length > 0
+ ? {heading: headingWeights}
+ : {}),
+ ...(Object.keys(textWeights).length > 0 ? {text: textWeights} : {}),
+ },
+ };
+}
+
+/**
+ * Build the `--font-family-*` token overrides implied by a typography config.
+ * Heading inherits from body when it declares no family of its own.
+ */
+export function buildFontFamilyTokens(
+ typo: TypographyConfig,
+): Record<string, string> {
+ const tokens: Record<string, string> = {};
+
+ const bodyFamily = buildFontFamily(typo.body?.family, typo.body?.fallbacks);
+ const headingFamily =
+ buildFontFamily(typo.heading?.family, typo.heading?.fallbacks) ??
+ bodyFamily;
+ const codeFamily = buildFontFamily(typo.code?.family, typo.code?.fallbacks);
+
+ if (bodyFamily) {
+ tokens['--font-family-body'] = bodyFamily;
+ }
+ if (headingFamily) {
+ tokens['--font-family-heading'] = headingFamily;
+ }
+ if (codeFamily) {
+ tokens['--font-family-code'] = codeFamily;
+ }
+
+ return tokens;
+}
+
+// =============================================================================
+// Resolution
+// =============================================================================
+
+/**
+ * Resolve one theme layer's declarative axes into tokens and component styles.
+ *
+ * `seed` is the already-resolved layer underneath — the base theme for an
+ * `extends`, or nothing for a root theme. It sits below everything this input
+ * declares.
+ */
+export function resolveThemeValues(
+ input: ThemeValuesInput,
+ seed?: ThemeValuesSeed,
+ {strictTokens = false}: {strictTokens?: boolean} = {},
+): ResolvedThemeValues {
+ const tokens: Record<string, string> = {...seed?.tokens};
+
+ const typo = input.typography;
+ const typeScaleConfig = typo ? buildTypeScaleConfig(typo) : undefined;
+
+ // 1. Color-generated tokens (lowest precedence for colors)
+ if (input.color) {
+ Object.assign(tokens, expandColorScale(input.color));
+ }
+
+ // 2. Type-scale-generated tokens
+ if (typeScaleConfig) {
+ Object.assign(tokens, expandTypeScale(typeScaleConfig));
+ }
+
+ // 3. Radius-generated tokens
+ if (input.radius) {
+ Object.assign(tokens, expandRadiusScale(input.radius));
+ }
+
+ // 4. Motion-generated tokens
+ if (input.motion) {
+ Object.assign(tokens, expandMotionScale(input.motion));
+ }
+
+ // 5. Font family tokens
+ if (typo) {
+ Object.assign(tokens, buildFontFamilyTokens(typo));
+ }
+
+ // 6. Syntax theme tokens
+ if (input.syntax) {
+ const prefix = '--color-syntax-';
+ for (const [key, value] of Object.entries(input.syntax.tokens)) {
+ tokens[prefix + key] = value;
+ }
+ }
+
+ // 7. Explicit token overrides — highest precedence within this input layer.
+ // A generated axis in the same root or adaptation value cannot beat them.
+ if (input.tokens) {
+ for (const [key, value] of Object.entries(input.tokens)) {
+ if (value !== undefined) {
+ tokens[key] = resolveTokenValue(value, {strict: strictTokens});
+ }
+ }
+ }
+
+ // Components: generated type-scale rules (lowest) → this input's own →
+ // all of it over the seed's.
+ let components = input.components;
+ if (typeScaleConfig) {
+ components = deepMergeComponents(
+ generateTypeScaleComponents(typeScaleConfig),
+ input.components,
+ );
+ }
+ if (seed?.components) {
+ components = deepMergeComponents(seed.components, components);
+ }
+
+ return {tokens, components};
+}
diff --git a/packages/core/src/theme/themeAdaptations.test.ts b/packages/core/src/theme/themeAdaptations.test.ts
new file mode 100644
index 0000000000..3ee264358b
--- /dev/null
+++ b/packages/core/src/theme/themeAdaptations.test.ts
@@ -0,0 +1,1199 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file themeAdaptations.test.ts
+ * Tests AST-012's ordered, closed, CSS-first theme adaptation contract,
+ * including normalization and final reachable-cascade validation.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {
+ DEFAULT_WIDTH_BREAKPOINTS,
+ WIDTH_BREAKPOINT_NAMES,
+ defineTheme,
+ generateAdaptationCSS,
+ generateThemeCSS,
+ type DefineThemeInput,
+ type DefinedTheme,
+} from './index';
+
+function adaptationInput(
+ rules: NonNullable<NonNullable<DefineThemeInput['adaptations']>['rules']>,
+): DefineThemeInput {
+ return {name: 'adaptive', adaptations: {rules}};
+}
+
+function mediaPreludes(css: string): string[] {
+ return [...css.matchAll(/@media ([^{]+) \{/g)].map(match => match[1]);
+}
+
+function count(haystack: string, needle: string): number {
+ return haystack.split(needle).length - 1;
+}
+
+describe('width breakpoint metadata', () => {
+ it('provides the accepted fixed names and defaults', () => {
+ const theme = defineTheme({name: 'defaults'});
+
+ expect(WIDTH_BREAKPOINT_NAMES).toEqual(['sm', 'md', 'lg', 'xl', '2xl']);
+ expect(DEFAULT_WIDTH_BREAKPOINTS).toEqual({
+ sm: 640,
+ md: 768,
+ lg: 1024,
+ xl: 1280,
+ '2xl': 1536,
+ });
+ expect(theme.__adaptations).toEqual({
+ widthBreakpoints: DEFAULT_WIDTH_BREAKPOINTS,
+ rules: [],
+ });
+ });
+
+ it('lets a theme override fixed points without emitting CSS', () => {
+ const theme = defineTheme({
+ name: 'points-only',
+ adaptations: {widthBreakpoints: {md: 800, lg: 1100}},
+ });
+
+ expect(theme.__adaptations.widthBreakpoints).toEqual({
+ ...DEFAULT_WIDTH_BREAKPOINTS,
+ md: 800,
+ lg: 1100,
+ });
+ expect(generateAdaptationCSS(theme)).toEqual({prose: '', component: ''});
+ expect(generateThemeCSS(theme).component).not.toContain('@media');
+ });
+
+ it('validates built breakpoint metadata even when there are no rules to emit', () => {
+ const built = {
+ name: 'stale-built-points',
+ __built: true,
+ tokens: {},
+ __adaptations: {
+ widthBreakpoints: {
+ sm: 640,
+ md: 768,
+ lg: 700,
+ xl: 1280,
+ '2xl': 1536,
+ },
+ rules: [],
+ },
+ __axes: {},
+ } as unknown as DefinedTheme;
+
+ expect(() => generateAdaptationCSS(built)).toThrow(/strictly increasing/);
+ });
+
+ it.each([
+ [{phone: 500}, /phone is not supported/],
+ [{md: 0}, /md must be a finite positive number/],
+ [{md: Number.NaN}, /md must be a finite positive number/],
+ [{md: 1100, lg: 1000}, /strictly increasing/],
+ ])('rejects an invalid breakpoint map %#', (widthBreakpoints, message) => {
+ expect(() =>
+ defineTheme({
+ name: 'bad-points',
+ adaptations: {
+ widthBreakpoints,
+ } as unknown as DefineThemeInput['adaptations'],
+ }),
+ ).toThrow(message);
+ });
+});
+
+describe('closed conditions and media queries', () => {
+ it('lowers inclusive from and exclusive below edges', () => {
+ const theme = defineTheme(
+ adaptationInput([
+ {
+ when: {width: {below: 'sm'}},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ {
+ when: {width: {from: 'lg', below: 'xl'}},
+ value: {tokens: {'--spacing-4': '20px'}},
+ },
+ {
+ when: {width: {from: '2xl'}},
+ value: {tokens: {'--spacing-4': '24px'}},
+ },
+ ]),
+ );
+
+ expect(mediaPreludes(generateAdaptationCSS(theme).component)).toEqual([
+ '(width < 640px)',
+ '(width >= 1024px) and (width < 1280px)',
+ '(width >= 1536px)',
+ ]);
+ });
+
+ it('ANDs width, pointer, contrast, and motion in a stable order', () => {
+ const theme = defineTheme(
+ adaptationInput([
+ {
+ when: {
+ motion: 'reduce',
+ pointer: 'coarse',
+ width: {from: 'md', below: 'xl'},
+ contrast: 'more',
+ },
+ value: {tokens: {'--duration-fast': '0ms'}},
+ },
+ ]),
+ );
+
+ expect(mediaPreludes(generateAdaptationCSS(theme).component)).toEqual([
+ '(width >= 768px) and (width < 1280px) and (pointer: coarse) and (prefers-contrast: more) and (prefers-reduced-motion: reduce)',
+ ]);
+ });
+
+ it.each([
+ [{}, /must contain at least one condition/],
+ [{pointer: undefined}, /must contain at least one condition/],
+ [{width: {}}, /must contain `from`, `below`, or both/],
+ [{width: {from: 'lg', below: 'md'}}, /must resolve to `from < below`/],
+ [{hover: true}, /hover is not supported/],
+ [{pointer: 'any'}, /pointer must be 'coarse' or 'fine'/],
+ ])('rejects an invalid condition %#', (when, message) => {
+ expect(() =>
+ defineTheme(
+ adaptationInput([
+ {
+ when,
+ value: {tokens: {'--spacing-4': '12px'}},
+ } as never,
+ ]),
+ ),
+ ).toThrow(message);
+ });
+
+ it('rejects positional rules and root-owned fields in a rule value', () => {
+ expect(() =>
+ defineTheme({
+ name: 'tuple-rule',
+ adaptations: {
+ rules: [[{pointer: 'coarse'}, {tokens: {'--spacing-4': '12px'}}]],
+ },
+ } as unknown as DefineThemeInput),
+ ).toThrow(/must be an object/);
+
+ expect(() =>
+ defineTheme({
+ name: 'identity-in-rule',
+ adaptations: {
+ rules: [{when: {pointer: 'coarse'}, value: {icons: {}}}],
+ },
+ } as unknown as DefineThemeInput),
+ ).toThrow(/value.icons is not supported/);
+ });
+
+ it('rejects sparse rule arrays during normalization', () => {
+ const rules = new Array(1) as NonNullable<
+ NonNullable<DefineThemeInput['adaptations']>['rules']
+ >;
+
+ expect(() => defineTheme(adaptationInput(rules))).toThrow(
+ /adaptations\.rules\[0\].*must be present/i,
+ );
+ });
+});
+
+describe('rule order and writes', () => {
+ it('preserves duplicate conditions and later root-restoring writes', () => {
+ const theme = defineTheme({
+ name: 'ordered',
+ tokens: {'--spacing-4': '16px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--spacing-4': '16px'}},
+ },
+ ],
+ },
+ });
+ const css = generateAdaptationCSS(theme).component;
+
+ expect(count(css, '@media (pointer: coarse)')).toBe(2);
+ expect(css.indexOf('--spacing-4: 12px')).toBeLessThan(
+ css.indexOf('--spacing-4: 16px'),
+ );
+ });
+
+ it('uses declaration order rather than inferred condition specificity', () => {
+ const theme = defineTheme(
+ adaptationInput([
+ {
+ when: {width: {from: 'md', below: 'lg'}, pointer: 'coarse'},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--spacing-4': '20px'}},
+ },
+ ]),
+ );
+ const css = generateAdaptationCSS(theme).component;
+
+ expect(css.indexOf('--spacing-4: 12px')).toBeLessThan(
+ css.indexOf('--spacing-4: 20px'),
+ );
+ });
+
+ it('emits no block for an empty value while retaining the normalized rule', () => {
+ const theme = defineTheme(
+ adaptationInput([
+ {when: {pointer: 'coarse'}, value: {}},
+ {
+ when: {pointer: 'fine'},
+ value: {tokens: {'--spacing-4': '18px'}},
+ },
+ ]),
+ );
+
+ expect(theme.__adaptations.rules).toHaveLength(2);
+ expect(count(generateAdaptationCSS(theme).component, '@media')).toBe(1);
+ });
+
+ it('lets explicit values beat generated values within one rule', () => {
+ const theme = defineTheme({
+ name: 'rule-precedence',
+ color: {accent: '#0064E0'},
+ adaptations: {
+ rules: [
+ {
+ when: {contrast: 'more'},
+ value: {
+ color: {accent: '#00AA00'},
+ tokens: {'--color-accent': '#FF0000'},
+ },
+ },
+ ],
+ },
+ });
+
+ expect(theme.__adaptationRules?.[0].tokens['--color-accent']).toBe(
+ '#FF0000',
+ );
+ });
+
+ it('treats generated leaves as rule writes above root token pins', () => {
+ const theme = defineTheme({
+ name: 'generated-write',
+ typography: {scale: {base: 14, ratio: 1.2}},
+ tokens: {'--font-size-base': '2rem'},
+ adaptations: {
+ rules: [
+ {
+ when: {width: {below: 'sm'}},
+ value: {typography: {scale: {base: 16}}},
+ },
+ ],
+ },
+ });
+
+ expect(theme.tokens['--font-size-base']).toBe('2rem');
+ expect(theme.__adaptationRules?.[0].tokens['--font-size-base']).toBe(
+ '1rem',
+ );
+ });
+
+ it('writes font families without re-expanding an untouched root scale', () => {
+ const theme = defineTheme({
+ name: 'family-only',
+ typography: {scale: {base: 14, ratio: 1.2}},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {typography: {body: {family: 'Geist'}}},
+ },
+ ],
+ },
+ });
+
+ const rule = theme.__adaptationRules?.[0];
+ expect(rule?.tokens['--font-family-body']).toBe('Geist');
+ expect(rule?.tokens['--font-size-base']).toBeUndefined();
+ expect(rule?.components).toBeUndefined();
+ });
+
+ it('completes partial scales from root metadata and refuses approximations', () => {
+ const complete = defineTheme({
+ name: 'complete-scale',
+ typography: {scale: {base: 14, ratio: 1.25}},
+ radius: {base: 6, multiplier: 1},
+ adaptations: {
+ rules: [
+ {
+ when: {width: {below: 'md'}},
+ value: {
+ typography: {scale: {base: 16}},
+ radius: {multiplier: 2},
+ },
+ },
+ ],
+ },
+ });
+
+ expect(complete.__adaptationRules?.[0].tokens['--font-size-lg']).toBe(
+ '1.25rem',
+ );
+ expect(complete.__adaptationRules?.[0].tokens['--radius-element']).toBe(
+ '24px',
+ );
+
+ expect(() =>
+ defineTheme({
+ name: 'missing-scale',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {motion: {fast: 100}},
+ },
+ ],
+ },
+ }),
+ ).toThrow(/must supply `fast`, `medium`, and `ratio`/);
+ });
+
+ it('lowers component writes through the ordinary derived-variable path', () => {
+ const theme = defineTheme(
+ adaptationInput([
+ {
+ when: {pointer: 'coarse'},
+ value: {components: {button: {base: {borderRadius: '20px'}}}},
+ },
+ ]),
+ );
+
+ const css = generateAdaptationCSS(theme).component;
+ expect(css).toContain('--_button-radius: 20px');
+ });
+});
+
+describe('theme-local adaptation values', () => {
+ const localName = '--astryx-theme-local-root-control-height';
+
+ it('replaces an enrolled exact name and permits rule references to it', () => {
+ const theme = defineTheme({
+ name: 'local-root',
+ localTokens: {[localName]: '32px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ localTokens: {[localName]: '44px'},
+ components: {
+ button: {base: {minHeight: `var(${localName})`}},
+ },
+ },
+ },
+ ],
+ },
+ });
+
+ expect(theme.__adaptationRules?.[0].localTokens).toEqual({
+ [localName]: '44px',
+ });
+ expect(generateAdaptationCSS(theme).component).toContain(
+ `${localName}: 44px`,
+ );
+ });
+
+ it('does not let a rule enroll or misroute a local name', () => {
+ expect(() =>
+ defineTheme({
+ name: 'rule-enroll',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ localTokens: {
+ '--astryx-theme-rule-enroll-new-name': '44px',
+ },
+ },
+ },
+ ],
+ },
+ }),
+ ).toThrow(/cannot enroll a theme-local token/);
+
+ expect(() =>
+ defineTheme({
+ name: 'local-root',
+ localTokens: {[localName]: '32px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {[localName]: '44px'}},
+ },
+ ],
+ },
+ } as unknown as DefineThemeInput),
+ ).toThrow(/write it through value.localTokens/);
+ });
+
+ it('rejects reserved local-token names through value.tokens even when unenrolled', () => {
+ expect(() =>
+ defineTheme({
+ name: 'reserved-rule-token',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ tokens: {
+ '--astryx-theme-unrelated-owner-control-height': '44px',
+ },
+ },
+ },
+ ],
+ },
+ } as unknown as DefineThemeInput),
+ ).toThrow(/reserved.*value\.localTokens/i);
+ });
+
+ it('rejects undeclared references and conditional cycles', () => {
+ expect(() =>
+ defineTheme({
+ name: 'local-root',
+ localTokens: {[localName]: '32px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ components: {
+ button: {
+ base: {
+ minHeight: 'var(--astryx-theme-local-root-missing-name)',
+ },
+ },
+ },
+ },
+ },
+ ],
+ },
+ }),
+ ).toThrow(/has no declaration/);
+
+ const a = '--astryx-theme-cycle-local-a';
+ const b = '--astryx-theme-cycle-local-b';
+ expect(() =>
+ defineTheme({
+ name: 'cycle-local',
+ localTokens: {[a]: '1px', [b]: `var(${a})`},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {[a]: `var(${b})`}},
+ },
+ ],
+ },
+ }),
+ ).toThrow(/Theme token cycle detected/);
+ });
+
+ it('rejects a cycle formed only by simultaneously matching rules', () => {
+ const a = '--astryx-theme-overlap-cycle-a';
+ const b = '--astryx-theme-overlap-cycle-b';
+
+ expect(() =>
+ defineTheme({
+ name: 'overlap-cycle',
+ localTokens: {[a]: '1px', [b]: '2px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {[a]: `var(${b})`}},
+ },
+ {
+ when: {contrast: 'more'},
+ value: {localTokens: {[b]: `var(${a})`}},
+ },
+ ],
+ },
+ }),
+ ).toThrow(/overlapping rules \[0, 1\].*cycle detected/i);
+ });
+
+ it('rejects cycles routed through portable adaptation tokens', () => {
+ const local = '--astryx-theme-portable-cycle-a';
+ expect(() =>
+ defineTheme({
+ name: 'portable-cycle',
+ localTokens: {[local]: '1px'},
+ tokens: {'--color-background-body': 'white'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ tokens: {'--color-background-body': `var(${local})`},
+ },
+ },
+ {
+ when: {contrast: 'more'},
+ value: {
+ localTokens: {[local]: 'var(--color-background-body)'},
+ },
+ },
+ ],
+ },
+ }),
+ ).toThrow(/overlapping rules \[0, 1\].*cycle detected/i);
+
+ const singleLocal = '--astryx-theme-single-portable-cycle-a';
+ expect(() =>
+ defineTheme({
+ name: 'single-portable-cycle',
+ localTokens: {[singleLocal]: '1px'},
+ tokens: {'--color-background-body': 'white'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ tokens: {
+ '--color-background-body': `var(${singleLocal})`,
+ },
+ localTokens: {
+ [singleLocal]: 'var(--color-background-body)',
+ },
+ },
+ },
+ ],
+ },
+ }),
+ ).toThrow(/adaptations rule \[0\].*cycle detected/i);
+
+ expect(() =>
+ defineTheme({
+ name: 'portable-only-cycle',
+ tokens: {
+ '--color-background-body': 'white',
+ '--color-background-surface': 'gray',
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ tokens: {
+ '--color-background-body': 'var(--color-background-surface)',
+ },
+ },
+ },
+ {
+ when: {contrast: 'more'},
+ value: {
+ tokens: {
+ '--color-background-surface': 'var(--color-background-body)',
+ },
+ },
+ },
+ ],
+ },
+ }),
+ ).toThrow(/overlapping rules \[0, 1\].*cycle detected/i);
+ });
+
+ it('does not attribute an unrelated pre-existing root cycle to a rule', () => {
+ expect(() =>
+ defineTheme({
+ name: 'unrelated-root-cycle',
+ tokens: {
+ '--color-background-body': 'var(--color-background-surface)',
+ '--color-background-surface': 'var(--color-background-body)',
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ ],
+ },
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects a rule cycle that shares an edge with a root-only cycle', () => {
+ expect(() =>
+ defineTheme({
+ name: 'shared-cycle-edge',
+ tokens: {
+ '--color-background-body':
+ 'linear-gradient(var(--color-background-surface), var(--color-background-muted))',
+ '--color-background-surface': 'var(--color-background-card)',
+ '--color-background-card': 'var(--color-background-body)',
+ '--color-background-muted': 'white',
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ tokens: {
+ '--color-background-muted': 'var(--color-background-card)',
+ },
+ },
+ },
+ ],
+ },
+ }),
+ ).toThrow(/adaptations rule \[0\].*cycle detected/i);
+ });
+
+ it('rejects a three-rule cycle that no pair creates', () => {
+ const a = '--astryx-theme-three-way-cycle-a';
+ const b = '--astryx-theme-three-way-cycle-b';
+ const c = '--astryx-theme-three-way-cycle-c';
+
+ expect(() =>
+ defineTheme({
+ name: 'three-way-cycle',
+ localTokens: {[a]: '1px', [b]: '2px', [c]: '3px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {[a]: `var(${b})`}},
+ },
+ {
+ when: {contrast: 'more'},
+ value: {localTokens: {[b]: `var(${c})`}},
+ },
+ {
+ when: {motion: 'reduce'},
+ value: {localTokens: {[c]: `var(${a})`}},
+ },
+ ],
+ },
+ }),
+ ).toThrow(/overlapping rules \[0, 1, 2\].*cycle detected/i);
+ });
+
+ it('allows mutually exclusive writes and a later matching cycle repair', () => {
+ const exclusiveA = '--astryx-theme-exclusive-cycle-a';
+ const exclusiveB = '--astryx-theme-exclusive-cycle-b';
+ expect(() =>
+ defineTheme({
+ name: 'exclusive-cycle',
+ localTokens: {[exclusiveA]: '1px', [exclusiveB]: '2px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {[exclusiveA]: `var(${exclusiveB})`}},
+ },
+ {
+ when: {pointer: 'fine'},
+ value: {localTokens: {[exclusiveB]: `var(${exclusiveA})`}},
+ },
+ ],
+ },
+ }),
+ ).not.toThrow();
+
+ const widthA = '--astryx-theme-width-exclusive-cycle-a';
+ const widthB = '--astryx-theme-width-exclusive-cycle-b';
+ expect(() =>
+ defineTheme({
+ name: 'width-exclusive-cycle',
+ localTokens: {[widthA]: '1px', [widthB]: '2px'},
+ adaptations: {
+ rules: [
+ {
+ when: {width: {below: 'md'}},
+ value: {localTokens: {[widthA]: `var(${widthB})`}},
+ },
+ {
+ when: {width: {from: 'md'}},
+ value: {localTokens: {[widthB]: `var(${widthA})`}},
+ },
+ ],
+ },
+ }),
+ ).not.toThrow();
+
+ const repairedA = '--astryx-theme-repaired-cycle-a';
+ const repairedB = '--astryx-theme-repaired-cycle-b';
+ expect(() =>
+ defineTheme({
+ name: 'repaired-cycle',
+ localTokens: {[repairedA]: '1px', [repairedB]: '2px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {[repairedA]: `var(${repairedB})`}},
+ },
+ {
+ when: {contrast: 'more'},
+ value: {localTokens: {[repairedB]: `var(${repairedA})`}},
+ },
+ {
+ when: {pointer: 'coarse', contrast: 'more'},
+ value: {localTokens: {[repairedB]: '4px'}},
+ },
+ ],
+ },
+ }),
+ ).not.toThrow();
+ });
+
+ it('allows a later co-matching rule to repair a cycle from one rule', () => {
+ const a = '--astryx-theme-direct-repair-a';
+ const b = '--astryx-theme-direct-repair-b';
+
+ expect(() =>
+ defineTheme({
+ name: 'direct-repair',
+ localTokens: {[a]: '1px', [b]: `var(${a})`},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {[a]: `var(${b})`}},
+ },
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {[b]: '2px'}},
+ },
+ ],
+ },
+ }),
+ ).not.toThrow();
+ });
+
+ it('checks inherited and child rules in the same reachable cascade', () => {
+ const a = '--astryx-theme-cycle-base-a';
+ const b = '--astryx-theme-cycle-base-b';
+ const base = defineTheme({
+ name: 'cycle-base',
+ localTokens: {[a]: '1px', [b]: '2px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {localTokens: {[a]: `var(${b})`}},
+ },
+ ],
+ },
+ });
+
+ expect(() =>
+ defineTheme({
+ name: 'cycle-child',
+ extends: base,
+ adaptations: {
+ rules: [
+ {
+ when: {contrast: 'more'},
+ value: {localTokens: {[b]: `var(${a})`}},
+ },
+ ],
+ },
+ }),
+ ).toThrow(
+ /overlapping rules \[0, 1\].*pointer: coarse.*prefers-contrast: more.*cycle detected/i,
+ );
+ });
+});
+
+describe('extension semantics and built metadata', () => {
+ it('inherits breakpoint overrides and appends child rules', () => {
+ const base = defineTheme({
+ name: 'base-order',
+ adaptations: {
+ widthBreakpoints: {md: 800},
+ rules: [
+ {
+ when: {width: {from: 'md'}},
+ value: {tokens: {'--spacing-4': '18px'}},
+ },
+ ],
+ },
+ });
+ const child = defineTheme({
+ name: 'child-order',
+ extends: base,
+ adaptations: {
+ widthBreakpoints: {md: 820},
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--size-element-md': '44px'}},
+ },
+ ],
+ },
+ });
+
+ expect(child.__adaptations.widthBreakpoints.md).toBe(820);
+ expect(child.__adaptations.rules).toHaveLength(2);
+ expect(mediaPreludes(generateAdaptationCSS(child).component)).toEqual([
+ '(width >= 820px)',
+ '(pointer: coarse)',
+ ]);
+ });
+
+ it("re-resolves inherited rules against the child's effective root axis", () => {
+ const base = defineTheme({
+ name: 'base-axis',
+ typography: {scale: {base: 14, ratio: 1.2}},
+ adaptations: {
+ rules: [
+ {
+ when: {width: {below: 'sm'}},
+ value: {typography: {scale: {base: 16}}},
+ },
+ ],
+ },
+ });
+ const child = defineTheme({
+ name: 'child-axis',
+ extends: base,
+ typography: {scale: {base: 15, ratio: 1.25}},
+ });
+
+ expect(child.__adaptationRules?.[0].tokens['--font-size-lg']).toBe(
+ '1.25rem',
+ );
+ });
+
+ it("merges a child's partial typography axis before re-resolving inherited rules", () => {
+ const base = defineTheme({
+ name: 'partial-typography-base',
+ typography: {
+ scale: {base: 14, ratio: 1.25},
+ body: {family: 'Inter', fallbacks: 'sans-serif'},
+ heading: {family: 'Playfair', fallbacks: 'serif'},
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {width: {from: 'lg'}},
+ value: {typography: {scale: {base: 18}}},
+ },
+ ],
+ },
+ });
+ const child = defineTheme({
+ name: 'partial-typography-child',
+ extends: base,
+ typography: {body: {family: 'Georgia'}},
+ });
+
+ expect(child.__axes.typography?.scale).toEqual({base: 14, ratio: 1.25});
+ expect(child.__axes.typography?.body?.family).toBe('Georgia');
+ expect(child.__axes.typography?.body?.fallbacks).toBeUndefined();
+ expect(child.__axes.typography?.heading?.family).toBeUndefined();
+ expect(child.__axes.typography?.heading?.fallbacks).toBeUndefined();
+ expect(child.tokens['--font-family-heading']).toBe('Georgia');
+ expect(child.__adaptationRules?.[0].tokens['--font-family-body']).toBe(
+ 'Georgia',
+ );
+ expect(child.__adaptationRules?.[0].tokens['--font-family-heading']).toBe(
+ 'Georgia',
+ );
+ expect(child.__adaptationRules?.[0].tokens['--font-size-lg']).toBe(
+ '1.4375rem',
+ );
+ });
+
+ it('keeps typography weights owned by the last config that declares a scale', () => {
+ const rule = {
+ when: {width: {from: 'lg' as const}},
+ value: {typography: {scale: {base: 18}}},
+ };
+ const weightedBase = defineTheme({
+ name: 'weight-owner-base',
+ typography: {
+ scale: {base: 14, ratio: 1.25},
+ body: {weight: 'medium'},
+ heading: {weight: 'bold'},
+ },
+ adaptations: {rules: [rule]},
+ });
+ const newScale = defineTheme({
+ name: 'weight-owner-new-scale',
+ extends: weightedBase,
+ typography: {scale: {base: 16, ratio: 1.2}},
+ });
+
+ expect(newScale.__adaptationRules?.[0].tokens['--text-body-weight']).toBe(
+ newScale.tokens['--text-body-weight'],
+ );
+ expect(
+ newScale.__adaptationRules?.[0].tokens['--text-heading-1-weight'],
+ ).toBe(newScale.tokens['--text-heading-1-weight']);
+
+ const defaultBase = defineTheme({
+ name: 'weight-owner-default-base',
+ typography: {scale: {base: 14, ratio: 1.25}},
+ adaptations: {rules: [rule]},
+ });
+ const weightWithoutScale = defineTheme({
+ name: 'weight-owner-no-scale',
+ extends: defaultBase,
+ typography: {heading: {weight: 'bold'}},
+ });
+
+ expect(
+ weightWithoutScale.__adaptationRules?.[0].tokens[
+ '--text-heading-1-weight'
+ ],
+ ).toBe(weightWithoutScale.tokens['--text-heading-1-weight']);
+ });
+
+ it('ignores a child fallback that has no family, matching root resolution', () => {
+ const base = defineTheme({
+ name: 'fallback-only-base',
+ typography: {
+ scale: {base: 14, ratio: 1.25},
+ heading: {family: 'Playfair', fallbacks: 'sans-serif'},
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {width: {from: 'lg'}},
+ value: {typography: {scale: {base: 18}}},
+ },
+ ],
+ },
+ });
+ const child = defineTheme({
+ name: 'fallback-only-child',
+ extends: base,
+ typography: {heading: {fallbacks: 'serif'}},
+ });
+
+ expect(child.tokens['--font-family-heading']).toBe('Playfair, sans-serif');
+ expect(child.__adaptationRules?.[0].tokens['--font-family-heading']).toBe(
+ child.tokens['--font-family-heading'],
+ );
+ });
+
+ it("uses a child's own color axis when re-resolving inherited rules", () => {
+ const rule = {
+ when: {contrast: 'more' as const},
+ value: {color: {contrast: 'high' as const}},
+ };
+ const base = defineTheme({
+ name: 'partial-color-base',
+ color: {accent: '#B7410E'},
+ adaptations: {rules: [rule]},
+ });
+ const child = defineTheme({
+ name: 'partial-color-child',
+ extends: base,
+ color: {neutralStyle: 'warm'},
+ });
+ const expected = defineTheme({
+ name: 'partial-color-expected',
+ color: {neutralStyle: 'warm', contrast: 'high'},
+ });
+
+ expect(child.__axes.color).toEqual({neutralStyle: 'warm'});
+ expect(child.__adaptationRules?.[0].tokens).toEqual(expected.tokens);
+ });
+
+ it("keeps inherited rules above the child's root values", () => {
+ const base = defineTheme({
+ name: 'base-rule',
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ ],
+ },
+ });
+ const child = defineTheme({
+ name: 'child-root',
+ extends: base,
+ tokens: {'--spacing-4': '20px'},
+ });
+
+ expect(child.tokens['--spacing-4']).toBe('20px');
+ expect(child.__adaptationRules?.[0].tokens['--spacing-4']).toBe('12px');
+ });
+
+ it('recomputes inherited rules from built-theme metadata without CSS text', () => {
+ const live = defineTheme({
+ name: 'built-base',
+ typography: {scale: {base: 14, ratio: 1.25}},
+ adaptations: {
+ widthBreakpoints: {sm: 700},
+ rules: [
+ {
+ when: {width: {below: 'sm'}},
+ value: {typography: {scale: {base: 16}}},
+ },
+ ],
+ },
+ });
+ const built = {
+ name: live.name,
+ __built: true,
+ tokens: live.tokens,
+ components: live.components,
+ __adaptations: live.__adaptations,
+ __axes: live.__axes,
+ } as DefinedTheme;
+
+ const child = defineTheme({name: 'built-child', extends: built});
+ expect(child.__adaptationRules?.[0].query).toBe('(width < 700px)');
+ expect(child.__adaptationRules?.[0].tokens['--font-size-lg']).toBe(
+ '1.25rem',
+ );
+ expect(JSON.stringify(built)).not.toContain('@media');
+ });
+});
+
+describe('CSS cascade placement', () => {
+ it('emits root values, then adaptations, then media-surface overrides', () => {
+ const theme = defineTheme({
+ name: 'surface-order',
+ tokens: {'--color-background-body': '#ffffff'},
+ adaptations: {
+ rules: [
+ {
+ when: {contrast: 'more'},
+ value: {tokens: {'--color-background-body': '#eeeeee'}},
+ },
+ ],
+ },
+ onDark: {tokens: {'--color-background-body': '#111111'}},
+ });
+
+ const css = generateThemeCSS(theme).component;
+ expect(css.indexOf('#ffffff')).toBeLessThan(css.indexOf('#eeeeee'));
+ expect(css.indexOf('#eeeeee')).toBeLessThan(css.lastIndexOf('#111111'));
+ });
+
+ it('makes rule shorthand padding override root directional container padding', () => {
+ const theme = defineTheme({
+ name: 'conditional-container-padding',
+ components: {
+ card: {base: {paddingBlock: '8px', paddingInline: '16px'}},
+ section: {base: {paddingBlock: '10px', paddingInline: '18px'}},
+ },
+ adaptations: {
+ rules: [
+ {
+ when: {width: {from: 'lg'}},
+ value: {
+ components: {
+ card: {base: {padding: '32px'}},
+ section: {base: {padding: '32px'}},
+ },
+ },
+ },
+ ],
+ },
+ });
+
+ const rootCss = generateThemeCSS(theme).component;
+ expect(rootCss).toContain('--astryx-card-padding-block-start: 8px');
+ expect(rootCss).toContain('--astryx-section-padding-inline: 18px');
+
+ const ruleCss = generateAdaptationCSS(theme).component;
+ for (const component of ['card', 'section']) {
+ expect(ruleCss).toContain(`--astryx-${component}-padding: 32px`);
+ expect(ruleCss).toContain(
+ `--astryx-${component}-padding-inline: initial`,
+ );
+ expect(ruleCss).toContain(
+ `--astryx-${component}-padding-inline-start: initial`,
+ );
+ expect(ruleCss).toContain(
+ `--astryx-${component}-padding-inline-end: initial`,
+ );
+ expect(ruleCss).toContain(
+ `--astryx-${component}-padding-block-start: initial`,
+ );
+ expect(ruleCss).toContain(
+ `--astryx-${component}-padding-block-end: initial`,
+ );
+ }
+ });
+
+ it('resets only the more-specific inline siblings for a rule paddingInline write', () => {
+ const theme = defineTheme({
+ name: 'conditional-inline-padding',
+ components: {card: {base: {padding: '16px'}}},
+ adaptations: {
+ rules: [
+ {
+ when: {width: {from: 'lg'}},
+ value: {components: {card: {base: {paddingInline: '32px'}}}},
+ },
+ ],
+ },
+ });
+
+ const ruleCss = generateAdaptationCSS(theme).component;
+ expect(ruleCss).toContain('--astryx-card-padding-inline: 32px');
+ expect(ruleCss).toContain('--astryx-card-padding-inline-start: initial');
+ expect(ruleCss).toContain('--astryx-card-padding-inline-end: initial');
+ expect(ruleCss).not.toContain('--astryx-card-padding: initial');
+ expect(ruleCss).not.toContain('--astryx-card-padding-block-start: initial');
+ });
+
+ it('keeps media-surface component writes above matching adaptations', () => {
+ const theme = defineTheme({
+ name: 'surface-component-order',
+ components: {button: {base: {borderWidth: '1px'}}},
+ adaptations: {
+ rules: [
+ {
+ when: {contrast: 'more'},
+ value: {components: {button: {base: {borderWidth: '2px'}}}},
+ },
+ ],
+ },
+ onDark: {components: {button: {base: {borderWidth: '3px'}}}},
+ });
+
+ const css = generateThemeCSS(theme).component;
+ expect(css.indexOf('border-width: 1px')).toBeLessThan(
+ css.indexOf('border-width: 2px'),
+ );
+ expect(css.indexOf('border-width: 2px')).toBeLessThan(
+ css.lastIndexOf('border-width: 3px'),
+ );
+ });
+
+ it('keeps JavaScript token reads on root values', () => {
+ const theme = defineTheme({
+ name: 'css-first',
+ tokens: {'--spacing-4': '16px'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--spacing-4': '12px'}},
+ },
+ ],
+ },
+ });
+
+ expect(theme.tokens['--spacing-4']).toBe('16px');
+ expect(theme.__adaptationRules?.[0].tokens['--spacing-4']).toBe('12px');
+ });
+});
diff --git a/packages/core/src/theme/themeAdaptations.ts b/packages/core/src/theme/themeAdaptations.ts
new file mode 100644
index 0000000000..ed4981d9c8
--- /dev/null
+++ b/packages/core/src/theme/themeAdaptations.ts
@@ -0,0 +1,969 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file themeAdaptations.ts
+ * @input Ordered environment-conditioned theme value rules from defineTheme
+ * @output Validated breakpoint metadata and resolved CSS-first rule layers
+ * @position Theme system core; consumed by defineTheme, AppShell, and the CSS compiler
+ *
+ * Adaptations are deliberately closed and ordered. Width points are fixed names,
+ * sparse rules and reserved token routing are rejected during normalization,
+ * condition fields are ANDed, and rule order is the precedence model: every
+ * matching rule writes after the root theme and later matching writes win. Token
+ * cycles are judged only after each reachable ordered cascade is complete.
+ *
+ * SYNC: When modified, update:
+ * - /packages/core/src/theme/defineTheme.ts (`DefineThemeInput.adaptations`)
+ * - /packages/core/src/theme/generateThemeRules.ts (`generateAdaptationCSS`)
+ * - /packages/core/src/AppShell/AppShell.tsx (named breakpoint consumption)
+ * - /packages/cli/assets/theme.template.ts
+ * - /packages/cli/assets/docs/theme.doc.mjs
+ * - /packages/cli/api/theme/build/build.mjs
+ */
+
+import type {ComponentStyleMap, TokenName, TokenValue} from './defineTheme';
+import type {TypographyConfig, TypographyRole} from './types';
+import type {MotionScaleConfig} from './expandMotionScale';
+import type {RadiusScaleConfig} from './expandRadiusScale';
+import type {ColorScaleConfig} from './expandColorScale';
+import {resolveThemeValues, type ThemeValuesInput} from './resolveThemeValues';
+import {
+ assertNoTokenCycles,
+ isReservedThemeLocalTokenName,
+ resolveAdaptationLocalTokens,
+} from './localTokens';
+
+// =============================================================================
+// Public authoring vocabulary
+// =============================================================================
+
+/** Fixed names for viewport-width tier start points. */
+export const WIDTH_BREAKPOINT_NAMES = ['sm', 'md', 'lg', 'xl', '2xl'] as const;
+
+/** One fixed viewport-width breakpoint name. */
+export type WidthBreakpointName = (typeof WIDTH_BREAKPOINT_NAMES)[number];
+
+/** A complete, validated map of viewport-width tier start points in CSS px. */
+export type WidthBreakpoints = Record<WidthBreakpointName, number>;
+
+/** The default Astryx viewport-width tier start points in CSS px. */
+export const DEFAULT_WIDTH_BREAKPOINTS: Readonly<WidthBreakpoints> =
+ Object.freeze({
+ sm: 640,
+ md: 768,
+ lg: 1024,
+ xl: 1280,
+ '2xl': 1536,
+ });
+
+/** Inclusive lower and exclusive upper edges for one width condition. */
+export interface ThemeAdaptationWidthCondition {
+ /** Match at and above this named point. */
+ from?: WidthBreakpointName;
+ /** Match strictly below this named point. */
+ below?: WidthBreakpointName;
+}
+
+/** Closed environmental condition vocabulary. Fields are ANDed. */
+export interface ThemeAdaptationCondition {
+ /** Viewport-width range, using named start points. */
+ width?: ThemeAdaptationWidthCondition;
+ /** Primary pointing-device precision. */
+ pointer?: 'coarse' | 'fine';
+ /** User contrast preference. */
+ contrast?: 'more' | 'less' | 'no-preference';
+ /** User reduced-motion preference. */
+ motion?: 'reduce' | 'no-preference';
+}
+
+/** Typography overrides inside an adaptation rule. */
+export interface ThemeAdaptationTypographyConfig extends Omit<
+ TypographyConfig,
+ 'scale'
+> {
+ /** Partial type scale, completed from the effective root axis. */
+ scale?: Partial<NonNullable<TypographyConfig['scale']>>;
+}
+
+/** Theme values an adaptation rule may write. */
+export interface ThemeAdaptationValue {
+ /** Typography axis overrides, completed from root metadata. */
+ typography?: ThemeAdaptationTypographyConfig;
+ /** Color axis overrides, completed from root metadata. */
+ color?: Partial<ColorScaleConfig>;
+ /** Radius axis overrides, completed from root metadata. */
+ radius?: Partial<RadiusScaleConfig>;
+ /** Motion axis overrides, completed from root metadata. */
+ motion?: Partial<MotionScaleConfig>;
+ /** Portable semantic-token writes. */
+ tokens?: Partial<Record<TokenName, TokenValue>>;
+ /** Replacements for exact theme-local names enrolled by the root lineage. */
+ localTokens?: Record<string, TokenValue>;
+ /** Component target/style-key writes. */
+ components?: ComponentStyleMap;
+}
+
+/** One ordered condition-to-value adaptation rule. */
+export interface ThemeAdaptationRule {
+ /** Environmental fields that must all match. */
+ when: ThemeAdaptationCondition;
+ /** Theme values written while the condition matches. */
+ value: ThemeAdaptationValue;
+}
+
+/** Adaptation authoring input accepted by defineTheme. */
+export interface ThemeAdaptations {
+ /** Overrides for the five fixed width points. Configuration alone emits no CSS. */
+ widthBreakpoints?: Partial<WidthBreakpoints>;
+ /** Ordered condition-to-value rules. */
+ rules?: ThemeAdaptationRule[];
+}
+
+// =============================================================================
+// Normalized and resolved metadata
+// =============================================================================
+
+/** Validated authoring data retained for source-equivalent theme extension. */
+export interface NormalizedThemeAdaptations {
+ /** Effective complete width map, including defaults and inherited overrides. */
+ widthBreakpoints: WidthBreakpoints;
+ /** Inherited rules followed by child-authored rules, preserving order. */
+ rules: ThemeAdaptationRule[];
+}
+
+/** Generative-axis metadata needed to complete partial adaptation values. */
+export interface ThemeGenerativeAxes {
+ typography?: TypographyConfig;
+ color?: ColorScaleConfig;
+ radius?: RadiusScaleConfig;
+ motion?: MotionScaleConfig;
+}
+
+/** One rule lowered to concrete CSS writes. */
+export interface ResolvedThemeAdaptationRule {
+ /** Validated condition, retained for diagnostics. */
+ when: ThemeAdaptationCondition;
+ /** CSS media-query prelude without the `@media` keyword. */
+ query: string;
+ /** Concrete portable token writes produced by this rule. */
+ tokens: Record<string, string>;
+ /** Concrete theme-local token writes produced by this rule. */
+ localTokens?: Record<string, string>;
+ /** Concrete component writes produced by this rule. */
+ components?: ComponentStyleMap;
+}
+
+// =============================================================================
+// Structural validation
+// =============================================================================
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
+}
+
+function assertRecord(
+ value: unknown,
+ path: string,
+): asserts value is Record<string, unknown> {
+ if (!isRecord(value)) {
+ throw new Error(`${path} must be an object.`);
+ }
+}
+
+function assertAllowedKeys(
+ value: Record<string, unknown>,
+ allowed: ReadonlySet<string>,
+ path: string,
+): void {
+ for (const key of Object.keys(value)) {
+ if (!allowed.has(key)) {
+ throw new Error(`${path}.${key} is not supported.`);
+ }
+ }
+}
+
+function cloneData<T>(value: T): T {
+ if (Array.isArray(value)) {
+ const cloned: unknown[] = [];
+ for (const item of value) {
+ cloned.push(cloneData(item));
+ }
+ return cloned as T;
+ }
+ if (isRecord(value)) {
+ return Object.fromEntries(
+ Object.entries(value).map(([key, nested]) => [key, cloneData(nested)]),
+ ) as T;
+ }
+ return value;
+}
+
+const BREAKPOINT_NAMES = new Set<string>(WIDTH_BREAKPOINT_NAMES);
+const ADAPTATION_KEYS = new Set(['widthBreakpoints', 'rules']);
+const RULE_KEYS = new Set(['when', 'value']);
+const CONDITION_AXES = [
+ 'width',
+ 'pointer',
+ 'contrast',
+ 'motion',
+] as const satisfies ReadonlyArray<keyof ThemeAdaptationCondition>;
+type UnhandledConditionAxis = Exclude<
+ keyof ThemeAdaptationCondition,
+ (typeof CONDITION_AXES)[number]
+>;
+const CONDITION_KEYS: UnhandledConditionAxis extends never
+ ? ReadonlySet<keyof ThemeAdaptationCondition>
+ : never = new Set(CONDITION_AXES);
+const WIDTH_CONDITION_KEYS = new Set(['from', 'below']);
+const VALUE_KEYS = new Set([
+ 'typography',
+ 'color',
+ 'radius',
+ 'motion',
+ 'tokens',
+ 'localTokens',
+ 'components',
+]);
+
+function normalizeBreakpointOverrides(
+ value: unknown,
+ path: string,
+): Partial<WidthBreakpoints> {
+ assertRecord(value, path);
+ assertAllowedKeys(value, BREAKPOINT_NAMES, path);
+ const result: Partial<WidthBreakpoints> = {};
+ for (const name of WIDTH_BREAKPOINT_NAMES) {
+ const point = value[name];
+ if (point === undefined) {
+ continue;
+ }
+ if (typeof point !== 'number' || !Number.isFinite(point) || point <= 0) {
+ throw new Error(
+ `${path}.${name} must be a finite positive number of CSS pixels.`,
+ );
+ }
+ result[name] = point;
+ }
+ return result;
+}
+
+function assertCompleteBreakpoints(
+ value: unknown,
+ path: string,
+): WidthBreakpoints {
+ const overrides = normalizeBreakpointOverrides(value, path);
+ for (const name of WIDTH_BREAKPOINT_NAMES) {
+ if (overrides[name] === undefined) {
+ throw new Error(
+ `${path}.${name} is missing from the effective breakpoint map.`,
+ );
+ }
+ }
+ return overrides as WidthBreakpoints;
+}
+
+function assertIncreasingBreakpoints(
+ points: WidthBreakpoints,
+ path: string,
+): void {
+ let previous: WidthBreakpointName | undefined;
+ for (const name of WIDTH_BREAKPOINT_NAMES) {
+ if (previous !== undefined && points[name] <= points[previous]) {
+ throw new Error(
+ `${path} must be strictly increasing: ${name} (${points[name]}) is not above ${previous} (${points[previous]}).`,
+ );
+ }
+ previous = name;
+ }
+}
+
+function normalizeCondition(
+ value: unknown,
+ path: string,
+): ThemeAdaptationCondition {
+ assertRecord(value, path);
+ assertAllowedKeys(value, CONDITION_KEYS, path);
+ const defined = Object.fromEntries(
+ Object.entries(value).filter(([, nested]) => nested !== undefined),
+ );
+ if (Object.keys(defined).length === 0) {
+ throw new Error(`${path} must contain at least one condition.`);
+ }
+
+ const condition = cloneData(defined) as ThemeAdaptationCondition;
+ if (condition.width !== undefined) {
+ assertRecord(condition.width, `${path}.width`);
+ assertAllowedKeys(condition.width, WIDTH_CONDITION_KEYS, `${path}.width`);
+ if (
+ condition.width.from === undefined &&
+ condition.width.below === undefined
+ ) {
+ throw new Error(
+ `${path}.width must contain \`from\`, \`below\`, or both.`,
+ );
+ }
+ for (const edge of ['from', 'below'] as const) {
+ const name = condition.width[edge];
+ if (
+ name !== undefined &&
+ (typeof name !== 'string' || !BREAKPOINT_NAMES.has(name))
+ ) {
+ throw new Error(
+ `${path}.width.${edge} must be one of ${WIDTH_BREAKPOINT_NAMES.join(', ')}.`,
+ );
+ }
+ }
+ }
+
+ if (
+ condition.pointer !== undefined &&
+ condition.pointer !== 'coarse' &&
+ condition.pointer !== 'fine'
+ ) {
+ throw new Error(`${path}.pointer must be 'coarse' or 'fine'.`);
+ }
+ if (
+ condition.contrast !== undefined &&
+ condition.contrast !== 'more' &&
+ condition.contrast !== 'less' &&
+ condition.contrast !== 'no-preference'
+ ) {
+ throw new Error(
+ `${path}.contrast must be 'more', 'less', or 'no-preference'.`,
+ );
+ }
+ if (
+ condition.motion !== undefined &&
+ condition.motion !== 'reduce' &&
+ condition.motion !== 'no-preference'
+ ) {
+ throw new Error(`${path}.motion must be 'reduce' or 'no-preference'.`);
+ }
+
+ return condition;
+}
+
+function normalizeValue(value: unknown, path: string): ThemeAdaptationValue {
+ assertRecord(value, path);
+ assertAllowedKeys(value, VALUE_KEYS, path);
+ for (const key of VALUE_KEYS) {
+ const nested = value[key];
+ if (nested !== undefined && !isRecord(nested)) {
+ throw new Error(`${path}.${key} must be an object.`);
+ }
+ }
+ return cloneData(value);
+}
+
+function normalizeRule(value: unknown, path: string): ThemeAdaptationRule {
+ assertRecord(value, path);
+ assertAllowedKeys(value, RULE_KEYS, path);
+ if (!Object.prototype.hasOwnProperty.call(value, 'when')) {
+ throw new Error(`${path}.when is required.`);
+ }
+ if (!Object.prototype.hasOwnProperty.call(value, 'value')) {
+ throw new Error(`${path}.value is required.`);
+ }
+ return {
+ when: normalizeCondition(value.when, `${path}.when`),
+ value: normalizeValue(value.value, `${path}.value`),
+ };
+}
+
+function normalizeRules(value: unknown, path: string): ThemeAdaptationRule[] {
+ if (!Array.isArray(value)) {
+ throw new Error(`${path} must be an array of {when, value} objects.`);
+ }
+ for (let index = 0; index < value.length; index++) {
+ if (!Object.prototype.hasOwnProperty.call(value, index)) {
+ throw new Error(`${path}[${index}] must be present.`);
+ }
+ }
+ return value.map((rule, index) => normalizeRule(rule, `${path}[${index}]`));
+}
+
+/**
+ * Merge and validate inherited plus locally-authored adaptation metadata.
+ * Inherited rules retain order; child rules append.
+ */
+export function normalizeThemeAdaptations(
+ themeName: string,
+ inherited: NormalizedThemeAdaptations | undefined,
+ input: ThemeAdaptations | undefined,
+): NormalizedThemeAdaptations {
+ const rootPath = `defineTheme("${themeName}").adaptations`;
+
+ let inheritedPoints: WidthBreakpoints = {...DEFAULT_WIDTH_BREAKPOINTS};
+ let inheritedRules: ThemeAdaptationRule[] = [];
+ if (inherited !== undefined) {
+ assertRecord(
+ inherited,
+ `defineTheme("${themeName}").extends.__adaptations`,
+ );
+ assertAllowedKeys(
+ inherited,
+ new Set(['widthBreakpoints', 'rules']),
+ `defineTheme("${themeName}").extends.__adaptations`,
+ );
+ inheritedPoints = assertCompleteBreakpoints(
+ inherited.widthBreakpoints,
+ `defineTheme("${themeName}").extends.__adaptations.widthBreakpoints`,
+ );
+ inheritedRules = normalizeRules(
+ inherited.rules,
+ `defineTheme("${themeName}").extends.__adaptations.rules`,
+ );
+ }
+
+ let ownPoints: Partial<WidthBreakpoints> = {};
+ let ownRules: ThemeAdaptationRule[] = [];
+ if (input !== undefined) {
+ assertRecord(input, rootPath);
+ assertAllowedKeys(input, ADAPTATION_KEYS, rootPath);
+ if (input.widthBreakpoints !== undefined) {
+ ownPoints = normalizeBreakpointOverrides(
+ input.widthBreakpoints,
+ `${rootPath}.widthBreakpoints`,
+ );
+ }
+ if (input.rules !== undefined) {
+ ownRules = normalizeRules(input.rules, `${rootPath}.rules`);
+ }
+ }
+
+ const widthBreakpoints: WidthBreakpoints = {
+ ...inheritedPoints,
+ ...ownPoints,
+ };
+ assertIncreasingBreakpoints(widthBreakpoints, `${rootPath}.widthBreakpoints`);
+
+ return {
+ widthBreakpoints,
+ rules: [...inheritedRules, ...ownRules],
+ };
+}
+
+// =============================================================================
+// Axis completion and rule resolution
+// =============================================================================
+
+function mergeRole(
+ root: TypographyRole | undefined,
+ rule: TypographyRole | undefined,
+): TypographyRole | undefined {
+ if (!root) {
+ return rule;
+ }
+ if (!rule) {
+ return root;
+ }
+ return {
+ ...root,
+ ...rule,
+ weights:
+ root.weights || rule.weights
+ ? {...root.weights, ...rule.weights}
+ : undefined,
+ };
+}
+
+function assertFiniteNumber(
+ value: unknown,
+ path: string,
+): asserts value is number {
+ if (typeof value !== 'number' || !Number.isFinite(value)) {
+ throw new Error(`${path} must be a finite number.`);
+ }
+}
+
+function completeTypography(
+ root: TypographyConfig | undefined,
+ rule: ThemeAdaptationTypographyConfig,
+ path: string,
+): TypographyConfig {
+ const writesScale =
+ rule.scale !== undefined ||
+ [rule.body, rule.heading, rule.code].some(
+ role => role?.weight !== undefined || role?.weights !== undefined,
+ );
+ let scale = writesScale ? root?.scale : undefined;
+ if (rule.scale !== undefined) {
+ const base = rule.scale.base ?? root?.scale?.base;
+ const ratio = rule.scale.ratio ?? root?.scale?.ratio;
+ if (base === undefined || ratio === undefined) {
+ throw new Error(
+ `${path}.scale must supply both \`base\` and \`ratio\` unless the missing field exists on the effective root typography axis.`,
+ );
+ }
+ assertFiniteNumber(base, `${path}.scale.base`);
+ assertFiniteNumber(ratio, `${path}.scale.ratio`);
+ scale = {base, ratio};
+ } else if (writesScale && scale === undefined) {
+ throw new Error(
+ `${path} sets typography weights without an effective root scale. Supply \`scale.base\` and \`scale.ratio\` in the same rule.`,
+ );
+ }
+
+ return {
+ ...(scale ? {scale} : {}),
+ body: mergeRole(root?.body, rule.body),
+ heading: mergeRole(root?.heading, rule.heading),
+ code: mergeRole(root?.code, rule.code),
+ };
+}
+
+function completeRadius(
+ root: RadiusScaleConfig | undefined,
+ rule: Partial<RadiusScaleConfig>,
+ path: string,
+): RadiusScaleConfig {
+ const base = rule.base ?? root?.base;
+ const multiplier = rule.multiplier ?? root?.multiplier;
+ if (base === undefined || multiplier === undefined) {
+ throw new Error(
+ `${path} must supply both \`base\` and \`multiplier\` unless the missing field exists on the effective root radius axis.`,
+ );
+ }
+ assertFiniteNumber(base, `${path}.base`);
+ assertFiniteNumber(multiplier, `${path}.multiplier`);
+ return {base, multiplier};
+}
+
+function completeMotion(
+ root: MotionScaleConfig | undefined,
+ rule: Partial<MotionScaleConfig>,
+ path: string,
+): MotionScaleConfig {
+ const fast = rule.fast ?? root?.fast;
+ const medium = rule.medium ?? root?.medium;
+ const ratio = rule.ratio ?? root?.ratio;
+ if (fast === undefined || medium === undefined || ratio === undefined) {
+ throw new Error(
+ `${path} must supply \`fast\`, \`medium\`, and \`ratio\` unless each missing field exists on the effective root motion axis.`,
+ );
+ }
+ assertFiniteNumber(fast, `${path}.fast`);
+ assertFiniteNumber(medium, `${path}.medium`);
+ assertFiniteNumber(ratio, `${path}.ratio`);
+ const slow = rule.slow ?? root?.slow;
+ if (slow !== undefined) {
+ assertFiniteNumber(slow, `${path}.slow`);
+ }
+ const easing = rule.easing ?? root?.easing;
+ return {
+ fast,
+ medium,
+ ratio,
+ ...(slow !== undefined ? {slow} : {}),
+ ...(easing !== undefined ? {easing} : {}),
+ };
+}
+
+function valueToThemeInput(
+ themeName: string,
+ ruleIndex: number,
+ value: ThemeAdaptationValue,
+ axes: ThemeGenerativeAxes,
+): ThemeValuesInput {
+ const path = `defineTheme("${themeName}").adaptations.rules[${ruleIndex}].value`;
+ return {
+ typography: value.typography
+ ? completeTypography(
+ axes.typography,
+ value.typography,
+ `${path}.typography`,
+ )
+ : undefined,
+ color: value.color ? {...axes.color, ...value.color} : undefined,
+ radius: value.radius
+ ? completeRadius(axes.radius, value.radius, `${path}.radius`)
+ : undefined,
+ motion: value.motion
+ ? completeMotion(axes.motion, value.motion, `${path}.motion`)
+ : undefined,
+ tokens: value.tokens,
+ components: value.components,
+ };
+}
+
+function assertConcreteLeaf(value: unknown, path: string): void {
+ if (typeof value === 'string') {
+ if (/\b(?:NaN|undefined)\b/.test(value)) {
+ throw new Error(`${path} resolved to the invalid CSS value "${value}".`);
+ }
+ return;
+ }
+ if (isRecord(value)) {
+ for (const [key, nested] of Object.entries(value)) {
+ assertConcreteLeaf(nested, `${path}.${key}`);
+ }
+ return;
+ }
+ throw new Error(`${path} must resolve to a concrete CSS string.`);
+}
+
+function mediaQueryForCondition(
+ themeName: string,
+ ruleIndex: number,
+ condition: ThemeAdaptationCondition,
+ points: WidthBreakpoints,
+): string {
+ const path = `defineTheme("${themeName}").adaptations.rules[${ruleIndex}].when`;
+ const parts: string[] = [];
+
+ if (condition.width) {
+ const from = condition.width.from;
+ const below = condition.width.below;
+ if (
+ from !== undefined &&
+ below !== undefined &&
+ points[from] >= points[below]
+ ) {
+ throw new Error(
+ `${path}.width must resolve to \`from < below\`; ${from} is ${points[from]}px and ${below} is ${points[below]}px.`,
+ );
+ }
+ if (from !== undefined) {
+ parts.push(`(width >= ${points[from]}px)`);
+ }
+ if (below !== undefined) {
+ parts.push(`(width < ${points[below]}px)`);
+ }
+ }
+ if (condition.pointer !== undefined) {
+ parts.push(`(pointer: ${condition.pointer})`);
+ }
+ if (condition.contrast !== undefined) {
+ parts.push(`(prefers-contrast: ${condition.contrast})`);
+ }
+ if (condition.motion !== undefined) {
+ parts.push(`(prefers-reduced-motion: ${condition.motion})`);
+ }
+
+ if (parts.length === 0) {
+ throw new Error(`${path} must contain at least one concrete condition.`);
+ }
+ return parts.join(' and ');
+}
+
+type PointerEnvironment =
+ NonNullable<ThemeAdaptationCondition['pointer']> | 'none';
+type ContrastEnvironment =
+ NonNullable<ThemeAdaptationCondition['contrast']> | 'custom';
+type MotionEnvironment = NonNullable<ThemeAdaptationCondition['motion']>;
+
+interface AdaptationEnvironment {
+ width: number;
+ pointer: PointerEnvironment;
+ contrast: ContrastEnvironment;
+ motion: MotionEnvironment;
+}
+
+const ENVIRONMENT_VALUES = {
+ pointer: ['coarse', 'fine', 'none'],
+ contrast: ['more', 'less', 'no-preference', 'custom'],
+ motion: ['reduce', 'no-preference'],
+} as const satisfies {
+ pointer: ReadonlyArray<PointerEnvironment>;
+ contrast: ReadonlyArray<ContrastEnvironment>;
+ motion: ReadonlyArray<MotionEnvironment>;
+};
+type EnvironmentTypes = {
+ pointer: PointerEnvironment;
+ contrast: ContrastEnvironment;
+ motion: MotionEnvironment;
+};
+const COMPLETE_ENVIRONMENT_VALUES: {
+ [Axis in keyof EnvironmentTypes]: Exclude<
+ EnvironmentTypes[Axis],
+ (typeof ENVIRONMENT_VALUES)[Axis][number]
+ > extends never
+ ? (typeof ENVIRONMENT_VALUES)[Axis]
+ : never;
+} = ENVIRONMENT_VALUES;
+
+/** Whether one normalized rule matches one representative environment cell. */
+function conditionMatchesEnvironment(
+ condition: ThemeAdaptationCondition,
+ points: WidthBreakpoints,
+ environment: AdaptationEnvironment,
+): boolean {
+ const from = condition.width?.from;
+ if (from !== undefined && environment.width < points[from]) {
+ return false;
+ }
+ const below = condition.width?.below;
+ if (below !== undefined && environment.width >= points[below]) {
+ return false;
+ }
+ if (
+ condition.pointer !== undefined &&
+ condition.pointer !== environment.pointer
+ ) {
+ return false;
+ }
+ if (
+ condition.contrast !== undefined &&
+ condition.contrast !== environment.contrast
+ ) {
+ return false;
+ }
+ if (
+ condition.motion !== undefined &&
+ condition.motion !== environment.motion
+ ) {
+ return false;
+ }
+ return true;
+}
+
+/**
+ * Reject token cycles reachable in any matching adaptation-rule cascade.
+ *
+ * Conditions use a finite, closed vocabulary. Sampling zero and each named
+ * width boundary covers every distinct width truth region; the discrete axes
+ * enumerate every browser state relevant to the supported queries. For each
+ * reachable match set, portable and local writes are applied in authored order
+ * before checking the effective graph, so a later matching rule may
+ * intentionally repair an earlier cycle just as it does in CSS.
+ */
+function assertNoReachableTokenCycles(
+ themeName: string,
+ points: WidthBreakpoints,
+ rootTokens: Record<string, string>,
+ rootLocalTokens: Record<string, string> | undefined,
+ rules: ResolvedThemeAdaptationRule[],
+): void {
+ const tokenRuleIndexes = rules.flatMap((rule, index) =>
+ Object.keys(rule.tokens).length > 0 ||
+ (rule.localTokens && Object.keys(rule.localTokens).length > 0)
+ ? [index]
+ : [],
+ );
+ if (tokenRuleIndexes.length === 0) {
+ return;
+ }
+
+ const widthEnvironments = [
+ 0,
+ ...WIDTH_BREAKPOINT_NAMES.map(name => points[name]),
+ ];
+ const checkedMatchSets = new Set<string>();
+
+ for (const width of widthEnvironments) {
+ for (const pointer of COMPLETE_ENVIRONMENT_VALUES.pointer) {
+ for (const contrast of COMPLETE_ENVIRONMENT_VALUES.contrast) {
+ for (const motion of COMPLETE_ENVIRONMENT_VALUES.motion) {
+ const environment = {width, pointer, contrast, motion};
+ const matchingRuleIndexes = tokenRuleIndexes.filter(index =>
+ conditionMatchesEnvironment(rules[index].when, points, environment),
+ );
+ if (matchingRuleIndexes.length === 0) {
+ continue;
+ }
+
+ const signature = matchingRuleIndexes.join(',');
+ if (checkedMatchSets.has(signature)) {
+ continue;
+ }
+ checkedMatchSets.add(signature);
+
+ const effective = {...rootTokens, ...rootLocalTokens};
+ const relevantNames = new Set<string>();
+ for (const index of matchingRuleIndexes) {
+ const rule = rules[index];
+ Object.assign(effective, rule.tokens, rule.localTokens);
+ for (const name of Object.keys(rule.tokens)) {
+ relevantNames.add(name);
+ }
+ for (const name of Object.keys(rule.localTokens ?? {})) {
+ relevantNames.add(name);
+ }
+ }
+
+ const indexes = matchingRuleIndexes.join(', ');
+ const queries = matchingRuleIndexes
+ .map(index => rules[index].query)
+ .join('; ');
+ assertNoTokenCycles(
+ effective,
+ `defineTheme("${themeName}").adaptations ${
+ matchingRuleIndexes.length === 1 ? 'rule' : 'overlapping rules'
+ } [${indexes}] (${queries})`,
+ relevantNames,
+ );
+ }
+ }
+ }
+ }
+}
+
+/**
+ * Resolve the effective root generative metadata through a theme extension.
+ * An explicitly supplied root axis replaces the inherited axis; omission inherits.
+ */
+export function resolveThemeGenerativeAxes(
+ inherited: ThemeGenerativeAxes | undefined,
+ own: ThemeGenerativeAxes,
+): ThemeGenerativeAxes {
+ const inheritedTypography = inherited?.typography;
+ const ownTypography = own.typography;
+ const resolveFamily = (
+ inheritedRole: TypographyRole | undefined,
+ ownRole: TypographyRole | undefined,
+ followsOwnBody = false,
+ ): TypographyRole | undefined => {
+ const merged = mergeRole(inheritedRole, ownRole);
+ if (!merged) {
+ return undefined;
+ }
+ if (ownRole?.family) {
+ return {
+ ...merged,
+ family: ownRole.family,
+ fallbacks: ownRole.fallbacks,
+ };
+ }
+ if (followsOwnBody) {
+ return {...merged, family: undefined, fallbacks: undefined};
+ }
+ // A fallback without a family is inert in buildFontFamilyTokens(), so it
+ // cannot replace the fallback attached to an inherited effective family.
+ return {
+ ...merged,
+ family: inheritedRole?.family,
+ fallbacks: inheritedRole?.fallbacks,
+ };
+ };
+
+ let body = resolveFamily(inheritedTypography?.body, ownTypography?.body);
+ let heading = resolveFamily(
+ inheritedTypography?.heading,
+ ownTypography?.heading,
+ Boolean(ownTypography?.body?.family && !ownTypography?.heading?.family),
+ );
+ let code = resolveFamily(inheritedTypography?.code, ownTypography?.code);
+
+ // Weights reach tokens only when a scale is expanded. The most recent
+ // config that declares a scale owns every weight; omitted weights become the
+ // expander defaults rather than resurrecting values from an earlier scale.
+ const weightOwner = ownTypography?.scale
+ ? ownTypography
+ : inheritedTypography?.scale
+ ? inheritedTypography
+ : undefined;
+ const applyWeights = (
+ role: TypographyRole | undefined,
+ owner: TypographyRole | undefined,
+ ): TypographyRole | undefined =>
+ role
+ ? {...role, weight: owner?.weight, weights: owner?.weights}
+ : undefined;
+ body = applyWeights(body, weightOwner?.body);
+ heading = applyWeights(heading, weightOwner?.heading);
+ code = applyWeights(code, weightOwner?.code);
+
+ const typography =
+ inheritedTypography || ownTypography
+ ? {
+ ...inheritedTypography,
+ ...ownTypography,
+ scale: ownTypography?.scale ?? inheritedTypography?.scale,
+ body,
+ heading,
+ code,
+ }
+ : undefined;
+ // A color config regenerates its neutral ramp even when `accent` is omitted,
+ // so an authored child config replaces rather than field-merges the base axis.
+ const color = own.color ?? inherited?.color;
+ const radius = own.radius
+ ? {...inherited?.radius, ...own.radius}
+ : inherited?.radius;
+ const motion = own.motion
+ ? {...inherited?.motion, ...own.motion}
+ : inherited?.motion;
+
+ return {
+ ...(typography ? {typography} : {}),
+ ...(color ? {color} : {}),
+ ...(radius ? {radius} : {}),
+ ...(motion ? {motion} : {}),
+ };
+}
+
+/** Lower ordered normalized rules to concrete CSS writes. */
+export function resolveThemeAdaptationRules(
+ themeName: string,
+ adaptations: NormalizedThemeAdaptations,
+ axes: ThemeGenerativeAxes,
+ rootTokens: Record<string, string>,
+ rootLocalTokens: Record<string, string> | undefined,
+): ResolvedThemeAdaptationRule[] | undefined {
+ if (adaptations.rules.length === 0) {
+ return undefined;
+ }
+
+ const resolvedRules = adaptations.rules.map((rule, index) => {
+ const resolved = resolveThemeValues(
+ valueToThemeInput(themeName, index, rule.value, axes),
+ undefined,
+ // Authored adaptation values are a new surface with no legacy
+ // acceptance to preserve, so a malformed token is rejected here rather
+ // than emitted. The root path stays lenient for compatibility.
+ // SYNC: packages/core/src/theme/resolveThemeValues.ts (resolveTokenValue)
+ {strictTokens: true},
+ );
+ for (const [name, value] of Object.entries(resolved.tokens)) {
+ assertConcreteLeaf(
+ value,
+ `defineTheme("${themeName}").adaptations.rules[${index}].value.tokens["${name}"]`,
+ );
+ }
+ if (resolved.components) {
+ assertConcreteLeaf(
+ resolved.components,
+ `defineTheme("${themeName}").adaptations.rules[${index}].value.components`,
+ );
+ }
+
+ for (const name of Object.keys(rule.value.tokens ?? {})) {
+ if (isReservedThemeLocalTokenName(name)) {
+ throw new Error(
+ `defineTheme("${themeName}").adaptations.rules[${index}].value.tokens["${name}"] uses the reserved --astryx-theme-* namespace; write it through value.localTokens instead.`,
+ );
+ }
+ }
+
+ const localTokens = resolveAdaptationLocalTokens(
+ themeName,
+ index,
+ rule.value.localTokens,
+ rootLocalTokens,
+ resolved.tokens,
+ resolved.components,
+ );
+
+ return {
+ when: rule.when,
+ query: mediaQueryForCondition(
+ themeName,
+ index,
+ rule.when,
+ adaptations.widthBreakpoints,
+ ),
+ tokens: resolved.tokens,
+ localTokens,
+ components: resolved.components,
+ };
+ });
+
+ assertNoReachableTokenCycles(
+ themeName,
+ adaptations.widthBreakpoints,
+ rootTokens,
+ rootLocalTokens,
+ resolvedRules,
+ );
+ return resolvedRules;
+}
diff --git a/packages/core/src/theme/tokenValueCompat.test.ts b/packages/core/src/theme/tokenValueCompat.test.ts
new file mode 100644
index 0000000000..621958e169
--- /dev/null
+++ b/packages/core/src/theme/tokenValueCompat.test.ts
@@ -0,0 +1,201 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file The token-value acceptance boundary between the root and adaptation
+ * paths.
+ *
+ * `TokenValue` is a compile-time contract only. Themes reach `defineTheme`
+ * through casts, broad spreads, generated objects and plain JavaScript, so
+ * values outside that type genuinely arrive at runtime — and historically the
+ * root path accepted them: a two-element array became `light-dark()`, and
+ * anything else passed through untouched.
+ *
+ * Extracting the resolver into `resolveThemeValues` made it throw on all of
+ * them, which turned working non-adaptation themes into hard failures. These
+ * tests pin the boundary that fixes it:
+ *
+ * - the ROOT/legacy path keeps its historical acceptance, verbatim;
+ * - values authored inside an ADAPTATION rule are validated strictly, because
+ * that surface is new and has no acceptance to preserve;
+ * - theme-LOCAL tokens keep the strict validation they shipped with (#5844),
+ * which predates this and is not part of the boundary.
+ */
+
+import {describe, expect, it} from 'vitest';
+import {defineTheme} from './defineTheme';
+import {resolveTokenValue} from './resolveThemeValues';
+
+/** Exactly what the pre-extraction implementation did with each shape. */
+const LEGACY_ACCEPTED: [string, unknown, unknown][] = [
+ ['a number', 16, 16],
+ ['zero', 0, 0],
+ ['a boolean', false, false],
+ ['null', null, null],
+ ['a three-element array', ['a', 'b', 'c'], 'light-dark(a, b)'],
+ ['a one-element array', ['a'], 'light-dark(a, undefined)'],
+];
+
+describe('root token values keep their historical acceptance', () => {
+ it.each(LEGACY_ACCEPTED)('accepts %s', (_label, value, expected) => {
+ const theme = defineTheme({
+ name: 'legacy',
+ tokens: {'--color-background-body': value as string},
+ });
+
+ expect(theme.tokens['--color-background-body']).toBe(expected);
+ });
+
+ it('still resolves the documented shapes', () => {
+ const theme = defineTheme({
+ name: 'documented',
+ tokens: {
+ '--color-background-body': '#fff',
+ '--color-text-primary': ['#000', '#fff'],
+ },
+ });
+
+ expect(theme.tokens['--color-background-body']).toBe('#fff');
+ expect(theme.tokens['--color-text-primary']).toBe('light-dark(#000, #fff)');
+ });
+
+ it('builds a whole non-adaptation theme carrying an out-of-type token', () => {
+ // The regression in the wild: a theme with no adaptations at all, whose
+ // tokens came through a cast or a spread, stopped building entirely.
+ const spread = {'--spacing-4': 12} as unknown as Record<string, string>;
+
+ const theme = defineTheme({
+ name: 'legacy-spread',
+ tokens: {'--color-background-body': '#fff', ...spread},
+ components: {button: {base: {borderRadius: '4px'}}},
+ });
+
+ expect(theme.name).toBe('legacy-spread');
+ expect(theme.tokens['--spacing-4']).toBe(12);
+ expect(theme.components?.button).toEqual({base: {borderRadius: '4px'}});
+ });
+
+ it('keeps accepting them through `extends`', () => {
+ const base = defineTheme({
+ name: 'legacy-base',
+ tokens: {'--color-background-body': 16 as unknown as string},
+ });
+
+ const child = defineTheme({
+ name: 'legacy-child',
+ extends: base,
+ tokens: {'--color-accent': '#09f'},
+ });
+
+ expect(child.tokens['--color-background-body']).toBe(16);
+ expect(child.tokens['--color-accent']).toBe('#09f');
+ });
+
+ it('keeps accepting them on an on-media surface', () => {
+ const theme = defineTheme({
+ name: 'legacy-on-media',
+ tokens: {'--color-background-body': '#fff'},
+ onDark: {tokens: {'--color-background-body': 0 as unknown as string}},
+ });
+
+ expect(theme.__onDark?.tokens['--color-background-body']).toBe(0);
+ });
+});
+
+describe('adaptation-authored token values are validated', () => {
+ it.each(LEGACY_ACCEPTED)('rejects %s inside a rule', (_label, value) => {
+ expect(() =>
+ defineTheme({
+ name: 'adaptive',
+ tokens: {'--color-background-body': '#fff'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {tokens: {'--color-background-body': value as string}},
+ },
+ ],
+ },
+ }),
+ ).toThrow(/must be CSS strings or \[light, dark\] string tuples/);
+ });
+
+ it('accepts the documented shapes inside a rule', () => {
+ const theme = defineTheme({
+ name: 'adaptive-ok',
+ tokens: {'--color-background-body': '#fff'},
+ adaptations: {
+ rules: [
+ {
+ when: {pointer: 'coarse'},
+ value: {
+ tokens: {
+ '--size-element-md': '44px',
+ '--color-border': ['#000', '#fff'],
+ },
+ },
+ },
+ ],
+ },
+ });
+
+ const rule = theme.__adaptationRules?.[0];
+ expect(rule?.tokens?.['--size-element-md']).toBe('44px');
+ expect(rule?.tokens?.['--color-border']).toBe('light-dark(#000, #fff)');
+ });
+
+ it('does not let a lenient ROOT value weaken its own rules', () => {
+ // One theme, both surfaces: the root keeps its out-of-type value and the
+ // rule beside it is still rejected.
+ expect(() =>
+ defineTheme({
+ name: 'mixed',
+ tokens: {'--color-background-body': 16 as unknown as string},
+ adaptations: {
+ rules: [
+ {
+ when: {contrast: 'more'},
+ value: {tokens: {'--color-border': 32 as unknown as string}},
+ },
+ ],
+ },
+ }),
+ ).toThrow(/must be CSS strings or \[light, dark\] string tuples/);
+ });
+});
+
+describe('resolveTokenValue', () => {
+ it('is lenient by default', () => {
+ expect(resolveTokenValue(16 as unknown as string)).toBe(16);
+ });
+
+ it('throws only when asked to be strict', () => {
+ expect(() =>
+ resolveTokenValue(16 as unknown as string, {strict: true}),
+ ).toThrow(/must be CSS strings or \[light, dark\] string tuples/);
+ });
+
+ it('resolves documented shapes identically in both modes', () => {
+ for (const strict of [false, true]) {
+ expect(resolveTokenValue('#fff', {strict})).toBe('#fff');
+ expect(resolveTokenValue(['#000', '#fff'], {strict})).toBe(
+ 'light-dark(#000, #fff)',
+ );
+ }
+ });
+});
+
+describe('theme-local tokens keep their own pre-existing strictness', () => {
+ it('rejects a malformed local token value', () => {
+ // Not part of this boundary: local tokens shipped strict in #5844, before
+ // adaptations existed, so nothing here may loosen them.
+ expect(() =>
+ defineTheme({
+ name: 'local',
+ tokens: {'--color-background-body': '#fff'},
+ localTokens: {
+ '--astryx-theme-local-brand-fill': 16 as unknown as string,
+ },
+ }),
+ ).toThrow(/must be a CSS string or a \[light, dark\] string tuple/);
+ });
+});
diff --git a/packages/core/src/theme/useTheme.ts b/packages/core/src/theme/useTheme.ts
index c841a3c570..b07fe5ec6b 100644
--- a/packages/core/src/theme/useTheme.ts
+++ b/packages/core/src/theme/useTheme.ts
@@ -5,7 +5,7 @@
/**
* @file useTheme.ts
* @input ThemeContext provided by Theme
- * @output Exports useTheme and useThemeName hooks for programmatic theme access
+ * @output Exports useTheme, useThemeName, and internal theme-object access
* @position Theme hook; used by data viz, canvas, and non-CSS consumers
*
* Provides synchronous access to theme token values resolved for the
@@ -237,6 +237,18 @@ export function useThemeName(): string | null {
return ctx?.theme.name ?? rootThemeName;
}
+/**
+ * Return the nearest theme object, falling back to the registered root theme
+ * only when no provider context is available.
+ * @internal
+ */
+export function useThemeDefinition(): DefinedTheme | undefined {
+ const ctx = use(ThemeContext);
+ const hasCtx = ctx != null;
+ const rootThemeName = useRootThemeNameAttr(hasCtx);
+ return ctx?.theme ?? getRegisteredTheme(rootThemeName) ?? undefined;
+}
+
/**
* Access the current Astryx theme's token values, resolved for the active color mode.
*
diff --git a/scripts/check-theme-template.test.mjs b/scripts/check-theme-template.test.mjs
index d43b6c2aad..5f66664ba6 100644
--- a/scripts/check-theme-template.test.mjs
+++ b/scripts/check-theme-template.test.mjs
@@ -174,15 +174,16 @@ function docTopics() {
// ---------------------------------------------------------------------------
/**
- * Top-level keys the template sets, plus the optional ones it shows commented
- * out (`// syntax: dracula,`). A commented field must carry a value, so an
- * ordinary prose comment is not mistaken for one.
+ * Top-level keys the template sets, plus optional fields shown commented out.
+ * A commented field must carry either a same-line value (`// syntax: dracula,`)
+ * or open a commented object block (`// adaptations: {`), so ordinary prose is
+ * not mistaken for a field.
*/
function templateFields() {
const set = [...template.matchAll(/^ {2}(\w+):/gm)].map(m => m[1]);
- const commented = [...template.matchAll(/^ {2}\/\/ (\w+): .+,$/gm)].map(
- m => m[1],
- );
+ const commented = [
+ ...template.matchAll(/^ {2}\/\/ (\w+): (?:.+,|\{)$/gm),
+ ].map(m => m[1]);
return [...new Set([...set, ...commented])];
}