@lostgradient/cinder 0.27.1 → 0.28.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 (261) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/components.json +1 -1
  3. package/dist/_internal/code-highlighter-context.d.ts +28 -0
  4. package/dist/cli/index.js +12 -8
  5. package/dist/components/approval-card/index.js +4 -4
  6. package/dist/components/button/button.css +25 -0
  7. package/dist/components/calendar/calendar.css +14 -0
  8. package/dist/components/capability-gate/capability-gate.css +5 -0
  9. package/dist/components/checkbox/checkbox.css +19 -0
  10. package/dist/components/chip/chip.css +14 -0
  11. package/dist/components/code-block/code-block.d.svelte.ts +1 -1
  12. package/dist/components/code-block/code-block.examples.json +1 -1
  13. package/dist/components/code-block/code-block.schema.js +3 -3
  14. package/dist/components/code-block/code-block.svelte.d.ts +1 -1
  15. package/dist/components/code-block/code-block.types.d.ts +14 -12
  16. package/dist/components/code-block/index.js +2 -2
  17. package/dist/components/color-picker/color-picker.css +2 -0
  18. package/dist/components/combobox/combobox.css +9 -1
  19. package/dist/components/command-palette/command-palette.css +7 -5
  20. package/dist/components/file-upload/file-upload.css +2 -1
  21. package/dist/components/guidance-region/index.css +1 -1
  22. package/dist/components/image/image.examples.json +1 -1
  23. package/dist/components/input/input.css +20 -6
  24. package/dist/components/json-schema-editor/index.js +5 -5
  25. package/dist/components/json-schema-editor/json-view-highlighter.d.ts +14 -0
  26. package/dist/components/key-value-editor/index.css +1 -1
  27. package/dist/components/modal-region/index.css +1 -1
  28. package/dist/components/multi-select/multi-select.css +9 -0
  29. package/dist/components/pagination/pagination.css +12 -0
  30. package/dist/components/pin-input/pin-input.css +9 -1
  31. package/dist/components/radio-group/radio-group.css +16 -0
  32. package/dist/components/run-step-timeline/index.js +2 -2
  33. package/dist/components/schema-form/index.js +2 -2
  34. package/dist/components/schema-form/schema-form.css +9 -0
  35. package/dist/components/segmented-control/segmented-control.css +3 -3
  36. package/dist/components/selection-popover/selection-popover.css +7 -1
  37. package/dist/components/tag-input/tag-input.css +10 -1
  38. package/dist/components/terminal-frame/index.js +2 -2
  39. package/dist/components/terminal-frame/terminal-frame.schema.js +2 -2
  40. package/dist/components/terminal-frame/terminal-frame.types.d.ts +8 -0
  41. package/dist/components/textarea/textarea.css +1 -1
  42. package/dist/components/toggle/toggle.css +16 -0
  43. package/dist/components/tree/tree.examples.json +1 -1
  44. package/dist/components/virtual-list/index.js +2 -2
  45. package/dist/components/virtual-list/virtual-list.css +42 -9
  46. package/dist/highlighters/shiki/default.d.ts +13 -1
  47. package/dist/highlighters/shiki/default.js +2 -2
  48. package/dist/highlighters/shiki/index.d.ts +20 -12
  49. package/dist/highlighters/shiki/index.js +2 -2
  50. package/dist/index.browser.css +1 -1
  51. package/dist/index.d.ts +2 -0
  52. package/dist/index.js +23 -23
  53. package/dist/scripts/knowledge/index.d.ts +5 -1
  54. package/dist/server/components/approval-card/index.js +1 -1
  55. package/dist/server/components/code-block/index.js +1 -1
  56. package/dist/server/components/color-field/index.js +2 -2
  57. package/dist/server/components/color-picker/index.js +2 -2
  58. package/dist/server/components/json-schema-editor/index.js +2 -2
  59. package/dist/server/components/run-step-timeline/index.js +1 -1
  60. package/dist/server/components/terminal-frame/index.js +1 -1
  61. package/dist/server/components/virtual-list/index.js +1 -1
  62. package/dist/server/github-dark-e7nywpbe.js +3 -0
  63. package/dist/server/github-light-bqtmm1zq.js +3 -0
  64. package/dist/server/highlighters/shiki/default.js +2 -2
  65. package/dist/server/highlighters/shiki/index.js +2 -2
  66. package/dist/server/index.js +6 -6
  67. package/dist/server/{index.server-4qyyw4y5.js → index.server-043cfznf.js} +1 -1
  68. package/dist/server/{index.server-p46tn4eb.js → index.server-09tjs48p.js} +2 -2
  69. package/dist/server/index.server-0hyvdf74.js +8 -0
  70. package/dist/server/{index.server-dxgkh9tk.js → index.server-17thvpd3.js} +1 -1
  71. package/dist/server/index.server-19z6hqd6.js +4 -0
  72. package/dist/server/index.server-31020qgk.js +3 -0
  73. package/dist/server/{index.server-w3nqzde5.js → index.server-45wmvjrn.js} +3 -3
  74. package/dist/server/{index.server-3tkgm2gn.js → index.server-6mb7w5g4.js} +2 -2
  75. package/dist/server/{index.server-2vxmn7x1.js → index.server-c5yajkkc.js} +4 -4
  76. package/dist/server/index.server-e6fknxd9.js +4 -0
  77. package/dist/server/index.server-fev4kwm0.js +4 -0
  78. package/dist/server/index.server-k4vjk75r.js +4 -0
  79. package/dist/server/index.server-mjbtd1gs.js +7 -0
  80. package/dist/server/{index.server-2bfkhzzq.js → index.server-rkp4py5n.js} +2 -2
  81. package/dist/server/index.server-wdz9tsq4.js +3 -0
  82. package/dist/server/index.server-zj9909hd.js +4 -0
  83. package/dist/server/json-68twtta3.js +3 -0
  84. package/dist/server/tokens/registry.generated.js +1 -1
  85. package/dist/server/tokens/runtime/index.js +92 -0
  86. package/dist/styles/check-token-contrast-test-values.d.ts +1 -3
  87. package/dist/styles/token-contrast-test-readers.d.ts +1 -1
  88. package/dist/tokens/registry.generated.js +2 -2
  89. package/dist/tokens/resolved/dark-reduced-motion.json +104 -43
  90. package/dist/tokens/resolved/dark.json +104 -43
  91. package/dist/tokens/resolved/light-reduced-motion.json +104 -43
  92. package/dist/tokens/resolved/light.json +104 -43
  93. package/dist/tokens/runtime/authoring-catalogue.d.ts +19 -0
  94. package/dist/tokens/runtime/authoring-catalogue.generated.d.ts +8 -0
  95. package/dist/tokens/runtime/authoring-palette.d.ts +25 -0
  96. package/dist/tokens/runtime/authoring-profiles.d.ts +48 -0
  97. package/dist/tokens/runtime/authoring-provenance.d.ts +31 -0
  98. package/dist/tokens/runtime/authoring-types.d.ts +182 -0
  99. package/dist/tokens/runtime/base-corpus.d.ts +29 -0
  100. package/dist/tokens/runtime/base-corpus.generated.d.ts +8 -0
  101. package/dist/tokens/runtime/context-order.d.ts +60 -0
  102. package/dist/tokens/runtime/context-stack.d.ts +11 -0
  103. package/dist/tokens/runtime/contrast/color-difference.d.ts +16 -0
  104. package/dist/{styles/color-contrast-utilities.d.ts → tokens/runtime/contrast/color-math.d.ts} +2 -17
  105. package/dist/tokens/runtime/contrast/color-mix.d.ts +3 -0
  106. package/dist/tokens/runtime/contrast/css-color.d.ts +29 -0
  107. package/dist/tokens/runtime/contrast/index.d.ts +7 -0
  108. package/dist/tokens/runtime/contrast/measure.d.ts +45 -0
  109. package/dist/tokens/runtime/contrast/pairings.d.ts +36 -0
  110. package/dist/tokens/runtime/contrast/thresholds.d.ts +47 -0
  111. package/dist/tokens/runtime/corpus-documents.d.ts +36 -0
  112. package/dist/tokens/runtime/corpus-validation.d.ts +10 -0
  113. package/dist/tokens/runtime/corpus.d.ts +35 -0
  114. package/dist/tokens/runtime/css-configuration.d.ts +1 -0
  115. package/dist/tokens/runtime/css-stylelint.d.ts +2 -0
  116. package/dist/tokens/runtime/css-support.d.ts +110 -0
  117. package/dist/tokens/runtime/evaluate.d.ts +95 -0
  118. package/dist/tokens/runtime/evaluated-provenance.d.ts +36 -0
  119. package/dist/tokens/runtime/index.d.ts +38 -0
  120. package/dist/tokens/runtime/index.js +95 -0
  121. package/dist/tokens/runtime/package-version.generated.d.ts +9 -0
  122. package/dist/tokens/runtime/projection.d.ts +32 -0
  123. package/dist/tokens/runtime/registry.d.ts +125 -0
  124. package/dist/tokens/runtime/resolve-extends.d.ts +30 -0
  125. package/dist/tokens/runtime/resolve-references.d.ts +49 -0
  126. package/dist/tokens/runtime/resolve-shared.d.ts +34 -0
  127. package/dist/tokens/runtime/resolve.d.ts +44 -0
  128. package/dist/tokens/runtime/resolver-order.d.ts +89 -0
  129. package/dist/tokens/runtime/source-digest.d.ts +20 -0
  130. package/dist/tokens/runtime/stylesheet-skeleton.d.ts +31 -0
  131. package/dist/tokens/runtime/theme-runtime.test-support.d.ts +24 -0
  132. package/dist/tokens/runtime/theme-sources.d.ts +46 -0
  133. package/dist/tokens/runtime/theme-stylesheet.d.ts +31 -0
  134. package/dist/tokens/runtime/types.d.ts +115 -0
  135. package/dist/tokens/runtime/validate-resolver.d.ts +31 -0
  136. package/dist/tokens/runtime/validate-schema.d.ts +22 -0
  137. package/dist/tokens/runtime/validate-tokens.d.ts +25 -0
  138. package/dist/tokens/runtime/validate-values.d.ts +33 -0
  139. package/dist/tokens/runtime/validate.d.ts +3 -0
  140. package/dist/tokens/runtime/value-color-parse.d.ts +128 -0
  141. package/dist/tokens/runtime/value-color.d.ts +85 -0
  142. package/dist/tokens/runtime/value-entry.d.ts +3 -0
  143. package/dist/tokens/runtime/value-formatters.d.ts +59 -0
  144. package/dist/tokens/sets/colors.tokens.json +65 -13
  145. package/dist/tokens/sets/foundation.tokens.json +23 -0
  146. package/dist/tokens/sets/semantic.tokens.json +136 -30
  147. package/dist/utilities/highlighter.d.ts +5 -5
  148. package/dist/utilities/retrying-loader-cache.d.ts +3 -6
  149. package/package.json +15 -3
  150. package/src/_internal/code-highlighter-context.ts +41 -0
  151. package/src/components/button/button.css +25 -0
  152. package/src/components/calendar/calendar.css +14 -0
  153. package/src/components/capability-gate/capability-gate.css +5 -0
  154. package/src/components/checkbox/checkbox.css +19 -0
  155. package/src/components/chip/chip.css +14 -0
  156. package/src/components/code-block/code-block.examples.json +1 -1
  157. package/src/components/code-block/code-block.schema.json +2 -2
  158. package/src/components/code-block/code-block.schema.ts +2 -2
  159. package/src/components/code-block/code-block.svelte +15 -19
  160. package/src/components/code-block/code-block.types.ts +14 -12
  161. package/src/components/color-picker/color-picker.css +2 -0
  162. package/src/components/combobox/combobox.css +9 -1
  163. package/src/components/command-palette/command-palette.css +7 -5
  164. package/src/components/file-upload/file-upload.css +2 -1
  165. package/src/components/image/image.examples.json +1 -1
  166. package/src/components/input/input.css +20 -6
  167. package/src/components/json-schema-editor/json-view-highlighter.ts +23 -0
  168. package/src/components/json-schema-editor/json-view.svelte +2 -0
  169. package/src/components/multi-select/multi-select.css +9 -0
  170. package/src/components/pagination/pagination.css +12 -0
  171. package/src/components/pin-input/pin-input.css +9 -1
  172. package/src/components/radio-group/radio-group.css +16 -0
  173. package/src/components/schema-form/schema-form.css +9 -0
  174. package/src/components/segmented-control/segmented-control.css +3 -3
  175. package/src/components/selection-popover/selection-popover.css +7 -1
  176. package/src/components/tag-input/tag-input.css +10 -1
  177. package/src/components/terminal-frame/terminal-frame.schema.json +5 -0
  178. package/src/components/terminal-frame/terminal-frame.schema.ts +6 -0
  179. package/src/components/terminal-frame/terminal-frame.svelte +6 -2
  180. package/src/components/terminal-frame/terminal-frame.types.ts +8 -0
  181. package/src/components/textarea/textarea.css +1 -1
  182. package/src/components/toggle/toggle.css +16 -0
  183. package/src/components/tree/tree.examples.json +1 -1
  184. package/src/components/virtual-list/virtual-list.css +42 -9
  185. package/src/components/virtual-list/virtual-list.svelte +54 -20
  186. package/src/highlighters/shiki/default.ts +13 -1
  187. package/src/highlighters/shiki/index.ts +20 -12
  188. package/src/index.ts +5 -0
  189. package/src/styles/foundation.css +33 -1
  190. package/src/styles/tokens-base.css +4 -4
  191. package/src/tokens/registry.generated.json +3 -3
  192. package/src/tokens/resolved/dark-reduced-motion.json +104 -43
  193. package/src/tokens/resolved/dark.json +104 -43
  194. package/src/tokens/resolved/light-reduced-motion.json +104 -43
  195. package/src/tokens/resolved/light.json +104 -43
  196. package/src/tokens/runtime/authoring-catalogue.generated.ts +19300 -0
  197. package/src/tokens/runtime/authoring-catalogue.ts +256 -0
  198. package/src/tokens/runtime/authoring-palette.ts +100 -0
  199. package/src/tokens/runtime/authoring-profiles.ts +288 -0
  200. package/src/tokens/runtime/authoring-provenance.ts +290 -0
  201. package/src/tokens/runtime/authoring-types.ts +199 -0
  202. package/src/tokens/runtime/base-corpus.generated.ts +10 -0
  203. package/src/tokens/runtime/base-corpus.ts +78 -0
  204. package/src/tokens/runtime/context-order.ts +182 -0
  205. package/src/tokens/runtime/context-stack.ts +52 -0
  206. package/src/tokens/runtime/contrast/color-difference.ts +114 -0
  207. package/src/tokens/runtime/contrast/color-math.ts +89 -0
  208. package/src/tokens/runtime/contrast/color-mix.ts +20 -0
  209. package/src/tokens/runtime/contrast/css-color.ts +312 -0
  210. package/src/tokens/runtime/contrast/index.ts +7 -0
  211. package/src/tokens/runtime/contrast/measure.ts +185 -0
  212. package/src/tokens/runtime/contrast/pairings.ts +324 -0
  213. package/src/tokens/runtime/contrast/thresholds.ts +81 -0
  214. package/src/tokens/runtime/corpus-documents.ts +289 -0
  215. package/src/tokens/runtime/corpus-validation.ts +336 -0
  216. package/src/tokens/runtime/corpus.ts +179 -0
  217. package/src/tokens/runtime/css-configuration.ts +1 -0
  218. package/src/tokens/runtime/css-stylelint.ts +15 -0
  219. package/src/tokens/runtime/css-support.ts +407 -0
  220. package/src/tokens/runtime/evaluate.ts +262 -0
  221. package/src/tokens/runtime/evaluated-provenance.ts +116 -0
  222. package/src/tokens/runtime/format-validator.generated.d.ts +18 -0
  223. package/src/tokens/runtime/format-validator.generated.js +13029 -0
  224. package/src/tokens/runtime/index.ts +78 -0
  225. package/src/tokens/runtime/package-version.generated.ts +9 -0
  226. package/src/tokens/runtime/projection.ts +65 -0
  227. package/src/tokens/runtime/registry.ts +365 -0
  228. package/src/tokens/runtime/resolve-extends.ts +211 -0
  229. package/src/tokens/runtime/resolve-references.ts +313 -0
  230. package/src/tokens/runtime/resolve-shared.ts +186 -0
  231. package/src/tokens/runtime/resolve.ts +246 -0
  232. package/src/tokens/runtime/resolver-order.ts +326 -0
  233. package/src/tokens/runtime/resolver-validator.generated.d.ts +18 -0
  234. package/src/tokens/runtime/resolver-validator.generated.js +15492 -0
  235. package/src/tokens/runtime/source-digest.ts +49 -0
  236. package/src/tokens/runtime/stylesheet-skeleton.ts +123 -0
  237. package/src/tokens/runtime/theme-sources.ts +121 -0
  238. package/src/tokens/runtime/theme-stylesheet.ts +177 -0
  239. package/src/tokens/runtime/types.ts +140 -0
  240. package/src/tokens/runtime/validate-resolver.ts +338 -0
  241. package/src/tokens/runtime/validate-schema.ts +269 -0
  242. package/src/tokens/runtime/validate-tokens.ts +181 -0
  243. package/src/tokens/runtime/validate-values.ts +396 -0
  244. package/src/tokens/runtime/validate.ts +57 -0
  245. package/src/tokens/runtime/value-color-parse.ts +309 -0
  246. package/src/tokens/runtime/value-color.ts +217 -0
  247. package/src/tokens/runtime/value-entry.ts +52 -0
  248. package/src/tokens/runtime/value-formatters.ts +414 -0
  249. package/src/tokens/sets/colors.tokens.json +65 -13
  250. package/src/tokens/sets/foundation.tokens.json +23 -0
  251. package/src/tokens/sets/semantic.tokens.json +136 -30
  252. package/src/utilities/highlighter.ts +5 -5
  253. package/src/utilities/retrying-loader-cache.ts +3 -6
  254. package/dist/components/code-block/code-block-default-highlighter.d.ts +0 -40
  255. package/dist/server/index.server-298z43yn.js +0 -4
  256. package/dist/server/index.server-3h11wjyh.js +0 -8
  257. package/dist/server/index.server-a3aerbfr.js +0 -4
  258. package/dist/server/index.server-kge3zp6n.js +0 -4
  259. package/dist/server/index.server-syf81nwz.js +0 -6
  260. package/dist/server/index.server-zs08f5te.js +0 -3
  261. package/src/components/code-block/code-block-default-highlighter.ts +0 -63
