@styleframe/cli 3.0.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +124 -0
  2. package/dist/build-CBdsifMN.js +47 -0
  3. package/dist/build-D7cinF0l.cjs +50 -0
  4. package/dist/build-dtcg-BpbjBRCf.js +429 -0
  5. package/dist/build-dtcg-vuGHy-Sl.cjs +434 -0
  6. package/dist/chunk-D6vf50IK.cjs +28 -0
  7. package/dist/commands/build.d.ts +22 -0
  8. package/dist/commands/build.d.ts.map +1 -0
  9. package/dist/commands/dtcg/build-dtcg.d.ts +36 -0
  10. package/dist/commands/dtcg/build-dtcg.d.ts.map +1 -0
  11. package/dist/commands/dtcg/build-dtcg.test.d.ts +2 -0
  12. package/dist/commands/dtcg/build-dtcg.test.d.ts.map +1 -0
  13. package/dist/commands/dtcg/evaluate.d.ts +30 -0
  14. package/dist/commands/dtcg/evaluate.d.ts.map +1 -0
  15. package/dist/commands/dtcg/evaluate.test.d.ts +2 -0
  16. package/dist/commands/dtcg/evaluate.test.d.ts.map +1 -0
  17. package/dist/commands/dtcg/export.d.ts +24 -0
  18. package/dist/commands/dtcg/export.d.ts.map +1 -0
  19. package/dist/commands/dtcg/import.d.ts +38 -0
  20. package/dist/commands/dtcg/import.d.ts.map +1 -0
  21. package/dist/commands/dtcg/index.d.ts +3 -0
  22. package/dist/commands/dtcg/index.d.ts.map +1 -0
  23. package/dist/commands/figma/export.d.ts +24 -0
  24. package/dist/commands/figma/export.d.ts.map +1 -0
  25. package/dist/commands/figma/import.d.ts +38 -0
  26. package/dist/commands/figma/import.d.ts.map +1 -0
  27. package/dist/commands/figma/index.d.ts +3 -0
  28. package/dist/commands/figma/index.d.ts.map +1 -0
  29. package/dist/commands/init/nuxt.d.ts +2 -0
  30. package/dist/commands/init/nuxt.d.ts.map +1 -0
  31. package/dist/commands/init/vite.d.ts +2 -0
  32. package/dist/commands/init/vite.d.ts.map +1 -0
  33. package/dist/commands/init.d.ts +26 -0
  34. package/dist/commands/init.d.ts.map +1 -0
  35. package/dist/constants.d.ts +8 -0
  36. package/dist/constants.d.ts.map +1 -0
  37. package/dist/dtcg-D1-iITOr.js +14 -0
  38. package/dist/dtcg-D84AfyzO.cjs +13 -0
  39. package/dist/export-CBdPGGEq.js +66 -0
  40. package/dist/export-DmPAU9Wh.cjs +69 -0
  41. package/dist/export-ONk9eKoZ.cjs +86 -0
  42. package/dist/export-suUS16eO.js +83 -0
  43. package/dist/figma-BvXoqRPU.cjs +13 -0
  44. package/dist/figma-D2RJh56T.js +14 -0
  45. package/dist/import-BQrcHNjK.cjs +126 -0
  46. package/dist/import-Bll_uBvJ.js +123 -0
  47. package/dist/import-MqLYxb8d.js +114 -0
  48. package/dist/import-ibQc_GXm.cjs +117 -0
  49. package/dist/index.cjs +21 -8669
  50. package/dist/index.d.ts +3 -4
  51. package/dist/index.d.ts.map +1 -0
  52. package/dist/index.js +16 -18
  53. package/dist/init-CAO0mA_w.js +262 -0
  54. package/dist/init-CaJoUVv2.cjs +265 -0
  55. package/dist/utils.d.ts +7 -0
  56. package/dist/utils.d.ts.map +1 -0
  57. package/package.json +14 -17
  58. package/dist/build-BFZSJ2Zh.js +0 -49
  59. package/dist/export-SH70kD-5.js +0 -139
  60. package/dist/import-CwuwczM7.js +0 -90
  61. package/dist/index-C3Gqfamh.js +0 -3689
  62. package/dist/index-DH3Hm47n.js +0 -14
  63. package/dist/index-DtEAy_us.js +0 -4475
  64. package/dist/init-DnrkQJYO.js +0 -234
package/CHANGELOG.md CHANGED
@@ -1,5 +1,129 @@
1
1
  # @styleframe/cli
2
2
 