@@ -0,0 +1,338 @@
1
+ import type { ValidationIssue } from './types.ts';
2
+ import { TokenValidationError } from './types.ts';
3
+ import { type ResolverDocumentShape, addIssue, isObject, isString } from './validate-values.ts';
4
+
5
+ export function isResolverReference(value: unknown): value is { $ref: string } {
6
+ return isObject(value) && typeof value['$ref'] === 'string';
7
+ }
8
+
9
+ export function unknownReservedPropertyReason(key: string): string {
10
+ return `unknown reserved property ${key}`;
11
+ }
12
+
13
+ /**
14
+ * Parses a resolutionOrder entry's `$ref` (e.g. "#/sets/foundation" or
15
+ * "#/modifiers/theme") into its target kind and name. JSON Pointer
16
+ * tilde-escapes are decoded per RFC 6901; returns undefined for anything
17
+ * that isn't a well-formed pointer into `sets` or `modifiers`.
18
+ */
19
+ export function isResolverTargetKind(value: string): value is 'sets' | 'modifiers' {
20
+ return value === 'sets' || value === 'modifiers';
21
+ }
22
+
23
+ export function resolutionOrderTarget(
24
+ ref: string,
25
+ ): { kind: 'sets' | 'modifiers'; name: string } | undefined {
26
+ // RFC 6901 §6 order: percent-decode the whole fragment, then split
27
+ // structurally on `/`, then tilde-decode the segment. Decoding before
28
+ // splitting is what makes `#/sets/foo%2Fbar` decode to the three-segment
29
+ // pointer `/sets/foo/bar` and be rejected -- a set named `foo/bar` is only
30
+ // addressable as `#/sets/foo~1bar` -- while `#/sets/high%20contrast`
31
+ // correctly names `high contrast`.
32
+ let decoded: string;
33
+ try {
34
+ decoded = decodeURIComponent(ref);
35
+ } catch {
36
+ return undefined;
37
+ }
38
+ // `[^/]+` rather than `.+`: an unescaped `/` makes this a deeper pointer
39
+ // than `#/<kind>/<name>`, not a name containing a slash.
40
+ const match = /^#\/(sets|modifiers)\/([^/]+)$/.exec(decoded);
41
+ if (!match) return undefined;
42
+ const [, kind, rawName] = match;
43
+ if (
44
+ kind === undefined ||
45
+ rawName === undefined ||
46
+ !isResolverTargetKind(kind) ||
47
+ /~(?:[^01]|$)/.test(rawName)
48
+ )
49
+ return undefined;
50
+ const name = rawName.replaceAll('~1', '/').replaceAll('~0', '~');
51
+ return { kind, name };
52
+ }
53
+
54
+ /**
55
+ * Semantic checks the official DTCG 2025.10 resolver JSON Schema cannot
56
+ * express: `default` matching a live context key, resolutionOrder entries
57
+ * resolving to a set or modifier that actually exists (schema can only
58
+ * constrain the `$ref` string's shape, not cross-reference sibling `sets`/
59
+ * `modifiers` object keys), non-empty source/context arrays, and
60
+ * resolutionOrder covering every set and modifier exactly once -- EXCEPT a
61
+ * set that is reached only through a resolver-internal `#/sets/<name>`
62
+ * reference from another set's `sources` or a modifier context (CIN-464):
63
+ * that set contributes its documents at the position of whatever references
64
+ * it, so requiring it in resolutionOrder too would be redundant. Such a set
65
+ * MAY still appear in resolutionOrder as well -- nothing here forbids it --
66
+ * it is simply no longer REQUIRED to.
67
+ */
68
+ export function validateResolverDocument(document: ResolverDocumentShape): void {
69
+ const issues: ValidationIssue[] = [];
70
+ if (document.version !== '2025.10')
71
+ addIssue(issues, '$.version', 'resolver version must be 2025.10');
72
+
73
+ // CIN-464: a set or modifier context source may itself be a
74
+ // resolver-internal `#/sets/<name>` reference rather than a token-document
75
+ // path (see `validate-corpus.ts`'s `expandSetSources`/`expandContextSources`,
76
+ // which resolve these into the referenced set's own documents). A set
77
+ // pulled in only through another SET, or only through a MODIFIER CONTEXT
78
+ // -- never named directly in `resolutionOrder` -- still contributes its
79
+ // documents, at the position of whatever references it, so it must NOT
80
+ // also be required in `resolutionOrder` itself below. This function only
81
+ // has the resolver's STRUCTURE to work with, never the actual token
82
+ // documents, so it cannot check whether a modifier-context-only set's
83
+ // individual token paths already have a base declaration from some other
84
+ // set -- see the "context-only override set" note further below for why
85
+ // that check does not belong here.
86
+ // Keyed by CHILD set name -> the set of PARENT set names that reference it
87
+ // internally. More than one parent referencing the same child means that
88
+ // child gets expanded more than once into the resolved document tree --
89
+ // reject that below (see the "Reject a child set expanded by multiple
90
+ // ordered parents" check) rather than let it surface as the same
91
+ // CSS-vs-resolved-JSON disagreement the single-parent-plus-explicit-listing
92
+ // case already guards against.
93
+ const parentsReferencingSet = new Map<string, Set<string>>();
94
+ // Direct set-to-set reference edges (parent -> the child set names its own
95
+ // sources reference), used below to compute each ORDERED set's full
96
+ // transitive descendant closure -- the direct-parents-only version of that
97
+ // check missed a child reachable through a CHAIN of internal references
98
+ // (e.g. resolutionOrder "A, theme, Wrapper" where A -> Base and
99
+ // Wrapper -> B -> Base: Base's only DIRECT parents are A and B, and only A
100
+ // is itself ordered, so a direct-parent check sees no conflict even though
101
+ // Base is genuinely expanded at both ordered positions).
102
+ const setDirectChildren = new Map<string, Set<string>>();
103
+ const setReferencedByAnotherSet = new Set<string>();
104
+ const setReferencedByModifierContext = new Set<string>();
105
+ function noteSetReferencedByAnotherSet(parentName: string, sources: unknown): void {
106
+ if (!Array.isArray(sources)) return;
107
+ for (const source of sources) {
108
+ if (!isResolverReference(source)) continue;
109
+ const target = resolutionOrderTarget(source['$ref']);
110
+ if (target?.kind !== 'sets') continue;
111
+ setReferencedByAnotherSet.add(target.name);
112
+ const parents = parentsReferencingSet.get(target.name) ?? new Set();
113
+ parents.add(parentName);
114
+ parentsReferencingSet.set(target.name, parents);
115
+ const children = setDirectChildren.get(parentName) ?? new Set();
116
+ children.add(target.name);
117
+ setDirectChildren.set(parentName, children);
118
+ }
119
+ }
120
+ function noteSetReferencedByModifierContext(sources: unknown): void {
121
+ if (!Array.isArray(sources)) return;
122
+ for (const source of sources) {
123
+ if (!isResolverReference(source)) continue;
124
+ const target = resolutionOrderTarget(source['$ref']);
125
+ if (target?.kind === 'sets') setReferencedByModifierContext.add(target.name);
126
+ }
127
+ }
128
+
129
+ const modifierNames = new Set(Object.keys(document.modifiers));
130
+ for (const [name, modifier] of Object.entries(document.modifiers)) {
131
+ if (!isObject(modifier) || !isObject(modifier['contexts'])) {
132
+ addIssue(issues, `$.modifiers.${name}`, 'modifier must have a contexts object');
133
+ continue;
134
+ }
135
+ const contexts = modifier['contexts'];
136
+ for (const [contextName, sources] of Object.entries(contexts)) {
137
+ if (!Array.isArray(sources) || sources.length === 0 || !sources.every(isResolverReference))
138
+ addIssue(
139
+ issues,
140
+ `$.modifiers.${name}.contexts.${contextName}`,
141
+ 'context must be a non-empty array of $ref sources',
142
+ );
143
+ else noteSetReferencedByModifierContext(sources);
144
+ }
145
+ if (
146
+ modifier['default'] !== undefined &&
147
+ (!isString(modifier['default']) || !Object.keys(contexts).includes(modifier['default']))
148
+ )
149
+ addIssue(issues, `$.modifiers.${name}`, 'modifier default must be one of its context names');
150
+ }
151
+
152
+ const setNames = new Set(Object.keys(document.sets));
153
+ if (setNames.size === 0) addIssue(issues, '$.sets', 'resolver must include at least one set');
154
+ for (const [name, set] of Object.entries(document.sets)) {
155
+ if (
156
+ !isObject(set) ||
157
+ !Array.isArray(set['sources']) ||
158
+ set['sources'].length === 0 ||
159
+ !set['sources'].every(isResolverReference)
160
+ )
161
+ addIssue(issues, `$.sets.${name}`, 'set must have a non-empty array of $ref sources');
162
+ else noteSetReferencedByAnotherSet(name, set['sources']);
163
+ }
164
+ const internallyReferencedSetNames = new Set([
165
+ ...setReferencedByAnotherSet,
166
+ ...setReferencedByModifierContext,
167
+ ]);
168
+
169
+ const resolutionOrderTargets = new Set<string>();
170
+ const explicitSetOrderPath = new Map<string, string>();
171
+ for (const [index, entry] of document.resolutionOrder.entries()) {
172
+ if (!isResolverReference(entry)) {
173
+ addIssue(issues, `$.resolutionOrder.${index}`, 'resolutionOrder entry must be a $ref object');
174
+ continue;
175
+ }
176
+ const target = resolutionOrderTarget(entry['$ref']);
177
+ if (!target || !(target.kind === 'sets' ? setNames : modifierNames).has(target.name)) {
178
+ addIssue(
179
+ issues,
180
+ `$.resolutionOrder.${index}`,
181
+ `resolutionOrder must reference an existing set or modifier: ${entry['$ref']}`,
182
+ );
183
+ continue;
184
+ }
185
+ const key = `${target.kind}/${target.name}`;
186
+ if (resolutionOrderTargets.has(key))
187
+ addIssue(issues, `$.resolutionOrder.${index}`, 'resolutionOrder entries must be unique');
188
+ resolutionOrderTargets.add(key);
189
+ if (target.kind === 'sets') explicitSetOrderPath.set(target.name, `$.resolutionOrder.${index}`);
190
+ }
191
+ const expectedTargets = new Set([
192
+ ...[...setNames]
193
+ .filter((name) => !internallyReferencedSetNames.has(name))
194
+ .map((name) => `sets/${name}`),
195
+ ...[...modifierNames].map((name) => `modifiers/${name}`),
196
+ ]);
197
+ const unlistedTargets = [...expectedTargets].filter(
198
+ (target) => !resolutionOrderTargets.has(target),
199
+ );
200
+ if (unlistedTargets.length > 0)
201
+ addIssue(issues, '$.resolutionOrder', 'must list every set and modifier exactly once');
202
+
203
+ // A set referenced by another SET is exempt from resolutionOrder because it
204
+ // still contributes through that set's own expansion -- but nothing stops
205
+ // it from ALSO being listed explicitly. That double inclusion is never
206
+ // correct: `buildResolvedContexts` walks the full resolutionOrder, so if a
207
+ // modifier sits between the referencing set and the explicit entry (e.g.
208
+ // "A, theme, B" where A internally references B), expanding A re-applies
209
+ // B's values AFTER the modifier, silently resetting whatever the modifier
210
+ // just overrode -- while `buildTokensBaseCss` collects every set into
211
+ // `:root` once and emits theme documents separately, so the generated CSS
212
+ // and the resolved JSON snapshots disagree about which value wins. Reject
213
+ // the combination outright rather than let it surface as that disagreement
214
+ // later.
215
+ for (const setName of setReferencedByAnotherSet) {
216
+ const explicitPath = explicitSetOrderPath.get(setName);
217
+ if (explicitPath !== undefined) {
218
+ addIssue(
219
+ issues,
220
+ explicitPath,
221
+ `set "${setName}" is already referenced internally by another ordered set and must not ` +
222
+ 'also appear in resolutionOrder -- it would be included twice',
223
+ );
224
+ }
225
+ }
226
+
227
+ // The single-parent-plus-explicit-listing case above doesn't cover a child
228
+ // set reachable from TWO DIFFERENT ordered positions through a chain of
229
+ // internal references -- e.g. resolutionOrder "A, theme, Wrapper" where
230
+ // A -> Base directly, and Wrapper -> B -> Base (Base's only DIRECT parents
231
+ // are A and B; only A is itself ordered, so a direct-parents-only check
232
+ // sees no conflict even though Base is genuinely expanded again through
233
+ // Wrapper's own recursive expansion). Compute each ordered set's full
234
+ // TRANSITIVE descendant closure and reject any set reachable from more
235
+ // than one ordered position -- this subsumes the direct-parent case above,
236
+ // since a direct parent is a one-hop descendant.
237
+ function transitiveDescendants(setName: string): Set<string> {
238
+ const seen = new Set<string>();
239
+ const stack = [setName];
240
+ while (stack.length > 0) {
241
+ const current = stack.pop()!;
242
+ for (const child of setDirectChildren.get(current) ?? []) {
243
+ if (seen.has(child)) continue; // also guards against a reference cycle
244
+ seen.add(child);
245
+ stack.push(child);
246
+ }
247
+ }
248
+ return seen;
249
+ }
250
+ const reachingOrderedSets = new Map<string, Set<string>>();
251
+ for (const target of resolutionOrderTargets) {
252
+ if (!target.startsWith('sets/')) continue;
253
+ const orderedSetName = target.slice('sets/'.length);
254
+ for (const descendant of transitiveDescendants(orderedSetName)) {
255
+ const reachers = reachingOrderedSets.get(descendant) ?? new Set();
256
+ reachers.add(orderedSetName);
257
+ reachingOrderedSets.set(descendant, reachers);
258
+ }
259
+ }
260
+ for (const [setName, orderedAncestors] of reachingOrderedSets) {
261
+ if (orderedAncestors.size > 1) {
262
+ addIssue(
263
+ issues,
264
+ '$.resolutionOrder',
265
+ `set "${setName}" is reachable from more than one ordered set ` +
266
+ `(${[...orderedAncestors].toSorted().join(', ')}) and would be expanded more than once`,
267
+ );
268
+ }
269
+ }
270
+
271
+ // Reachability for the closed-cycle check below is broader than
272
+ // `reachingOrderedSets` above: a set reachable ONLY through a chain
273
+ // rooted at a modifier context (e.g. theme.light -> lightOverrides ->
274
+ // sharedOverrides, where neither lightOverrides nor sharedOverrides is
275
+ // itself ordered) is legitimately consumed by generation, per the
276
+ // context-only-override exemption -- `reachingOrderedSets` is seeded only
277
+ // from directly ordered sets and would wrongly flag `sharedOverrides` as
278
+ // an unreachable closed cycle. Every modifier-context-referenced set is
279
+ // therefore also a valid entry point here, not just ordered sets. This
280
+ // does NOT feed the multi-ordered-position check above, which is
281
+ // specifically about two DISTINCT ordered resolutionOrder positions
282
+ // double-expanding the same set within one resolved combination --
283
+ // mutually exclusive modifier contexts don't have that problem.
284
+ const reachableFromAnyEntryPoint = new Set(reachingOrderedSets.keys());
285
+ for (const target of resolutionOrderTargets) {
286
+ if (target.startsWith('sets/')) reachableFromAnyEntryPoint.add(target.slice('sets/'.length));
287
+ }
288
+ for (const rootSetName of setReferencedByModifierContext) {
289
+ reachableFromAnyEntryPoint.add(rootSetName);
290
+ for (const descendant of transitiveDescendants(rootSetName))
291
+ reachableFromAnyEntryPoint.add(descendant);
292
+ }
293
+
294
+ // The `expectedTargets`/`unlistedTargets` check above exempts any set
295
+ // referenced by another set from needing its own resolutionOrder entry --
296
+ // but that exemption is unsound for a CLOSED CYCLE of sets that reference
297
+ // only each other (e.g. "a" -> "b" -> "a"): each member is "referenced by
298
+ // another set", so both are exempted, and neither is ever required to be
299
+ // ordered. The cycle is then unreachable from every actual entry point,
300
+ // and `buildTokensBaseCss`/`buildBaseDocuments` silently omit its
301
+ // documents entirely. `reachableFromAnyEntryPoint` (computed above)
302
+ // already captures every set genuinely reachable from an ordered
303
+ // position OR a modifier context -- anything internally referenced but
304
+ // absent from it is unreachable, cycle or not.
305
+ for (const setName of setReferencedByAnotherSet) {
306
+ const directlyOrdered = resolutionOrderTargets.has(`sets/${setName}`);
307
+ if (!directlyOrdered && !reachableFromAnyEntryPoint.has(setName)) {
308
+ addIssue(
309
+ issues,
310
+ '$.resolutionOrder',
311
+ `set "${setName}" is referenced internally but not reachable from any ordered set ` +
312
+ '(possibly part of a closed cycle of sets that only reference each other) -- ' +
313
+ 'its documents would never be included',
314
+ );
315
+ }
316
+ }
317
+
318
+ // NOTE: an earlier version of this file rejected a modifier context's
319
+ // internal set reference whenever the referenced SET (not its individual
320
+ // token paths) had no independent path into resolutionOrder's base. That
321
+ // check operated at the wrong granularity: this function only has the
322
+ // resolver's STRUCTURE to work with, never the actual token documents, so
323
+ // it can only reason about set names, not the token paths a set actually
324
+ // contributes. A context-only override set (e.g. "lightOverrides",
325
+ // referenced solely by theme's "light" context) is a legitimate,
326
+ // already-generator-supported pattern -- see generate.test.ts's "a theme
327
+ // context referencing a set via #/sets/<name> does not throw" -- whenever
328
+ // its OVERRIDE tokens share paths with a base declaration contributed by
329
+ // some OTHER set. The set-level check could not see that and rejected
330
+ // exactly this shape, a false positive against an already-shipped,
331
+ // already-tested pattern. Removed rather than narrowed: token-path-level
332
+ // reachability can only be checked where token documents are actually
333
+ // loaded (validate-corpus.ts or generation), and generation already
334
+ // rejects a genuinely-unreachable override with a clear "no matching base
335
+ // token" error at the correct granularity.
336
+
337
+ if (issues.length > 0) throw new TokenValidationError(issues);
338
+ }
@@ -0,0 +1,269 @@
1
+ /**
2
+ * First-pass structural validation against the official DTCG 2025.10 JSON
3
+ * Schemas (vendored under `scripts/tokens/schemas`, see that directory's README.md).
4
+ *
5
+ * This layer catches shape violations JSON Schema can express directly:
6
+ * required composite members, enum membership, value types, and pattern
7
+ * constraints. It intentionally runs *before* the hand-rolled semantic
8
+ * checks in `validate.ts`, which cover rules JSON Schema structurally
9
+ * cannot express -- `$type` inheritance from an ancestor group, alias and
10
+ * `$extends` cycle detection, resolver axis ordering, and Cinder's own
11
+ * token-name restrictions.
12
+ *
13
+ * The official schema's per-type value discriminator keys off a token's
14
+ * *own* `$type` property. The private validation projection below supplies
15
+ * effective inherited types, including `$extends` group references, so valid
16
+ * lossless source documents do not need authored discriminator properties.
17
+ */
18
+ import type { ErrorObject } from 'ajv';
19
+
20
+ import validateFormat from './format-validator.generated.js';
21
+ import { mergeAndExpandExtends } from './resolve.ts';
22
+ import validateResolver from './resolver-validator.generated.js';
23
+ import {
24
+ TOKEN_TYPES,
25
+ TokenValidationError,
26
+ type TokenDocument,
27
+ type ValidationIssue,
28
+ } from './types.ts';
29
+
30
+ /**
31
+ * The validators are standalone modules generated from the vendored schemas
32
+ * (`scripts/tokens/schemas`) by `tokens:generate`, so this module needs no
33
+ * filesystem access and no runtime code generation. They are CSP-safe and run
34
+ * in the browser unchanged.
35
+ */
36
+ type SchemaValidator = ((data: unknown) => boolean) & { errors?: ErrorObject[] | null };
37
+
38
+ function isJsonSchemaDocument(value: unknown): value is Record<string, unknown> {
39
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
40
+ }
41
+
42
+ function isTokenDocument(value: unknown): value is TokenDocument {
43
+ return isJsonSchemaDocument(value);
44
+ }
45
+
46
+ function decodeJsonPointerSegment(segment: string): string {
47
+ return segment.replaceAll('~1', '/').replaceAll('~0', '~');
48
+ }
49
+
50
+ function instancePathToTokenPath(source: string, instancePath: string): string {
51
+ if (!instancePath) return source;
52
+ const segments = instancePath.slice(1).split('/').map(decodeJsonPointerSegment);
53
+ return [source, ...segments].join('.');
54
+ }
55
+
56
+ function describeAjvError(error: ErrorObject): string {
57
+ switch (error.keyword) {
58
+ case 'additionalProperties': {
59
+ const propertyName = (error.params as { additionalProperty?: string }).additionalProperty;
60
+ return `must NOT have additional property '${propertyName}'`;
61
+ }
62
+ case 'required': {
63
+ const propertyName = (error.params as { missingProperty?: string }).missingProperty;
64
+ return `must have required property '${propertyName}'`;
65
+ }
66
+ case 'enum': {
67
+ const allowedValues = (error.params as { allowedValues?: unknown[] }).allowedValues ?? [];
68
+ return `must be one of ${JSON.stringify(allowedValues)}`;
69
+ }
70
+ case 'const': {
71
+ const allowedValue = (error.params as { allowedValue?: unknown }).allowedValue;
72
+ return `must equal ${JSON.stringify(allowedValue)}`;
73
+ }
74
+ default:
75
+ return error.message ?? 'failed schema validation';
76
+ }
77
+ }
78
+
79
+ /** Longer JSON Pointers are more specific; surfacing those first keeps sibling `oneOf` noise last. */
80
+ function bySpecificity(left: ErrorObject, right: ErrorObject): number {
81
+ return right.instancePath.length - left.instancePath.length;
82
+ }
83
+
84
+ function isTokenType(value: unknown): value is string {
85
+ return typeof value === 'string' && TOKEN_TYPES.some((type) => type === value);
86
+ }
87
+
88
+ /**
89
+ * Adds effective ancestor types to a validation-only copy of a token document.
90
+ * The DTCG schema discriminates token values using each token's own `$type`,
91
+ * while the format allows a token to inherit that type from its nearest group.
92
+ * Keeping this projection private preserves authored source and its metadata.
93
+ */
94
+ type ProjectionIndex = {
95
+ groups: Map<string, Record<string, unknown>>;
96
+ tokenTypes: Map<string, string>;
97
+ };
98
+
99
+ function isTokenNode(value: Record<string, unknown>): boolean {
100
+ return '$value' in value || '$ref' in value;
101
+ }
102
+
103
+ function collectProjectionMetadata(value: unknown, path: string, index: ProjectionIndex): void {
104
+ if (!isJsonSchemaDocument(value)) return;
105
+ if (isTokenNode(value)) {
106
+ if (isTokenType(value['$type'])) index.tokenTypes.set(path, value['$type']);
107
+ return;
108
+ }
109
+ index.groups.set(path, value);
110
+ for (const [name, child] of Object.entries(value)) {
111
+ if (name === '$root') collectProjectionMetadata(child, path, index);
112
+ else if (!name.startsWith('$'))
113
+ collectProjectionMetadata(child, path ? `${path}.${name}` : name, index);
114
+ }
115
+ }
116
+
117
+ export function assertSafeExtensionMetadata(value: unknown, path: string, source: string): void {
118
+ if (!isJsonSchemaDocument(value)) return;
119
+ const extension = value['$extends'];
120
+ if (
121
+ extension !== undefined &&
122
+ !(
123
+ (typeof extension === 'string' && /^\{[^{}]+\}$/.test(extension)) ||
124
+ (typeof extension === 'string' && extension.startsWith('#/'))
125
+ )
126
+ ) {
127
+ throw new TokenValidationError([
128
+ {
129
+ path: `${source}${path ? `.${path}` : ''}.$extends`,
130
+ reason: '$extends must be a token reference',
131
+ },
132
+ ]);
133
+ }
134
+ for (const [name, child] of Object.entries(value)) {
135
+ if (!name.startsWith('$'))
136
+ assertSafeExtensionMetadata(child, path ? `${path}.${name}` : name, source);
137
+ }
138
+ }
139
+
140
+ function projectTokenDocumentForValidation(
141
+ value: unknown,
142
+ lookupDocuments: readonly unknown[] = [],
143
+ source = '$',
144
+ sourceByDocument?: ReadonlyMap<object, string>,
145
+ ): unknown {
146
+ const index: ProjectionIndex = { groups: new Map(), tokenTypes: new Map() };
147
+ if (isTokenDocument(value)) {
148
+ assertSafeExtensionMetadata(value, '', source);
149
+ const contextDocuments = lookupDocuments.filter(isTokenDocument);
150
+ const candidatePosition = contextDocuments.indexOf(value);
151
+ // The loaded corpus validates each document's own extension metadata at
152
+ // its owning path before entering this projection. Direct callers do not
153
+ // have that ownership record, so retain the historical lookup check when
154
+ // the candidate is not one of the ordered context documents.
155
+ if (candidatePosition < 0)
156
+ for (const contextDocument of contextDocuments)
157
+ assertSafeExtensionMetadata(contextDocument, '', source);
158
+ try {
159
+ // Type metadata belongs to the ordered prefix through the authored
160
+ // source. Later ordinary overrides must not change how an earlier value
161
+ // is validated. The complete context remains the lookup scope so a
162
+ // source may refer forward through `$extends`.
163
+ const orderedPrefix =
164
+ candidatePosition >= 0 ? contextDocuments.slice(0, candidatePosition + 1) : [value];
165
+ const documents = orderedPrefix.length > 0 ? orderedPrefix : [value];
166
+ const expanded = mergeAndExpandExtends(
167
+ documents,
168
+ contextDocuments.length > 0 ? contextDocuments : documents,
169
+ sourceByDocument,
170
+ );
171
+ collectProjectionMetadata(expanded, '', index);
172
+ } catch (error) {
173
+ // A failed composition cannot be replaced with raw groups: a later
174
+ // partial group would hide inherited extension edges and their cycles.
175
+ if (error instanceof TokenValidationError)
176
+ throw new TokenValidationError(
177
+ error.issues.map(({ path, reason }) => ({
178
+ path: error.sourceOwned ? path : path ? `${source}.${path}` : source,
179
+ reason,
180
+ })),
181
+ error.sourceOwned,
182
+ );
183
+ throw error;
184
+ }
185
+ }
186
+ function project(node: unknown, path: string, inheritedType?: string): unknown {
187
+ if (Array.isArray(node)) return node.map((entry) => entry);
188
+ if (!isJsonSchemaDocument(node)) return node;
189
+ const token = isTokenNode(node);
190
+ const tokenType = token ? index.tokenTypes.get(path) : undefined;
191
+ const ownType = token ? undefined : index.groups.get(path)?.['$type'];
192
+ const groupType = isTokenType(ownType) ? ownType : inheritedType;
193
+ const projected: Record<string, unknown> = {};
194
+ const defineProjectedProperty = (key: string, entry: unknown): void => {
195
+ Object.defineProperty(projected, key, {
196
+ configurable: true,
197
+ enumerable: true,
198
+ value: entry,
199
+ writable: true,
200
+ });
201
+ };
202
+ for (const [key, entry] of Object.entries(node)) {
203
+ if (key === '$root' && isJsonSchemaDocument(entry))
204
+ defineProjectedProperty(key, project(entry, path, groupType));
205
+ else if (!key.startsWith('$') && !token)
206
+ defineProjectedProperty(key, project(entry, path ? `${path}.${key}` : key, groupType));
207
+ else defineProjectedProperty(key, entry);
208
+ }
209
+ // `$ref` has no value discriminator. Leaving it untouched ensures that
210
+ // unresolved or cyclic aliases cannot gain acceptance through the copy.
211
+ if (token && '$value' in node && node['$type'] === undefined && (tokenType ?? groupType))
212
+ defineProjectedProperty('$type', tokenType ?? groupType);
213
+ return projected;
214
+ }
215
+
216
+ return project(value, '');
217
+ }
218
+
219
+ function runSchemaValidation(
220
+ validator: SchemaValidator,
221
+ document: unknown,
222
+ source: string,
223
+ lookupDocuments: readonly unknown[] = [],
224
+ sourceByDocument?: ReadonlyMap<object, string>,
225
+ ): unknown {
226
+ const schemaDocument =
227
+ validator === validateFormat
228
+ ? projectTokenDocumentForValidation(document, lookupDocuments, source, sourceByDocument)
229
+ : document;
230
+ if (validator(schemaDocument)) return schemaDocument;
231
+ const errors = [...(validator.errors ?? [])].toSorted(bySpecificity);
232
+ const issues: ValidationIssue[] = errors.map((error) => ({
233
+ path: instancePathToTokenPath(source, error.instancePath),
234
+ reason: describeAjvError(error),
235
+ }));
236
+ throw new TokenValidationError(issues);
237
+ }
238
+
239
+ /** Validates a token document against the official DTCG 2025.10 format JSON Schema. */
240
+ export function validateTokenDocumentSchema(
241
+ document: unknown,
242
+ source = '$',
243
+ lookupDocuments: readonly unknown[] = [],
244
+ sourceByDocument?: ReadonlyMap<object, string>,
245
+ ): unknown {
246
+ return runSchemaValidation(validateFormat, document, source, lookupDocuments, sourceByDocument);
247
+ }
248
+
249
+ /**
250
+ * Validates a document against the official DTCG 2025.10 resolver JSON Schema.
251
+ *
252
+ * Wired into `assertValidResolverDocument` as its first-pass gate, alongside
253
+ * the token-document equivalent above.
254
+ *
255
+ * `cinder.resolver.json` previously used an array-of-`{name, source}` shape
256
+ * for `sets`/`modifiers` and a plain string array for `resolutionOrder`, while
257
+ * declaring the official schema's `$schema` URI. Those are genuinely different
258
+ * document models, not a naming quibble: the official schema keys `sets` and
259
+ * `modifiers` by name (`{ sources: [...] }` / `{ contexts: { [value]: sources[] } }`)
260
+ * and requires `resolutionOrder` entries to be `{ "$ref": "#/sets/..." }`
261
+ * reference objects -- see the `resolver/set.json`, `resolver/modifier.json`,
262
+ * and `resolver/resolutionOrder.json` definitions embedded in the vendored
263
+ * file. The document was migrated to the conformant shape rather than leaving
264
+ * this validator unwired, and a regression test pins the old shape as
265
+ * rejected so it cannot come back.
266
+ */
267
+ export function validateResolverDocumentSchema(document: unknown, source = '$'): void {
268
+ runSchemaValidation(validateResolver, document, source);
269
+ }