3
+ ## 4.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - [#229](https://github.com/styleframe-dev/styleframe/pull/229) [`19e9866`](https://github.com/styleframe-dev/styleframe/commit/19e986618c669546972924840189fc5f16f1a1cd) Thanks [@alexgrozav](https://github.com/alexgrozav)! - **Fix:** Resolve critical token loss bug in Figma plugin export where 121 of 464 variables were dropped due to `setNestedToken` overwriting group subtrees instead of promoting parent tokens to `$root`.
8
+
9
+ **Feature:** Add mode selector dropdown to Figma plugin Export tab for filtering variables by specific theme/mode before export.
10
+
11
+ **Feature:** Add CLI commands for Figma-compatible DTCG sync: `figma export` and `figma import` enable bidirectional token synchronization between Figma collections and design token files.
12
+
13
+ **Improvement:** Embed collection metadata in DTCG output via `$extensions.dev.styleframe.collection` for better round-trip awareness.
14
+
15
+ **Improvement:** Restore BOOLEAN variable support by converting to string type with `dev.styleframe.boolean: true` extension metadata.
16
+
17
+ **Fix:** Correct UI variable count display to read from `msg.result.tokens` instead of wrapper object, ensuring accurate exported variable count and collection name extraction.
18
+
19
+ ### Patch Changes
20
+
21
+ - [#231](https://github.com/styleframe-dev/styleframe/pull/231) [`c0cfbdc`](https://github.com/styleframe-dev/styleframe/commit/c0cfbdc65ddca0b5ea4a420902be2a23580b392f) Thanks [@alexgrozav](https://github.com/alexgrozav)! - Update `styleframe init` to install v3.x dependencies instead of v2.x. Remove `@styleframe/pro` from scaffolded dependencies.
22
+
23
+ - [#235](https://github.com/styleframe-dev/styleframe/pull/235) [`6acd766`](https://github.com/styleframe-dev/styleframe/commit/6acd766eefc82139d8cd98dfb9b553449945d704) Thanks [@alexgrozav](https://github.com/alexgrozav)! - Generate DTS output as two files that describe the virtual modules in two complementary forms. The transpiler's `dts` mode now emits:
24
+ - `styleframe.d.ts` — top-level exports describing the `virtual:styleframe` module
25
+ - `shims.d.ts` — self-contained ambient declarations: a `declare module "virtual:styleframe"` carrying the full typed exports, plus the `virtual:styleframe.css` string shim
26
+
27
+ Non-Vue consumers resolve both virtual modules from `shims.d.ts` alone (picked up via the `.styleframe/**/*.d.ts` include) with **zero `paths` configuration**. Vue consumers additionally map `virtual:styleframe` to `styleframe.d.ts` via a `compilerOptions.paths` entry, because `vue-tsc` won't resolve a bare-specifier ambient module imported inside a `.vue` SFC. `styleframe init` detects plain Vue projects (a `vue` dependency without `nuxt`) and writes that `paths` entry only for them, merging into any existing `paths`; non-Vue projects just get the includes. Nuxt is excluded because its module already injects the mapping via `prepare:types`, and writing `paths` into an `extends`-based Nuxt root tsconfig would replace (not merge) Nuxt's inherited aliases.
28
+
29
+ The Nuxt module registers the same `virtual:styleframe` path mapping into Nuxt's generated types via the `prepare:types` hook, so imports type-check without manual tsconfig changes. It also fixes the module's `configKey`/`name`, which were leftover `unpluginStarter` placeholders that caused `styleframe: {}` options in `nuxt.config` to be ignored.
30
+
31
+ - [#233](https://github.com/styleframe-dev/styleframe/pull/233) [`0ef38e6`](https://github.com/styleframe-dev/styleframe/commit/0ef38e69ca941cefab31463c23980f52cae1541f) Thanks [@alexgrozav](https://github.com/alexgrozav)! - Migrate from Vite 7 to Vite 8 with native Rolldown integration. Replace esbuild transforms with Oxc in the plugin, rename `rollupOptions` to `rolldownOptions`, upgrade `vite-plugin-dts` v4 to v5 (`rollupTypes` → `bundleTypes`), and bump vitest from v3 to v4.
32
+
33
+ - Updated dependencies [[`19e9866`](https://github.com/styleframe-dev/styleframe/commit/19e986618c669546972924840189fc5f16f1a1cd), [`0ef38e6`](https://github.com/styleframe-dev/styleframe/commit/0ef38e69ca941cefab31463c23980f52cae1541f)]:
34
+ - @styleframe/figma@2.1.0
35
+ - @styleframe/loader@3.0.2
36
+
37
+ ## 4.0.0
38
+
39
+ ### Major Changes
40
+
41
+ - [#211](https://github.com/styleframe-dev/styleframe/pull/211) [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f) Thanks [@alexgrozav](https://github.com/alexgrozav)! - **BREAKING**: rename `styleframe figma export` → `styleframe dtcg export`.
42
+
43
+ The CLI command now lives under a top-level `dtcg` subcommand to reflect that it produces a generic spec-conformant DTCG document, not a Figma-specific format. The DTCG → Figma value conversion (rem→px, ms passthrough, etc.) lives in the `@styleframe/figma` plugin, which consumes the JSON.
44
+
45
+ `styleframe figma import` is unchanged — it generates Styleframe TypeScript code from a Figma-flavoured DTCG export.
46
+
47
+ Migration:
48
+
49
+ ```diff
50
+ - styleframe figma export -o tokens.json
51
+ + styleframe dtcg export -o tokens.json
52
+ ```
53
+
54
+ The `--baseFontSize` flag has been removed from the export — base font size is applied by the Figma plugin during import (default 16). Any CI scripts referring to the old command must be updated.
55
+
56
+ ### Minor Changes
57
+
58
+ - [#213](https://github.com/styleframe-dev/styleframe/pull/213) [`24eebba`](https://github.com/styleframe-dev/styleframe/commit/24eebba87c8fa6fc6822e18d67f4c0412192e793) Thanks [@alexgrozav](https://github.com/alexgrozav)! - **BREAKING**: rename `styleframe figma import` → `styleframe dtcg import`.
59
+
60
+ The CLI command now lives under the `dtcg` subcommand alongside `dtcg export`. The command takes a generic spec-conformant DTCG JSON file (whether produced by the `@styleframe/figma` plugin or any other DTCG-compatible tool) and generates Styleframe TypeScript code — there is nothing Figma-specific about it. The top-level `figma` subcommand has been removed; the namespace is reserved for future commands that genuinely interact with the Figma API.
61
+
62
+ All flags are unchanged (`--input`/`-i`, `--output`/`-o`, `--composables`, `--rem`, `--baseFontSize`, `--instanceName`).
63
+
64
+ Migration:
65
+
66
+ ```diff
67
+ - styleframe figma import -i tokens.json
68
+ + styleframe dtcg import -i tokens.json
69
+ ```
70
+
71
+ Any CI scripts referring to the old command must be updated.
72
+
73
+ ### Patch Changes
74
+
75
+ - [#211](https://github.com/styleframe-dev/styleframe/pull/211) [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f) Thanks [@alexgrozav](https://github.com/alexgrozav)! - Fix DTCG export from `@styleframe/cli`: variables now get the correct `$type` and references are preserved as aliases.
76
+
77
+ The previous CLI flow piped Styleframe AST through a lossy `FigmaExportFormat` intermediate, then through `figmaTypeToDtcg("STRING") → "fontFamily"` — so most variables ended up tagged as `fontFamily` in the resulting JSON. References were silently replaced with empty strings, and CSS template expressions like `${ref(a)} * ${ref(b)}` were joined into garbage like `" * "`.
78
+
79
+ **`@styleframe/dtcg`** gains a new `classifyValue(value, {path?})` helper plus `parseCubicBezier` and `easingKeywordToBezier`. The classifier combines value-content detection with optional path heuristics so callers get a single canonical `{type, value}` pair without per-package guessing.
80
+
81
+ **`@styleframe/cli`** now builds the DTCG document directly from the Styleframe `Root`. A small evaluator pre-resolves `Reference` chains and pure-arithmetic CSS templates so computed variables (e.g. `scale.min-powers.*`) emit concrete numbers instead of being skipped or corrupted. Unevaluable expressions (involving `clamp()`, `vw`, etc.) are preserved with a `dev.styleframe.expression` extension, surfaced in a diagnostics summary at the end of the run.
82
+
83
+ **`@styleframe/figma`** uses the same classifier with the Figma variable name as a path hint. `figmaTypeToDtcg("STRING")` no longer claims everything is a `fontFamily`; instead callers should use the new `classifyFigmaVariable(variable, value)` which correctly identifies durations under `duration/*`, easings under `easing/*`, stroke styles, and font weights. STRING values whose name gives no usable hint are emitted with a `dev.styleframe.unknownType` extension rather than silently mistyped.
84
+
85
+ Round-trip lossiness across Styleframe ↔ DTCG ↔ Figma is now documented in `tooling/dtcg/AGENTS.md`.
86
+
87
+ - [#211](https://github.com/styleframe-dev/styleframe/pull/211) [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f) Thanks [@alexgrozav](https://github.com/alexgrozav)! - Fix `dtcg export`: fluid font-size tokens (and any other tokens whose value reduces to a `calc()` mixing `100vw`, `rem`, and `px` literals) are now normalised to a concrete pixel value using the project's `fluid.max-width` (default 1440) instead of being emitted as opaque `calc(...)` expressions with a `dev.styleframe.unknownType` extension.
88
+
89
+ Previously every `font-size.*` token in a config that used `useFluidFontSizeDesignTokens` shipped to Figma as a useless `STRING` variable holding the raw `calc(...)` formula. They now ship as spec-conformant `dimension` tokens (`{value, unit: "px"}`) that the Figma plugin renders as real numeric variables (`font-size/md = 18`, `font-size/lg = 22.5`, etc.).
90
+
91
+ The substitution runs only as a fallback after the standard arithmetic check fails, so well-formed numeric expressions are unaffected. Affected tokens carry a `dev.styleframe.fluidBound: "max"` extension so the derivation is auditable. The export run reports `Normalised <n> fluid token(s) using max viewport (<n>px).`
92
+
93
+ - [#211](https://github.com/styleframe-dev/styleframe/pull/211) [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f) Thanks [@alexgrozav](https://github.com/alexgrozav)! - Fix dark mode round-trip from Styleframe → DTCG → Figma.
94
+
95
+ Previously, `styleframe dtcg export` emitted a `tokens.resolver.json` that the Figma plugin had no way to consume — the plugin UI accepted only one file and its import handler always called the single-mode `fromDTCG()`. As a result, dark mode values never reached Figma. The exported resolver was also malformed: `default` referenced a non-existent context, and the resolver lacked a `set` linking to the base `tokens.json`, so any spec-conformant consumer would have failed too.
96
+
97
+ **`@styleframe/cli`** — `buildDTCG` now emits a self-contained resolver: `resolutionOrder` begins with a `set` referencing the base tokens file (controllable via `tokensSourceRef`), every theme contributes a capitalized context (`dark` → `Dark`), and a `Default` context (with no overrides) covers the unthemed mode. `default` correctly points at `Default`. Override tokens also carry `$type` so the `mergeDocuments` token-level replacement preserves typing — without this, dark color values lost their `color` type and downstream consumers (e.g. Figma) couldn't convert them, falling back to default white.
98
+
99
+ **`@styleframe/figma`** — the plugin UI exposes a second drop slot for `tokens.resolver.json`. When a resolver is provided, `code.ts` routes through `fromDTCGResolver` with an in-memory file loader so each declared context becomes a Figma mode populated with the correct per-mode values.
100
+
101
+ - [#211](https://github.com/styleframe-dev/styleframe/pull/211) [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f) Thanks [@alexgrozav](https://github.com/alexgrozav)! - Fix two regressions in DTCG export uncovered by dogfooding the storybook config:
102
+
103
+ **Keyword-classification ambiguity.** The previous classifier matched `FONT_WEIGHT_KEYWORDS` and `STROKE_STYLE_KEYWORDS` on value content alone — but `"normal"` is a perfectly valid value for `letter-spacing`, `font-style`, and `line-height`, not just `font-weight`. Same for `"thin"`/`"medium"`/`"thick"` which are CSS border-width shorthand keywords. The result was that `border-width`, `font-style`, `letter-spacing`, and similar tokens were misclassified as `fontWeight` whenever their alias chain bottomed out at one of these CSS keywords.
104
+
105
+ The fix: keyword-based detectors now only fire when the path also indicates the corresponding category (`font-weight` segment for fontWeight, `border-style`/`outline-style`/`stroke` for strokeStyle, `font-family` for fontFamily). Callers that don't supply a path still get the keyword-based behaviour for back-compat. Tokens with no resolvable type emit a `dev.styleframe.unknownType` extension instead of a wrong `$type`.
106
+
107
+ **Parent/child path collisions wiped out children.** Styleframe configs commonly define both a parent variable (e.g. `border-width` aliased to `border-width.thin`) AND its child variants (`border-width.thin`, `border-width.medium`, `border-width.thick`). The previous `setNestedToken` logic unconditionally overwrote the slot, so depending on processing order either the parent or all the children were silently lost.
108
+
109
+ The fix: `setNestedToken` now uses the spec's reserved `$root` slot for parent tokens that coexist with siblings — a pattern explicitly defined in the Format Module 2025.10 for "group with a base value plus variants". Children survive alongside the parent, and the walker / validator / Figma plugin import all recognise `$root` as the parent's effective leaf.
110
+
111
+ The CLI also gains a one-line tip in its diagnostic output explaining that "untyped" tokens are usually CSS keywords with no DTCG equivalent.
112
+
113
+ **Numeric-string misclassification as colour.** `classifyValue("100")` and similar 3-character numeric strings were incorrectly classified as `$type: "color"` because culori's `parse()` interprets them as shorthand CSS hex (`"100"` → `#100`). Z-index tokens like `z-index.dropdown = "100"` consequently appeared as sRGB color variables in the exported JSON.
114
+
115
+ The fix: `classifyValue` now only forwards strings to culori that structurally look like CSS colors — those starting with `#`, containing `(` (function notation), or beginning with an ASCII letter (named color). Plain numeric strings are excluded before reaching the parser.
116
+
117
+ **Plugin import crash on viewport-relative units.** Importing a `tokens.json` that contained any `{value: 100, unit: "vw"}` dimension token caused the entire Figma plugin import to throw `Cannot convert "100vw" to a Figma FLOAT`. The exception propagated through the entire import, leaving all variables (including colors) at their default `#FFFFFF`.
118
+
119
+ The fix: `dtcgDimensionToFloat` now returns `undefined` for unsupported units (vw, vh, dvw, svw, etc.) instead of throwing, and `fromDTCG` silently skips variables whose value cannot be converted rather than crashing the whole batch. Colors and other tokens now import correctly even when the document contains fluid/viewport tokens.
120
+
121
+ **Out-of-gamut sRGB clamping.** Converting oklch colours to Figma's sRGB RGBA could produce slightly negative channel values (e.g. `r = -4.21e-15`) due to floating-point rounding in the matrix multiplication. The fix clamps `r`, `g`, and `b` to `[0, 1]` in `dtcgColorToFigmaRgba`.
122
+
123
+ - Updated dependencies [[`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f), [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f), [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f), [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f), [`8826eda`](https://github.com/styleframe-dev/styleframe/commit/8826edad3fcb2e969024a586a20c2059229d958f)]:
124
+ - @styleframe/dtcg@1.1.0
125
+ - @styleframe/figma@2.0.0
126
+
3
127
  ## 3.0.0
4
128
 
5
129
  ### Major Changes
@@ -0,0 +1,47 @@
1
+ import { defineCommand } from "citty";
2
+ import path from "node:path";
3
+ import { build, loadConfiguration } from "@styleframe/loader";
4
+ import consola from "consola";
5
+ //#region src/commands/build.ts
6
+ var build_default = defineCommand({
7
+ meta: {
8
+ name: "build",
9
+ description: "Build Styleframe project from source files"
10
+ },
11
+ args: {
12
+ entry: {
13
+ type: "positional",
14
+ description: "Entry point file(s) for the build",
15
+ default: "styleframe.config.ts",
16
+ valueHint: "path"
17
+ },
18
+ outputDir: {
19
+ type: "string",
20
+ description: "Output directory for built files",
21
+ default: "styleframe",
22
+ alias: ["o", "out"],
23
+ valueHint: "path"
24
+ },
25
+ clean: {
26
+ type: "boolean",
27
+ description: "Clean output directory before build",
28
+ default: false
29
+ }
30
+ },
31
+ async run({ args }) {
32
+ consola.info(`Loading configuration from "${path.relative(process.cwd(), path.resolve(args.entry))}"...`);
33
+ const instance = await loadConfiguration({ entry: args.entry });
34
+ consola.info("Building styleframe...");
35
+ try {
36
+ await build(instance, {
37
+ outputDir: args.outputDir,
38
+ clean: args.clean
39
+ });
40
+ consola.success("Styleframe built successfully!");
41
+ } catch (error) {
42
+ consola.error("Failed to build Styleframe:", error);
43
+ }
44
+ }
45
+ });
46
+ //#endregion
47
+ export { build_default as default };
@@ -0,0 +1,50 @@
1
+ const require_chunk = require("./chunk-D6vf50IK.cjs");
2
+ let citty = require("citty");
3
+ let node_path = require("node:path");
4
+ node_path = require_chunk.__toESM(node_path, 1);
5
+ let _styleframe_loader = require("@styleframe/loader");
6
+ let consola = require("consola");
7
+ consola = require_chunk.__toESM(consola, 1);
8
+ //#region src/commands/build.ts
9
+ var build_default = (0, citty.defineCommand)({
10
+ meta: {
11
+ name: "build",
12
+ description: "Build Styleframe project from source files"
13
+ },
14
+ args: {
15
+ entry: {
16
+ type: "positional",
17
+ description: "Entry point file(s) for the build",
18
+ default: "styleframe.config.ts",
19
+ valueHint: "path"
20
+ },
21
+ outputDir: {
22
+ type: "string",
23
+ description: "Output directory for built files",
24
+ default: "styleframe",
25
+ alias: ["o", "out"],
26
+ valueHint: "path"
27
+ },
28
+ clean: {
29
+ type: "boolean",
30
+ description: "Clean output directory before build",
31
+ default: false
32
+ }
33
+ },
34
+ async run({ args }) {
35
+ consola.default.info(`Loading configuration from "${node_path.default.relative(process.cwd(), node_path.default.resolve(args.entry))}"...`);
36
+ const instance = await (0, _styleframe_loader.loadConfiguration)({ entry: args.entry });
37
+ consola.default.info("Building styleframe...");
38
+ try {
39
+ await (0, _styleframe_loader.build)(instance, {
40
+ outputDir: args.outputDir,
41
+ clean: args.clean
42
+ });
43
+ consola.default.success("Styleframe built successfully!");
44
+ } catch (error) {
45
+ consola.default.error("Failed to build Styleframe:", error);
46
+ }
47
+ }
48
+ });
49
+ //#endregion
50
+ exports.default = build_default;
@@ -0,0 +1,429 @@
1
+ import { classifyValue, formatAlias } from "@styleframe/dtcg";
2
+ //#region src/commands/dtcg/evaluate.ts
3
+ function isReference(value) {
4
+ return typeof value === "object" && value !== null && "type" in value && value.type === "reference";
5
+ }
6
+ function isCss(value) {
7
+ return typeof value === "object" && value !== null && "type" in value && value.type === "css";
8
+ }
9
+ function isPrimitive(value) {
10
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
11
+ }
12
+ /**
13
+ * Resolve a Reference's *primitive* value (following alias chains). Returns
14
+ * null if the chain is broken (missing target or cycle).
15
+ */
16
+ function resolveReferenceTarget(ref, context) {
17
+ const visited = context.visited ?? /* @__PURE__ */ new Set();
18
+ if (visited.has(ref.name)) return {
19
+ resolved: null,
20
+ reason: `Reference cycle: ${[...visited, ref.name].join(" → ")}`
21
+ };
22
+ const target = context.variables.get(ref.name);
23
+ if (!target) {
24
+ if (ref.fallback !== void 0 && ref.fallback !== null) return evaluateValue(ref.fallback, context);
25
+ return {
26
+ resolved: null,
27
+ reason: `Unknown reference target: ${ref.name}`
28
+ };
29
+ }
30
+ const nextContext = {
31
+ variables: context.variables,
32
+ visited: new Set([...visited, ref.name]),
33
+ maxViewport: context.maxViewport
34
+ };
35
+ return evaluateValue(target.value, nextContext);
36
+ }
37
+ /**
38
+ * Try to evaluate a CSS template literal. Two strategies:
39
+ *
40
+ * 1. **String-template fold**: replace each `Reference` part with its
41
+ * resolved primitive (stringified) and concatenate. If the resulting
42
+ * string parses as a known CSS form (cubic-bezier(...), a hex color,
43
+ * a dimension, a duration), return it.
44
+ * 2. **Pure arithmetic**: if every part reduces to a finite number or one
45
+ * of `+`/`-`/`*`/`/`/`(`/`)` operators with whitespace, evaluate the
46
+ * arithmetic and return the numeric result.
47
+ *
48
+ * Otherwise, return `{resolved: null, cssExpression: <fold>}` so the caller
49
+ * can preserve the expression in an extension.
50
+ */
51
+ function evaluateCss(css, context) {
52
+ const parts = [];
53
+ let unevaluable = false;
54
+ let unevaluableReason;
55
+ for (const part of css.value) {
56
+ if (typeof part === "string") {
57
+ parts.push({
58
+ kind: "literal",
59
+ text: part
60
+ });
61
+ continue;
62
+ }
63
+ const evaluated = evaluateValue(part, context);
64
+ if (evaluated.resolved === null) {
65
+ unevaluable = true;
66
+ unevaluableReason = evaluated.reason;
67
+ parts.push({
68
+ kind: "value",
69
+ text: ""
70
+ });
71
+ continue;
72
+ }
73
+ const text = String(evaluated.resolved);
74
+ const numeric = typeof evaluated.resolved === "number" ? evaluated.resolved : void 0;
75
+ parts.push({
76
+ kind: "value",
77
+ text,
78
+ numeric
79
+ });
80
+ }
81
+ const folded = parts.map((p) => p.text).join("");
82
+ if (unevaluable) return {
83
+ resolved: null,
84
+ cssExpression: folded,
85
+ reason: unevaluableReason ?? "Computed expression includes an unresolvable reference"
86
+ };
87
+ if (parts.every((p) => {
88
+ if (p.kind === "value") return p.numeric !== void 0;
89
+ return /^[\d.\s+\-*/()]*$/.test(p.text);
90
+ }) && parts.some((p) => p.kind === "value")) try {
91
+ const result = safeArithmetic(folded.trim());
92
+ if (typeof result === "number" && Number.isFinite(result)) return { resolved: result };
93
+ } catch (err) {
94
+ return {
95
+ resolved: null,
96
+ cssExpression: folded,
97
+ reason: `Arithmetic evaluation failed: ${err.message}`
98
+ };
99
+ }
100
+ const subResult = substituteFluidUnits(folded, context.maxViewport ?? 1440);
101
+ if (subResult && /^[\d.\s+\-*/()]+$/.test(subResult.rebased)) try {
102
+ const result = safeArithmetic(subResult.rebased.trim());
103
+ if (typeof result === "number" && Number.isFinite(result)) return {
104
+ resolved: result,
105
+ ...subResult.substituted ? { normalisationSource: "fluid-max" } : {}
106
+ };
107
+ } catch {}
108
+ return { resolved: folded };
109
+ }
110
+ /**
111
+ * Replace fluid-friendly literals so a `calc()` expression mixing `100vw`,
112
+ * `rem`, and `px` reduces to pure arithmetic.
113
+ *
114
+ * Returns `null` when the input still contains units we don't substitute
115
+ * (e.g. `vh`, `%`, `em`) — the caller should fall back to the
116
+ * verbatim-string path.
117
+ *
118
+ * `substituted` indicates whether at least one fluid unit was actually
119
+ * substituted. `false` means we only stripped a bare `calc(...)` wrapper —
120
+ * the expression was effectively pure arithmetic and the result should NOT
121
+ * be flagged as fluid-normalised.
122
+ */
123
+ function substituteFluidUnits(expression, maxViewport) {
124
+ let substituted = false;
125
+ let rebased = expression.replace(/\bcalc\b/g, "");
126
+ if (rebased.includes("100vw")) {
127
+ rebased = rebased.replace(/100vw/g, String(maxViewport));
128
+ substituted = true;
129
+ }
130
+ if (/(-?\d*\.?\d+)\s*rem/.test(rebased)) {
131
+ rebased = rebased.replace(/(-?\d*\.?\d+)\s*rem/g, "($1 * 16)");
132
+ substituted = true;
133
+ }
134
+ if (/(-?\d*\.?\d+)\s*px/.test(rebased)) {
135
+ rebased = rebased.replace(/(-?\d*\.?\d+)\s*px/g, "$1");
136
+ substituted = true;
137
+ }
138
+ if (/[a-zA-Z%]/.test(rebased)) return null;
139
+ return {
140
+ rebased,
141
+ substituted
142
+ };
143
+ }
144
+ /**
145
+ * Safe arithmetic over a whitespace-trimmed expression containing only
146
+ * numbers, parentheses, and `+`/`-`/`*`/`/`. Throws on anything else.
147
+ */
148
+ function safeArithmetic(expression) {
149
+ if (!/^[\d.\s+\-*/()]+$/.test(expression)) throw new Error(`Disallowed characters in expression: "${expression}"`);
150
+ return new Function(`return (${expression});`)();
151
+ }
152
+ function evaluateValue(value, context) {
153
+ if (value === null || value === void 0) return {
154
+ resolved: null,
155
+ reason: "Value is null/undefined"
156
+ };
157
+ if (isPrimitive(value)) return { resolved: value };
158
+ if (isReference(value)) {
159
+ const targetResolution = resolveReferenceTarget(value, context);
160
+ if ((!context.visited || context.visited.size === 0) && targetResolution.resolved !== null) return {
161
+ ...targetResolution,
162
+ aliasTarget: value.name
163
+ };
164
+ return targetResolution;
165
+ }
166
+ if (isCss(value)) return evaluateCss(value, context);
167
+ if (Array.isArray(value)) return {
168
+ resolved: null,
169
+ reason: "Heterogeneous array — DTCG composite encoding not yet implemented"
170
+ };
171
+ return {
172
+ resolved: null,
173
+ reason: `Unsupported value shape: ${typeof value}`
174
+ };
175
+ }
176
+ //#endregion
177
+ //#region src/commands/dtcg/build-dtcg.ts
178
+ var TOKENS_SCHEMA_URL = "https://design-tokens.org/schemas/2025.10/tokens.json";
179
+ var RESOLVER_SCHEMA_URL = "https://www.designtokens.org/schemas/2025.10/resolver.json";
180
+ function buildVariableMap(root) {
181
+ const map = /* @__PURE__ */ new Map();
182
+ for (const v of root.variables) map.set(v.name, v);
183
+ for (const theme of root.themes) for (const v of theme.variables) if (!map.has(v.name)) map.set(v.name, v);
184
+ return map;
185
+ }
186
+ function processVariable(variable, context) {
187
+ const evaluation = evaluateValue(variable.value, context);
188
+ const classification = classifyValueForVariable(variable.name, evaluation);
189
+ return {
190
+ name: variable.name,
191
+ evaluation,
192
+ classification
193
+ };
194
+ }
195
+ function classifyValueForVariable(name, evaluation) {
196
+ if (evaluation.resolved === null) return void 0;
197
+ return classifyValue(evaluation.resolved, { path: name });
198
+ }
199
+ /**
200
+ * Place a token at `dotPath` in `doc`. Two collision cases need handling:
201
+ *
202
+ * 1. **Token at a path whose group already has children.** If we set
203
+ * `border-width = {...token}` after `border-width.thin = {...}` was
204
+ * written, a naive overwrite drops the children. Instead, we promote
205
+ * the parent token into a `$root` slot inside the existing group.
206
+ * 2. **Children written into a slot that's already a token.** Reverse
207
+ * ordering: if `border-width = {...token}` was written first and we
208
+ * now need to add `border-width.thin = {...}`, we move the existing
209
+ * token into `$root` and continue descending into the new group.
210
+ *
211
+ * Both cases are handled by checking whether the slot looks like a token
212
+ * (`$value` present) or a group, and by upgrading to `$root` whenever a
213
+ * token coexists with siblings at the same path.
214
+ */
215
+ function setNestedToken(doc, dotPath, token) {
216
+ const segments = dotPath.split(".");
217
+ let cursor = doc;
218
+ for (let i = 0; i < segments.length - 1; i++) {
219
+ const segment = segments[i];
220
+ const next = cursor[segment];
221
+ if (typeof next !== "object" || next === null || Array.isArray(next)) cursor[segment] = {};
222
+ else if ("$value" in next) cursor[segment] = { $root: next };
223
+ cursor = cursor[segment];
224
+ }
225
+ const leaf = segments[segments.length - 1];
226
+ const existing = cursor[leaf];
227
+ if (typeof existing === "object" && existing !== null && !Array.isArray(existing) && !("$value" in existing)) existing.$root = token;
228
+ else cursor[leaf] = token;
229
+ }
230
+ function hasRootToken(doc, dotPath) {
231
+ const segments = dotPath.split(".");
232
+ let cursor = doc;
233
+ for (const segment of segments) {
234
+ if (typeof cursor !== "object" || cursor === null || Array.isArray(cursor)) return false;
235
+ cursor = cursor[segment];
236
+ }
237
+ return typeof cursor === "object" && cursor !== null && !Array.isArray(cursor) && "$root" in cursor;
238
+ }
239
+ function setNestedOverride(context, dotPath, value, type) {
240
+ const segments = dotPath.split(".");
241
+ let cursor = context;
242
+ for (let i = 0; i < segments.length - 1; i++) {
243
+ const segment = segments[i];
244
+ const next = cursor[segment];
245
+ if (typeof next !== "object" || next === null || Array.isArray(next) || "$value" in next) cursor[segment] = {};
246
+ cursor = cursor[segment];
247
+ }
248
+ const token = { $value: value };
249
+ if (type !== void 0) token.$type = type;
250
+ cursor[segments[segments.length - 1]] = token;
251
+ }
252
+ function makeAliasToken(target, type, description) {
253
+ const token = { $value: formatAlias(target) };
254
+ if (type !== void 0) token.$type = type;
255
+ if (description) token.$description = description;
256
+ return token;
257
+ }
258
+ function makeValueToken(classification, description, fluidBound) {
259
+ const token = {
260
+ $value: classification.value,
261
+ $type: classification.type
262
+ };
263
+ if (description) token.$description = description;
264
+ if (fluidBound) token.$extensions = { "dev.styleframe": { fluidBound } };
265
+ return token;
266
+ }
267
+ function makeExpressionToken(expression, description) {
268
+ const token = {
269
+ $value: expression,
270
+ $extensions: { "dev.styleframe": { expression } }
271
+ };
272
+ if (description) token.$description = description;
273
+ return token;
274
+ }
275
+ function valuesEqual(a, b) {
276
+ if (a === b) return true;
277
+ if (typeof a !== typeof b) return false;
278
+ if (typeof a === "object") return JSON.stringify(a) === JSON.stringify(b);
279
+ return false;
280
+ }
281
+ function capitalizeContextName(name) {
282
+ if (name.length === 0) return name;
283
+ return name.charAt(0).toUpperCase() + name.slice(1);
284
+ }
285
+ function buildDTCG(root, options = {}) {
286
+ const includeSchema = options.includeSchema ?? true;
287
+ const schemaUrl = options.schemaUrl ?? TOKENS_SCHEMA_URL;
288
+ const modifierName = options.modifierName ?? "theme";
289
+ const collectionName = options.collectionName ?? "Design Tokens";
290
+ const defaultModeName = options.defaultModeName ?? "Default";
291
+ const tokensSourceRef = options.tokensSourceRef ?? "tokens.json";
292
+ const variableMap = buildVariableMap(root);
293
+ const fluidMaxVariable = variableMap.get("fluid.max-width");
294
+ const fluidMaxResolved = fluidMaxVariable ? evaluateValue(fluidMaxVariable.value, { variables: variableMap }).resolved : null;
295
+ const maxViewport = typeof fluidMaxResolved === "number" ? fluidMaxResolved : 1440;
296
+ const context = {
297
+ variables: variableMap,
298
+ maxViewport
299
+ };
300
+ const processed = /* @__PURE__ */ new Map();
301
+ const typeMap = /* @__PURE__ */ new Map();
302
+ for (const variable of root.variables) {
303
+ const p = processVariable(variable, context);
304
+ processed.set(variable.name, p);
305
+ if (p.classification) typeMap.set(variable.name, p.classification.type);
306
+ }
307
+ const resolveTypeFromAliasChain = (name, seen) => {
308
+ if (seen.has(name)) return void 0;
309
+ const direct = typeMap.get(name);
310
+ if (direct) return direct;
311
+ const p = processed.get(name);
312
+ if (p?.evaluation.aliasTarget) return resolveTypeFromAliasChain(p.evaluation.aliasTarget, new Set([...seen, name]));
313
+ };
314
+ const tokens = {};
315
+ if (includeSchema) tokens.$schema = schemaUrl;
316
+ tokens.$extensions = { "dev.styleframe": { collection: collectionName } };
317
+ const diagnostics = [];
318
+ let emittedCount = 0;
319
+ let fluidNormalisedCount = 0;
320
+ for (const variable of root.variables) {
321
+ const p = processed.get(variable.name);
322
+ if (!p) continue;
323
+ const { evaluation, classification } = p;
324
+ if (evaluation.aliasTarget) {
325
+ const targetType = resolveTypeFromAliasChain(evaluation.aliasTarget, /* @__PURE__ */ new Set());
326
+ setNestedToken(tokens, variable.name, makeAliasToken(evaluation.aliasTarget, targetType));
327
+ emittedCount++;
328
+ continue;
329
+ }
330
+ if (classification) {
331
+ const fluidBound = evaluation.normalisationSource === "fluid-max" ? "max" : void 0;
332
+ const promoted = fluidBound && classification.type === "number" && typeof classification.value === "number" ? {
333
+ type: "dimension",
334
+ value: {
335
+ value: classification.value,
336
+ unit: "px"
337
+ }
338
+ } : classification;
339
+ setNestedToken(tokens, variable.name, makeValueToken(promoted, void 0, fluidBound));
340
+ if (fluidBound) fluidNormalisedCount++;
341
+ emittedCount++;
342
+ continue;
343
+ }
344
+ if (evaluation.cssExpression) {
345
+ setNestedToken(tokens, variable.name, makeExpressionToken(evaluation.cssExpression));
346
+ diagnostics.push({
347
+ name: variable.name,
348
+ level: "warn",
349
+ reason: evaluation.reason ?? "Computed expression — preserved as dev.styleframe.expression extension"
350
+ });
351
+ emittedCount++;
352
+ continue;
353
+ }
354
+ if (evaluation.resolved !== null && typeof evaluation.resolved !== "boolean") {
355
+ setNestedToken(tokens, variable.name, {
356
+ $value: String(evaluation.resolved),
357
+ $extensions: { "dev.styleframe": { unknownType: true } }
358
+ });
359
+ diagnostics.push({
360
+ name: variable.name,
361
+ level: "warn",
362
+ reason: "Could not infer DTCG $type — emitted as untyped string"
363
+ });
364
+ emittedCount++;
365
+ continue;
366
+ }
367
+ diagnostics.push({
368
+ name: variable.name,
369
+ level: "warn",
370
+ reason: evaluation.reason ?? "Unrepresentable value — skipped"
371
+ });
372
+ }
373
+ const themedThemes = root.themes.filter((t) => t.variables.length > 0);
374
+ let resolver;
375
+ if (themedThemes.length > 0) {
376
+ const contexts = {};
377
+ for (const theme of themedThemes) {
378
+ const contextDoc = {};
379
+ for (const variable of theme.variables) {
380
+ const themeProcessed = processVariable(variable, context);
381
+ const defaultProcessed = processed.get(variable.name);
382
+ let themeValue;
383
+ let themeType;
384
+ if (themeProcessed.evaluation.aliasTarget) {
385
+ themeValue = formatAlias(themeProcessed.evaluation.aliasTarget);
386
+ themeType = resolveTypeFromAliasChain(themeProcessed.evaluation.aliasTarget, /* @__PURE__ */ new Set());
387
+ } else if (themeProcessed.classification) {
388
+ themeValue = themeProcessed.classification.value;
389
+ themeType = themeProcessed.classification.type;
390
+ }
391
+ if (themeValue === void 0) continue;
392
+ let defaultValue;
393
+ if (defaultProcessed?.evaluation.aliasTarget) defaultValue = formatAlias(defaultProcessed.evaluation.aliasTarget);
394
+ else if (defaultProcessed?.classification) defaultValue = defaultProcessed.classification.value;
395
+ if (defaultValue !== void 0 && valuesEqual(themeValue, defaultValue)) continue;
396
+ setNestedOverride(contextDoc, hasRootToken(tokens, variable.name) ? `${variable.name}.$root` : variable.name, themeValue, themeType);
397
+ }
398
+ contexts[capitalizeContextName(theme.name)] = contextDoc;
399
+ }
400
+ for (const key of Object.keys(contexts)) if (Object.keys(contexts[key]).length === 0) delete contexts[key];
401
+ const themeContextNames = Object.keys(contexts);
402
+ if (themeContextNames.length > 0) {
403
+ const allContexts = { [defaultModeName]: [] };
404
+ for (const name of themeContextNames) allContexts[name] = [contexts[name]];
405
+ resolver = {
406
+ $schema: RESOLVER_SCHEMA_URL,
407
+ version: "2025.10",
408
+ modifiers: { [modifierName]: {
409
+ contexts: allContexts,
410
+ default: defaultModeName
411
+ } },
412
+ resolutionOrder: [{
413
+ type: "set",
414
+ sources: [{ $ref: tokensSourceRef }]
415
+ }, { $ref: `#/modifiers/${modifierName}` }]
416
+ };
417
+ }
418
+ }
419
+ return {
420
+ tokens,
421
+ resolver,
422
+ diagnostics,
423
+ emittedCount,
424
+ fluidNormalisedCount,
425
+ maxViewport
426
+ };
427
+ }
428
+ //#endregion
429
+ export { buildDTCG as t };