@tanrei/mcp 0.0.0-stage → 0.1.0-next.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 (111) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +58 -0
  3. package/README.md +135 -2
  4. package/bin/tanrei-mcp.js +15 -0
  5. package/dist/server.js +3008 -0
  6. package/dist/vocabulary/docs/governance/mimicry-gaps.json +592 -0
  7. package/dist/vocabulary/tanrei.config.json +23 -0
  8. package/dist/vocabulary/tokens/AGENTS.md +15 -0
  9. package/dist/vocabulary/tokens/comp/accordion.tokens.json +436 -0
  10. package/dist/vocabulary/tokens/comp/app-bar.tokens.json +211 -0
  11. package/dist/vocabulary/tokens/comp/app-shell.tokens.json +248 -0
  12. package/dist/vocabulary/tokens/comp/avatar.tokens.json +187 -0
  13. package/dist/vocabulary/tokens/comp/badge.tokens.json +100 -0
  14. package/dist/vocabulary/tokens/comp/bottom-sheet.tokens.json +256 -0
  15. package/dist/vocabulary/tokens/comp/breadcrumbs.tokens.json +253 -0
  16. package/dist/vocabulary/tokens/comp/button-group.tokens.json +118 -0
  17. package/dist/vocabulary/tokens/comp/button-with-menu.tokens.json +582 -0
  18. package/dist/vocabulary/tokens/comp/button.tokens.json +1102 -0
  19. package/dist/vocabulary/tokens/comp/calendar.tokens.json +490 -0
  20. package/dist/vocabulary/tokens/comp/callout.tokens.json +754 -0
  21. package/dist/vocabulary/tokens/comp/card.tokens.json +204 -0
  22. package/dist/vocabulary/tokens/comp/carousel.tokens.json +409 -0
  23. package/dist/vocabulary/tokens/comp/chat-composer.tokens.json +309 -0
  24. package/dist/vocabulary/tokens/comp/checkbox.tokens.json +591 -0
  25. package/dist/vocabulary/tokens/comp/chip.tokens.json +665 -0
  26. package/dist/vocabulary/tokens/comp/code-block.tokens.json +459 -0
  27. package/dist/vocabulary/tokens/comp/color-input.tokens.json +49 -0
  28. package/dist/vocabulary/tokens/comp/combobox.tokens.json +587 -0
  29. package/dist/vocabulary/tokens/comp/copy-button.tokens.json +39 -0
  30. package/dist/vocabulary/tokens/comp/date-time-picker.tokens.json +766 -0
  31. package/dist/vocabulary/tokens/comp/description-list.tokens.json +181 -0
  32. package/dist/vocabulary/tokens/comp/dialog.tokens.json +280 -0
  33. package/dist/vocabulary/tokens/comp/divider.tokens.json +139 -0
  34. package/dist/vocabulary/tokens/comp/embedded-text-input.tokens.json +103 -0
  35. package/dist/vocabulary/tokens/comp/empty-state.tokens.json +154 -0
  36. package/dist/vocabulary/tokens/comp/fab-menu.tokens.json +509 -0
  37. package/dist/vocabulary/tokens/comp/field-group.tokens.json +191 -0
  38. package/dist/vocabulary/tokens/comp/field.tokens.json +279 -0
  39. package/dist/vocabulary/tokens/comp/figure.tokens.json +215 -0
  40. package/dist/vocabulary/tokens/comp/file-item.tokens.json +445 -0
  41. package/dist/vocabulary/tokens/comp/file-picker.tokens.json +282 -0
  42. package/dist/vocabulary/tokens/comp/file-upload.tokens.json +35 -0
  43. package/dist/vocabulary/tokens/comp/image-preview.tokens.json +297 -0
  44. package/dist/vocabulary/tokens/comp/inline-code.tokens.json +86 -0
  45. package/dist/vocabulary/tokens/comp/input-box.tokens.json +938 -0
  46. package/dist/vocabulary/tokens/comp/keyboard-shortcut.tokens.json +192 -0
  47. package/dist/vocabulary/tokens/comp/link-card.tokens.json +301 -0
  48. package/dist/vocabulary/tokens/comp/link.tokens.json +321 -0
  49. package/dist/vocabulary/tokens/comp/list.tokens.json +447 -0
  50. package/dist/vocabulary/tokens/comp/loading-indicator.tokens.json +208 -0
  51. package/dist/vocabulary/tokens/comp/main-action-button.tokens.json +345 -0
  52. package/dist/vocabulary/tokens/comp/menu.tokens.json +919 -0
  53. package/dist/vocabulary/tokens/comp/menubar.tokens.json +228 -0
  54. package/dist/vocabulary/tokens/comp/navigation-bar.tokens.json +479 -0
  55. package/dist/vocabulary/tokens/comp/navigation-drawer.tokens.json +770 -0
  56. package/dist/vocabulary/tokens/comp/navigation-rail.tokens.json +254 -0
  57. package/dist/vocabulary/tokens/comp/number-input.tokens.json +75 -0
  58. package/dist/vocabulary/tokens/comp/one-time-code-input.tokens.json +231 -0
  59. package/dist/vocabulary/tokens/comp/page-header.tokens.json +247 -0
  60. package/dist/vocabulary/tokens/comp/pagination.tokens.json +194 -0
  61. package/dist/vocabulary/tokens/comp/popover.tokens.json +292 -0
  62. package/dist/vocabulary/tokens/comp/progress-indicator.tokens.json +208 -0
  63. package/dist/vocabulary/tokens/comp/prose.tokens.json +267 -0
  64. package/dist/vocabulary/tokens/comp/radio-button.tokens.json +417 -0
  65. package/dist/vocabulary/tokens/comp/search.tokens.json +675 -0
  66. package/dist/vocabulary/tokens/comp/segmented-button.tokens.json +360 -0
  67. package/dist/vocabulary/tokens/comp/select.tokens.json +553 -0
  68. package/dist/vocabulary/tokens/comp/side-sheet.tokens.json +285 -0
  69. package/dist/vocabulary/tokens/comp/skeleton.tokens.json +111 -0
  70. package/dist/vocabulary/tokens/comp/slider.tokens.json +435 -0
  71. package/dist/vocabulary/tokens/comp/snackbar.tokens.json +1334 -0
  72. package/dist/vocabulary/tokens/comp/steps.tokens.json +190 -0
  73. package/dist/vocabulary/tokens/comp/switch.tokens.json +349 -0
  74. package/dist/vocabulary/tokens/comp/tab-view.tokens.json +142 -0
  75. package/dist/vocabulary/tokens/comp/table-of-contents.tokens.json +404 -0
  76. package/dist/vocabulary/tokens/comp/table.tokens.json +442 -0
  77. package/dist/vocabulary/tokens/comp/tabs.tokens.json +970 -0
  78. package/dist/vocabulary/tokens/comp/tag-group.tokens.json +57 -0
  79. package/dist/vocabulary/tokens/comp/tag.tokens.json +527 -0
  80. package/dist/vocabulary/tokens/comp/text-input.tokens.json +166 -0
  81. package/dist/vocabulary/tokens/comp/timeline.tokens.json +243 -0
  82. package/dist/vocabulary/tokens/comp/toolbar.tokens.json +155 -0
  83. package/dist/vocabulary/tokens/comp/tooltip.tokens.json +415 -0
  84. package/dist/vocabulary/tokens/comp/tree-view.tokens.json +393 -0
  85. package/dist/vocabulary/tokens/dial/dial.tokens.json +117 -0
  86. package/dist/vocabulary/tokens/fidelity/m3-expressive-like.fidelity.json +68 -0
  87. package/dist/vocabulary/tokens/fidelity/m3-like.fidelity.json +178 -0
  88. package/dist/vocabulary/tokens/fidelity/reference/androidx-material3-buttons.json +67 -0
  89. package/dist/vocabulary/tokens/fidelity/reference/material-web.json +802 -0
  90. package/dist/vocabulary/tokens/generated/m3-expressive-like/fidelity.json +99 -0
  91. package/dist/vocabulary/tokens/generated/m3-like/fidelity.json +24 -0
  92. package/dist/vocabulary/tokens/icon-sets/material-symbols.icon-set.json +278 -0
  93. package/dist/vocabulary/tokens/ref/typeface.tokens.json +116 -0
  94. package/dist/vocabulary/tokens/schema/icon-set.schema.json +82 -0
  95. package/dist/vocabulary/tokens/schema/system.schema.json +570 -0
  96. package/dist/vocabulary/tokens/sys/behavior.tokens.json +119 -0
  97. package/dist/vocabulary/tokens/sys/color.vocabulary.json +58 -0
  98. package/dist/vocabulary/tokens/sys/elevation.tokens.json +362 -0
  99. package/dist/vocabulary/tokens/sys/measure.tokens.json +358 -0
  100. package/dist/vocabulary/tokens/sys/motion.tokens.json +949 -0
  101. package/dist/vocabulary/tokens/sys/shape.tokens.json +169 -0
  102. package/dist/vocabulary/tokens/sys/space.tokens.json +256 -0
  103. package/dist/vocabulary/tokens/sys/state.tokens.json +70 -0
  104. package/dist/vocabulary/tokens/sys/typescale.tokens.json +551 -0
  105. package/dist/vocabulary/tokens/systems/cupertino.system.json +640 -0
  106. package/dist/vocabulary/tokens/systems/m3-expressive-like.system.json +83 -0
  107. package/dist/vocabulary/tokens/systems/m3-like.system.json +855 -0
  108. package/dist/vocabulary/tokens/systems/tanrei.system.json +409 -0
  109. package/dist/vocabulary/tokens/tanrei.resolver.json +358 -0
  110. package/dist/vocabulary/tokens/vocabulary.lock.json +7052 -0
  111. package/package.json +36 -3
package/dist/server.js ADDED
@@ -0,0 +1,3008 @@
1
+ // Bundled from the Tanrei monorepo (packages/mcp, packages/tokens-build, packages/token-engine).
2
+
3
+ // src/server.js
4
+ import fs8 from "node:fs";
5
+ import Ajv20202 from "ajv/dist/2020.js";
6
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
7
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
8
+ import { CallToolRequestSchema, ErrorCode, ListResourceTemplatesRequestSchema, ListResourcesRequestSchema, ListToolsRequestSchema, McpError, ReadResourceRequestSchema } from "@modelcontextprotocol/sdk/types.js";
9
+
10
+ // src/resources.js
11
+ import fs6 from "node:fs";
12
+ import path7 from "node:path";
13
+
14
+ // src/systems.js
15
+ import fs5 from "node:fs";
16
+ import path6 from "node:path";
17
+
18
+ // ../token-engine/src/contexts.js
19
+ var SCHEMES = ["light", "light-medium", "light-high", "dark", "dark-medium", "dark-high"];
20
+ var CONTRAST_INDEX = { standard: 0, medium: 1, high: 2 };
21
+ function parseScheme(scheme) {
22
+ const [theme, contrast2 = "standard"] = scheme.split("-");
23
+ return { theme, contrast: contrast2 };
24
+ }
25
+ function pick(list, contrast2) {
26
+ return list[Math.min(CONTRAST_INDEX[contrast2], list.length - 1)];
27
+ }
28
+ function inContext(value, scheme) {
29
+ const { theme, contrast: contrast2 } = parseScheme(scheme);
30
+ let v = value;
31
+ if (v !== null && typeof v === "object" && !Array.isArray(v)) {
32
+ if (!(theme in v)) throw new Error(`context map has no "${theme}" entry: ${JSON.stringify(value)}`);
33
+ v = v[theme];
34
+ }
35
+ return Array.isArray(v) ? pick(v, contrast2) : v;
36
+ }
37
+
38
+ // ../token-engine/src/errors.js
39
+ var SystemError = class extends Error {
40
+ };
41
+
42
+ // ../token-engine/src/rules.js
43
+ var DERIVE = "dev.tanrei.derive";
44
+ var VOCABULARY = "dev.tanrei.vocabulary";
45
+ var ENUM = "dev.tanrei.enum";
46
+ var enumName = (token) => token?.$extensions?.[ENUM]?.values?.[token.$value];
47
+ var ROUND = { dimension: 0.25, duration: 1, number: 1e-4, tracking: 1e-4 };
48
+ function roundTo(value, step) {
49
+ const inverse = 1 / step;
50
+ return Math.round(value * inverse) / inverse;
51
+ }
52
+ var isRef = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
53
+ var refId = (v) => v.slice(1, -1);
54
+ function ruleDependencies(rule) {
55
+ if (!rule || typeof rule !== "object" || "fixed" in rule) return [];
56
+ if (!("fn" in rule)) return Object.values(rule).flatMap(ruleDependencies);
57
+ return [rule.of, rule.base, rule.exp, rule.with, rule.amount, rule.on, ...Array.isArray(rule.from) ? rule.from : []].filter(isRef).map(refId);
58
+ }
59
+ function evaluateNumeric(rule, lookup, ctx) {
60
+ const num = (v) => isRef(v) ? lookup(refId(v)).value : v;
61
+ switch (rule.fn) {
62
+ case "mul": {
63
+ const of = lookup(refId(rule.of));
64
+ const exp = rule.exp === void 0 ? 1 : num(rule.exp);
65
+ const coefficient = exp === 1 ? rule.by : rule.by ** exp;
66
+ return { value: roundTo(of.value * coefficient, ROUND[ctx.type] ?? ROUND.number), unit: of.unit };
67
+ }
68
+ case "scale": {
69
+ const base = lookup(refId(rule.base));
70
+ return { value: roundTo(base.value * rule.ratio ** rule.step, ROUND[ctx.type] ?? ROUND.number), unit: base.unit };
71
+ }
72
+ case "clamp": {
73
+ const of = lookup(refId(rule.of));
74
+ return { value: Math.min(rule.max, Math.max(rule.min, of.value)), unit: of.unit };
75
+ }
76
+ case "em":
77
+ if (ctx.fontSize === void 0) throw new Error('"em" is only valid for typography.letterSpacing');
78
+ return { value: roundTo(ctx.fontSize * rule.by, ROUND.tracking), unit: "px" };
79
+ default:
80
+ throw new Error(`unknown rule function "${rule.fn}"`);
81
+ }
82
+ }
83
+ function* walkTokens(node, path9 = [], inherited = {}) {
84
+ const here = {
85
+ type: node.$type ?? inherited.type,
86
+ rationale: node.$extensions?.[VOCABULARY]?.rationale ?? inherited.rationale
87
+ };
88
+ if ("$value" in node) {
89
+ yield { id: path9.join("."), token: node, type: here.type, rationale: here.rationale };
90
+ return;
91
+ }
92
+ for (const [key, child] of Object.entries(node)) {
93
+ if (key.startsWith("$") || child === null || typeof child !== "object") continue;
94
+ yield* walkTokens(child, [...path9, key], here);
95
+ }
96
+ }
97
+
98
+ // ../token-engine/src/states.js
99
+ var STATES = "dev.tanrei.states";
100
+ var COLOR_RULES = /* @__PURE__ */ new Set(["mix", "alpha", "tone", "contrast-pick"]);
101
+ var isColorRule = (op) => Boolean(op && !("$value" in op) && COLOR_RULES.has(op.derive?.fn));
102
+ var isRef2 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
103
+ var refId2 = (v) => v.slice(1, -1);
104
+ var clone = (v) => JSON.parse(JSON.stringify(v));
105
+ function expandStateVocabulary(compDocuments) {
106
+ const out = [];
107
+ const visit = (node, path9) => {
108
+ const decl = node.$extensions?.[STATES];
109
+ if (decl) {
110
+ const component = path9.join(".");
111
+ const rationale = node.$extensions?.[VOCABULARY]?.rationale;
112
+ for (const state of decl.states) {
113
+ for (const variant of decl.variants ?? []) {
114
+ for (const [part, type] of Object.entries(decl.perVariant ?? {})) out.push({ id: `${component}.${variant}.${state}.${part}`, type, component, variant, state, part, enabled: `${component}.${variant}.${part}`, rationale });
115
+ }
116
+ for (const [part, type] of Object.entries(decl.perComponent ?? {})) out.push({ id: `${component}.${state}.${part}`, type, component, state, part, rationale });
117
+ }
118
+ }
119
+ for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object" && !("$value" in child)) visit(child, [...path9, key]);
120
+ };
121
+ for (const doc of compDocuments) visit(doc, []);
122
+ return out;
123
+ }
124
+ var patternSegments = /* @__PURE__ */ new Map();
125
+ function matchPattern(pattern, id, s = id.split(".")) {
126
+ let p = patternSegments.get(pattern);
127
+ if (!p) patternSegments.set(pattern, p = pattern.split("."));
128
+ if (p.length !== s.length) return null;
129
+ const captures = [];
130
+ for (let i = 0; i < p.length; i++) {
131
+ if (p[i] === "*") captures.push(s[i]);
132
+ else if (p[i] !== s[i]) return null;
133
+ }
134
+ return captures;
135
+ }
136
+ var substitute = (value, captures) => typeof value === "string" ? value.replace(/\$(\d)/g, (_, n) => captures[n - 1] ?? `$${n}`) : Array.isArray(value) ? value.map((v) => substitute(v, captures)) : value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, substitute(v, captures)])) : value;
137
+ var ruleIndexes = /* @__PURE__ */ new WeakMap();
138
+ function ruleIndex(rules) {
139
+ let index = ruleIndexes.get(rules);
140
+ if (!index || index.count !== rules.length) {
141
+ const byLength = /* @__PURE__ */ new Map();
142
+ for (const rule of rules) {
143
+ const p = rule.match.split(".");
144
+ if (!byLength.has(p.length)) byLength.set(p.length, []);
145
+ byLength.get(p.length).push({ rule, p });
146
+ }
147
+ index = { count: rules.length, byLength, chosen: /* @__PURE__ */ new Map() };
148
+ ruleIndexes.set(rules, index);
149
+ }
150
+ return index;
151
+ }
152
+ function operationFor(id, system) {
153
+ if (system.tokens[id]) return system.tokens[id];
154
+ if (!system.rules?.length) return null;
155
+ const index = ruleIndex(system.rules);
156
+ let best = index.chosen.get(id);
157
+ if (best === void 0) {
158
+ best = null;
159
+ const s = id.split(".");
160
+ for (const { rule, p } of index.byLength.get(s.length) ?? []) {
161
+ const captures = [];
162
+ let hit = true;
163
+ for (let i = 0; i < p.length && hit; i++) {
164
+ if (p[i] === "*") captures.push(s[i]);
165
+ else hit = p[i] === s[i];
166
+ }
167
+ if (hit && (!best || captures.length <= best.captures.length)) best = { rule, captures };
168
+ }
169
+ index.chosen.set(id, best);
170
+ }
171
+ if (!best) return null;
172
+ const { match, ...operation } = best.rule;
173
+ return substitute(clone(operation), best.captures);
174
+ }
175
+ function matchingRules(id, layers) {
176
+ const hits = [];
177
+ for (const layer of layers) {
178
+ (layer.rules ?? []).forEach((rule, index) => {
179
+ const captures = matchPattern(rule.match, id);
180
+ if (captures) hits.push({ layer: layer.id, index, match: rule.match, wildcards: captures.length });
181
+ });
182
+ }
183
+ const explicit = [...layers].reverse().find((layer) => layer.tokens?.[id]);
184
+ const fewest = Math.min(...hits.map((h) => h.wildcards));
185
+ const winner = explicit ? null : hits.filter((h) => h.wildcards === fewest).at(-1);
186
+ const rules = hits.map((hit) => {
187
+ if (explicit) return { ...hit, wins: false, because: `an explicit entry under "tokens" (layer "${explicit.id}") beats every pattern` };
188
+ if (hit === winner) {
189
+ const tied = hits.filter((h) => h !== hit && h.wildcards === fewest);
190
+ const why = hits.length === 1 ? "the only pattern that matches" : !tied.length ? `fewest wildcards (${hit.wildcards})` : `${hits.some((h) => h.wildcards > fewest) ? `fewest wildcards (${hit.wildcards}), and ` : ""}written after ${tied.map((h) => `"${h.layer}" rules[${h.index}]`).join(", ")}, which ${tied.length === 1 ? "is" : "are"} equally specific \u2014 the later one wins a tie`;
191
+ return { ...hit, wins: true, because: why };
192
+ }
193
+ return { ...hit, wins: false, because: hit.wildcards > fewest ? `more wildcards (${hit.wildcards}) than "${winner.layer}" rules[${winner.index}] (${winner.wildcards})` : `equally specific, but "${winner.layer}" rules[${winner.index}] was written later` };
194
+ });
195
+ return { explicit: explicit ? { layer: explicit.id } : null, rules };
196
+ }
197
+ function mixColors(base, over2, amount) {
198
+ const t = Math.min(1, Math.max(0, amount));
199
+ const a = base.a * (1 - t) + over2.a * t;
200
+ if (a === 0) return { r: 0, g: 0, b: 0, a: 0 };
201
+ const ch = (k) => (base[k] * base.a * (1 - t) + over2[k] * over2.a * t) / a;
202
+ return { r: ch("r"), g: ch("g"), b: ch("b"), a };
203
+ }
204
+ function toDtcgColor({ r, g, b, a }) {
205
+ const byte = (c) => Math.round(Math.min(1, Math.max(0, c)) * 255);
206
+ const [R, G, B] = [byte(r), byte(g), byte(b)];
207
+ const round = (n) => Math.round(n / 255 * 1e4) / 1e4;
208
+ const value = { colorSpace: "srgb", components: [round(R), round(G), round(B)] };
209
+ const alpha = Math.round(a * 1e4) / 1e4;
210
+ if (alpha !== 1) value.alpha = alpha;
211
+ value.hex = `#${[R, G, B].map((c) => c.toString(16).padStart(2, "0")).join("")}`;
212
+ return value;
213
+ }
214
+ var linear = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
215
+ var luminance = ({ r, g, b }) => 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);
216
+ function contrastRatio(fg, bg) {
217
+ const a = fg.a ?? 1;
218
+ const over2 = { r: fg.r * a + bg.r * (1 - a), g: fg.g * a + bg.g * (1 - a), b: fg.b * a + bg.b * (1 - a) };
219
+ const [hi, lo] = [luminance(over2), luminance(bg)].sort((x, y) => y - x);
220
+ return (hi + 0.05) / (lo + 0.05);
221
+ }
222
+ function pickByContrast(on, candidates) {
223
+ let best = null;
224
+ for (const candidate of candidates) {
225
+ const ratio = contrastRatio(candidate.color, on);
226
+ if (!best || ratio > best.ratio) best = { ...candidate, ratio };
227
+ }
228
+ return best;
229
+ }
230
+ function checkContrastPick(rule, id) {
231
+ if (!isRef2(rule.on)) throw new SystemError(`${id}: "contrast-pick" needs "on": the color token the result must be readable on, as "{\u2026}"`);
232
+ if (!Array.isArray(rule.from) || rule.from.length < 2 || !rule.from.every(isRef2)) throw new SystemError(`${id}: "contrast-pick" needs "from": two or more color tokens to choose among, each as "{\u2026}"`);
233
+ }
234
+ function statePlan(system, documents, NS3, across) {
235
+ if (across?.plan) return across.plan;
236
+ const comp = Object.entries(documents).filter(([name]) => name.startsWith("comp/")).map(([, doc]) => doc);
237
+ const vocabulary = expandStateVocabulary(comp);
238
+ const authored = /* @__PURE__ */ new Map();
239
+ const authoredColors = /* @__PURE__ */ new Set();
240
+ for (const doc of Object.values(documents)) for (const entry of walkTokens(doc)) authored.set(entry.id, entry.token), entry.type === "color" && authoredColors.add(entry.id);
241
+ const rationales = new Map(vocabulary.map((v) => [v.component, v.rationale]));
242
+ const declaring = (node, path9) => {
243
+ if (node.$extensions?.[STATES] && !rationales.has(path9.join("."))) rationales.set(path9.join("."), node.$extensions[VOCABULARY]?.rationale);
244
+ for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object" && !("$value" in child)) declaring(child, [...path9, key]);
245
+ };
246
+ for (const doc of comp) declaring(doc, []);
247
+ const resting = Object.entries(system.tokens).filter(([id, op]) => id.startsWith(`${NS3}.comp.`) && authoredColors.has(id) && isColorRule(op)).map(([id]) => ({ id, type: "color", state: null, rationale: rationales.get(id.split(".").slice(0, 3).join(".")) }));
248
+ for (const entry of resting) if (!entry.rationale) throw new SystemError(`${entry.id}: a resting color takes a color rule only in a component that declares states`);
249
+ vocabulary.push(...resting);
250
+ const said = /* @__PURE__ */ new Map();
251
+ const plan = {
252
+ vocabulary,
253
+ declared: new Map(vocabulary.map((v) => [v.id, v])),
254
+ authored,
255
+ operations: /* @__PURE__ */ new Map(),
256
+ written: /* @__PURE__ */ new Map(),
257
+ /** One `dev.tanrei.vocabulary` entry per rationale: a component's tokens say the same thing. */
258
+ rationale: (text2) => said.get(text2) ?? said.set(text2, Object.freeze({ rationale: text2 })).get(text2)
259
+ };
260
+ if (across) across.plan = plan;
261
+ return plan;
262
+ }
263
+ var fromDtcgColor = (v) => ({ r: v.components[0], g: v.components[1], b: v.components[2], a: v.alpha ?? 1 });
264
+ function generateStateDocument({ system, documents, roleColor, toneColor, note, scheme, across }) {
265
+ const NS3 = system.namespace ?? "tanrei";
266
+ const NS_PATTERN = NS3.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
267
+ const SYS_COLOR4 = `${NS3}.sys.color.`;
268
+ const REF_PALETTE = `${NS3}.ref.palette.`;
269
+ const plan = statePlan(system, documents, NS3, across);
270
+ const { vocabulary, declared, authored } = plan;
271
+ if (!vocabulary.length) return null;
272
+ const resolved = /* @__PURE__ */ new Map();
273
+ const picked = /* @__PURE__ */ new Map();
274
+ const operation = (id) => {
275
+ if (!plan.operations.has(id)) plan.operations.set(id, operationFor(id, system));
276
+ return plan.operations.get(id);
277
+ };
278
+ const amount = (id, rule, trail) => {
279
+ const v = rule.amount;
280
+ if (isRef2(v)) return resolve(refId2(v), trail);
281
+ const isMap = Array.isArray(v) || v !== null && typeof v === "object";
282
+ if (isMap && !scheme) throw new SystemError(`${id}: the "${rule.fn}" rule's amount ${JSON.stringify(v)} is a context map, and generateStateDocument was called without a scheme to read it for`);
283
+ let n;
284
+ try {
285
+ n = isMap ? inContext(v, scheme) : v;
286
+ } catch (error) {
287
+ throw new SystemError(`${id}: the "${rule.fn}" rule's amount cannot be read for scheme "${scheme}": ${error.message}`);
288
+ }
289
+ if (typeof n !== "number" || !Number.isFinite(n)) throw new SystemError(`${id}: the "${rule.fn}" rule's amount must be a number from 0 to 1, a "{\u2026}" reference to one, or a context map of numbers ([standard, medium, high] or { "light": [\u2026], "dark": [\u2026] }) \u2014 not ${JSON.stringify(v)}`);
290
+ return n;
291
+ };
292
+ function resolve(id, trail = []) {
293
+ if (trail.includes(id)) throw new Error(`cycle: ${[...trail, id].join(" \u2192 ")}`);
294
+ if (resolved.has(id)) return resolved.get(id);
295
+ let result;
296
+ if (id.startsWith(SYS_COLOR4)) result = roleColor(id.slice(SYS_COLOR4.length));
297
+ else if (id.startsWith(REF_PALETTE) && toneColor) {
298
+ const [palette, tone] = id.slice(REF_PALETTE.length).split(".");
299
+ result = toneColor(palette, Number(tone));
300
+ } else if (declared.has(id)) {
301
+ const op = operation(id);
302
+ if (!op) throw new Error(`${id}: system "${system.id}" gives this state no value. Add a rule such as { "match": "${id.replace(new RegExp(`^(${NS_PATTERN}\\.comp)\\.[^.]+\\.[^.]+`), "$1.*.*")}", \u2026 }.`);
303
+ const next = [...trail, id];
304
+ if (op.derive?.fn === "mix") result = mixColors(resolve(refId2(op.derive.base), next), resolve(refId2(op.derive.with), next), amount(id, op.derive, next));
305
+ else if (op.derive?.fn === "alpha") {
306
+ const of = resolve(refId2(op.derive.of), next);
307
+ result = { ...of, a: of.a * amount(id, op.derive, next) };
308
+ } else if (op.derive?.fn === "tone") {
309
+ if (declared.get(id).type !== "color") throw new SystemError(`${id}: "tone" values a color, and this token is a ${declared.get(id).type}`);
310
+ if (typeof op.derive.palette !== "string" || op.derive.tone === void 0) throw new SystemError(`${id}: "tone" needs "palette" (a declared palette) and "tone" (0\u2013100; [standard, medium, high]; or { "light": [\u2026], "dark": [\u2026] })`);
311
+ if (!toneColor) throw new Error(`${id}: the "tone" rule needs the palette engine (generateStateDocument was called without toneColor)`);
312
+ result = toneColor(op.derive.palette, op.derive.tone, id);
313
+ } else if (op.derive?.fn === "contrast-pick") {
314
+ checkContrastPick(op.derive, id);
315
+ const on = resolve(refId2(op.derive.on), next);
316
+ const winner = pickByContrast(on, op.derive.from.map((ref) => ({ ref, color: resolve(refId2(ref), next) })));
317
+ picked.set(id, winner.ref);
318
+ result = winner.color;
319
+ } else if (op.derive) throw new SystemError(`${id}: state tokens support the "mix", "alpha", "tone" and "contrast-pick" rules, not "${op.derive.fn}"`);
320
+ else if (isRef2(op.$value)) result = resolve(refId2(op.$value), next);
321
+ else result = op.$value;
322
+ } else {
323
+ const token = authored.get(id);
324
+ if (!token) throw new Error(`${trail.at(-1) ?? "?"}: references unknown token {${id}}`);
325
+ const v = token.$value;
326
+ result = isRef2(v) ? resolve(refId2(v), [...trail, id]) : v;
327
+ }
328
+ if (result && typeof result === "object" && "colorSpace" in result) result = fromDtcgColor(result);
329
+ resolved.set(id, result);
330
+ return result;
331
+ }
332
+ const root2 = { $description: note };
333
+ for (const entry of vocabulary) {
334
+ const op = operation(entry.id);
335
+ const value = resolve(entry.id);
336
+ let node = root2;
337
+ const parts = entry.parts ??= entry.id.split(".");
338
+ for (let i = 0; i < parts.length - 1; i += 1) node = node[parts[i]] ??= {};
339
+ let written = plan.written.get(entry.id);
340
+ if (!written) {
341
+ const aliasOnly = op && !op.derive && isRef2(op.$value);
342
+ const $extensions = { [VOCABULARY]: plan.rationale(entry.rationale), ...entry.state ? { "dev.tanrei.state": entry.state } : {} };
343
+ if (op?.derive) $extensions[DERIVE] = op.derive;
344
+ else if (!aliasOnly) $extensions[DERIVE] = { fixed: op.reason ?? "Set by the system layer." };
345
+ Object.freeze($extensions);
346
+ written = aliasOnly ? { token: Object.freeze({ $type: entry.type, $value: op.$value, $extensions }) } : { $extensions };
347
+ plan.written.set(entry.id, written);
348
+ }
349
+ node[parts.at(-1)] = written.token ?? { $type: entry.type, $value: picked.has(entry.id) ? picked.get(entry.id) : entry.type === "color" ? toDtcgColor(value) : value, $extensions: written.$extensions };
350
+ }
351
+ return root2;
352
+ }
353
+
354
+ // ../token-engine/src/palette.js
355
+ var STANDARD_TONES = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 100];
356
+ var argbToRgb = (argb, a = 1) => ({ r: (argb >> 16 & 255) / 255, g: (argb >> 8 & 255) / 255, b: (argb & 255) / 255, a });
357
+ function hexToArgb(hex) {
358
+ return (4278190080 | Number.parseInt(hex.slice(1), 16)) >>> 0;
359
+ }
360
+ function argbToColor(argb, alphaValue) {
361
+ const r = argb >> 16 & 255;
362
+ const g = argb >> 8 & 255;
363
+ const b = argb & 255;
364
+ const round = (n) => Math.round(n / 255 * 1e4) / 1e4;
365
+ const hex = `#${[r, g, b].map((c) => c.toString(16).padStart(2, "0")).join("")}`;
366
+ const value = { colorSpace: "srgb", components: [round(r), round(g), round(b)] };
367
+ if (alphaValue !== void 0) value.alpha = alphaValue;
368
+ value.hex = hex;
369
+ return value;
370
+ }
371
+ function createPaletteEngine({ Hct: Hct2, TonalPalette: TonalPalette2, namespace: NS3 = "tanrei" }) {
372
+ const SYS_COLOR4 = `${NS3}.sys.color.`;
373
+ const REF_PALETTE = `${NS3}.ref.palette.`;
374
+ function buildPalette(declaration, name) {
375
+ const source = declaration.source ?? {};
376
+ let generated;
377
+ if ("seed" in source) {
378
+ const hct = Hct2.fromInt(hexToArgb(source.seed));
379
+ generated = TonalPalette2.fromHueAndChroma(hct.hue, hct.chroma);
380
+ } else if ("hue" in source && "chroma" in source) generated = TonalPalette2.fromHueAndChroma(source.hue, source.chroma);
381
+ else throw new Error(`palette "${name}": unsupported source ${JSON.stringify(source)}`);
382
+ const fixed = new Map(Object.entries(source.tones ?? {}).map(([tone, hex]) => [Number(tone), hexToArgb(hex)]));
383
+ if (!fixed.size) return generated;
384
+ return { tone: (t) => fixed.get(t) ?? generated.tone(t) };
385
+ }
386
+ const INTENT_TONES = {
387
+ "{name}": { light: [45, 38, 30], dark: [72, 80, 87] },
388
+ "on-{name}": { light: [100], dark: [10] },
389
+ "{name}-container": { light: [93, 91, 89], dark: [22] },
390
+ "on-{name}-container": { light: [20, 15, 10], dark: [88, 92, 96] }
391
+ };
392
+ function roleTable(system, vocabulary) {
393
+ const table = /* @__PURE__ */ new Map();
394
+ const pattern = vocabulary.sets.intent.roles;
395
+ const add = (name, palette, rationale, declared) => {
396
+ for (const p of pattern) table.set(p.replace("{name}", name), { rationale, template: palette ? { palette, tone: INTENT_TONES[p] } : null, declared });
397
+ };
398
+ for (const [name, rationale] of Object.entries(vocabulary.intents)) add(name, name in system.palettes ? name : null, rationale, false);
399
+ for (const [role, rationale] of Object.entries(vocabulary.roles)) table.set(role, { rationale, template: null, declared: false });
400
+ for (const [name, decl] of Object.entries(system.palettes)) {
401
+ if (decl.roles !== "intent") continue;
402
+ if (name in vocabulary.intents) continue;
403
+ if (!decl.description) throw new Error(`palette "${name}": a declared palette with roles needs a "description" \u2014 why does this system need it?`);
404
+ add(name, name, decl.description, true);
405
+ }
406
+ for (const [id, decl] of Object.entries(system.vocabulary ?? {})) {
407
+ if (decl.kind !== "token" || !id.startsWith(SYS_COLOR4)) continue;
408
+ const role = id.slice(SYS_COLOR4.length);
409
+ if (table.has(role)) continue;
410
+ if (decl.type !== "color") throw new Error(`${id}: a color role is declared with "$type": "color"`);
411
+ table.set(role, { rationale: decl.rationale, template: null, declared: true, extension: { declaredBy: decl.declaredBy, onRole: decl.onRole } });
412
+ }
413
+ return table;
414
+ }
415
+ function rolesFor(system, scheme, vocabulary, palettes = buildPalettes(system)) {
416
+ const table = roleTable(system, vocabulary);
417
+ for (const id of Object.keys(system.tokens)) {
418
+ if (id.startsWith(SYS_COLOR4) && !table.has(id.slice(SYS_COLOR4.length))) {
419
+ throw new Error(`${id}: not a color role. Core roles are fixed by the vocabulary; for anything else declare a palette with "roles": "intent".`);
420
+ }
421
+ }
422
+ const out = {};
423
+ const picks = [];
424
+ for (const [role, { template }] of table) {
425
+ const id = `${SYS_COLOR4}${role}`;
426
+ const op = system.tokens[id];
427
+ if (op && "$value" in op && typeof op.$value !== "string") {
428
+ throw new Error(`${id}: a color role cannot hold a literal. Alias another role ("{\u2026}"), use a tone or alpha rule, or declare a palette for the color.`);
429
+ }
430
+ const rule = op?.derive ?? (template ? { fn: "tone", ...template } : void 0);
431
+ if (typeof op?.$value === "string") out[role] = { ref: op.$value };
432
+ else if (rule?.fn === "tone") {
433
+ if (!(rule.palette in system.palettes)) throw new Error(`${id}: unknown palette "${rule.palette}"`);
434
+ out[role] = { p: rule.palette, t: inContext(rule.tone, scheme) };
435
+ } else if (rule?.fn === "alpha") out[role] = { alpha: inContext(rule.of, scheme), a: inContext(rule.amount, scheme) };
436
+ else if (rule?.fn === "contrast-pick") picks.push({ role, id, rule });
437
+ else if (rule?.fn) throw new SystemError(`${id}: a color role accepts the "tone", "alpha" and "contrast-pick" rules, not "${rule.fn}"`);
438
+ else throw new Error(`${id}: the system gives this core role no value. Add a rule, an alias, or a palette named after its intent.`);
439
+ }
440
+ const pending = new Map(picks.map((pick2) => [pick2.role, pick2]));
441
+ const colorOf = (ref, trail) => {
442
+ const target = ref.slice(1, -1);
443
+ if (target.startsWith(REF_PALETTE)) {
444
+ const [p, t] = target.slice(REF_PALETTE.length).split(".");
445
+ if (!palettes[p]) throw new SystemError(`${trail.at(-1)}: {${target}} names the palette "${p}", which this system does not declare`);
446
+ return argbToRgb(palettes[p].tone(Number(t)));
447
+ }
448
+ if (!target.startsWith(SYS_COLOR4)) throw new SystemError(`${trail.at(-1)}: "contrast-pick" on a color role chooses among color roles and ${REF_PALETTE}<palette>.<tone> \u2014 {${target}} is neither`);
449
+ const role = target.slice(SYS_COLOR4.length);
450
+ if (trail.includes(target)) throw new SystemError(`cycle: ${[...trail, target].join(" \u2192 ")}`);
451
+ if (pending.has(role)) decide(pending.get(role), trail);
452
+ const def = out[role];
453
+ if (!def) throw new SystemError(`${trail.at(-1)}: unknown color role {${target}}`);
454
+ if (def.ref) return colorOf(def.ref, [...trail, target]);
455
+ if (def.alpha) return { r: def.alpha === "white" ? 1 : 0, g: def.alpha === "white" ? 1 : 0, b: def.alpha === "white" ? 1 : 0, a: def.a / 100 };
456
+ return argbToRgb(palettes[def.p].tone(def.t));
457
+ };
458
+ function decide({ role, id, rule }, trail = []) {
459
+ checkContrastPick(rule, id);
460
+ const next = [...trail, id];
461
+ const winner = pickByContrast(colorOf(rule.on, next), rule.from.map((ref) => ({ ref, color: colorOf(ref, next) })));
462
+ pending.delete(role);
463
+ out[role] = { ref: winner.ref };
464
+ }
465
+ for (const pick2 of picks) if (pending.has(pick2.role)) decide(pick2);
466
+ return Object.fromEntries([...table.keys()].map((role) => [role, out[role]]));
467
+ }
468
+ const buildPalettes = (system) => Object.fromEntries(Object.entries(system.palettes).map(([name, decl]) => [name, buildPalette(decl, name)]));
469
+ function generateColorFiles(system, { sourcePath, vocabulary, documents }) {
470
+ const table = roleTable(system, vocabulary);
471
+ const palettes = buildPalettes(system);
472
+ const usedTones = Object.fromEntries(Object.keys(palettes).map((name) => [name, new Set(STANDARD_TONES)]));
473
+ const usedAlpha = { black: /* @__PURE__ */ new Set(), white: /* @__PURE__ */ new Set() };
474
+ const resolved = {};
475
+ for (const scheme of SCHEMES) {
476
+ resolved[scheme] = rolesFor(system, scheme, vocabulary, palettes);
477
+ for (const def of Object.values(resolved[scheme])) {
478
+ if (def.ref) continue;
479
+ if (def.alpha) usedAlpha[def.alpha].add(def.a);
480
+ else usedTones[def.p].add(def.t);
481
+ }
482
+ }
483
+ for (const [, palette2, tone] of JSON.stringify([system.tokens, system.rules ?? []]).matchAll(new RegExp(`\\{${REF_PALETTE.replaceAll(".", "\\.")}([a-z0-9-]+)\\.(\\d+)\\}`, "g"))) usedTones[palette2]?.add(Number(tone));
484
+ const note = `Generated by @tanrei/tokens-build from ${sourcePath} (${system.specVersion}). Do not edit.`;
485
+ const files = {};
486
+ const palette = { $type: "color" };
487
+ for (const [name, tones] of Object.entries(usedTones)) {
488
+ palette[name] = {};
489
+ for (const tone of [...tones].sort((a, b) => a - b)) palette[name][String(tone)] = { $value: argbToColor(palettes[name].tone(tone)) };
490
+ }
491
+ const alphaGroup = { $type: "color" };
492
+ for (const [base, steps] of Object.entries(usedAlpha)) {
493
+ alphaGroup[base] = {};
494
+ const argb = base === "black" ? 4278190080 : 4294967295;
495
+ for (const step of [...steps].sort((a, b) => a - b)) alphaGroup[base][String(step)] = { $value: argbToColor(argb, step / 100) };
496
+ }
497
+ files["ref.palette.tokens.json"] = { $description: note, [NS3]: { ref: { palette, alpha: alphaGroup } } };
498
+ const across = {};
499
+ for (const scheme of SCHEMES) {
500
+ const color = { $type: "color", ...vocabulary.llm ? { $extensions: { "dev.tanrei.llm": vocabulary.llm } } : {} };
501
+ for (const [role, def] of Object.entries(resolved[scheme])) {
502
+ const value = def.ref ?? (def.alpha ? `{${NS3}.ref.alpha.${def.alpha}.${def.a}}` : `{${NS3}.ref.palette.${def.p}.${def.t}}`);
503
+ const { rationale, declared, extension } = table.get(role);
504
+ const origin = extension ? { declaredBy: extension.declaredBy, extension: true, ...extension.onRole ? { onRole: extension.onRole } : {} } : declared ? { declaredBy: system.id } : {};
505
+ color[role] = { $value: value, $description: rationale, $extensions: { "dev.tanrei.vocabulary": { rationale, ...origin } } };
506
+ }
507
+ files[`sys.color.${scheme}.tokens.json`] = { $description: note, [NS3]: { sys: { color } } };
508
+ if (documents) {
509
+ const roleColor = (role, trail = []) => {
510
+ const def = resolved[scheme][role];
511
+ if (!def) throw new Error(`unknown color role "${role}"`);
512
+ if (def.ref) return roleColor(def.ref.slice(1, -1).slice(SYS_COLOR4.length), [...trail, role]);
513
+ if (def.alpha) return { r: def.alpha === "white" ? 1 : 0, g: def.alpha === "white" ? 1 : 0, b: def.alpha === "white" ? 1 : 0, a: def.a / 100 };
514
+ return argbToRgb(palettes[def.p].tone(def.t));
515
+ };
516
+ const toneColor = (palette2, tone, id = "?") => {
517
+ if (!palettes[palette2]) throw new SystemError(`${id}: unknown palette "${palette2}". Declared: ${Object.keys(palettes).join(", ")}.`);
518
+ const t = inContext(tone, scheme);
519
+ if (typeof t !== "number" || t < 0 || t > 100) throw new SystemError(`${id}: a tone is a number from 0 to 100, not ${JSON.stringify(t)}`);
520
+ return argbToRgb(palettes[palette2].tone(t));
521
+ };
522
+ const states = generateStateDocument({ system: { namespace: NS3, ...system }, documents, roleColor, toneColor, note, scheme, across });
523
+ if (states) files[`comp.states.${scheme}.tokens.json`] = states;
524
+ }
525
+ }
526
+ return files;
527
+ }
528
+ return { buildPalette, roleTable, rolesFor, generateColorFiles };
529
+ }
530
+
531
+ // ../token-engine/src/operations.js
532
+ var DEFAULT_NAMESPACE = "tanrei";
533
+ var REASON = "<why this product needs it \u2014 8+ characters>";
534
+ var RATIONALE = "<why this design system or product needs it \u2014 8+ characters>";
535
+ var cannot = (namespace = DEFAULT_NAMESPACE) => [
536
+ "remove or retype a core token \u2014 extensions are additive only",
537
+ "add an interaction state \u2014 hovered, focused, pressed and disabled are bound to platform behaviour",
538
+ "add a name to a choice of kind (pressed-feedback, focus-style) \u2014 the list of names is vocabulary; a layer chooses among them",
539
+ `reference a layer\u2019s own token from a ${namespace}.* token \u2014 the core never depends on a layer\u2019s namespace`,
540
+ "change an accessibility threshold \u2014 they are constants; a violation in a product layer is a warning printed by every build, and an imitation preset is held to fidelity to its original instead"
541
+ ];
542
+ var CANNOT = cannot();
543
+ var tierOf = (id) => id.split(".")[1];
544
+ var isPaletteIn = (NS3) => (id) => id.startsWith(`${NS3}.ref.palette.`) || id.startsWith(`${NS3}.ref.alpha.`);
545
+ function tokenKind({ id, alias, rule }, { namespace: NS3 = DEFAULT_NAMESPACE } = {}) {
546
+ if (alias) return "alias";
547
+ if (id.startsWith(`${NS3}.sys.color.`) || isPaletteIn(NS3)(id)) return "derived";
548
+ if (rule && "fixed" in rule) return "fixed";
549
+ if (rule) return "derived";
550
+ return tierOf(id) === "dial" ? "dial" : "fixed";
551
+ }
552
+ var sample = (type) => type === "fontFamily" ? ["<Family a product installs>", "system-ui", "sans-serif"] : type === "number" ? 1 : type === "dimension" ? { value: 12, unit: "px" } : type === "duration" ? { value: 200, unit: "ms" } : type === "color" ? { colorSpace: "srgb", components: [0.9, 0.1, 0.1], hex: "#e61a1a" } : "<a literal of this $type>";
553
+ function legalOperations(descriptor, { namespace: NS3 = DEFAULT_NAMESPACE } = {}) {
554
+ const { id, type, value, alias, rule, state, choices } = descriptor;
555
+ const SYS_COLOR4 = `${NS3}.sys.color.`;
556
+ const isPalette = isPaletteIn(NS3);
557
+ const kind = tokenKind(descriptor, { namespace: NS3 });
558
+ const entry = (op, write, effect) => ({ op, write: { tokens: { [id]: write } }, effect });
559
+ const literal = sample(type);
560
+ if (Array.isArray(choices) && choices.length) {
561
+ const current = typeof value === "number" ? choices[value] : value;
562
+ const other = choices.find((name) => name !== current) ?? choices[0];
563
+ return [{
564
+ ...entry("choose", { $value: choices.indexOf(other), reason: REASON }, `One of: ${choices.map((name, i) => `${name} (${i})`).join(", ")}. It is "${current}" now; this example chooses "${other}". Write the index \u2014 or the name, which the engine accepts too: { "$value": "${other}" }. The names are part of the vocabulary: a layer chooses among them and cannot add one. Nothing scales or derives a choice.`),
565
+ choices,
566
+ current
567
+ }];
568
+ }
569
+ if (tierOf(id) === "dial") return [entry("set the dial", { $value: value, reason: REASON }, "Every token derived from this dial follows, on every platform. Tokens a layer pinned do not. This is the first thing to reach for.")];
570
+ if (isPalette(id)) {
571
+ const palette = id.split(".")[3];
572
+ return [{ op: "change the palette", write: { palettes: { [palette]: { source: { seed: "#rrggbb" } } } }, effect: `ref.palette tones are generated. Re-declare "${palette}" under "palettes" (a seed, or hue + chroma); every role that uses it follows in all six schemes.` }];
573
+ }
574
+ if (id.startsWith(SYS_COLOR4)) {
575
+ const role = id.slice(SYS_COLOR4.length);
576
+ return [
577
+ { op: "change the palette", write: { palettes: { "<palette>": { source: { seed: "#rrggbb" } } } }, effect: "Usually what you want: the role keeps its tone rule and takes the new hue. `rule.palette` names the palette this role reads." },
578
+ entry("derive", { derive: { fn: "tone", palette: rule?.palette ?? "<palette>", tone: { light: [40, 30, 20], dark: [80, 85, 90] } } }, 'Pick tones per theme; the three numbers are standard, medium and high contrast (one number applies to all three). A role also accepts `{"fn": "alpha", "of": "black", "amount": {\u2026}}` and "contrast-pick" (below).'),
579
+ entry("derive (contrast-pick)", { derive: { fn: "contrast-pick", on: `{${SYS_COLOR4}<the role it is drawn on>}`, from: [`{${SYS_COLOR4}<candidate>}`, `{${SYS_COLOR4}<another candidate>}`] } }, 'The role aliases whichever candidate has the highest WCAG contrast against `on`, decided per scheme (the first wins a tie). Candidates are color roles or palette tones ("{' + NS3 + '.ref.palette.<palette>.<tone>}").'),
580
+ entry("re-point alias", { $value: `{${SYS_COLOR4}<another-role>}` }, `"${role}" takes another role's color in every scheme.`),
581
+ { op: "declare a palette", write: { palettes: { "<name>": { description: "<why this product needs this color family>", source: { seed: "#rrggbb" }, roles: "intent" } } }, effect: "For a brand or domain color: generates <name>, on-<name>, <name>-container, on-<name>-container with contrast checks. A literal hex on a role is not accepted." },
582
+ { op: "declare a single role", write: { vocabulary: { [`${SYS_COLOR4}<new-role>`]: { $type: "color", rationale: RATIONALE, derive: { fn: "tone", palette: "<palette>", tone: { light: [90], dark: [30] } }, onRole: `${SYS_COLOR4}<role drawn on it>` } } }, effect: "For one more role rather than a family of four (a reference system\u2019s `primary-fixed`). `onRole` registers the pair with the contrast checks." }
583
+ ];
584
+ }
585
+ if (state) {
586
+ const parts = id.split(".");
587
+ const pattern = parts.map((part, i) => i === 2 || i === 3 && parts[4] === state ? "*" : part).join(".");
588
+ return [
589
+ entry("re-point alias", { $value: `{${NS3}.comp.<component>.<variant>.<part>}` }, "This state looks like another token (for example its resting value: a system without hover)."),
590
+ ...type === "color" ? [
591
+ entry("derive", { derive: { fn: "mix", base: `{${NS3}.comp.\u2026container.color}`, with: `{${NS3}.comp.\u2026state-layer.color}`, amount: `{${NS3}.sys.state.hover-state-layer-opacity}` } }, 'A state layer ("mix") or a dim ("alpha": { "of": "{\u2026}", "amount": n }), computed from this system\u2019s colors in every scheme.'),
592
+ entry("derive (tone)", { derive: { fn: "tone", palette: "<palette>", tone: { light: [70, 60, 50], dark: [70, 80, 90] } } }, "An explicit tone of a declared palette for this one state \u2014 for ramps that are not monotonic (rest 80, hover 70, pressed 40), which no mix can express. The three numbers are standard, medium and high contrast; one number applies everywhere."),
593
+ entry("derive (contrast-pick)", { derive: { fn: "contrast-pick", on: `{${NS3}.comp.\u2026container.color}`, from: [`{${SYS_COLOR4}<candidate>}`, `{${SYS_COLOR4}<another candidate>}`] } }, "Whichever candidate is most readable (highest WCAG contrast) on `on`, decided per scheme; the first wins a tie. State tokens accept mix, alpha, tone and contrast-pick. Nothing else.")
594
+ ] : [],
595
+ entry("pin $value", { $value: literal, reason: REASON }, "An explicit value for this one state."),
596
+ { op: "pattern rule", write: { rules: [{ match: pattern, $value: "{\u2026$1\u2026$2\u2026}" }] }, effect: 'Value the same state of every component/variant at once. `*` matches one segment and is available as $1, $2\u2026. An explicit entry in "tokens" beats a pattern; fewer wildcards beat more; the later layer wins a tie.' }
597
+ ];
598
+ }
599
+ const operations = [];
600
+ if (type === "typography" && alias) {
601
+ return [
602
+ entry("re-point alias", { $value: `{${alias.split(".").slice(0, -1).join(".")}.<another-role>}` }, `Use a different text style. It is "{${alias}}" now. To change the style itself, edit {${alias}}.`)
603
+ ];
604
+ }
605
+ if (type === "fontFamily") {
606
+ const stack = Array.isArray(value) ? value : value ? [value] : null;
607
+ return [
608
+ entry("set the font stack", { $value: literal, reason: REASON }, `Named families first, in order of preference, then a system or generic fallback (system-ui, ui-monospace, sans-serif, serif, monospace) so text still renders where the font is missing.${stack ? ` It is ${JSON.stringify(stack)} now.` : ""} Fonts are referenced by NAME and never bundled: the product installs or registers each named family on every platform it ships (\`tanrei build\` lists them).`),
609
+ entry("re-point alias", { $value: `{${NS3}.ref.typeface.<brand|plain|mono|icon>}` }, `Follow one of the system\u2019s typefaces${alias ? ` \u2014 it is "{${alias}}" now` : ""}. Every text style that uses that typeface follows with it.`)
610
+ ];
611
+ }
612
+ if (type === "typography") {
613
+ operations.push(entry("scale", { scale: { fontSize: 1.125 } }, "Multiply the inherited rule of the named fields; the token still follows dial.type.base."));
614
+ operations.push(entry("pin $value", { $value: { fontSize: { value: 11, unit: "px" } }, reason: REASON }, "Pins only the named fields (fontSize, lineHeight, fontWeight, \u2026); the others keep following their rules."));
615
+ operations.push(entry("derive", { derive: { fontSize: { fn: "mul", of: `{${NS3}.dial.type.base}`, by: 1.25 } } }, "Replace the rule of a field. Closed rule language: mul, scale, clamp, em."));
616
+ return operations;
617
+ }
618
+ if (kind === "alias") {
619
+ operations.push(entry("re-point alias", { $value: `{${alias.split(".").slice(0, -1).join(".")}.<another-step>}` }, `Use a different step of the same scale. It is "{${alias}}" now. The target must exist and be of the same $type.`));
620
+ if (["dimension", "duration", "number"].includes(type)) operations.push(entry("scale", { scale: 2 }, "N \xD7 the inherited alias target, still following its dial."));
621
+ }
622
+ if (kind === "derived" && rule?.fn === "mul") operations.push(entry("scale", { scale: 1.5 }, `N \xD7 the inherited rule (${rule.of} \xD7 ${rule.by}); still follows the dial. Composes with a parent layer's scale.`));
623
+ if (kind === "derived" || kind === "fixed") operations.push(entry("re-point alias", { $value: `{${NS3}.sys.<scale>.<step>}` }, "Make it follow another token instead of its own rule."));
624
+ operations.push(entry("derive", { derive: { fn: "mul", of: `{${NS3}.dial.<family>.unit}`, by: 3 } }, "Replace the rule. Closed language: mul, scale, clamp (numeric). No addition, conditionals or functions of your own."));
625
+ operations.push(entry("pin $value", { $value: literal, reason: REASON }, "A literal that no longer follows any dial. Last resort; the reason is mandatory and is written into the generated tokens."));
626
+ if (kind === "fixed") operations.unshift({ op: "note", effect: `This token is fixed${rule?.fixed ? ` ("${rule.fixed}")` : ""}: "scale" is not legal on it \u2014 pin another $value (with a reason) or give it a rule.` });
627
+ return operations;
628
+ }
629
+ function extensionRecipes({ id, type, rule, alias, axis, choices }, layerId = "<layer id>", { namespace: NS3 = DEFAULT_NAMESPACE } = {}) {
630
+ const recipes = [];
631
+ const SYS_COLOR4 = `${NS3}.sys.color.`;
632
+ if (choices?.length) return [];
633
+ const parent = id.split(".").slice(0, -1).join(".");
634
+ if (axis) {
635
+ recipes.push({ op: `add a ${axis.id.split(".").at(-1)}`, write: { vocabulary: { [`${axis.id}.<new-value>`]: { from: axis.key, ...axis.id.endsWith(".size") ? { scale: 1.5 } : {}, rationale: RATIONALE } } }, effect: `One line values every member of the axis from "${axis.key}"${axis.id.endsWith(".size") ? ", scaled and still following the dials" : "; the system\u2019s pattern rules value its hovered, focused, pressed and disabled tokens"}. Override single members under "tokens". Existing values: ${axis.values.join(", ")}.` });
636
+ } else if (id.startsWith(`${NS3}.sys.motion.spring.`)) {
637
+ const [scheme, name] = id.split(".").slice(4);
638
+ recipes.push({ op: "add a spring set", write: { vocabulary: { [`${NS3}.sys.motion.spring.${scheme}.<new-name>`]: { from: name, rationale: RATIONALE } } }, effect: `A named spring is a group of four tokens (damping, stiffness, easing, duration), so it is cloned whole from "${name}" and can never be half a spring; change single fields under "tokens". Declare it in every spring scheme the product uses (standard, expressive).` });
639
+ } else if (tierOf(id) === "sys" && !id.startsWith(SYS_COLOR4)) {
640
+ const definition = type === "typography" ? { $value: "<a full text style, or an alias to another role>" } : rule?.fn === "mul" ? { derive: { ...rule, by: "<coefficient>" } } : alias ? { $value: `{${alias}}` } : { $value: sample(type), reason: REASON };
641
+ recipes.push({ op: "add a step to this series", write: { vocabulary: { [`${parent}.<new-step>`]: { $type: type, rationale: RATIONALE, ...definition } } }, effect: "A new step next to this one, dial-driven like its neighbours. Platforms keep their named fields for core steps and reach yours through a typed accessor generated with your system." });
642
+ }
643
+ recipes.push({ op: "add your own token", write: { vocabulary: { [`${layerId}.comp.<your-component>.<part>`]: { $type: type, rationale: RATIONALE, $value: `{${id}}` } } }, effect: `For your own components: lives in your layer's namespace ("${layerId}.\u2026"), may reference any ${NS3}.* token (here: this one), follows dials and schemes, and is generated for every platform as a typed object next to your system.` });
644
+ return recipes;
645
+ }
646
+ function dependencyIndex(documents) {
647
+ const dependents = /* @__PURE__ */ new Map();
648
+ const add = (from, to) => (dependents.get(to) ?? dependents.set(to, /* @__PURE__ */ new Set()).get(to)).add(from);
649
+ for (const doc of Object.values(documents)) {
650
+ for (const { id, token } of walkTokens(doc)) {
651
+ if (typeof token.$value === "string" && /^\{[^}]+\}$/.test(token.$value)) add(id, token.$value.slice(1, -1));
652
+ for (const dep of ruleDependencies(token.$extensions?.[DERIVE])) add(id, dep);
653
+ }
654
+ }
655
+ const followers = (id, seen = /* @__PURE__ */ new Set()) => {
656
+ for (const next of dependents.get(id) ?? []) if (!seen.has(next)) followers(next, seen.add(next));
657
+ return seen;
658
+ };
659
+ return { dependents, followers };
660
+ }
661
+
662
+ // ../token-engine/src/vocabulary.js
663
+ var AXES = "dev.tanrei.axes";
664
+ var KEY = /^[a-z0-9][a-z0-9-]*$/;
665
+ var isRef3 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
666
+ var clone2 = (v) => JSON.parse(JSON.stringify(v));
667
+ var kindOf = (entry, id) => !("from" in entry) ? "token" : id.split(".")[1] === "sys" ? "group" : "axis-value";
668
+ function collectVocabulary(layers, { namespace: CORE_NS = "tanrei" } = {}) {
669
+ const out = {};
670
+ for (const layer of layers) {
671
+ for (const [id, entry] of Object.entries(layer.vocabulary ?? {})) {
672
+ if (out[id]) throw new SystemError(`${id}: already declared by layer "${out[id].declaredBy}". Declare a token once; change its value under "tokens".`);
673
+ if (typeof entry.rationale !== "string" || entry.rationale.length < 8) throw new SystemError(`${id}: an extension needs a "rationale" \u2014 why does this design system or product need it?`);
674
+ const namespace = id.split(".")[0];
675
+ const kind = kindOf(entry, id);
676
+ if (namespace !== CORE_NS) {
677
+ if (namespace !== layer.id) throw new SystemError(`${id}: a layer's own tokens live in its own namespace \u2014 "${layer.id}.\u2026", not "${namespace}.\u2026"`);
678
+ if (kind === "group") throw new SystemError(`${id}: a step cloned with "from" belongs to a series of the core vocabulary \u2014 "${CORE_NS}.sys.<series>.\u2026". In your own namespace declare each token with "$type".`);
679
+ if (kind !== "token") throw new SystemError(`${id}: an axis value belongs to a Tanrei component \u2014 "${CORE_NS}.comp.<component>.<axis>.<value>"`);
680
+ }
681
+ for (const segment of id.split(".").slice(1)) if (!KEY.test(segment)) throw new SystemError(`${id}: "${segment}" is not a valid name (lowercase letters, digits and hyphens)`);
682
+ const { rationale, $description, from, scale, onRole, $type, ...definition } = entry;
683
+ out[id] = { kind, type: $type, from, scale, rationale, description: $description, onRole, declaredBy: layer.id, definition };
684
+ }
685
+ }
686
+ return out;
687
+ }
688
+ var stamp = (node, decl) => {
689
+ (node.$extensions ??= {})[VOCABULARY] = { rationale: decl.rationale, declaredBy: decl.declaredBy, extension: true, ...decl.onRole ? { onRole: decl.onRole } : {} };
690
+ if (decl.description) node.$description = decl.description;
691
+ };
692
+ var isToken = (node) => node && typeof node === "object" && "$value" in node;
693
+ function groupAt(doc, segments2) {
694
+ let node = doc;
695
+ for (const key of segments2) {
696
+ node = node?.[key];
697
+ if (!node || typeof node !== "object" || isToken(node)) return void 0;
698
+ }
699
+ return node;
700
+ }
701
+ function ownerOf(docs, segments2) {
702
+ let best = null;
703
+ for (const [name, doc] of Object.entries(docs)) {
704
+ let depth = 0;
705
+ while (depth < segments2.length - 1 && groupAt(doc, segments2.slice(0, depth + 1))) depth += 1;
706
+ if (!best || depth > best.depth) best = { name, doc, depth };
707
+ }
708
+ return best;
709
+ }
710
+ function scaleNode(node, factor, id, type) {
711
+ if (factor === 1 || factor === void 0) return;
712
+ if (type !== "dimension" && type !== "number" && type !== "duration") return;
713
+ const ext = node.$extensions ??= {};
714
+ if (isRef3(node.$value)) {
715
+ ext[DERIVE] = { fn: "mul", of: node.$value, by: factor };
716
+ node.$value = null;
717
+ } else if (ext[DERIVE]?.fn === "mul") ext[DERIVE] = { ...ext[DERIVE], by: ext[DERIVE].by * factor };
718
+ else throw new SystemError(`${id}: cannot scale a fixed value \u2014 give this member a value under "tokens"`);
719
+ }
720
+ function* tokensUnder(node, path9 = [], type) {
721
+ const here = node.$type ?? type;
722
+ if (isToken(node)) {
723
+ yield { path: path9, token: node, type: here };
724
+ return;
725
+ }
726
+ for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object") yield* tokensUnder(child, [...path9, key], here);
727
+ }
728
+ function addAxisValue(docs, id, decl) {
729
+ const segments2 = id.split(".");
730
+ const value = segments2.at(-1);
731
+ const axis = segments2.at(-2);
732
+ const componentPath = segments2.slice(0, -2);
733
+ const home = Object.values(docs).find((doc) => groupAt(doc, componentPath)?.$extensions?.[AXES]);
734
+ const component = home && groupAt(home, componentPath);
735
+ const declared = component?.$extensions[AXES][axis];
736
+ if (!declared) throw new SystemError(`${id}: "${componentPath.join(".")}" has no axis "${axis}". Axes are declared by the component in $extensions["${AXES}"].`);
737
+ const states = component.$extensions[STATES];
738
+ const values = declared.from === "states" ? states.variants : declared.values;
739
+ if (!values.includes(decl.from)) throw new SystemError(`${id}: "from" must be an existing ${axis} (${values.join(", ")}), not "${decl.from}"`);
740
+ if (values.includes(value)) return `${id}: "${value}" is now a core ${axis} of ${componentPath.join(".")}; this declaration can be deleted (values under "tokens" still apply).`;
741
+ if ((states?.states ?? []).includes(value)) throw new SystemError(`${id}: "${value}" is an interaction state; states are not extensible`);
742
+ if (declared.from === "states") {
743
+ if (component[value]) throw new SystemError(`${id}: "${componentPath.join(".")}.${value}" already exists`);
744
+ const copy = clone2(component[decl.from]);
745
+ const own = `{${[...componentPath, decl.from].join(".")}.`;
746
+ for (const { token } of tokensUnder(copy)) {
747
+ if (typeof token.$value === "string" && token.$value.startsWith(own)) token.$value = `{${[...componentPath, value].join(".")}.${token.$value.slice(own.length)}`;
748
+ stamp(token, decl);
749
+ }
750
+ component[value] = copy;
751
+ states.variants = [...states.variants, value];
752
+ } else {
753
+ for (const member of declared.members) {
754
+ const group = groupAt(home, [...componentPath, ...member.split(".")]);
755
+ if (!group || !isToken(group[decl.from])) throw new SystemError(`${id}: axis member "${member}" has no "${decl.from}"`);
756
+ const copy = clone2(group[decl.from]);
757
+ const factor = typeof decl.scale === "object" ? decl.scale[member] : decl.scale;
758
+ scaleNode(copy, factor, `${componentPath.join(".")}.${member}.${value}`, copy.$type ?? group.$type);
759
+ stamp(copy, decl);
760
+ group[value] = copy;
761
+ }
762
+ if (typeof decl.scale === "object") {
763
+ for (const member of Object.keys(decl.scale)) if (!declared.members.includes(member)) throw new SystemError(`${id}: "scale" names "${member}", which is not a member of the ${axis} axis (${declared.members.join(", ")})`);
764
+ }
765
+ declared.values = [...declared.values, value];
766
+ }
767
+ (declared.extensions ??= []).push({ value, declaredBy: decl.declaredBy });
768
+ return null;
769
+ }
770
+ function addGroup(docs, id, decl) {
771
+ const segments2 = id.split(".");
772
+ const name = segments2.at(-1);
773
+ const home = Object.values(docs).find((doc) => groupAt(doc, segments2.slice(0, -1)));
774
+ const series = home && groupAt(home, segments2.slice(0, -1));
775
+ const siblings = series ? Object.keys(series).filter((key) => !key.startsWith("$") && !isToken(series[key])) : [];
776
+ if (!series || !siblings.length) throw new SystemError(`${id}: "${segments2.slice(0, -1).join(".")}" is not a series whose steps are groups of tokens (such as ${segments2[0]}.sys.motion.spring.standard). A single token is declared with "$type", not "from".`);
777
+ if (series[name]) return `${id}: "${name}" is now a core step of ${segments2.slice(0, -1).join(".")}; this declaration can be deleted (values under "tokens" still apply).`;
778
+ if (!siblings.includes(decl.from)) throw new SystemError(`${id}: "from" must be an existing step of ${segments2.slice(0, -1).join(".")} (${siblings.join(", ")}), not "${decl.from}"`);
779
+ if (decl.scale !== void 0) throw new SystemError(`${id}: "scale" does not apply to a cloned step; change its fields under "tokens"`);
780
+ if (Object.entries(series[decl.from]).some(([key, child]) => !key.startsWith("$") && !isToken(child))) throw new SystemError(`${id}: "${decl.from}" is not a step but a group of steps. A cloned step is one named set of tokens, e.g. ${segments2.slice(0, -1).join(".")}.${decl.from}.<name>.`);
781
+ const copy = clone2(series[decl.from]);
782
+ for (const { token } of tokensUnder(copy)) stamp(token, decl);
783
+ if (decl.description) copy.$description = decl.description;
784
+ series[name] = copy;
785
+ return null;
786
+ }
787
+ function addToken(docs, id, decl, core, system) {
788
+ const CORE_NS = system.namespace ?? "tanrei";
789
+ const segments2 = id.split(".");
790
+ if (core.has(id)) {
791
+ const existing = core.get(id);
792
+ if (existing.type !== decl.type) throw new SystemError(`${id}: core now has this id as "${existing.type}", not "${decl.type}". Rename the extension.`);
793
+ const { $value: $value2, derive: derive2, reason: reason2 } = decl.definition;
794
+ if (!system.tokens[id] && ($value2 !== void 0 || derive2)) system.tokens[id] = { ...$value2 !== void 0 ? { $value: $value2, reason: reason2 ?? decl.rationale } : {}, ...derive2 ? { derive: derive2 } : {}, layer: decl.declaredBy };
795
+ return `${id}: now a core token; this declaration can be deleted (its value still applies).`;
796
+ }
797
+ if (!decl.type) throw new SystemError(`${id}: a declared token needs "$type"`);
798
+ const namespace = segments2[0];
799
+ let owner;
800
+ if (namespace === CORE_NS) {
801
+ owner = ownerOf(docs, segments2);
802
+ if (!owner || owner.depth < segments2.length - 1) throw new SystemError(`${id}: "${segments2.slice(0, -1).join(".")}" is not a group of the vocabulary. Inside ${CORE_NS}.* a layer adds a step to an existing series (e.g. ${CORE_NS}.sys.space.\u2026); for anything new use your layer's own namespace.`);
803
+ } else {
804
+ const name = `ext/${namespace}.tokens.json`;
805
+ docs[name] ??= {};
806
+ owner = { name, doc: docs[name] };
807
+ }
808
+ let node = owner.doc;
809
+ for (const key of segments2.slice(0, -1)) {
810
+ if (isToken(node[key])) throw new SystemError(`${id}: "${key}" is a token; a token cannot have children`);
811
+ node = node[key] ??= {};
812
+ }
813
+ if (node[segments2.at(-1)]) throw new SystemError(`${id}: a group with this name already exists`);
814
+ const { $value, derive, reason } = decl.definition;
815
+ if (decl.type === "typography" && $value === void 0 && derive) throw new SystemError(`${id}: a text style declared with "derive" alone has no fontFamily, fontWeight or lineHeight \u2014 its rules value only fontSize and letterSpacing. Write "$value" with the whole style, e.g. { "fontFamily": "{${CORE_NS}.ref.typeface.plain}", "fontSize": { "value": 14, "unit": "px" }, "fontWeight": 400, "letterSpacing": { "value": 0, "unit": "px" }, "lineHeight": 1.5 }, and keep "derive" for the fields that follow the dials; or alias an existing style with "$value": "{${CORE_NS}.sys.typescale.<role>}" and no "derive".`);
816
+ const token = { $type: decl.type, $value: $value === void 0 ? null : clone2($value) };
817
+ if (derive) token.$extensions = { [DERIVE]: clone2(derive) };
818
+ else if ($value !== void 0 && !isRef3($value)) token.$extensions = { [DERIVE]: { fixed: reason ?? decl.rationale } };
819
+ stamp(token, decl);
820
+ node[segments2.at(-1)] = token;
821
+ return null;
822
+ }
823
+ function materializeVocabulary(docs, system) {
824
+ const vocabulary = system.vocabulary ?? {};
825
+ const SYS_COLOR4 = `${system.namespace ?? "tanrei"}.sys.color.`;
826
+ const notices = [];
827
+ if (!Object.keys(vocabulary).length) return notices;
828
+ const core = /* @__PURE__ */ new Map();
829
+ for (const doc of Object.values(docs)) for (const entry of walkTokens(doc)) core.set(entry.id, entry);
830
+ const ordered = Object.entries(vocabulary).sort(([, a], [, b]) => Number(a.kind === "axis-value") - Number(b.kind === "axis-value"));
831
+ for (const [id, decl] of ordered) {
832
+ if (decl.kind === "token" && id.startsWith(SYS_COLOR4)) continue;
833
+ const notice = decl.kind === "axis-value" ? addAxisValue(docs, id, decl) : decl.kind === "group" ? addGroup(docs, id, decl) : addToken(docs, id, decl, core, system);
834
+ if (notice) notices.push(notice);
835
+ }
836
+ return notices;
837
+ }
838
+ function listExtensions(system) {
839
+ return Object.entries(system.vocabulary ?? {}).map(([id, d]) => ({ id, kind: d.kind, ...d.type ? { $type: d.type } : {}, ...d.from ? { from: d.from } : {}, declaredBy: d.declaredBy, rationale: d.rationale }));
840
+ }
841
+
842
+ // ../token-engine/src/system.js
843
+ var DEFAULT_NAMESPACE2 = "tanrei";
844
+ var isRef4 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
845
+ var refId3 = (v) => v.slice(1, -1);
846
+ var clone3 = (v) => JSON.parse(JSON.stringify(v));
847
+ function mergeLayers(layers, { namespace = DEFAULT_NAMESPACE2 } = {}) {
848
+ const SYS_COLOR4 = `${namespace}.sys.color.`;
849
+ const merged = { id: layers.at(-1).id, namespace, name: layers.at(-1).name, specVersion: layers[0].specVersion, palettes: {}, tokens: {}, rules: [], chain: layers.map((l) => l.id), vocabulary: collectVocabulary(layers, { namespace }), notices: [] };
850
+ for (const layer of layers) {
851
+ for (const [id, decl] of Object.entries(merged.vocabulary)) {
852
+ if (decl.declaredBy === layer.id && decl.kind === "token" && id.startsWith(SYS_COLOR4)) merged.tokens[id] = { ...clone3(decl.definition), layer: layer.id };
853
+ }
854
+ if (layer.specVersion) merged.specVersion = layer.specVersion;
855
+ for (const [name, declaration] of Object.entries(layer.palettes ?? {})) {
856
+ if (declaration === null) delete merged.palettes[name];
857
+ else merged.palettes[name] = clone3(declaration);
858
+ }
859
+ merged.rules.push(...clone3(layer.rules ?? []).map((rule) => ({ ...rule, layer: void 0 })));
860
+ for (const [id, op] of Object.entries(layer.tokens ?? {})) {
861
+ const previous = merged.tokens[id];
862
+ const replaces = "$value" in op || "derive" in op;
863
+ const inherited = replaces ? 1 : previous?.scale ?? 1;
864
+ const own = op.scale ?? 1;
865
+ let scale;
866
+ if (typeof inherited === "number" && typeof own === "number") scale = inherited * own;
867
+ else {
868
+ const fields = (v) => typeof v === "number" ? { fontSize: v } : v;
869
+ const [x, y] = [fields(inherited), fields(own)];
870
+ scale = Object.fromEntries([.../* @__PURE__ */ new Set([...Object.keys(x), ...Object.keys(y)])].map((field) => [field, (x[field] ?? 1) * (y[field] ?? 1)]));
871
+ }
872
+ merged.tokens[id] = { ...replaces ? {} : previous, ...clone3(op), ...scale !== 1 ? { scale } : {}, layer: layer.id };
873
+ if (scale === 1) delete merged.tokens[id].scale;
874
+ }
875
+ }
876
+ return merged;
877
+ }
878
+ function scaleRule(rule, factor, id) {
879
+ if (!rule || "fixed" in rule) throw new SystemError(`${id}: cannot scale a fixed value \u2014 set "$value" instead`);
880
+ if (rule.fn === "mul") return { ...rule, by: rule.by * factor };
881
+ throw new SystemError(`${id}: "scale" is supported on "mul" rules and aliases, not on "${rule.fn}"`);
882
+ }
883
+ function generatedFrom(id, op, type, { namespace, stateIds }) {
884
+ if (id.startsWith(`${namespace}.sys.color.`)) return "roles";
885
+ if (stateIds.has(id)) return "states";
886
+ if (type === "color" && id.startsWith(`${namespace}.comp.`) && isColorRule(op)) return "colors";
887
+ return null;
888
+ }
889
+ var stateIdsOf = (documents) => new Set(expandStateVocabulary(Object.entries(documents).filter(([name]) => name.startsWith("comp/")).map(([, doc]) => doc)).map((v) => v.id));
890
+ function resolveNumericTokens(sources, system) {
891
+ const NS3 = system.namespace ?? DEFAULT_NAMESPACE2;
892
+ const SYS_COLOR4 = `${NS3}.sys.color.`;
893
+ const isColorRef = (id) => id.startsWith(SYS_COLOR4) || id.startsWith(`${NS3}.ref.palette.`) || id.startsWith(`${NS3}.ref.alpha.`);
894
+ const docs = Object.fromEntries(Object.entries(sources).map(([name, doc]) => [name, clone3(doc)]));
895
+ const work = { ...system, tokens: clone3(system.tokens) };
896
+ system.notices = materializeVocabulary(docs, work);
897
+ const index = /* @__PURE__ */ new Map();
898
+ for (const doc of Object.values(docs)) for (const entry of walkTokens(doc)) index.set(entry.id, entry);
899
+ const stateIds = stateIdsOf(docs);
900
+ for (const [id, op] of Object.entries(work.tokens)) {
901
+ const entry = index.get(id);
902
+ const generated = generatedFrom(id, op, entry?.type, { namespace: NS3, stateIds });
903
+ if (generated === "roles" || generated === "states") continue;
904
+ if (!entry) throw new SystemError(`${id}: unknown token (layer "${op.layer}"). To add it, declare it under "vocabulary" with a rationale.`);
905
+ if (op.$type && op.$type !== entry.type) throw new SystemError(`${id}: a layer cannot change $type (${entry.type} \u2192 ${op.$type})`);
906
+ if (generated) continue;
907
+ const token = entry.token;
908
+ const ext = token.$extensions ??= {};
909
+ const names = ext[ENUM]?.values;
910
+ if (names) {
911
+ if ("scale" in op || "derive" in op) throw new SystemError(`${id}: a choice of kind is neither scaled nor derived. Choose one of its names: { "$value": "${names[1] ?? names[0]}", "reason": "\u2026" } (${names.join(" | ")}).`);
912
+ if ("$value" in op && !isRef4(op.$value)) {
913
+ const index2 = typeof op.$value === "string" ? names.indexOf(op.$value) : op.$value;
914
+ if (!Number.isInteger(index2) || index2 < 0 || index2 >= names.length) throw new SystemError(`${id}: ${JSON.stringify(op.$value)} is not one of its choices (layer "${op.layer}"). Allowed: ${names.map((name, i) => `"${name}" (${i})`).join(", ")}. The list is part of the vocabulary; a layer chooses among the names, it does not add one.`);
915
+ op.$value = index2;
916
+ }
917
+ }
918
+ if ("$value" in op) {
919
+ if (isRef4(op.$value)) {
920
+ if (!index.has(refId3(op.$value)) && !isColorRef(refId3(op.$value))) throw new SystemError(`${id}: alias target ${op.$value} does not exist`);
921
+ token.$value = op.$value;
922
+ delete ext[DERIVE];
923
+ } else {
924
+ if (typeof op.reason !== "string" || op.reason.length < 8) throw new SystemError(`${id}: pinning a fixed value needs a "reason"`);
925
+ if (entry.type === "typography" && typeof op.$value === "object") {
926
+ const rule = clone3(ext[DERIVE] ?? {});
927
+ for (const field of Object.keys(op.$value)) delete rule[field];
928
+ token.$value = { ...token.$value, ...op.$value };
929
+ ext[DERIVE] = Object.keys(rule).length ? { ...rule, pinned: { fields: Object.keys(op.$value), reason: op.reason } } : { fixed: op.reason };
930
+ } else {
931
+ token.$value = op.$value;
932
+ ext[DERIVE] = { fixed: op.reason };
933
+ }
934
+ }
935
+ }
936
+ if ("derive" in op) {
937
+ const pinned = ext[DERIVE]?.pinned;
938
+ if (isRef4(token.$value) && entry.type !== "typography") token.$value = null;
939
+ ext[DERIVE] = clone3(op.derive);
940
+ if (pinned) for (const field of pinned.fields) delete ext[DERIVE][field];
941
+ if (pinned) ext[DERIVE].pinned = pinned;
942
+ }
943
+ if ("scale" in op) {
944
+ const factors = typeof op.scale === "number" ? null : op.scale;
945
+ if (isRef4(token.$value) && entry.type === "typography") throw new SystemError(`${id}: "scale" does not apply to an alias of a text style. Re-point it to another text style, or scale ${token.$value} itself.`);
946
+ if (isRef4(token.$value)) {
947
+ ext[DERIVE] = { fn: "mul", of: token.$value, by: op.scale };
948
+ token.$value = null;
949
+ } else if (entry.type === "typography") {
950
+ const rule = ext[DERIVE];
951
+ const f = factors ?? { fontSize: op.scale };
952
+ for (const [field, n] of Object.entries(f)) rule[field] = scaleRule(rule[field], n, `${id}.${field}`);
953
+ } else {
954
+ ext[DERIVE] = scaleRule(ext[DERIVE], op.scale, id);
955
+ }
956
+ }
957
+ }
958
+ for (const [id, { token }] of index) if (token.$value === null && !token.$extensions?.[DERIVE]) throw new SystemError(`${id}: declared under "vocabulary" but never given a value \u2014 add "$value" or "derive" to the declaration, or an entry under "tokens"`);
959
+ const state = /* @__PURE__ */ new Map();
960
+ const resolve = (id, trail = []) => {
961
+ if (isColorRef(id)) return { color: id };
962
+ const entry = index.get(id);
963
+ if (!entry) throw new SystemError(`${trail.at(-1) ?? "?"}: references unknown token {${id}}`);
964
+ if (trail.length && trail.at(-1).startsWith(`${NS3}.`) && !id.startsWith(`${NS3}.`)) throw new SystemError(`${trail.at(-1)}: a ${NS3}.* token cannot reference {${id}}, a token in a layer's own namespace`);
965
+ if (state.get(id) === "visiting") throw new SystemError(`cycle: ${[...trail, id].join(" \u2192 ")}`);
966
+ const { token, type } = entry;
967
+ if (state.get(id) !== "done") {
968
+ state.set(id, "visiting");
969
+ const rule = token.$extensions?.[DERIVE];
970
+ const lookup = (dep) => resolve(dep, [...trail, id]);
971
+ if (isRef4(token.$value)) resolve(refId3(token.$value), [...trail, id]);
972
+ else if (rule && !("fixed" in rule)) {
973
+ if (type === "typography") {
974
+ if (!token.$value || typeof token.$value !== "object") throw new SystemError(`${id}: a text style's "derive" values its fontSize and letterSpacing, and this one has no style to write them into (${JSON.stringify(token.$value)}). Give it "$value" with the whole style \u2014 fontFamily, fontSize, fontWeight, letterSpacing, lineHeight \u2014 and keep "derive" for the fields that follow the dials.`);
975
+ if (rule.fontSize) token.$value.fontSize = evaluateNumeric(rule.fontSize, lookup, { type: "dimension" });
976
+ if (rule.letterSpacing) token.$value.letterSpacing = evaluateNumeric(rule.letterSpacing, lookup, { type: "dimension", fontSize: token.$value.fontSize.value });
977
+ } else {
978
+ const result = evaluateNumeric(rule, lookup, { type });
979
+ token.$value = type === "number" ? result.value : result;
980
+ }
981
+ }
982
+ state.set(id, "done");
983
+ }
984
+ const v = isRef4(token.$value) ? resolve(refId3(token.$value), [...trail, id]) : token.$value;
985
+ return typeof v === "number" ? { value: v } : v;
986
+ };
987
+ for (const id of index.keys()) resolve(id);
988
+ for (const [id, { token }] of index) for (const dep of ruleDependencies(token.$extensions?.[DERIVE])) if (!index.has(dep) && !isColorRef(dep)) throw new SystemError(`${id}: rule references unknown token {${dep}}`);
989
+ return docs;
990
+ }
991
+
992
+ // ../tokens-build/src/bundle.js
993
+ import fs2 from "node:fs";
994
+ import path3 from "node:path";
995
+ import Ajv2020 from "ajv/dist/2020.js";
996
+
997
+ // ../../tanrei.config.json
998
+ var tanrei_config_default = {
999
+ $comment: "Single source for naming. Every generated artifact derives names from here; never hardcode them elsewhere. Checked by `pnpm validate`.",
1000
+ name: "Tanrei",
1001
+ namespace: "tanrei",
1002
+ version: "0.1.0-next.0",
1003
+ license: "Apache-2.0",
1004
+ repository: {
1005
+ public: "chnotchy/tanrei"
1006
+ },
1007
+ packages: {
1008
+ npmScope: "@tanrei",
1009
+ swiftPackage: "Tanrei",
1010
+ mavenGroup: "io.github.chnotchy",
1011
+ mavenArtifactPrefix: "tanrei",
1012
+ pubPackage: "tanrei"
1013
+ },
1014
+ web: {
1015
+ cssPrefix: "--tanrei",
1016
+ tagPrefix: "tanrei"
1017
+ },
1018
+ platforms: ["web", "swiftui", "compose", "flutter", "react-native"],
1019
+ statuses: ["planned", "lagging", "alpha", "beta", "stable", "deprecated"]
1020
+ };
1021
+
1022
+ // ../tokens-build/src/config.js
1023
+ var CONFIG = tanrei_config_default;
1024
+
1025
+ // ../tokens-build/src/pure.js
1026
+ var SYSTEM_ID = /^[a-z0-9][a-z0-9-]*$/;
1027
+ var isSystemId = (value) => typeof value === "string" && SYSTEM_ID.test(value);
1028
+ function assertSystemId(value, where = '"extends"') {
1029
+ if (!isSystemId(value)) throw new Error(`${where}: ${JSON.stringify(value) ?? String(value)} is not a system id (lowercase letters, digits and hyphens: ${SYSTEM_ID.source}). A parent layer is named by its id, never by a path.`);
1030
+ return value;
1031
+ }
1032
+ var kebab = (parts) => parts.join("-");
1033
+ function rgba(color) {
1034
+ const [r, g, b] = color.components.map((c) => Math.round(c * 255));
1035
+ return { r, g, b, a: color.alpha ?? 1 };
1036
+ }
1037
+
1038
+ // ../tokens-build/src/scheme.js
1039
+ import crypto from "node:crypto";
1040
+ import fs from "node:fs";
1041
+ import path2 from "node:path";
1042
+
1043
+ // ../tokens-build/src/mcu.js
1044
+ import { createRequire } from "node:module";
1045
+ import path from "node:path";
1046
+ import { pathToFileURL } from "node:url";
1047
+ var require2 = createRequire(import.meta.url);
1048
+ var root = path.dirname(require2.resolve("@material/material-color-utilities"));
1049
+ var load = (p) => import(pathToFileURL(path.join(root, p)).href);
1050
+ var { Hct } = await load("hct/hct.js");
1051
+ var { TonalPalette } = await load("palettes/tonal_palette.js");
1052
+
1053
+ // ../tokens-build/src/scheme.js
1054
+ var NAMESPACE = CONFIG.namespace;
1055
+ var engine = createPaletteEngine({ Hct, TonalPalette, namespace: NAMESPACE });
1056
+ var systemPath = (id) => `tokens/systems/${id}.system.json`;
1057
+ function loadSystem(repoRoot, id = NAMESPACE) {
1058
+ assertSystemId(id, "a shipped system");
1059
+ return JSON.parse(fs.readFileSync(path2.join(repoRoot, systemPath(id)), "utf8"));
1060
+ }
1061
+ function colorVocabulary(repoRoot) {
1062
+ return JSON.parse(fs.readFileSync(path2.join(repoRoot, "tokens/sys/color.vocabulary.json"), "utf8"));
1063
+ }
1064
+ function generateSchemeFiles(system, repoRoot, documents) {
1065
+ const merged = system.chain ? system : mergeLayers([system], { namespace: NAMESPACE });
1066
+ const docs = documents ?? resolveNumericTokens(sourceFiles(repoRoot), merged);
1067
+ return engine.generateColorFiles(merged, { sourcePath: systemPath(merged.id), vocabulary: colorVocabulary(repoRoot), documents: docs });
1068
+ }
1069
+ function sourcePaths(repoRoot) {
1070
+ const dir = path2.join(repoRoot, "tokens");
1071
+ const resolverFile = `${NAMESPACE}.resolver.json`;
1072
+ const resolver = JSON.parse(fs.readFileSync(path2.join(dir, resolverFile), "utf8"));
1073
+ const refs = Object.values(resolver.sets).flatMap((set) => set.sources.map((s) => s.$ref)).filter((ref) => !ref.startsWith("generated/"));
1074
+ return { dir, resolverFile, refs };
1075
+ }
1076
+ function sourceFiles(repoRoot) {
1077
+ const { dir, refs } = sourcePaths(repoRoot);
1078
+ return Object.fromEntries(refs.map((ref) => [ref, JSON.parse(fs.readFileSync(path2.join(dir, ref), "utf8"))]));
1079
+ }
1080
+ function vocabularyDigest(repoRoot) {
1081
+ const { dir, resolverFile, refs } = sourcePaths(repoRoot);
1082
+ const files = [resolverFile, ...refs, "sys/color.vocabulary.json"];
1083
+ const stamp2 = (file) => {
1084
+ try {
1085
+ const { size, mtimeMs } = fs.statSync(path2.join(dir, file));
1086
+ return `${file}:${size}:${mtimeMs}`;
1087
+ } catch {
1088
+ return `${file}:missing`;
1089
+ }
1090
+ };
1091
+ return crypto.createHash("sha256").update(files.map(stamp2).join("\n")).digest("hex").slice(0, 32);
1092
+ }
1093
+
1094
+ // ../tokens-build/src/bundle.js
1095
+ var ROOT_SYSTEM = CONFIG.namespace;
1096
+ var RECIPE = "dev.tanrei.system";
1097
+ function listSystems(repoRoot) {
1098
+ return fs2.readdirSync(path3.join(repoRoot, "tokens/systems")).filter((f) => f.endsWith(".system.json")).map((f) => f.replace(".system.json", "")).sort();
1099
+ }
1100
+ var validateLayer;
1101
+ function validateLayerFile(repoRoot, layer, fileId) {
1102
+ if (!validateLayer) {
1103
+ const schema = JSON.parse(fs2.readFileSync(path3.join(repoRoot, "tokens/schema/system.schema.json"), "utf8"));
1104
+ validateLayer = new Ajv2020({ allErrors: true, strict: false }).compile(schema);
1105
+ }
1106
+ const problems = validateLayer(layer) ? [] : validateLayer.errors.map((e) => `${fileId}.system.json ${e.instancePath || "/"} ${e.message}`);
1107
+ if (layer.id !== fileId) problems.push(`${fileId}.system.json: "id" must equal the file name`);
1108
+ if (fileId === ROOT_SYSTEM ? "extends" in layer : !layer.extends) problems.push(`${fileId}.system.json: only the root layer "${ROOT_SYSTEM}" omits "extends"`);
1109
+ return problems;
1110
+ }
1111
+ function layerChain(id, read) {
1112
+ const chain = [];
1113
+ const seen = /* @__PURE__ */ new Set();
1114
+ for (let current = id; current; current = chain[0].extends) {
1115
+ if (chain.length) assertSystemId(current, `${chain[0].id}.system.json "extends"`);
1116
+ if (seen.has(current)) throw new Error(`"extends" cycle: ${[...seen, current].join(" \u2192 ")}`);
1117
+ seen.add(current);
1118
+ chain.unshift(read(current));
1119
+ }
1120
+ if (chain[0].id !== ROOT_SYSTEM) throw new Error(`system "${id}" does not extend "${ROOT_SYSTEM}"`);
1121
+ return chain;
1122
+ }
1123
+ function buildBundle(repoRoot, chain) {
1124
+ const system = mergeLayers(chain, { namespace: CONFIG.namespace });
1125
+ const files = resolveNumericTokens(sourceFiles(repoRoot), system);
1126
+ for (const [name, doc] of Object.entries(generateSchemeFiles(system, repoRoot, files))) files[`generated/${name}`] = doc;
1127
+ const resolver = JSON.parse(fs2.readFileSync(path3.join(repoRoot, "tokens", `${ROOT_SYSTEM}.resolver.json`), "utf8"));
1128
+ resolver.name = system.name ?? system.id;
1129
+ resolver.description = `Design system "${system.id}" (${system.chain.join(" \u2190 ")}), fully valued. Generated by Tanrei; do not edit.`;
1130
+ const own = Object.keys(files).filter((name) => name.startsWith("ext/")).sort();
1131
+ if (own.length) resolver.resolutionOrder.push({ $ref: "#/sets/ext" });
1132
+ if (own.length) resolver.sets.ext = { description: "Tokens that layers of this system declare in their own namespace.", sources: own.map((name) => ({ $ref: name })) };
1133
+ files[`${system.id}.resolver.json`] = resolver;
1134
+ const dial = files["dial/dial.tokens.json"];
1135
+ const extensions = listExtensions(system);
1136
+ files["dial/dial.tokens.json"] = { $extensions: { [RECIPE]: { id: system.id, chain: system.chain, ...extensions.length ? { extensions } : {}, layers: chain } }, ...dial };
1137
+ return { system, files };
1138
+ }
1139
+
1140
+ // ../tokens-build/src/model.js
1141
+ import fs3 from "node:fs";
1142
+ import path4 from "node:path";
1143
+ import { fileURLToPath, pathToFileURL as pathToFileURL2 } from "node:url";
1144
+
1145
+ // ../tokens-build/src/reader.js
1146
+ var TokenReadError = class extends Error {
1147
+ };
1148
+ var collator = new Intl.Collator("en-us", { numeric: true });
1149
+ var ALIAS = /^\{([^}]+)\}$/;
1150
+ var isAlias = (value) => typeof value === "string" && ALIAS.test(value);
1151
+ var isObject = (value) => value !== null && typeof value === "object";
1152
+ var DTCG_TYPES = /* @__PURE__ */ new Set(["color", "dimension", "fontFamily", "fontWeight", "duration", "cubicBezier", "number", "strokeStyle", "border", "transition", "shadow", "gradient", "typography"]);
1153
+ var NESTED = {
1154
+ border: { color: ["color"], stroke: ["strokeStyle"], width: ["dimension"] },
1155
+ gradient: { color: ["color"], position: ["number"] },
1156
+ shadow: { color: ["color"], offsetX: ["dimension"], offsetY: ["dimension"], blur: ["dimension"], spread: ["dimension"], inset: ["boolean"] },
1157
+ strokeStyle: { dashArray: ["dimension"] },
1158
+ transition: { duration: ["duration"], delay: ["duration"], timingFunction: ["cubicBezier"] },
1159
+ typography: { fontFamily: ["fontFamily"], fontWeight: ["fontWeight"], fontSize: ["dimension"], lineHeight: ["dimension", "number"], letterSpacing: ["dimension"], paragraphSpacing: ["dimension", "string"], wordSpacing: ["dimension", "string"] }
1160
+ };
1161
+ var FONT_WEIGHTS = {
1162
+ thin: 100,
1163
+ hairline: 100,
1164
+ "extra-light": 200,
1165
+ "ultra-light": 200,
1166
+ light: 300,
1167
+ normal: 400,
1168
+ regular: 400,
1169
+ book: 400,
1170
+ medium: 500,
1171
+ "semi-bold": 600,
1172
+ "demi-bold": 600,
1173
+ bold: 700,
1174
+ "extra-bold": 800,
1175
+ "ultra-bold": 800,
1176
+ black: 900,
1177
+ heavy: 900,
1178
+ "extra-black": 950,
1179
+ "ultra-black": 950
1180
+ };
1181
+ function merge(under, over2) {
1182
+ if (under === void 0 || !isObject(over2) || Array.isArray(over2)) return over2;
1183
+ if (under === null) return null;
1184
+ if (typeof under !== "object") return over2;
1185
+ const out = Array.isArray(under) ? [...under] : { ...under };
1186
+ for (const key of Object.keys(over2)) out[key] = Object.hasOwn(under, key) ? merge(under[key], over2[key]) : over2[key];
1187
+ return out;
1188
+ }
1189
+ var GROUP_KEYS = /* @__PURE__ */ new Set(["$type", "$description", "$deprecated", "$extensions", "$value", "$schema"]);
1190
+ var resolvedForms = /* @__PURE__ */ new WeakMap();
1191
+ var normalForms = /* @__PURE__ */ new WeakMap();
1192
+ function normalColor(value, id) {
1193
+ if (typeof value === "string" && !isAlias(value)) throw new TokenReadError(`${id}: a color written as a string ("${value}") is not read; write it in the object notation`);
1194
+ if (!isObject(value) || value.alpha !== void 0) return value;
1195
+ return normalForm(value, "color", () => ({ ...value, alpha: 1 }));
1196
+ }
1197
+ function normalForm(value, type, make) {
1198
+ let forms = normalForms.get(value);
1199
+ if (!forms) normalForms.set(value, forms = /* @__PURE__ */ new Map());
1200
+ if (!forms.has(type)) forms.set(type, make());
1201
+ return forms.get(type);
1202
+ }
1203
+ var fontFamily = (value) => typeof value === "string" ? [value] : value;
1204
+ var fontWeight = (value) => typeof value === "string" && FONT_WEIGHTS[value] || value;
1205
+ function withFields(value, changes) {
1206
+ let out = value;
1207
+ for (const [key, next] of changes) {
1208
+ if (next === value[key] && key in value) continue;
1209
+ if (out === value) out = Array.isArray(value) ? [...value] : { ...value };
1210
+ out[key] = next;
1211
+ }
1212
+ return out;
1213
+ }
1214
+ function normalize(value, type, id) {
1215
+ switch (type) {
1216
+ case "color":
1217
+ return normalColor(value, id);
1218
+ case "fontFamily":
1219
+ return fontFamily(value);
1220
+ case "fontWeight":
1221
+ return fontWeight(value);
1222
+ case "border":
1223
+ return isObject(value) && value.color ? normalForm(value, type, () => withFields(value, [["color", normalColor(value.color, id)]])) : value;
1224
+ case "shadow": {
1225
+ const layer = (shadow) => isObject(shadow) ? withFields(shadow, [...shadow.color ? [["color", normalColor(shadow.color, id)]] : [], ..."inset" in shadow ? [] : [["inset", false]]]) : shadow;
1226
+ if (!isObject(value)) return [value];
1227
+ return normalForm(value, type, () => Array.isArray(value) ? withFields(value, value.map((shadow, i) => [i, layer(shadow)])) : [layer(value)]);
1228
+ }
1229
+ case "gradient":
1230
+ if (!Array.isArray(value)) return value;
1231
+ return normalForm(value, type, () => withFields(value, value.map((stop, i) => [i, isObject(stop) && stop.color ? withFields(stop, [["color", normalColor(stop.color, id)]]) : stop])));
1232
+ case "transition":
1233
+ if (!isObject(value)) return value;
1234
+ return normalForm(value, type, () => withFields(value, [...value.duration ? [] : [["duration", { value: 0, unit: "ms" }]], ...value.delay ? [] : [["delay", { value: 0, unit: "ms" }]], ...value.timingFunction ? [] : [["timingFunction", [0, 0, 1, 1]]]]));
1235
+ case "typography":
1236
+ if (!isObject(value)) return value;
1237
+ return normalForm(value, type, () => withFields(value, [..."fontFamily" in value ? [["fontFamily", fontFamily(value.fontFamily)]] : [], ..."fontWeight" in value ? [["fontWeight", fontWeight(value.fontWeight)]] : []]));
1238
+ default:
1239
+ return value;
1240
+ }
1241
+ }
1242
+ var pointerPart = (part) => part.replaceAll("~", "~0").replaceAll("/", "~1");
1243
+ var Name = class _Name {
1244
+ constructor(parent, key) {
1245
+ this.id = parent ? parent.id ? `${parent.id}.${key}` : key : "";
1246
+ this.jsonID = parent ? `${parent.jsonID === "#/" ? "#" : parent.jsonID}/${pointerPart(key)}` : "#/";
1247
+ this.children = void 0;
1248
+ this.reference = void 0;
1249
+ this.rank = void 0;
1250
+ }
1251
+ child(key) {
1252
+ let child = (this.children ??= /* @__PURE__ */ new Map()).get(key);
1253
+ if (!child) this.children.set(key, child = new _Name(this, key));
1254
+ return child;
1255
+ }
1256
+ /** The reference a dependency is written as: the pointer of the token's value. */
1257
+ get ref() {
1258
+ return this.reference ??= `${this.jsonID}/$value`;
1259
+ }
1260
+ };
1261
+ var SCALARS = ["$type", "$description", "$deprecated", "$value", "$extensions", "aliasOf", "originalValue"];
1262
+ var LISTS = ["aliasChain", "aliasedBy", "dependencies"];
1263
+ var sameList = (a, b) => a === b || a !== void 0 && b !== void 0 && a.length === b.length && a.every((item, i) => item === b[i]);
1264
+ var sameShape = (a, b) => a === b || isObject(a) && isObject(b) && Array.isArray(a) === Array.isArray(b) && Object.keys(a).length === Object.keys(b).length && Object.keys(a).every((key) => key in b && sameShape(a[key], b[key]));
1265
+ function readBundle(files, systemId) {
1266
+ const name = `${systemId}.resolver.json`;
1267
+ const resolver = files[name];
1268
+ if (!resolver) throw new Error(`the bundle has no ${name}`);
1269
+ const documentOf = (source, where) => {
1270
+ if (typeof source?.$ref !== "string") return source;
1271
+ if (source.$ref.startsWith("#")) throw new TokenReadError(`${name} ${where}: a source that points into the resolver document ("${source.$ref}") is not read`);
1272
+ const doc = files[source.$ref];
1273
+ if (!doc) throw new Error(`the bundle has no ${source.$ref}`);
1274
+ return doc;
1275
+ };
1276
+ const steps = (resolver.resolutionOrder ?? []).map(({ $ref }, i) => {
1277
+ const [, kind, key] = /^#\/(sets|modifiers)\/(.+)$/.exec($ref ?? "") ?? [];
1278
+ const item = kind && resolver[kind]?.[key];
1279
+ if (!item) throw new TokenReadError(`${name} resolutionOrder[${i}]: "${$ref}" names no set and no modifier of this document`);
1280
+ return kind === "sets" ? { set: key, sources: item.sources ?? [] } : { modifier: key, contexts: item.contexts ?? {}, default: typeof item.default === "string" ? item.default : Object.keys(item.contexts ?? {})[0] };
1281
+ });
1282
+ const modifiers = steps.filter((step) => step.modifier);
1283
+ const schemeModifier = modifiers.find((step) => step.modifier === "scheme");
1284
+ const mergeSources = (tree, sources, where) => sources.reduce((acc, source) => merge(acc, documentOf(source, where)), tree);
1285
+ const firstModifier = steps.findIndex((step) => step.modifier);
1286
+ const shared = steps.slice(0, firstModifier < 0 ? steps.length : firstModifier);
1287
+ let common;
1288
+ const treeOf = (input) => {
1289
+ common ??= { tree: shared.reduce((tree2, step) => mergeSources(tree2, step.sources, `sets.${step.set}`), {}) };
1290
+ let tree = common.tree;
1291
+ for (const step of steps.slice(shared.length)) {
1292
+ if (step.set) tree = mergeSources(tree, step.sources, `sets.${step.set}`);
1293
+ else {
1294
+ const context = input[step.modifier] ?? step.default;
1295
+ if (!step.contexts[context]) throw new TokenReadError(`Modifier ${step.modifier} has no context ${JSON.stringify(context)}.`);
1296
+ tree = mergeSources(tree, step.contexts[context], `modifiers.${step.modifier}.contexts.${context}`);
1297
+ }
1298
+ }
1299
+ return tree;
1300
+ };
1301
+ const root2 = new Name();
1302
+ const canonical = /* @__PURE__ */ new Map();
1303
+ let sorted;
1304
+ const ranked = /* @__PURE__ */ new Set();
1305
+ const read = /* @__PURE__ */ new Map();
1306
+ function tokensOf(input) {
1307
+ const key = JSON.stringify(modifiers.map((step) => input[step.modifier] ?? step.default));
1308
+ if (!read.has(key)) read.set(key, resolveTree(treeOf(input)));
1309
+ return read.get(key);
1310
+ }
1311
+ function resolveTree(tree) {
1312
+ const entries = /* @__PURE__ */ new Map();
1313
+ const walk = (node, at, type, deprecated) => {
1314
+ const ownType = node.$type || type;
1315
+ const ownDeprecated = node.$deprecated ?? deprecated;
1316
+ if (Object.hasOwn(node, "$value")) entries.set(at.id, { name: at, node, type: ownType, deprecated: ownDeprecated, state: 0 });
1317
+ for (const key of Object.keys(node)) {
1318
+ const child = node[key];
1319
+ if (key.charCodeAt(0) === 36) {
1320
+ if (!GROUP_KEYS.has(key) && (key === "$ref" || key === "$extends" || key === "$root" || isObject(child))) throw new TokenReadError(`${at.id || "(the document)"}: "${key}" is not read by Tanrei's reader of its own bundles`);
1321
+ continue;
1322
+ }
1323
+ if (isObject(child) && !Array.isArray(child)) walk(child, at.child(key), ownType, ownDeprecated);
1324
+ }
1325
+ };
1326
+ walk(tree, root2, void 0, void 0);
1327
+ const fail = (entry, message) => {
1328
+ throw new TokenReadError(`${entry.name.id}: ${message}`);
1329
+ };
1330
+ const chainOf = (alias, entry) => {
1331
+ const target = entries.get(alias.slice(1, -1));
1332
+ if (!target) fail(entry, `Could not resolve alias ${alias}.`);
1333
+ if (target.way) return target.way;
1334
+ if (target.walking) fail(entry, "Circular alias detected.");
1335
+ target.walking = true;
1336
+ const links = isAlias(target.node.$value) ? [target, ...chainOf(target.node.$value, entry).links] : [target];
1337
+ target.walking = false;
1338
+ return target.way = { links, end: links.at(-1), ids: links.map((link) => link.name.id), refs: links.map((link) => link.name.ref).sort(collator.compare) };
1339
+ };
1340
+ const deep = (value, expected, path9, entry, partials) => {
1341
+ if (typeof value !== "string") {
1342
+ if (Array.isArray(value)) {
1343
+ const inner = expected?.includes("cubicBezier") ? ["number"] : expected;
1344
+ return withFields(value, value.flatMap((item, i) => item ? [[i, deep(item, inner, [...path9, i], entry, partials)]] : []));
1345
+ }
1346
+ const fields = isObject(value) && expected?.length ? NESTED[expected[0]] : void 0;
1347
+ return fields ? withFields(value, Object.keys(value).map((key) => [key, deep(value[key], fields[key], [...path9, key], entry, partials)])) : value;
1348
+ }
1349
+ if (!isAlias(value)) {
1350
+ if ((!expected?.[0] || DTCG_TYPES.has(expected[0])) && (value.includes("{") || value.includes("}"))) fail(entry, "Invalid alias syntax.");
1351
+ return value;
1352
+ }
1353
+ const way = chainOf(value, entry);
1354
+ if (expected?.length && !expected.includes(way.end.type)) fail(entry, `Cannot alias to $type "${way.end.type}" from $type "${expected.join(" / ")}".`);
1355
+ partials.push({ path: path9, way });
1356
+ return literal(way.end).value;
1357
+ };
1358
+ const literal = (entry) => {
1359
+ if (entry.state === 2) return entry;
1360
+ if (entry.state === 1) fail(entry, "Circular alias detected.");
1361
+ entry.state = 1;
1362
+ const raw = entry.node.$value;
1363
+ if (isObject(raw) && hasReference(raw)) fail(entry, `"$ref" inside a value is not read by Tanrei's reader of its own bundles`);
1364
+ entry.partials = [];
1365
+ entry.value = deep(raw, entry.type ? [entry.type] : void 0, [], entry, entry.partials);
1366
+ if (entry.value !== raw) {
1367
+ const ends = entry.partials.map((partial) => partial.way.end.value);
1368
+ const forms = resolvedForms.get(raw) ?? resolvedForms.set(raw, []).get(raw);
1369
+ const known = forms.find((form) => form.type === entry.type && sameList(form.ends, ends));
1370
+ if (known) entry.value = known.value;
1371
+ else forms.push({ type: entry.type, ends, value: entry.value });
1372
+ }
1373
+ entry.state = 2;
1374
+ return entry;
1375
+ };
1376
+ for (const entry of entries.values()) {
1377
+ const raw = entry.node.$value;
1378
+ if (!isAlias(raw)) {
1379
+ literal(entry);
1380
+ continue;
1381
+ }
1382
+ entry.walking = true;
1383
+ entry.chain = chainOf(raw, entry);
1384
+ entry.walking = false;
1385
+ const { end } = entry.chain;
1386
+ if (entry.type && entry.type !== end.type) fail(entry, `Cannot alias to $type "${end.type}" from $type "${entry.type}".`);
1387
+ entry.type ||= end.type;
1388
+ entry.value = literal(end).value || raw;
1389
+ }
1390
+ const aliasedBy = /* @__PURE__ */ new Map();
1391
+ const reached = (target, by) => {
1392
+ let set = aliasedBy.get(target);
1393
+ if (!set) aliasedBy.set(target, set = /* @__PURE__ */ new Set());
1394
+ set.add(by);
1395
+ };
1396
+ for (const entry of entries.values()) {
1397
+ for (const { links } of entry.chain ? [entry.chain] : entry.partials.map((partial) => partial.way)) {
1398
+ for (let i = 0; i < links.length; i += 1) {
1399
+ reached(links[i], entry.name);
1400
+ for (let j = 0; j < i; j += 1) reached(links[i], links[j].name);
1401
+ }
1402
+ }
1403
+ }
1404
+ const walked = [...entries.values()];
1405
+ if (!sorted || sorted.walked.length !== walked.length || !sorted.walked.every((at, i) => at === walked[i].name)) {
1406
+ const order = walked.map((entry) => entry.name).sort((a, b) => collator.compare(a.jsonID, b.jsonID));
1407
+ sorted = { walked: walked.map((entry) => entry.name), order };
1408
+ if (order.some((at) => at.rank === void 0)) {
1409
+ for (const at of order) ranked.add(at);
1410
+ [...ranked].sort((a, b) => collator.compare(a.id, b.id)).forEach((at, i) => at.rank = i);
1411
+ }
1412
+ }
1413
+ const byRank = (a, b) => a.rank - b.rank;
1414
+ const tokens = {};
1415
+ for (const at of sorted.order) {
1416
+ const entry = entries.get(at.id);
1417
+ const { node } = entry;
1418
+ const ways = entry.chain ? void 0 : entry.partials.map((partial) => partial.way);
1419
+ const token = {
1420
+ id: at.id,
1421
+ $type: entry.type,
1422
+ $description: node.$description || void 0,
1423
+ $deprecated: entry.deprecated ?? void 0,
1424
+ $value: normalize(entry.value, entry.type, at.id),
1425
+ $extensions: node.$extensions || void 0,
1426
+ aliasChain: entry.chain?.ids,
1427
+ aliasedBy: aliasedBy.has(entry) ? [...aliasedBy.get(entry)].sort(byRank).map((by) => by.id) : void 0,
1428
+ aliasOf: entry.chain?.end.name.id,
1429
+ partialAliasOf: entry.chain ? void 0 : partialAliases(entry),
1430
+ dependencies: entry.chain ? entry.chain.refs : ways.length === 1 ? ways[0].refs : ways.length ? [...new Set(ways.flatMap((way) => way.refs))].sort(collator.compare) : void 0,
1431
+ originalValue: node,
1432
+ jsonID: at.jsonID
1433
+ };
1434
+ tokens[at.id] = share(token);
1435
+ }
1436
+ return tokens;
1437
+ }
1438
+ function share(token) {
1439
+ const known = canonical.get(token.id);
1440
+ if (!known) return canonical.set(token.id, [token]), token;
1441
+ for (const other of known) {
1442
+ if (SCALARS.every((key) => token[key] === other[key]) && LISTS.every((key) => sameList(token[key], other[key])) && sameShape(token.partialAliasOf, other.partialAliasOf)) return other;
1443
+ }
1444
+ for (const key of LISTS) if (sameList(token[key], known[0][key])) token[key] = known[0][key];
1445
+ if (sameShape(token.partialAliasOf, known[0].partialAliasOf)) token.partialAliasOf = known[0].partialAliasOf;
1446
+ known.push(token);
1447
+ return token;
1448
+ }
1449
+ const reader = {
1450
+ schemes: Object.keys(schemeModifier?.contexts ?? {}),
1451
+ defaultScheme: schemeModifier?.default,
1452
+ /** The tokens of one scheme, by id. Read on first use, then kept. */
1453
+ tokens: (scheme) => tokensOf(scheme === void 0 ? {} : { scheme }),
1454
+ /** The same, in the words of a DTCG resolver: `apply({ scheme })`. */
1455
+ apply: (input = {}) => tokensOf(input)
1456
+ };
1457
+ return reader;
1458
+ }
1459
+ var referenceFree = /* @__PURE__ */ new WeakSet();
1460
+ function hasReference(value) {
1461
+ if (referenceFree.has(value)) return false;
1462
+ for (const [key, child] of Array.isArray(value) ? value.entries() : Object.entries(value)) {
1463
+ if (key === "$ref" || isObject(child) && hasReference(child)) return true;
1464
+ }
1465
+ referenceFree.add(value);
1466
+ return false;
1467
+ }
1468
+ function partialAliases(entry) {
1469
+ const value = entry.value;
1470
+ if (!entry.partials.length || !isObject(value)) return void 0;
1471
+ const loneShadow = entry.type === "shadow" && !Array.isArray(value);
1472
+ const out = Array.isArray(value) || entry.type === "shadow" ? [] : {};
1473
+ for (const { path: path9, way } of entry.partials) {
1474
+ if (!path9.length) continue;
1475
+ if (loneShadow && !out.length) out.push({});
1476
+ let into = loneShadow ? out[0] : out;
1477
+ let node = value;
1478
+ path9.forEach((key, i) => {
1479
+ if (isObject(node) && key in node && node[key] !== void 0) node = node[key];
1480
+ if (i === path9.length - 1) into[key] = way.ids[0];
1481
+ if (!(key in into)) into[key] = Array.isArray(node) ? [] : {};
1482
+ into = into[key];
1483
+ });
1484
+ }
1485
+ return out;
1486
+ }
1487
+
1488
+ // ../tokens-build/src/model.js
1489
+ var REPO_ROOT = process.env.TANREI_VOCABULARY_ROOT ? path4.resolve(process.env.TANREI_VOCABULARY_ROOT) : path4.resolve(path4.dirname(fileURLToPath(import.meta.url)), "../../..");
1490
+ var TOKENS_DIR = path4.join(REPO_ROOT, "tokens");
1491
+ var NS = CONFIG.namespace;
1492
+ var MEMORY = new URL("file:///tanrei-bundle-in-memory/");
1493
+ function componentDeclarations(bundleDir, systemId, read = (name) => JSON.parse(fs3.readFileSync(path4.join(bundleDir, name), "utf8"))) {
1494
+ const resolver = read(`${systemId}.resolver.json`);
1495
+ const out = {};
1496
+ for (const { $ref } of resolver.sets.comp?.sources ?? []) {
1497
+ const components = read($ref)[NS]?.comp ?? {};
1498
+ for (const [name, group] of Object.entries(components)) {
1499
+ const axes = group.$extensions?.["dev.tanrei.axes"];
1500
+ if (axes) out[name] = { axes, states: group.$extensions["dev.tanrei.states"] };
1501
+ }
1502
+ }
1503
+ return out;
1504
+ }
1505
+ var linted = /* @__PURE__ */ new Set();
1506
+ var LINTED_AT_MOST = 2e5;
1507
+ async function lintValues(tokens) {
1508
+ const written = (id) => tokens[id].aliasOf ? written(tokens[id].aliasOf) : inlined(tokens[id].originalValue.$value, tokens[id].partialAliasOf);
1509
+ const inlined = (value, partial) => {
1510
+ if (typeof partial === "string") return written(partial);
1511
+ if (!partial || value === null || typeof value !== "object") return value;
1512
+ if (Array.isArray(partial) && !Array.isArray(value)) return inlined(value, partial[0]);
1513
+ const out = Array.isArray(value) ? [...value] : { ...value };
1514
+ for (const key of Object.keys(partial)) out[key] = inlined(value[key], partial[key]);
1515
+ return out;
1516
+ };
1517
+ const lines = ["{"];
1518
+ const at = [null];
1519
+ const seen = /* @__PURE__ */ new Map();
1520
+ for (const token of Object.values(tokens)) {
1521
+ if (token.aliasOf) continue;
1522
+ const text2 = JSON.stringify({ $type: token.$type, $value: inlined(token.originalValue.$value, token.partialAliasOf) });
1523
+ if (linted.has(text2) || seen.has(text2)) continue;
1524
+ seen.set(text2, token.id);
1525
+ }
1526
+ if (!seen.size) return;
1527
+ [...seen].forEach(([text2, id], i) => {
1528
+ lines.push(`"v${i}": ${text2}${i === seen.size - 1 ? "" : ","}`);
1529
+ at.push(id);
1530
+ });
1531
+ lines.push("}");
1532
+ const { Logger, defineConfig, parse } = await import("@terrazzo/parser");
1533
+ class Problems extends Logger {
1534
+ error(...entries) {
1535
+ const said = entries.filter((entry) => !(entry.group === "lint" && entry.label === "lint"));
1536
+ throw new TokenReadError(said.map((entry) => `${at[entry.node?.loc?.start?.line - 1] ?? "a value"}: ${entry.message}${entry.group === "lint" ? ` (${entry.label})` : ""}`).join("\n"));
1537
+ }
1538
+ }
1539
+ const filename = new URL("values.tokens.json", MEMORY);
1540
+ await parse([{ filename, src: lines.join("\n") }], { config: defineConfig({}, { cwd: MEMORY }), logger: new Problems({ level: "error" }) });
1541
+ if (linted.size + seen.size > LINTED_AT_MOST) linted.clear();
1542
+ for (const text2 of seen.keys()) linted.add(text2);
1543
+ }
1544
+ var segments = (id) => id.split(".").slice(1);
1545
+ function simplify(token, paths) {
1546
+ let tokenPath = paths?.get(token.id);
1547
+ if (!tokenPath) paths?.set(token.id, tokenPath = segments(token.id));
1548
+ return simplified(token, tokenPath ?? segments(token.id));
1549
+ }
1550
+ function simplified(token, tokenPath) {
1551
+ return {
1552
+ id: token.id,
1553
+ path: tokenPath,
1554
+ // `tanrei` for the vocabulary (core and extensions inside its tree); a layer's id for its own tokens.
1555
+ namespace: token.id.split(".")[0],
1556
+ // Set on extensions: { rationale, declaredBy, extension: true, onRole? }.
1557
+ vocabulary: token.$extensions?.["dev.tanrei.vocabulary"],
1558
+ type: token.$type,
1559
+ value: token.$value,
1560
+ description: token.$description,
1561
+ deprecated: token.$deprecated || void 0,
1562
+ // Direct alias target (one hop), so emitters can keep the ref → sys → comp chain visible.
1563
+ alias: token.aliasChain?.[0],
1564
+ // The end of the alias chain (a comp token may alias another comp token that aliases a sys token).
1565
+ aliasFinal: token.aliasOf,
1566
+ partialAlias: token.partialAliasOf,
1567
+ // How the value is decided when it is not an alias: a rule, or { fixed: reason }.
1568
+ derive: token.$extensions?.["dev.tanrei.derive"],
1569
+ // Set on generated per-state component tokens: 'hovered' | 'focused' | 'pressed' | 'disabled'.
1570
+ state: token.$extensions?.["dev.tanrei.state"],
1571
+ // Set on a choice of kind: { values: [...] }; the value is an index into it.
1572
+ enum: token.$extensions?.["dev.tanrei.enum"]
1573
+ };
1574
+ }
1575
+ var SYS_COLOR = `${NS}.sys.color.`;
1576
+ var COMP = `${NS}.comp.`;
1577
+ var WHOLE_ALIAS = /^\{[^{}]+\}$/;
1578
+ function simplifyAll(set, paths) {
1579
+ const tokens = {};
1580
+ for (const [id, token] of Object.entries(set)) tokens[id] = simplify(token, paths);
1581
+ for (const token of Object.values(tokens)) {
1582
+ if (typeof token.value === "string" && WHOLE_ALIAS.test(token.value) && token.aliasFinal && tokens[token.aliasFinal]) token.value = tokens[token.aliasFinal].value;
1583
+ }
1584
+ return tokens;
1585
+ }
1586
+ function assertEveryRole(colors) {
1587
+ const roles = Object.keys(colors.light);
1588
+ for (const scheme of SCHEMES) {
1589
+ const missing = roles.filter((r) => !(r in colors[scheme]));
1590
+ if (missing.length) throw new Error(`Scheme "${scheme}" is missing color roles: ${missing.join(", ")}`);
1591
+ }
1592
+ }
1593
+ function partialModel(base, systemId, components, colors) {
1594
+ const tokens = simplifyAll(base);
1595
+ return { system: systemId, schemes: SCHEMES, tokens, colors, componentColors: { light: Object.fromEntries(Object.entries(tokens).filter(([id, t]) => id.startsWith(COMP) && t.type === "color")) }, components, partial: true };
1596
+ }
1597
+ async function colorsFromBundle(files, systemId = NS, reader = readBundle(files, systemId)) {
1598
+ const colors = {};
1599
+ for (const scheme of SCHEMES) {
1600
+ colors[scheme] = {};
1601
+ for (const [id, token] of Object.entries(reader.apply({ scheme }))) if (id.startsWith(SYS_COLOR)) colors[scheme][id.slice(SYS_COLOR.length)] = simplify(token);
1602
+ }
1603
+ assertEveryRole(colors);
1604
+ return colors;
1605
+ }
1606
+ async function invariantModel(files, systemId, light, reader) {
1607
+ return partialModel(light, systemId, componentDeclarations(null, systemId, (name) => files[name]), await colorsFromBundle(files, systemId, reader));
1608
+ }
1609
+
1610
+ // ../tokens-build/src/resolve.js
1611
+ import crypto2 from "node:crypto";
1612
+ import fs4 from "node:fs";
1613
+ import path5 from "node:path";
1614
+
1615
+ // ../tokens-build/src/invariants.js
1616
+ var lin = (c) => c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
1617
+ var luminance2 = ({ r, g, b }) => 0.2126 * lin(r / 255) + 0.7152 * lin(g / 255) + 0.0722 * lin(b / 255);
1618
+ var over = (fg, bg) => ({
1619
+ r: fg.r * fg.a + bg.r * (1 - fg.a),
1620
+ g: fg.g * fg.a + bg.g * (1 - fg.a),
1621
+ b: fg.b * fg.a + bg.b * (1 - fg.a),
1622
+ a: 1
1623
+ });
1624
+ var leadWithStructure = (warnings) => [...warnings.filter((w) => !/^\[[a-z-]+\] /.test(w)), ...warnings.filter((w) => /^\[[a-z-]+\] /.test(w))];
1625
+ var isCriterionFinding = (finding) => /^\[[a-z-]+\] [a-z0-9-]+ on [a-z0-9-]+: \d+\.\d+:1 < \d+(\.\d+)?:1 \(/.test(finding);
1626
+ var PRESET_CRITERIA_NOTE = "An imitation preset is held to fidelity to the system it imitates, not to Tanrei's accessibility criteria, in every contrast scheme. These are measurements against the fixed thresholds, kept as information: they are not warnings and not mimicry gaps.";
1627
+ function contrast(fgColor, bgColor) {
1628
+ const bg = rgba(bgColor);
1629
+ const fg = over(rgba(fgColor), bg);
1630
+ const [hi, lo] = [luminance2(fg), luminance2(bg)].sort((a, b) => b - a);
1631
+ return (hi + 0.05) / (lo + 0.05);
1632
+ }
1633
+ var SURFACES = [
1634
+ "surface",
1635
+ "surface-dim",
1636
+ "surface-bright",
1637
+ "surface-container-lowest",
1638
+ "surface-container-low",
1639
+ "surface-container",
1640
+ "surface-container-high",
1641
+ "surface-container-highest"
1642
+ ];
1643
+ var TEXT = 4.5;
1644
+ var NON_TEXT = 3;
1645
+ var STATUSES = ["info", "warning", "error", "success"];
1646
+ function intentsOf(roles) {
1647
+ return Object.keys(roles).filter((r) => [`on-${r}`, `${r}-container`, `on-${r}-container`].every((k) => k in roles));
1648
+ }
1649
+ function pairsFor(roles, focusStyle = "ring") {
1650
+ const intents = intentsOf(roles);
1651
+ const focus = focusStyle === "ring" ? "focus indicator (WCAG 2.4.13)" : `focus indicator, drawn as a ${focusStyle} (WCAG 2.4.13)`;
1652
+ return [
1653
+ ...intents.flatMap((r) => [
1654
+ [`on-${r}`, r, TEXT, "content on filled container"],
1655
+ [`on-${r}-container`, `${r}-container`, TEXT, "content on tonal container"]
1656
+ ]),
1657
+ ...STATUSES.filter((r) => intents.includes(r)).map((r) => [r, `${r}-container`, NON_TEXT, "status mark on its tonal container (WCAG 1.4.11)"]),
1658
+ ["inverse-on-surface", "inverse-surface", TEXT, "content on inverse surface"],
1659
+ // inverse-primary on inverse-surface is a snackbar's action label: text.
1660
+ ["inverse-primary", "inverse-surface", TEXT, "accent text on inverse surface"],
1661
+ // A link on a surface of the opposite theme: the counterpart of `link` on the surfaces below.
1662
+ ["inverse-link", "inverse-surface", TEXT, "inline links on inverse surface"],
1663
+ ...SURFACES.flatMap((s) => [
1664
+ ["on-surface", s, TEXT, "body text"],
1665
+ ["on-surface-variant", s, TEXT, "secondary text"],
1666
+ ["link", s, TEXT, "inline links"],
1667
+ ...intents.map((r) => [r, s, TEXT, `${r}-colored text`]),
1668
+ ["outline", s, NON_TEXT, "functional boundary (WCAG 1.4.11)"],
1669
+ ["focus-ring", s, NON_TEXT, focus]
1670
+ ])
1671
+ ];
1672
+ }
1673
+ var tonalPairs = (roles) => ["secondary", ...STATUSES].filter((r) => `${r}-container` in roles).flatMap((r) => [
1674
+ ["link", `${r}-container`, TEXT, "inline link on a tonal container"],
1675
+ ["focus-ring", `${r}-container`, NON_TEXT, "focus indicator on a tonal container (WCAG 2.4.13)"]
1676
+ ]);
1677
+ var HIGH_CONTRAST_TEXT = 7;
1678
+ var OTHER_THEME = { light: "dark", "light-medium": "dark-medium", "light-high": "dark-high", dark: "light", "dark-medium": "light-medium", "dark-high": "light-high" };
1679
+ var choiceOf = (model, name) => {
1680
+ const token = model.tokens[`${CONFIG.namespace}.sys.behavior.${name}`];
1681
+ return token?.enum?.values?.[token.value];
1682
+ };
1683
+ function checkInvariants(model) {
1684
+ const failures = [];
1685
+ const focusStyle = choiceOf(model, "focus-style");
1686
+ for (const scheme of model.schemes) {
1687
+ const roles = model.colors[scheme];
1688
+ const isHigh = scheme.endsWith("-high");
1689
+ const declared = Object.entries(roles).filter(([, token]) => token.vocabulary?.onRole).map(([role2, token]) => [token.vocabulary.onRole.split(".").at(-1), role2, TEXT, `content on the declared role "${role2}"`]);
1690
+ const tonal = model.system === CONFIG.namespace ? tonalPairs(roles) : [];
1691
+ for (const [fg, bg, min, why] of [...pairsFor(roles, focusStyle), ...tonal, ...declared]) {
1692
+ if (!roles[fg] || !roles[bg]) {
1693
+ failures.push(`[${scheme}] missing role for pair ${fg} / ${bg}`);
1694
+ continue;
1695
+ }
1696
+ const required = isHigh && min === TEXT ? HIGH_CONTRAST_TEXT : min;
1697
+ const ratio = contrast(roles[fg].value, roles[bg].value);
1698
+ if (ratio < required) {
1699
+ failures.push(`[${scheme}] ${fg} on ${bg}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
1700
+ }
1701
+ }
1702
+ }
1703
+ if (choiceOf(model, "pressed-feedback") === "dim") {
1704
+ const pressed = Object.values(model.tokens).filter((t) => t.path[0] === "comp" && /(^|\.)pressed\.opacity$/.test(t.path.slice(2).join(".")));
1705
+ if (pressed.length && pressed.every((t) => t.value >= 1)) failures.push(`sys.behavior.pressed-feedback is "dim", but every pressed opacity is 1 (${pressed.map((t) => t.id).join(", ")}): a press would show nothing \u2014 set the pressed opacity below 1, or choose another feedback`);
1706
+ }
1707
+ for (const token of Object.values(model.tokens)) {
1708
+ const tier = token.path[0];
1709
+ if (tier === "sys" && token.path[1] === "color") {
1710
+ if (!token.alias) failures.push(`${token.id}: sys.color roles must alias ref.palette / ref.alpha`);
1711
+ } else if ((tier === "sys" || tier === "comp") && !token.alias && !token.derive) {
1712
+ failures.push(`${token.id}: a literal needs a rule or a stated reason for being fixed; component tokens normally alias a sys token`);
1713
+ }
1714
+ }
1715
+ for (const token of Object.values(model.tokens)) {
1716
+ if (!token.enum) continue;
1717
+ const names = token.enum.values;
1718
+ const list = (values) => (values ?? []).map((name, i) => `${name} (${i})`).join(", ");
1719
+ let value = token.value;
1720
+ if (token.alias) {
1721
+ const targetId = token.aliasFinal ?? token.alias;
1722
+ const target = model.tokens[targetId];
1723
+ if (!Array.isArray(target?.enum?.values)) {
1724
+ failures.push(`${token.id}: aliases ${targetId}, which is not a choice of kind \u2014 a choice follows another choice or is one of its own names: ${list(names)}`);
1725
+ continue;
1726
+ }
1727
+ if (!Array.isArray(names) || names.length !== target.enum.values.length || names.some((name, i) => name !== target.enum.values[i])) {
1728
+ failures.push(`${token.id}: aliases ${targetId}, whose choices differ \u2014 ${list(names)} here, ${list(target.enum.values)} there`);
1729
+ continue;
1730
+ }
1731
+ value = target.value;
1732
+ }
1733
+ if (!Array.isArray(names) || !Number.isInteger(value) || value < 0 || value >= names.length) failures.push(`${token.id}: ${JSON.stringify(value)} is not one of its choices \u2014 ${list(names)}`);
1734
+ }
1735
+ for (const token of Object.values(model.tokens)) {
1736
+ if (token.type !== "shadow" || token.alias) continue;
1737
+ if (!Array.isArray(token.value)) failures.push(`${token.id}: a shadow is a list of layers (an empty list draws nothing)`);
1738
+ else token.value.forEach((_, i) => {
1739
+ if (!token.partialAlias?.[i]?.color?.startsWith(`${CONFIG.namespace}.sys.color.`)) failures.push(`${token.id}: shadow layer ${i + 1} must take its color from a sys.color role`);
1740
+ });
1741
+ }
1742
+ for (const token of Object.values(model.tokens)) {
1743
+ const [tier, component, part, property, size] = token.path;
1744
+ if (tier !== "comp" || part !== "container" || property !== "height") continue;
1745
+ const at = (...rest) => model.tokens[[CONFIG.namespace, "comp", component, ...rest].join(".")];
1746
+ const padding = at("container", "padding-block", size)?.value?.value;
1747
+ const label = at("label", "typescale", size)?.value;
1748
+ if (padding === void 0 || !label?.fontSize) continue;
1749
+ const needed = 2 * padding + Math.round(label.fontSize.value * label.lineHeight * 100) / 100;
1750
+ if (token.value.value < needed) failures.push(`${token.id}: ${token.value.value}px cannot hold its content \u2014 2 \xD7 padding-block (${padding}px) + one label line = ${needed}px`);
1751
+ }
1752
+ const role = (token) => {
1753
+ for (let at = token, hops = 0; at?.alias && hops < 16; at = model.tokens[at.alias], hops++) {
1754
+ if (at.alias.startsWith(`${CONFIG.namespace}.sys.color.`)) return at.alias.slice(`${CONFIG.namespace}.sys.color.`.length);
1755
+ }
1756
+ return void 0;
1757
+ };
1758
+ const short = (id) => id.slice(CONFIG.namespace.length + 1);
1759
+ for (const ring of Object.values(model.tokens)) {
1760
+ if (ring.path[0] !== "comp" || ring.type !== "color" || ring.path.at(-2) !== "focus-ring" || ring.path.at(-1) !== "color") continue;
1761
+ const barId = [CONFIG.namespace, ...ring.path.slice(0, -2), "container", "color"].join(".");
1762
+ const bar = model.tokens[barId];
1763
+ if (!bar) continue;
1764
+ const [ringRole, barRole] = [role(ring), role(bar)];
1765
+ for (const scheme of model.schemes) {
1766
+ const byRole = ringRole && barRole && model.colors[scheme][ringRole] && model.colors[scheme][barRole];
1767
+ const fg = byRole ? model.colors[scheme][ringRole].value : model.componentColors?.[scheme]?.[ring.id]?.value;
1768
+ const bg = byRole ? model.colors[scheme][barRole].value : model.componentColors?.[scheme]?.[barId]?.value;
1769
+ if (!fg || !bg || rgba(bg).a < 1) continue;
1770
+ const ratio = contrast(fg, bg);
1771
+ if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(ring.id)} on ${short(barId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (focus indicator on the component's own bar, WCAG 2.4.13)`);
1772
+ }
1773
+ }
1774
+ const snackbar = `${CONFIG.namespace}.comp.snackbar`;
1775
+ const inScheme = (scheme, id) => model.componentColors?.[scheme]?.[id]?.value;
1776
+ const number = (id) => typeof model.tokens[id]?.value === "number" ? model.tokens[id].value : 1;
1777
+ const faded = (color, opacity) => ({ ...color, alpha: (color.alpha ?? 1) * opacity });
1778
+ const flat = (fg, bg) => {
1779
+ const c = over(rgba(fg), rgba(bg));
1780
+ return { colorSpace: "srgb", components: [c.r / 255, c.g / 255, c.b / 255], alpha: 1 };
1781
+ };
1782
+ const sameColor = (x, y) => ["r", "g", "b", "a"].every((k) => rgba(x)[k] === rgba(y)[k]);
1783
+ const hex = (color) => `#${[rgba(color).r, rgba(color).g, rgba(color).b].map((n) => n.toString(16).padStart(2, "0")).join("")}${rgba(color).a < 1 ? ` at ${rgba(color).a}` : ""}`;
1784
+ if (model.system === CONFIG.namespace) {
1785
+ for (const scheme of model.schemes) {
1786
+ const other = OTHER_THEME[scheme];
1787
+ for (const id of Object.keys(model.componentColors?.[scheme] ?? {})) {
1788
+ if (!id.startsWith(`${snackbar}.`) || !STATUSES.some((status) => id.includes(`.inverse-${status}.`))) continue;
1789
+ const twin = id.replace(".inverse-", ".");
1790
+ const [here, there] = [inScheme(scheme, id), inScheme(other, twin)];
1791
+ if (!here || !there || sameColor(here, there)) continue;
1792
+ failures.push(`[${scheme}] ${short(id)} is ${hex(here)}, but ${short(twin)} is ${hex(there)} in ${other}: a status's inverse form is that status's form in the other theme (SNK-30)`);
1793
+ }
1794
+ }
1795
+ }
1796
+ const STATES2 = ["", "hovered.", "focused.", "pressed."];
1797
+ for (const status of STATUSES) {
1798
+ const form = `inverse-${status}`;
1799
+ const barId = `${snackbar}.${form}.container.color`;
1800
+ if (!model.tokens[barId]) continue;
1801
+ const pairs = [
1802
+ [`${form}.title.color`, null, 1, TEXT, "title on its bar"],
1803
+ [`${form}.supporting-text.color`, null, 1, TEXT, "message on its bar"],
1804
+ [`${form}.icon.color`, null, number(`${snackbar}.icon.opacity`), NON_TEXT, "status glyph at icon.opacity on its bar"],
1805
+ [`${form}.supporting-text.color`, null, number(`${snackbar}.supporting-text.under-title.opacity`), TEXT, "description at its opacity under a title"],
1806
+ ...STATES2.map((state) => [`close.${state}${form}.content.color`, `close.${state}${form}.container.color`, 1, NON_TEXT, "close glyph on its container over the bar"])
1807
+ ];
1808
+ for (const [fgName, groundName, opacity, min, why] of pairs) {
1809
+ const [fgId, groundId] = [`${snackbar}.${fgName}`, groundName && `${snackbar}.${groundName}`];
1810
+ if (!model.tokens[fgId] || groundId && !model.tokens[groundId]) continue;
1811
+ if (!groundId && opacity === 1 && role(model.tokens[fgId]) && role(model.tokens[barId])) continue;
1812
+ for (const scheme of model.schemes) {
1813
+ const [fg, bar, ground] = [inScheme(scheme, fgId), inScheme(scheme, barId), groundId && inScheme(scheme, groundId)];
1814
+ if (!fg || !bar || rgba(bar).a < 1 || groundId && !ground) continue;
1815
+ const bg = ground ? flat(ground, bar) : bar;
1816
+ const required = scheme.endsWith("-high") && min === TEXT ? HIGH_CONTRAST_TEXT : min;
1817
+ const ratio = contrast(faded(fg, opacity), bg);
1818
+ if (ratio < required) failures.push(`[${scheme}] ${short(fgId)} on ${short(groundId ?? barId)}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
1819
+ }
1820
+ }
1821
+ }
1822
+ const held = /* @__PURE__ */ new Map();
1823
+ for (const scheme of model.schemes) for (const [fg, bg, min] of pairsFor(model.colors[scheme], focusStyle)) held.set(`${fg} ${bg}`, Math.max(min, held.get(`${fg} ${bg}`) ?? 0));
1824
+ const codeBlock = `${CONFIG.namespace}.comp.code-block`;
1825
+ const inlineCode = `${CONFIG.namespace}.comp.inline-code`;
1826
+ const SYNTAX = Object.keys(model.tokens).filter((id) => id.startsWith(`${codeBlock}.syntax.color.`)).map((id) => id.slice(codeBlock.length + 1));
1827
+ const CODE_TEXT = ["code.color", "line-number.color", "prompt.color", ...SYNTAX];
1828
+ const CODE_MARKS = ["line.highlighted.mark.color", "line.added.mark.color", "line.removed.mark.color"];
1829
+ const codePairs = [
1830
+ ...CODE_TEXT.flatMap((part) => [
1831
+ [`${codeBlock}.${part}`, `${codeBlock}.filled.container.color`, TEXT, "code on the block's fill"],
1832
+ [`${codeBlock}.${part}`, `${codeBlock}.line.highlighted.container.color`, TEXT, "code on a highlighted line's band"]
1833
+ ]),
1834
+ ...CODE_MARKS.map((part) => [`${codeBlock}.${part}`, `${codeBlock}.filled.container.color`, NON_TEXT, "a marked line's bar on the block's fill"]),
1835
+ // An outlined block has no fill: its code is read on the surface it is placed on, so a syntax color is held on
1836
+ // every surface role. The other text colors of the block are roles the role pairs hold there.
1837
+ ...SYNTAX.flatMap((part) => SURFACES.map((surface) => [`${codeBlock}.${part}`, `${CONFIG.namespace}.sys.color.${surface}`, TEXT, "code in an outlined block on a surface"])),
1838
+ [`${inlineCode}.label.color`, `${inlineCode}.container.color`, TEXT, "inline code on its fill"]
1839
+ ];
1840
+ for (const [fgId, bgId, min, why] of codePairs) {
1841
+ const [fgToken, bgToken] = [model.tokens[fgId], model.tokens[bgId]];
1842
+ if (!fgToken || !bgToken) continue;
1843
+ const [fgRole, bgRole] = [role(fgToken), bgId.startsWith(`${CONFIG.namespace}.sys.color.`) ? bgId.split(".").at(-1) : role(bgToken)];
1844
+ if (fgRole && bgRole && (held.get(`${fgRole} ${bgRole}`) ?? 0) >= min) continue;
1845
+ for (const scheme of model.schemes) {
1846
+ const fg = fgRole && model.colors[scheme][fgRole] ? model.colors[scheme][fgRole].value : inScheme(scheme, fgId);
1847
+ const bg = bgRole && model.colors[scheme][bgRole] ? model.colors[scheme][bgRole].value : inScheme(scheme, bgId);
1848
+ if (!fg || !bg || rgba(bg).a < 1) continue;
1849
+ const required = scheme.endsWith("-high") && min === TEXT ? HIGH_CONTRAST_TEXT : min;
1850
+ const ratio = contrast(fg, bg);
1851
+ if (ratio < required) failures.push(`[${scheme}] ${short(fgId)} on ${short(bgId)}: ${ratio.toFixed(2)}:1 < ${required}:1 (${why})`);
1852
+ }
1853
+ }
1854
+ const TOLD_APART = [
1855
+ ["link", "standard.label.color", "sys.color.on-surface", "a link beside body text"],
1856
+ ["link", "inverse.label.color", "sys.color.inverse-on-surface", "a link beside text on an inverse surface"],
1857
+ ["breadcrumbs", "item.content.color", "comp.breadcrumbs.label.color", "a level that is a link beside a level that is text"]
1858
+ ];
1859
+ for (const [component, fgName, besideName, why] of TOLD_APART) {
1860
+ const choice = model.tokens[`${CONFIG.namespace}.comp.${component}.underline.visibility`];
1861
+ if (!choice?.enum) continue;
1862
+ const target = choice.alias ? model.tokens[choice.aliasFinal ?? choice.alias] : choice;
1863
+ const named = choice.enum.values?.[target?.value];
1864
+ if (!named || named === "always") continue;
1865
+ const [fgId, besideId] = [`${CONFIG.namespace}.comp.${component}.${fgName}`, `${CONFIG.namespace}.${besideName}`];
1866
+ const colorIn = (scheme, id) => {
1867
+ const colorRole = id.startsWith(`${CONFIG.namespace}.sys.color.`) ? id.split(".").at(-1) : model.tokens[id] && role(model.tokens[id]);
1868
+ return colorRole && model.colors[scheme][colorRole] ? model.colors[scheme][colorRole].value : inScheme(scheme, id);
1869
+ };
1870
+ for (const scheme of model.schemes) {
1871
+ const [fg, beside] = [colorIn(scheme, fgId), colorIn(scheme, besideId)];
1872
+ if (!fg || !beside || rgba(fg).a < 1 || rgba(beside).a < 1) continue;
1873
+ const ratio = contrast(fg, beside);
1874
+ if (ratio < NON_TEXT) failures.push(`[${scheme}] ${short(fgId)} against ${short(besideId)}: ${ratio.toFixed(2)}:1 < ${NON_TEXT}:1 (${why}, while ${short(choice.id)} is "${named}": a link not underlined at rest is told from text by color alone \u2014 WCAG 1.4.1; underline it always, or move the link color)`);
1875
+ }
1876
+ }
1877
+ return failures;
1878
+ }
1879
+
1880
+ // ../tokens-build/src/resolve.js
1881
+ var LAYER_SUFFIX = ".system.json";
1882
+ var systemIdOf = (file) => path5.basename(file, LAYER_SUFFIX);
1883
+ function localLayerFile(dir, id) {
1884
+ assertSystemId(id);
1885
+ const file = path5.join(dir, `${id}${LAYER_SUFFIX}`);
1886
+ if (!fs4.lstatSync(file, { throwIfNoEntry: false })) return null;
1887
+ const name = `${id}${LAYER_SUFFIX}`;
1888
+ let real;
1889
+ try {
1890
+ real = fs4.realpathSync(file);
1891
+ } catch {
1892
+ throw new Error(`${name}: a link that leads nowhere. A parent layer is a regular file in ${dir}`);
1893
+ }
1894
+ const root2 = fs4.realpathSync(dir);
1895
+ if (!real.startsWith(root2 + path5.sep)) throw new Error(`${name}: a link that leaves ${dir}. A parent layer is read only from inside the directory of the product's layers`);
1896
+ if (!fs4.statSync(real).isFile()) throw new Error(`${name}: not a regular file`);
1897
+ return file;
1898
+ }
1899
+ function readSystemChain({ system, layerFile, layers, dir } = {}) {
1900
+ const given = [system !== void 0, layerFile !== void 0, layers !== void 0].filter(Boolean).length;
1901
+ if (given !== 1) throw new Error('name the system with exactly one of "system" (a shipped id), "layerFile" (a path) or "layers" (layer objects, the last one being the system)');
1902
+ if (layers && (!Array.isArray(layers) || !layers.length || layers.some((l) => !l || typeof l !== "object" || typeof l.id !== "string" || !l.id))) throw new Error('"layers" is a non-empty list of layer objects, each with an "id"');
1903
+ const inline = new Map((layers ?? []).map((layer) => [layer.id, layer]));
1904
+ if (inline.size !== (layers ?? []).length) throw new Error(`"layers" names the same id twice (${(layers ?? []).map((l) => l.id).join(", ")})`);
1905
+ const local = dir ?? (layerFile ? path5.dirname(path5.resolve(layerFile)) : null);
1906
+ const shipped = new Set(listSystems(REPO_ROOT));
1907
+ const id = system ?? (layerFile ? systemIdOf(layerFile) : layers.at(-1).id);
1908
+ const origin = /* @__PURE__ */ new Map();
1909
+ const read = (wanted) => {
1910
+ if (inline.has(wanted)) return origin.set(wanted, null), inline.get(wanted);
1911
+ const own = layerFile && wanted === id ? path5.resolve(layerFile) : null;
1912
+ const file = system !== void 0 ? null : own ? fs4.existsSync(own) ? own : null : local ? localLayerFile(local, wanted) : null;
1913
+ if (file) return origin.set(wanted, file), JSON.parse(fs4.readFileSync(file, "utf8"));
1914
+ if (shipped.has(wanted)) return origin.set(wanted, path5.join(REPO_ROOT, systemPath(wanted))), loadSystem(REPO_ROOT, wanted);
1915
+ const where = [...inline.size ? ["not among the layers passed"] : [], ...local ? [`no ${wanted}${LAYER_SUFFIX} in ${layerFile ? `the directory of ${path5.basename(layerFile)}` : local}`] : []];
1916
+ throw new Error(`system "${wanted}" not found: ${[...where, `not a shipped system (${[...shipped].join(", ")})`].join(", ")}`);
1917
+ };
1918
+ const wantedIds = [];
1919
+ const chain = layerChain(id, (wanted) => (wantedIds.unshift(wanted), read(wanted)));
1920
+ return { id, chain, sources: wantedIds.map((wanted) => origin.get(wanted)), fileIds: wantedIds };
1921
+ }
1922
+ function validateSystem(input) {
1923
+ if (input.layerFile !== void 0 && !input.layerFile.endsWith(LAYER_SUFFIX)) return [`${input.layerFile}: a layer file is named <id>${LAYER_SUFFIX}`];
1924
+ const { id, chain, fileIds } = readSystemChain(input);
1925
+ if (input.system === void 0 && id === ROOT_SYSTEM) return [`"${ROOT_SYSTEM}" is the root system; a product layer needs its own id and "extends"`];
1926
+ const problems = [];
1927
+ if (chain.at(-1).id !== id) problems.push(`${id}${LAYER_SUFFIX}: "id" must equal the file name`);
1928
+ chain.forEach((layer, i) => problems.push(...validateLayerFile(REPO_ROOT, layer, fileIds[i])));
1929
+ return [...new Set(problems)];
1930
+ }
1931
+ var chainDigest = (chain) => crypto2.createHash("sha256").update(JSON.stringify(chain)).digest("hex").slice(0, 32);
1932
+ async function resolveChainByScheme(chain) {
1933
+ const id = chain.at(-1).id;
1934
+ const { system, files } = buildBundle(REPO_ROOT, chain);
1935
+ const reader = readBundle(files, id);
1936
+ const loaded = /* @__PURE__ */ new Set();
1937
+ const load2 = async (scheme) => {
1938
+ const tokens = reader.tokens(scheme);
1939
+ loaded.add(scheme);
1940
+ return tokens;
1941
+ };
1942
+ await lintValues(await load2("light"));
1943
+ let warnings;
1944
+ return {
1945
+ id,
1946
+ chain,
1947
+ digest: chainDigest(chain),
1948
+ system,
1949
+ files,
1950
+ tokens(scheme = "light") {
1951
+ if (!loaded.has(scheme)) throw new Error(`scheme "${scheme}" is not loaded yet: await load("${scheme}") first`);
1952
+ return reader.tokens(scheme);
1953
+ },
1954
+ load: load2,
1955
+ // From the light tokens and the role colors of every scheme: the model's warnings without the model's component colors.
1956
+ warnings: () => warnings ??= invariantModel(files, id, reader.tokens("light"), reader).then(checkInvariants),
1957
+ notices: system.notices ?? []
1958
+ };
1959
+ }
1960
+
1961
+ // src/systems.js
1962
+ var NS2 = CONFIG.namespace;
1963
+ var ROOT_SYSTEM2 = NS2;
1964
+ var VOCABULARY2 = "dev.tanrei.vocabulary";
1965
+ var LLM2 = "dev.tanrei.llm";
1966
+ var DERIVE2 = "dev.tanrei.derive";
1967
+ var STATE = "dev.tanrei.state";
1968
+ var RECIPE2 = "dev.tanrei.system";
1969
+ var SYS_COLOR2 = `${NS2}.sys.color.`;
1970
+ var SEGMENT = /^[a-z0-9][a-z0-9-]*$/;
1971
+ var isPlaceholder = (text2) => typeof text2 === "string" && /^\s*<[^>]*>\s*$/.test(text2);
1972
+ var clone4 = (value) => JSON.parse(JSON.stringify(value));
1973
+ var collectVocabulary2 = (layers) => collectVocabulary(layers, { namespace: NS2 });
1974
+ var LAYER_SUFFIX2 = ".system.json";
1975
+ var ToolError = class extends Error {
1976
+ constructor(message, details) {
1977
+ super(message);
1978
+ this.details = details;
1979
+ }
1980
+ };
1981
+ var shippedSystems = () => listSystems(REPO_ROOT);
1982
+ var shippedLayer = (id) => loadSystem(REPO_ROOT, id);
1983
+ var isRef5 = (v) => typeof v === "string" && /^\{[^}]+\}$/.test(v);
1984
+ function matchSegments(pattern, id) {
1985
+ const p = pattern.split(".");
1986
+ const s = id.split(".");
1987
+ return p.length === s.length && p.every((part, i) => part === "*" || part === s[i]);
1988
+ }
1989
+ function describeReference({ system, layerFile, layer, parents, dir } = {}) {
1990
+ if (layer) {
1991
+ if (parents !== void 0 && (!Array.isArray(parents) || parents.some((p) => !p || typeof p !== "object" || typeof p.id !== "string"))) throw new ToolError('"parents" is a list of layer objects, each with an "id": the layers that exist only in this request and that "layer" (or another parent) extends.');
1992
+ if (dir !== void 0 && (typeof dir !== "string" || !fs5.existsSync(path6.resolve(dir)))) throw new ToolError(`${dir}: no such directory. "dir" is where the product's other <id>${LAYER_SUFFIX2} files live.`);
1993
+ return { kind: "inline", layer, parents: parents ?? [], dir: dir === void 0 ? void 0 : path6.resolve(dir) };
1994
+ }
1995
+ if (!layerFile && typeof system === "string" && system.endsWith(LAYER_SUFFIX2)) layerFile = system;
1996
+ if (layerFile) {
1997
+ const file = path6.resolve(layerFile);
1998
+ if (!file.endsWith(LAYER_SUFFIX2)) throw new ToolError(`${layerFile}: a layer file is named <id>${LAYER_SUFFIX2}`);
1999
+ if (!fs5.existsSync(file)) throw new ToolError(`${layerFile}: no such file. Pass an absolute path, or one relative to the server's working directory (${process.cwd()}).`);
2000
+ return { kind: "file", file };
2001
+ }
2002
+ const id = system ?? ROOT_SYSTEM2;
2003
+ if (!shippedSystems().includes(id)) throw new ToolError(`"${id}" is not a shipped system. Shipped: ${shippedSystems().join(", ")}. For a product's own system pass "layerFile": the path of its <id>${LAYER_SUFFIX2}.`);
2004
+ return { kind: "shipped", id };
2005
+ }
2006
+ function readChain(reference) {
2007
+ const input = reference.kind === "shipped" ? { system: reference.id } : reference.kind === "file" ? { layerFile: reference.file } : { layers: [...reference.parents.filter((p) => p.id !== reference.layer.id), reference.layer], dir: reference.dir };
2008
+ const { id, chain, sources } = readSystemChain(input);
2009
+ return { id, chain, sources, input };
2010
+ }
2011
+ function readLayers(input) {
2012
+ const reference = describeReference(input);
2013
+ try {
2014
+ return { reference, ...readChain(reference) };
2015
+ } catch (error) {
2016
+ throw new ToolError(error.message);
2017
+ }
2018
+ }
2019
+ var declaredExtensions = (chain) => listExtensions({ vocabulary: collectVocabulary2(chain) });
2020
+ function componentsOf(files) {
2021
+ const out = {};
2022
+ for (const [name, doc] of Object.entries(files)) {
2023
+ if (!name.startsWith("comp/")) continue;
2024
+ for (const [component, group] of Object.entries(doc[NS2]?.comp ?? {})) {
2025
+ const axes = group?.$extensions?.[AXES];
2026
+ if (!axes) continue;
2027
+ const states = group.$extensions[STATES];
2028
+ out[component] = {
2029
+ id: `${NS2}.comp.${component}`,
2030
+ states: states?.states ?? [],
2031
+ axes: Object.fromEntries(Object.entries(axes).map(([axis, decl]) => [axis, { default: decl.default, values: decl.from === "states" ? states?.variants ?? [] : decl.values, members: decl.from === "states" ? null : decl.members }]))
2032
+ };
2033
+ }
2034
+ }
2035
+ return out;
2036
+ }
2037
+ function componentNamesOf(files) {
2038
+ return Object.entries(files).filter(([name]) => name.startsWith("comp/")).flatMap(([, doc]) => Object.keys(doc[NS2]?.comp ?? {}).filter((key) => !key.startsWith("$")));
2039
+ }
2040
+ function axisOf(components, id) {
2041
+ for (const component of Object.values(components)) {
2042
+ if (!id.startsWith(`${component.id}.`)) continue;
2043
+ const rest = id.slice(component.id.length + 1);
2044
+ for (const [axis, { values, members }] of Object.entries(component.axes)) {
2045
+ if (!members) continue;
2046
+ for (const member of members) for (const key of values) if (rest === `${member}.${key}`) return { id: `${component.id}.${axis}`, key, values };
2047
+ }
2048
+ for (const [axis, { values, members }] of Object.entries(component.axes)) {
2049
+ const key = rest.split(".")[0];
2050
+ if (!members && rest.includes(".") && values.includes(key)) return { id: `${component.id}.${axis}`, key, values };
2051
+ }
2052
+ }
2053
+ return null;
2054
+ }
2055
+ function collectMetadata(files) {
2056
+ const meta = /* @__PURE__ */ new Map();
2057
+ const visit = (node, trail, inherited) => {
2058
+ const ext = node.$extensions ?? {};
2059
+ const id = trail.join(".");
2060
+ const here = {
2061
+ vocabulary: ext[VOCABULARY2] ? { ...ext[VOCABULARY2], from: id } : inherited.vocabulary,
2062
+ llm: ext[LLM2] ? [...inherited.llm, { from: id, guidance: ext[LLM2] }] : inherited.llm
2063
+ };
2064
+ if ("$value" in node) return void meta.set(id, here);
2065
+ for (const [key, child] of Object.entries(node)) if (!key.startsWith("$") && child && typeof child === "object") visit(child, [...trail, key], here);
2066
+ };
2067
+ for (const [name, doc] of Object.entries(files)) {
2068
+ if (name.endsWith(".resolver.json")) continue;
2069
+ if (/^generated\/(sys\.color|comp\.states)\./.test(name) && !name.includes(".light.tokens")) continue;
2070
+ visit(doc, [], { vocabulary: void 0, llm: [] });
2071
+ }
2072
+ return meta;
2073
+ }
2074
+ var cache = /* @__PURE__ */ new Map();
2075
+ var CACHE_LIMIT = 6;
2076
+ function cached(id, chain) {
2077
+ const key = `${chainDigest(chain)}:${vocabularyDigest(REPO_ROOT)}`;
2078
+ const hit = cache.get(key);
2079
+ if (hit) {
2080
+ cache.delete(key);
2081
+ cache.set(key, hit);
2082
+ return hit;
2083
+ }
2084
+ const promise = assemble(id, chain).catch((error) => {
2085
+ if (cache.get(key) === promise) cache.delete(key);
2086
+ throw error;
2087
+ });
2088
+ cache.set(key, promise);
2089
+ while (cache.size > CACHE_LIMIT) cache.delete(cache.keys().next().value);
2090
+ return promise;
2091
+ }
2092
+ function loadContext(input, { scheme = "light" } = {}) {
2093
+ const reference = describeReference(input);
2094
+ let read;
2095
+ try {
2096
+ read = readChain(reference);
2097
+ } catch (error) {
2098
+ throw new ToolError(error.message);
2099
+ }
2100
+ const problems = layerProblems(reference, read);
2101
+ if (problems.length) return Promise.reject(new ToolError(`"${read.id}" is not a valid layer, so it has no values yet. Fix these first (validate_layer reports the same list):`, { problems }));
2102
+ return withScheme(cached(read.id, read.chain), scheme);
2103
+ }
2104
+ async function withScheme(context, scheme) {
2105
+ const ctx = await context;
2106
+ if (scheme !== "light") {
2107
+ try {
2108
+ await ctx.load(scheme);
2109
+ } catch (error) {
2110
+ throw new ToolError(`"${ctx.id}" cannot be built: ${error.message}`);
2111
+ }
2112
+ }
2113
+ return ctx;
2114
+ }
2115
+ function trialBuild(chain) {
2116
+ const layer = chain.at(-1);
2117
+ const problems = tidySchemaProblems(validateLayerFile(REPO_ROOT, layer, layer.id), [layer]);
2118
+ if (problems.length) throw new ToolError(`"${layer.id}" is not a valid layer`, { problems });
2119
+ return cached(layer.id, chain);
2120
+ }
2121
+ async function assemble(id, chain) {
2122
+ let resolved;
2123
+ try {
2124
+ resolved = await resolveChainByScheme(chain);
2125
+ } catch (error) {
2126
+ throw new ToolError(`"${id}" cannot be built: ${error.message}`);
2127
+ }
2128
+ const { system, files } = resolved;
2129
+ let dependencies;
2130
+ const extensions = files["dial/dial.tokens.json"].$extensions?.[RECIPE2]?.extensions ?? [];
2131
+ const components = componentsOf(files);
2132
+ return {
2133
+ id,
2134
+ chain,
2135
+ system,
2136
+ files,
2137
+ meta: collectMetadata(files),
2138
+ // What the layers of this system added to the vocabulary, as the bundle itself records it.
2139
+ extensions,
2140
+ components,
2141
+ /** Every component's name, whether it declares an axis or not (`components` holds those that do). */
2142
+ componentNames: componentNamesOf(files),
2143
+ axisOf: (tokenId) => axisOf(components, tokenId),
2144
+ /** { declaredBy, rationale, declaredAs? } when a layer added this token; null for core vocabulary. */
2145
+ extensionOf(token) {
2146
+ const own = token.$extensions?.[VOCABULARY2];
2147
+ if (own?.extension) return { declaredBy: own.declaredBy, rationale: own.rationale };
2148
+ const axis = axisOf(components, token.id);
2149
+ const declaration = axis && extensions.find((e) => e.id === `${axis.id}.${axis.key}`);
2150
+ return declaration ? { declaredBy: declaration.declaredBy, rationale: declaration.rationale, declaredAs: declaration.id } : null;
2151
+ },
2152
+ /** Every token whose value moves when `tokenId` does — through aliases and rules, transitively. Ids are the same in every scheme. */
2153
+ followers(tokenId) {
2154
+ dependencies ??= dependencyIndex(Object.fromEntries(Object.entries(files).filter(([name]) => !name.endsWith(".resolver.json") && (!name.startsWith("generated/") || !/\.(light-|dark)/.test(name)))));
2155
+ return [...dependencies.followers(tokenId)].sort();
2156
+ },
2157
+ tokens: resolved.tokens,
2158
+ load: resolved.load,
2159
+ // Accessibility and structure invariants: constants in @tanrei/tokens-build, the same ones a build reports.
2160
+ // Computed once, on first use, from the light tokens and the role colors of every scheme.
2161
+ warnings: resolved.warnings
2162
+ };
2163
+ }
2164
+ var rootIds;
2165
+ async function coreIds() {
2166
+ rootIds ??= loadContext({ system: ROOT_SYSTEM2 }).then((ctx) => new Map(Object.entries(ctx.tokens("light")).map(([id, token]) => [id, token.$type])));
2167
+ return rootIds;
2168
+ }
2169
+ var INTENT_ROLES = (name) => [name, `on-${name}`, `${name}-container`, `on-${name}-container`].map((role) => `${SYS_COLOR2}${role}`);
2170
+ function tidySchemaProblems(problems, layers) {
2171
+ const out = [];
2172
+ const told = /* @__PURE__ */ new Set();
2173
+ for (const problem of problems) {
2174
+ const keys = /^(\S+) \/vocabulary (?:must match pattern "(.+)"|property name must be valid)$/.exec(problem);
2175
+ if (keys) {
2176
+ const layer = layers.find((l) => `${l.id}${LAYER_SUFFIX2}` === keys[1]);
2177
+ if (keys[2] && layer) {
2178
+ for (const id of Object.keys(layer.vocabulary ?? {})) if (!new RegExp(keys[2]).test(id)) out.push(`${keys[1]} /vocabulary/${id}: not an id a layer can declare. Declare "${NS2}.sys.\u2026" / "${NS2}.comp.\u2026" (inside Tanrei's tree) or "${layer.id}.sys.\u2026" / "${layer.id}.comp.\u2026" (your own namespace); every segment is lowercase letters, digits and hyphens.`);
2179
+ }
2180
+ if (layer) continue;
2181
+ }
2182
+ const at = /^(\S+) \/vocabulary\/([^/\s]+)(\/\S*)? /.exec(problem);
2183
+ const entry = at && layers.find((l) => `${l.id}${LAYER_SUFFIX2}` === at[1])?.vocabulary?.[at[2]];
2184
+ if (!at || !entry || typeof entry !== "object") {
2185
+ out.push(problem);
2186
+ continue;
2187
+ }
2188
+ const where = `${at[1]} /vocabulary/${at[2]}`;
2189
+ const say = (message) => void (told.has(`${where}${message}`) || (told.add(`${where}${message}`), out.push(`${where}: ${message}`)));
2190
+ if ("from" in entry === "$type" in entry) say('an extension is either a token \u2014 "$type" with a value ("$value" or "derive") \u2014 or a value on a component axis \u2014 "from", an existing value of that axis. It has ' + ("from" in entry ? "both" : "neither") + ".");
2191
+ else if (typeof entry.rationale !== "string" || entry.rationale.length < 8) say('an extension needs a "rationale" (8+ characters): why does this design system or product need it?');
2192
+ else {
2193
+ const branchNoise = "from" in entry ? /required property '\$type'/ : /required property 'from'/;
2194
+ if (!/must match exactly one schema in oneOf/.test(problem) && !branchNoise.test(problem)) out.push(problem);
2195
+ }
2196
+ }
2197
+ return [...new Set(out)];
2198
+ }
2199
+ function layerProblems(reference, { chain, input }) {
2200
+ const problems = validateSystem(input);
2201
+ return reference.kind === "shipped" ? problems : tidySchemaProblems(problems, chain);
2202
+ }
2203
+ function checkVocabulary(chain, reports) {
2204
+ const problems = [];
2205
+ const failed = [];
2206
+ const fail = (layer, id, message) => {
2207
+ failed.push(id);
2208
+ if (reports(layer)) problems.push(`${layer}: vocabulary: ${message}`);
2209
+ };
2210
+ const accepted = chain.map((layer) => ({ id: layer.id, vocabulary: {} }));
2211
+ chain.forEach((layer, i) => {
2212
+ for (const [id, entry] of Object.entries(layer.vocabulary ?? {})) {
2213
+ if (isPlaceholder(entry?.rationale)) {
2214
+ fail(layer.id, id, `${id}: the "rationale" is still the placeholder. Say why this design system or product needs it \u2014 it is shown wherever the token is shown.`);
2215
+ continue;
2216
+ }
2217
+ try {
2218
+ collectVocabulary2([...accepted.slice(0, i), { id: layer.id, vocabulary: { ...accepted[i].vocabulary, [id]: entry } }]);
2219
+ accepted[i].vocabulary[id] = entry;
2220
+ } catch (error) {
2221
+ fail(layer.id, id, error.message);
2222
+ }
2223
+ }
2224
+ });
2225
+ const docs = clone4(sourceFiles(REPO_ROOT));
2226
+ const known = /* @__PURE__ */ new Map();
2227
+ const declared = Object.entries(collectVocabulary2(accepted)).sort(([, a], [, b]) => Number(a.kind === "axis-value") - Number(b.kind === "axis-value"));
2228
+ for (const [id, declaration] of declared) {
2229
+ if (declaration.kind === "token" && id.startsWith(SYS_COLOR2)) known.set(id, "color");
2230
+ try {
2231
+ materializeVocabulary(docs, { vocabulary: { [id]: declaration }, tokens: {} });
2232
+ } catch (error) {
2233
+ fail(declaration.declaredBy, id, error.message);
2234
+ }
2235
+ }
2236
+ for (const doc of Object.values(docs)) for (const { id, type } of walkTokens(doc)) known.set(id, type);
2237
+ for (const { id, type } of expandStateVocabulary(Object.entries(docs).filter(([name]) => name.startsWith("comp/")).map(([, doc]) => doc))) known.set(id, type);
2238
+ return { problems, failed, known };
2239
+ }
2240
+ function echoesFailure(tokenId, failed) {
2241
+ return failed.some((id) => {
2242
+ if (tokenId === id) return true;
2243
+ const parts = id.split(".");
2244
+ return parts[1] === "comp" && tokenId.startsWith(`${parts.slice(0, 3).join(".")}.`) && tokenId.split(".").includes(parts.at(-1));
2245
+ });
2246
+ }
2247
+ async function philosophyProblems(chain) {
2248
+ const shipped = new Set(shippedSystems());
2249
+ const reports = (layerId) => !shipped.has(layerId) || layerId === chain.at(-1).id;
2250
+ const vocabulary = checkVocabulary(chain, reports);
2251
+ const known = new Map([...await coreIds(), ...vocabulary.known]);
2252
+ for (const layer of chain) for (const [name, decl] of Object.entries(layer.palettes ?? {})) if (decl?.roles === "intent") for (const id of INTENT_ROLES(name)) known.set(id, "color");
2253
+ const problems = [...vocabulary.problems];
2254
+ for (const layer of chain) {
2255
+ if (!reports(layer.id)) continue;
2256
+ for (const [id, op] of Object.entries(layer.tokens ?? {})) {
2257
+ const at = `${layer.id}: ${id}`;
2258
+ if (!known.has(id)) {
2259
+ if (echoesFailure(id, vocabulary.failed)) continue;
2260
+ problems.push(`${at}: not a token of this system. If a token with this meaning already exists, use it (search_tokens). Otherwise ADD it: declare it under "vocabulary" with a "rationale" \u2014 a step in a series, a value on a component axis, or a token in this layer's own namespace ("${layer.id}.comp.\u2026") \u2014 and propose_extension writes the declaration for you. For a whole color family, declare a palette with "roles": "intent".`);
2261
+ continue;
2262
+ }
2263
+ if (op.$type && op.$type !== known.get(id)) problems.push(`${at}: a layer cannot change $type (${known.get(id)} \u2192 ${op.$type}). Extensions are additive: declare a token of your own instead.`);
2264
+ const pinsLiteral = "$value" in op && !isRef5(op.$value);
2265
+ if (pinsLiteral && id.startsWith(SYS_COLOR2)) problems.push(`${at}: a color role is not pinned to a literal. Give it a rule ({"derive": {"fn": "tone", "palette": \u2026, "tone": {"light": [\u2026], "dark": [\u2026]}}}), alias another role, or change the palette's seed under "palettes".`);
2266
+ else if (pinsLiteral && (typeof op.reason !== "string" || op.reason.length < 8)) problems.push(`${at}: pinning a literal "$value" needs a "reason" (8+ characters): a pinned token stops following the dials, and the next person must know why.`);
2267
+ else if (pinsLiteral && isPlaceholder(op.reason)) problems.push(`${at}: the "reason" is still the placeholder. Say why this value is pinned.`);
2268
+ }
2269
+ for (const [index, rule] of (layer.rules ?? []).entries()) {
2270
+ const at = `${layer.id}: rules[${index}] ${rule.match}`;
2271
+ if (![...known.keys()].some((id) => matchSegments(rule.match, id)) && !vocabulary.failed.length) problems.push(`${at}: matches no token. Patterns value the per-state component tokens that exist \u2014 core ones, and those of a variant declared under "vocabulary". Interaction states themselves are not extensible.`);
2272
+ if ("$value" in rule && !isRef5(rule.$value) && (typeof rule.reason !== "string" || rule.reason.length < 8)) problems.push(`${at}: a literal "$value" needs a "reason".`);
2273
+ }
2274
+ }
2275
+ return problems;
2276
+ }
2277
+ async function validateLayer2(input) {
2278
+ const reference = describeReference(input);
2279
+ if (reference.kind === "shipped") throw new ToolError('validate_layer checks a product layer: pass "layerFile" or "layer". Shipped systems are validated by the Tanrei repository itself.');
2280
+ if (reference.kind === "inline" && (typeof reference.layer.id !== "string" || !reference.layer.id)) return { id: null, chain: [], valid: false, problems: ["/ must have required property 'id'"] };
2281
+ let read;
2282
+ try {
2283
+ read = readChain(reference);
2284
+ } catch (error) {
2285
+ return { id: reference.layer?.id ?? systemIdOf(reference.file), chain: [], valid: false, problems: [error.message] };
2286
+ }
2287
+ const chain = read.chain.map((l) => l.id);
2288
+ const problems = layerProblems(reference, read);
2289
+ if (!problems.length) problems.push(...await philosophyProblems(read.chain));
2290
+ if (problems.length) return { id: read.id, chain, valid: false, problems };
2291
+ try {
2292
+ const ctx = await loadContext(input);
2293
+ return { id: read.id, chain, valid: true, problems: [], tokens: Object.keys(ctx.tokens("light")).length, extensions: ctx.extensions.length, ...ctx.system.notices?.length ? { notices: ctx.system.notices } : {}, warnings: await ctx.warnings() };
2294
+ } catch (error) {
2295
+ return { id: read.id, chain, valid: false, problems: [error.message, ...error.details?.problems ?? []] };
2296
+ }
2297
+ }
2298
+
2299
+ // src/resources.js
2300
+ var INSTRUCTIONS = `Tanrei is a small, simply named core vocabulary of design tokens shipped to five platforms, which any design system can reproduce exactly: a design system is a layer file (<id>.system.json) that changes VALUES and, where the core has no word for something, EXTENDS the vocabulary.
2301
+ Hard rules:
2302
+ - Values first. Find the existing token with search_tokens and change it in the layer, in this order of preference: set a dial, "scale" an inherited rule, re-point an alias, replace "derive", and only then pin a literal "$value" \u2014 a pinned literal needs a "reason" (8+ characters). New color families are declared under "palettes" with "roles": "intent". Never edit generated files.
2303
+ - If the word really is missing, add it \u2014 in the layer, under "vocabulary", with a "rationale" (8+ characters): a step in a series, a value on a component axis (a size, a variant), or the layer's own token in its own namespace ("<layer id>.comp.\u2026"). propose_extension writes and verifies the declaration. Additive only: never re-declare, remove or retype what exists (change its value under "tokens"); interaction states are not extensible; nothing in tanrei.* may reference a layer's own token.
2304
+ - Accessibility thresholds are constants, for extensions too. Nothing in a layer changes them; a violation in a product layer is a warning that every build prints. Do not try to silence it \u2014 fix the value or report it.
2305
+ - Call explain_token before editing a token and validate_layer before saving; after editing the layer run \`tanrei build\` (@tanrei/cli) to regenerate every platform.
2306
+ Read tanrei://philosophy once.`;
2307
+ var PHILOSOPHY = `# Tanrei in one page
2308
+
2309
+ Tanrei holds two ideals at once:
2310
+ - **(a) a small core** \u2014 Tanrei's own tokens are a necessary and sufficient set, simply named, fitted to no one design system;
2311
+ - **(b) exact reproduction** \u2014 by customizing Tanrei, any design system can be matched exactly, not approximated.
2312
+ Both hold because **the core stays small and any layer may extend it**. Nothing is added to the core for somebody else's sake.
2313
+
2314
+ ## The core: the one-product test
2315
+ A core token exists because ONE product may need the distinction, by meaning or by place (\`focus-ring\` is not \`primary\`:
2316
+ a product may want a saturated brand color and a quiet focus ring). It does not exist because one design system has it,
2317
+ nor because a component uses it today. Core changes happen only in the Tanrei repository (tokens/, lock file, review).
2318
+
2319
+ ## Tiers and kinds
2320
+ Four tiers, one reference order: \`dial < ref < sys < comp\`. Components read \`comp\` tokens only. Seven numeric dials sit
2321
+ under everything: type.base 16px, type.contrast 1, space.unit 8px, size.unit 4px, shape.unit 2px, stroke.unit 1px,
2322
+ motion.unit 50ms. Color seeds are palette declarations, not dials. Every value is one of three kinds:
2323
+ - **derived** \u2014 a rule in a closed language: \`mul\`, \`scale\`, \`clamp\`, \`em\`; \`tone\`, \`alpha\`, \`contrast-pick\` for color roles; \`mix\`, \`alpha\`, \`tone\`,
2324
+ \`contrast-pick\` ({ on, from: [\u2026] } \u2192 the most readable candidate, per scheme) for per-state component colors. No addition, conditionals or user functions.
2325
+ - **fixed** \u2014 a literal with a stated reason, exempt from the dials. - **alias** \u2014 a reference that can be re-pointed.
2326
+
2327
+ ## A design system is a layer
2328
+ \`<id>.system.json\`: \`id\`, \`extends\` (every chain ends at the root \`tanrei\`), \`vocabulary\`, \`palettes\`, \`tokens\`, \`rules\`.
2329
+ **Values first.** Operations under \`tokens\`, keyed by an existing token id \u2014 prefer the earliest that does the job:
2330
+ 1. set a dial \`"tanrei.dial.type.base": { "$value": { "value": 17, "unit": "px" }, "reason": "\u2026" }\`
2331
+ 2. scale \`{ "scale": 2 }\` \u2014 N \xD7 the inherited rule or alias, still following its dial
2332
+ 3. re-point alias \`{ "$value": "{tanrei.sys.space.space50}" }\`
2333
+ 4. replace the rule \`{ "derive": { "fn": "mul", "of": "{tanrei.dial.shape.unit}", "by": 4 } }\`
2334
+ 5. pin a literal \`{ "$value": \u2026, "reason": "\u2026" }\` \u2014 stops following dials; the reason is mandatory.
2335
+ \`palettes\`: re-declare a palette (\`{ "source": { "seed": "#rrggbb" } }\`) to recolor every role that reads it; \`"roles": "intent"\`
2336
+ plus a \`description\` gives \`<name>\`, \`on-<name>\`, \`<name>-container\`, \`on-<name>-container\`, contrast-checked; \`null\` drops one.
2337
+ A source may state single tones exactly \u2014 \`"tones": { "40": "#6750a4" }\` (a published ramp, a brand color); the rest are generated.
2338
+ Color roles take \`derive\` (tone / alpha / contrast-pick) or an alias, never a literal. A choice of kind (\`tanrei.sys.behavior.*\`) takes one of its NAMES (\`{ "$value": "ripple", "reason": "\u2026" }\`); a typeface takes a font stack that ends in a system or generic fallback.
2339
+ \`rules\`: pattern rules value per-state component tokens (\`tanrei.comp.*.*.hovered.container.color\`); \`*\` is one segment,
2340
+ available as $1, $2\u2026. An explicit \`tokens\` entry beats a pattern; fewer wildcards win; then the later layer.
2341
+
2342
+ ## Extending the vocabulary
2343
+ \`vocabulary\` says that something EXISTS; \`tokens\` and \`rules\` then value it like any core token. Three kinds, one mechanism:
2344
+ 1. **a step in a series**, inside Tanrei's tree \u2014 or a single color role with its \`onRole\`:
2345
+ \`"tanrei.sys.space.space1200": { "$type": "dimension", "rationale": "\u2026", "derive": { "fn": "mul", "of": "{tanrei.dial.space.unit}", "by": 12 } }\`
2346
+ 2. **a value on a component axis** \u2014 one line values every member; a variant's state tokens come from the pattern rules:
2347
+ \`"tanrei.comp.button.size.3x": { "from": "large", "scale": 1.5, "rationale": "\u2026" }\`, \`"tanrei.comp.button.variant.danger": { "from": "filled", "rationale": "\u2026" }\`
2348
+ 3. **the layer's own tokens**, in its own namespace = the layer id: \`"acme.comp.rating.star.size": { "$type": "dimension", \u2026 }\`.
2349
+ They may reference \`tanrei.*\`; nothing in \`tanrei.*\` may reference them. On the web they are \`--acme-\u2026\`.
2350
+ - Every declaration carries a **rationale** (8+ characters) and is attributed to its layer (\`declaredBy\`).
2351
+ - **Additive only**, inherited down \`extends\`. No layer removes or retypes vocabulary; re-declaring what core or an
2352
+ ancestor declared is an error \u2014 change its value under \`tokens\`.
2353
+ - **Interaction states are not extensible**: hovered, focused, pressed, disabled are platform behaviour. How they LOOK is a value.
2354
+ - Traits no token can express are Tanrei defects, listed by mimicry_gaps until a token can express them.
2355
+
2356
+ ## Accessibility
2357
+ The ruler never changes, for core and extensions alike: text 4.5:1 (7:1 in high contrast), non-text and focus 3:1, and a
2358
+ control's height must hold its content. These are constants in code. In the root system a violation fails the build; in
2359
+ a product layer it is a warning \u2014 printed, written to a11y-report.json, stamped into every generated file. An imitation
2360
+ preset is held to fidelity to its original, not to Tanrei's accessibility criteria, in every contrast scheme: its
2361
+ contrast is reported as measurements, not warnings; a structural or functional failure fails its build, as in the root.
2362
+
2363
+ ## Workflow for a product
2364
+ search_tokens \u2192 explain_token (\`howToChange\`, \`howToExtend\`) \u2192 propose_extension if a word is missing \u2192 edit the layer \u2192
2365
+ validate_layer \u2192 \`tanrei build\` (one layer in; DTCG bundle, CSS, Tailwind/shadcn, SwiftUI, Compose, Flutter, React Native out).
2366
+ `;
2367
+ var SYSTEM_URI = /^tanrei:\/\/systems\/([a-z0-9-]+)$/;
2368
+ function listResources() {
2369
+ return [
2370
+ { uri: "tanrei://philosophy", name: "Tanrei philosophy", description: "The two ideals (a small core, exact reproduction), tiers and kinds, the operations a layer may perform and the three ways it may extend the vocabulary. Read once before editing a layer.", mimeType: "text/markdown" },
2371
+ { uri: "tanrei://schema/system", name: "Layer JSON Schema", description: "JSON Schema of a design system layer (<id>.system.json).", mimeType: "application/schema+json" },
2372
+ ...shippedSystems().map((id) => {
2373
+ const layer = shippedLayer(id);
2374
+ return { uri: `tanrei://systems/${id}`, name: `System layer: ${id}`, description: `${layer.name ?? id}${layer.extends ? ` (extends ${layer.extends})` : " (root)"} \u2014 the layer file as authored. A worked example of every operation.`, mimeType: "application/json" };
2375
+ })
2376
+ ];
2377
+ }
2378
+ function readResource(uri) {
2379
+ if (uri === "tanrei://philosophy") return { uri, mimeType: "text/markdown", text: PHILOSOPHY };
2380
+ if (uri === "tanrei://schema/system") return { uri, mimeType: "application/schema+json", text: fs6.readFileSync(path7.join(REPO_ROOT, "tokens/schema/system.schema.json"), "utf8") };
2381
+ const id = SYSTEM_URI.exec(uri)?.[1];
2382
+ if (id && shippedSystems().includes(id)) return { uri, mimeType: "application/json", text: fs6.readFileSync(path7.join(REPO_ROOT, "tokens/systems", `${id}.system.json`), "utf8") };
2383
+ throw new ToolError(`unknown resource ${uri}. Known: ${listResources().map((r) => r.uri).join(", ")}`);
2384
+ }
2385
+
2386
+ // src/tools.js
2387
+ import fs7 from "node:fs";
2388
+ import path8 from "node:path";
2389
+
2390
+ // ../tokens-build/src/emit/css.js
2391
+ var PREFIX = CONFIG.web.cssPrefix;
2392
+ var varName = (path9) => `${PREFIX}-${kebab(path9)}`;
2393
+ var idToVar = (id) => id.startsWith(`${CONFIG.namespace}.`) ? varName(id.split(".").slice(1)) : `--${kebab(id.split("."))}`;
2394
+ var CORNER = `${CONFIG.namespace}.sys.shape.corner.`;
2395
+ var FULL = `${CORNER}full`;
2396
+
2397
+ // src/tools.js
2398
+ var legalOperations2 = (descriptor) => legalOperations(descriptor, { namespace: NS2 });
2399
+ var extensionRecipes2 = (descriptor, layerId) => extensionRecipes(descriptor, layerId, { namespace: NS2 });
2400
+ var CANNOT2 = cannot(NS2);
2401
+ var TIERS = ["dial", "ref", "sys", "comp"];
2402
+ var SYS_COLOR3 = `${NS2}.sys.color.`;
2403
+ var systemProperties = {
2404
+ system: { type: "string", description: `A shipped system id (default "${ROOT_SYSTEM2}"), or the path of a product's <id>.system.json.` },
2405
+ layerFile: { type: "string", description: "Path of a product's <id>.system.json (absolute, or relative to the server's working directory). Wins over `system`." }
2406
+ };
2407
+ var schemeProperty = { type: "string", enum: SCHEMES, default: "light", description: "Theme \xD7 contrast. Only colors differ between schemes." };
2408
+ var pagination = (limit, max) => ({
2409
+ limit: { type: "integer", minimum: 1, maximum: max, default: limit },
2410
+ offset: { type: "integer", minimum: 0, default: 0 }
2411
+ });
2412
+ function page(items, { offset = 0, limit }) {
2413
+ const slice = items.slice(offset, offset + limit);
2414
+ return { total: items.length, offset, limit, nextOffset: offset + slice.length < items.length ? offset + slice.length : null, items: slice };
2415
+ }
2416
+ var tierOf2 = (id) => id.split(".")[1];
2417
+ var clip = (text2, max = 140) => typeof text2 === "string" && text2.length > max ? `${text2.slice(0, max - 1)}\u2026` : text2;
2418
+ function formatValue(value) {
2419
+ if (Array.isArray(value)) return value.map(formatValue);
2420
+ if (!value || typeof value !== "object") return value;
2421
+ if ("colorSpace" in value) {
2422
+ const hex = value.hex ?? `#${value.components.map((c) => Math.round(c * 255).toString(16).padStart(2, "0")).join("")}`;
2423
+ return value.alpha === void 0 || value.alpha === 1 ? hex : `${hex} / ${value.alpha}`;
2424
+ }
2425
+ if ("value" in value && "unit" in value && Object.keys(value).length === 2) return `${value.value}${value.unit}`;
2426
+ return Object.fromEntries(Object.entries(value).map(([key, v]) => [key, formatValue(v)]));
2427
+ }
2428
+ var choiceOf2 = (token) => {
2429
+ const names = token.$extensions?.[ENUM]?.values;
2430
+ return names ? { value: enumName(token) ?? token.$value, choice: { name: enumName(token) ?? null, index: token.$value, of: names } } : null;
2431
+ };
2432
+ var shownValue = (token) => choiceOf2(token)?.value ?? formatValue(token.$value);
2433
+ function kindAndRule(ctx, token) {
2434
+ const id = token.id;
2435
+ if (id.startsWith(SYS_COLOR3)) {
2436
+ const op = ctx.system.tokens[id];
2437
+ if (isRef5(op?.$value)) return { kind: "alias" };
2438
+ const target = token.aliasChain?.[0]?.split(".") ?? [];
2439
+ return { kind: "derived", rule: op?.derive ?? { fn: "tone", palette: target[3], note: 'The default tones every intent palette gets; the palette is declared under "palettes".' } };
2440
+ }
2441
+ if (id.startsWith(`${NS2}.ref.palette.`)) {
2442
+ const [palette, tone] = id.split(".").slice(3);
2443
+ const exact = ctx.system.palettes?.[palette]?.source?.tones?.[tone];
2444
+ return { kind: "derived", rule: { palette, tone: Number(tone), ...exact ? { exact, note: 'An exact color the palette declares under "source.tones" \u2014 not generated from the seed. Change the palette under "palettes", not this token.' } : { note: 'A tone of a declared palette. Change the palette under "palettes", not this token.' } } };
2445
+ }
2446
+ if (isRef5(token.originalValue?.$value)) return { kind: "alias" };
2447
+ const rule = token.$extensions?.[DERIVE2];
2448
+ if (rule && "fixed" in rule) return { kind: "fixed", rule };
2449
+ if (rule) return { kind: "derived", rule };
2450
+ return { kind: tierOf2(id) === "dial" ? "dial" : "fixed" };
2451
+ }
2452
+ function requireToken(ctx, id, scheme = "light") {
2453
+ const token = ctx.tokens(scheme)[id];
2454
+ if (token) return token;
2455
+ const ids = Object.keys(ctx.tokens("light"));
2456
+ let prefix = id.split(".");
2457
+ let near = [];
2458
+ while (prefix.length > 3 && !near.length) {
2459
+ prefix = prefix.slice(0, -1);
2460
+ near = ids.filter((other) => other.startsWith(`${prefix.join(".")}.`));
2461
+ }
2462
+ throw new ToolError(`${id}: not in system "${ctx.id}". If a token with this meaning exists, use it (search_tokens; \`near\` lists its neighbours). To add it, declare it under "vocabulary" with a rationale \u2014 see propose_extension.`, { near: near.slice(0, 8) });
2463
+ }
2464
+ function descriptorOf(ctx, token, { kind, rule }) {
2465
+ return { id: token.id, type: token.$type, value: token.$value, alias: kind === "alias" ? token.aliasChain?.[0] ?? null : null, rule: rule ?? null, state: token.$extensions?.[STATE] ?? false, axis: ctx.axisOf(token.id) ?? void 0, choices: token.$extensions?.[ENUM]?.values };
2466
+ }
2467
+ var editableLayerId = (ctx) => shippedSystems().includes(ctx.id) ? void 0 : ctx.id;
2468
+ var extensionFlags = (ctx, token) => {
2469
+ const extension = ctx.extensionOf(token);
2470
+ return extension ? { extension: true, declaredBy: extension.declaredBy } : {};
2471
+ };
2472
+ function summarizeExtensions(extensions, first = 6) {
2473
+ const byKind = {};
2474
+ for (const { kind } of extensions) byKind[kind] = (byKind[kind] ?? 0) + 1;
2475
+ return { total: extensions.length, ...extensions.length ? { byKind } : {}, first: extensions.slice(0, first).map(({ id, kind, declaredBy }) => ({ id, kind, declaredBy })) };
2476
+ }
2477
+ function fidelityOf(id) {
2478
+ const file = path8.join(REPO_ROOT, "tokens/generated", id, "fidelity.json");
2479
+ if (!fs7.existsSync(file)) return void 0;
2480
+ const { equal, total, covered, different, unmapped, reference } = JSON.parse(fs7.readFileSync(file, "utf8"));
2481
+ return { equal, measured: total - covered, different: different.length, unmapped: unmapped.length, reference: { name: reference.name, version: reference.version, source: reference.source } };
2482
+ }
2483
+ function summarizeLayer(layer, chain) {
2484
+ const palettes = Object.entries(layer.palettes ?? {});
2485
+ return {
2486
+ id: layer.id,
2487
+ name: layer.name,
2488
+ extends: layer.extends ?? null,
2489
+ description: layer.description,
2490
+ inspiredBy: layer.attribution?.inspiredBy,
2491
+ palettes: palettes.filter(([, decl]) => decl).map(([name, decl]) => decl.roles === "intent" ? `${name} (intent roles)` : name),
2492
+ droppedPalettes: palettes.filter(([, decl]) => decl === null).map(([name]) => name),
2493
+ valueChanges: Object.keys(layer.tokens ?? {}).length,
2494
+ patternRules: (layer.rules ?? []).length,
2495
+ extensions: summarizeExtensions(declaredExtensions(chain))
2496
+ };
2497
+ }
2498
+ async function listSystemsTool({ layerFile, warnings = true }) {
2499
+ const ctx = layerFile ? await loadContext({ layerFile }) : null;
2500
+ const shipped = [];
2501
+ for (const id of shippedSystems()) {
2502
+ const summary = summarizeLayer(shippedLayer(id), readLayers({ system: id }).chain);
2503
+ const fidelity = fidelityOf(id);
2504
+ if (fidelity) summary.fidelity = fidelity;
2505
+ if (warnings) {
2506
+ const findings = await (await loadContext({ system: id })).warnings();
2507
+ if (id === ROOT_SYSTEM2) summary.accessibilityWarnings = findings.length;
2508
+ else {
2509
+ const failures = findings.filter((f) => !isCriterionFinding(f));
2510
+ summary.accessibility = { criteria: "not-applied", measurements: findings.length - failures.length, because: PRESET_CRITERIA_NOTE, ...failures.length ? { failures } : {} };
2511
+ }
2512
+ }
2513
+ shipped.push(summary);
2514
+ }
2515
+ const result = { root: ROOT_SYSTEM2, schemes: SCHEMES, shipped };
2516
+ if (ctx) {
2517
+ const known = new Set(shippedSystems());
2518
+ result.product = {
2519
+ id: ctx.id,
2520
+ chain: ctx.chain.map((l) => l.id),
2521
+ layers: ctx.chain.filter((l) => !known.has(l.id)).map((l) => summarizeLayer(l, ctx.chain.slice(0, ctx.chain.indexOf(l) + 1))),
2522
+ ...warnings ? { accessibilityWarnings: (await ctx.warnings()).length } : {}
2523
+ };
2524
+ }
2525
+ return result;
2526
+ }
2527
+ function matcher(query, namespaces = [NS2]) {
2528
+ if (!query) return () => true;
2529
+ if (!query.includes("*")) {
2530
+ const needle = query.toLowerCase();
2531
+ return (id) => id.toLowerCase().includes(needle);
2532
+ }
2533
+ const rooted = namespaces.includes(query.split(".")[0]) || query.startsWith("*") ? query : `${NS2}.${query}`;
2534
+ const segments2 = rooted.split(".");
2535
+ const source = segments2.map((segment, i) => segment === "**" || segment === "*" && i === segments2.length - 1 && i > 0 ? ".+" : segment.replace(/[$()+?[\]^{|}\\]/g, "\\$&").replace(/\*/g, "[^.]*")).join("\\.");
2536
+ const pattern = new RegExp(`^${source}$`);
2537
+ return (id) => pattern.test(id);
2538
+ }
2539
+ async function searchTokens({ query, tier, type, kind, extensions, limit = 25, offset = 0, ...reference }) {
2540
+ const ctx = await loadContext(reference);
2541
+ const all = Object.values(ctx.tokens("light"));
2542
+ const matches = matcher(query, [...new Set(all.map((token) => token.id.split(".")[0]))]);
2543
+ const found = [];
2544
+ for (const token of all) {
2545
+ if (!matches(token.id) || tier && tierOf2(token.id) !== tier || type && token.$type !== type) continue;
2546
+ const described = kindAndRule(ctx, token).kind;
2547
+ if (kind && described !== kind) continue;
2548
+ const flags = extensionFlags(ctx, token);
2549
+ if (extensions !== void 0 && extensions !== Boolean(flags.extension)) continue;
2550
+ found.push({ id: token.id, $type: token.$type, kind: described, ...choiceOf2(token) ? { value: choiceOf2(token).value, choices: choiceOf2(token).choice.of } : {}, ...flags, description: clip(token.$description ?? ctx.meta.get(token.id)?.vocabulary?.rationale) });
2551
+ }
2552
+ found.sort((a, b) => a.id.localeCompare(b.id));
2553
+ const { items, ...rest } = page(found, { offset, limit });
2554
+ return { system: ctx.id, ...rest, tokens: items };
2555
+ }
2556
+ function resolveOne(ctx, id, scheme, raw) {
2557
+ const token = requireToken(ctx, id, scheme);
2558
+ const { kind, rule } = kindAndRule(ctx, token);
2559
+ const tokens = ctx.tokens(scheme);
2560
+ const inputs = Object.fromEntries(ruleDependencies(rule).filter((dep) => tokens[dep]).map((dep) => [dep, formatValue(tokens[dep].$value)]));
2561
+ return {
2562
+ id,
2563
+ $type: token.$type,
2564
+ value: shownValue(token),
2565
+ ...choiceOf2(token) ? { choice: choiceOf2(token).choice } : {},
2566
+ ...raw ? { $value: token.$value } : {},
2567
+ kind,
2568
+ ...token.aliasChain?.length ? { aliasChain: token.aliasChain } : {},
2569
+ ...rule ? { rule } : {},
2570
+ ...Object.keys(inputs).length ? { inputs } : {},
2571
+ ...ctx.system.tokens[id]?.layer ? { setBy: ctx.system.tokens[id].layer } : {},
2572
+ ...extensionFlags(ctx, token),
2573
+ cssVar: idToVar(id)
2574
+ };
2575
+ }
2576
+ async function resolveTool({ token, tokens, scheme = "light", raw = false, ...reference }) {
2577
+ const ids = [...token ? [token] : [], ...tokens ?? []];
2578
+ if (!ids.length) throw new ToolError('Pass "token" (one id) or "tokens" (up to 50 ids). Use search_tokens to find ids.');
2579
+ const ctx = await loadContext(reference, { scheme });
2580
+ return {
2581
+ system: ctx.id,
2582
+ chain: ctx.chain.map((l) => l.id),
2583
+ scheme,
2584
+ tokens: ids.map((id) => {
2585
+ try {
2586
+ return resolveOne(ctx, id, scheme, raw);
2587
+ } catch (error) {
2588
+ if (!(error instanceof ToolError)) throw error;
2589
+ return { id, error: error.message, ...error.details };
2590
+ }
2591
+ })
2592
+ };
2593
+ }
2594
+ async function explainToken({ token: id, scheme = "light", ...reference }) {
2595
+ const ctx = await loadContext(reference, { scheme });
2596
+ const token = requireToken(ctx, id, scheme);
2597
+ const { kind, rule } = kindAndRule(ctx, token);
2598
+ const descriptor = descriptorOf(ctx, token, { kind, rule });
2599
+ const extension = ctx.extensionOf(token);
2600
+ const followers = ctx.followers(id);
2601
+ const meta = ctx.meta.get(id) ?? {};
2602
+ const palette = id.startsWith(SYS_COLOR3) ? rule?.palette ?? null : id.startsWith(`${NS2}.ref.palette.`) ? id.split(".")[3] : null;
2603
+ const precedence = matchingRules(id, ctx.chain);
2604
+ const touchedBy = [];
2605
+ for (const layer of ctx.chain) {
2606
+ const operation = layer.tokens?.[id];
2607
+ const rules = precedence.rules.filter((r) => r.layer === layer.id).map(({ index, wins, because }) => ({ ...layer.rules[index], index, wins, because }));
2608
+ const declares = palette && layer.palettes && palette in layer.palettes ? { [palette]: layer.palettes[palette] } : void 0;
2609
+ if (operation || rules.length || declares) touchedBy.push({ layer: layer.id, ...operation ? { operation } : {}, ...rules.length ? { rules } : {}, ...declares ? { palette: declares } : {} });
2610
+ }
2611
+ const effective = token.$extensions?.[STATE] ? operationFor(id, ctx.system) : ctx.system.tokens[id];
2612
+ const { layer: setBy, ...effectiveOperation } = effective ?? {};
2613
+ return {
2614
+ id,
2615
+ system: ctx.id,
2616
+ chain: ctx.chain.map((l) => l.id),
2617
+ $type: token.$type,
2618
+ kind,
2619
+ value: shownValue(token),
2620
+ ...choiceOf2(token) ? { choice: choiceOf2(token).choice } : {},
2621
+ scheme,
2622
+ ...token.aliasChain?.length ? { aliasChain: token.aliasChain } : {},
2623
+ ...rule ? { rule } : {},
2624
+ cssVar: idToVar(id),
2625
+ description: token.$description,
2626
+ ...token.$deprecated ? { deprecated: token.$deprecated } : {},
2627
+ // Core vocabulary, or an extension a layer of this system declared — with who declared it and why.
2628
+ ...extension ? { extension: true, ...extension } : {},
2629
+ vocabulary: meta.vocabulary ?? null,
2630
+ // Usage guidance for agents, from the token and every group above it (outermost first). Optional metadata.
2631
+ llm: meta.llm?.length ? meta.llm : null,
2632
+ touchedBy: touchedBy.length ? touchedBy : extension ? `No layer changes ${id} after "${extension.declaredBy}" declared it: it has the value of its declaration.` : `No layer changes ${id}: it has the default the vocabulary gives it.`,
2633
+ ...effective ? { effectiveOperation, ...setBy ? { setBy } : {} } : {},
2634
+ // For a per-state token: the ONE pattern rule that values it (or the explicit entry that beats them all), and why.
2635
+ ...precedence.rules.length ? { winningRule: precedence.explicit ? { explicit: true, layer: precedence.explicit.layer, because: `an explicit entry under "tokens" (layer "${precedence.explicit.layer}") beats every pattern` } : (({ layer, index, match, wildcards, because }) => ({ layer, index, match, wildcards, because }))(precedence.rules.find((r) => r.wins)) } : {},
2636
+ usedBy: token.aliasedBy?.length ? { total: token.aliasedBy.length, first: token.aliasedBy.slice(0, 8) } : void 0,
2637
+ // What follows this token: every token whose value moves when it does, through aliases and rules (transitively).
2638
+ followers: { total: followers.length, first: followers.slice(0, 8) },
2639
+ howToChange: legalOperations2(descriptor),
2640
+ howToExtend: extensionRecipes2(descriptor, editableLayerId(ctx)),
2641
+ cannot: CANNOT2,
2642
+ then: 'Every `write` is a fragment of a layer: merge it into the product\'s <id>.system.json ("tokens", "palettes", "rules" or "vocabulary"), check the file with validate_layer, then run `tanrei build`. For a complete, verified `vocabulary` declaration use propose_extension.'
2643
+ };
2644
+ }
2645
+ var groupOf = (id) => id.split(".").slice(1, 3).join(".");
2646
+ function onlyIn(ctx, tokens, ids) {
2647
+ const extensions = ids.flatMap((id) => {
2648
+ const extension = ctx.extensionOf(tokens[id]);
2649
+ return extension ? [{ id, declaredBy: extension.declaredBy }] : [];
2650
+ });
2651
+ const declared = new Set(extensions.map((e) => e.id));
2652
+ const fromPalettes = ids.filter((id) => !declared.has(id));
2653
+ return {
2654
+ total: ids.length,
2655
+ extensions: { total: extensions.length, first: extensions.slice(0, 12) },
2656
+ fromPalettes: { total: fromPalettes.length, first: fromPalettes.filter((id) => !id.startsWith(`${NS2}.ref.`)).slice(0, 12) }
2657
+ };
2658
+ }
2659
+ async function diffSystems({ a, b, scheme = "light", group, limit = 20, offset = 0 }) {
2660
+ const [left, right] = await Promise.all([loadContext({ system: a }, { scheme }), loadContext({ system: b }, { scheme })]);
2661
+ const [ta, tb] = [left.tokens(scheme), right.tokens(scheme)];
2662
+ const changed = [];
2663
+ const onlyInA = [];
2664
+ const onlyInB = Object.keys(tb).filter((id) => !(id in ta));
2665
+ for (const [id, token] of Object.entries(ta)) {
2666
+ if (!(id in tb)) onlyInA.push(id);
2667
+ else if (JSON.stringify(formatValue(token.$value)) !== JSON.stringify(formatValue(tb[id].$value))) {
2668
+ const direct = [left, right].flatMap((ctx) => ctx.system.tokens[id]?.layer && ctx.system.tokens[id].layer !== ROOT_SYSTEM2 ? [ctx.system.tokens[id].layer] : []);
2669
+ changed.push({ id, a: shownValue(token), b: shownValue(tb[id]), ...direct.length ? { setBy: [...new Set(direct)] } : {} });
2670
+ }
2671
+ }
2672
+ changed.sort((x, y) => TIERS.indexOf(tierOf2(x.id)) - TIERS.indexOf(tierOf2(y.id)) || x.id.localeCompare(y.id));
2673
+ const groups = {};
2674
+ for (const { id } of changed) groups[groupOf(id)] = (groups[groupOf(id)] ?? 0) + 1;
2675
+ const byTier = Object.fromEntries(TIERS.map((tier) => [tier, changed.filter(({ id }) => tierOf2(id) === tier).length]));
2676
+ const selected = group ? changed.filter(({ id }) => groupOf(id) === group || tierOf2(id) === group) : changed;
2677
+ const { items, ...rest } = page(selected, { offset, limit });
2678
+ return {
2679
+ a: left.id,
2680
+ b: right.id,
2681
+ scheme,
2682
+ compared: Object.keys(ta).length - onlyInA.length,
2683
+ changed: changed.length,
2684
+ byTier,
2685
+ byGroup: groups,
2686
+ // Token SETS differ for two legitimate reasons: a layer extended the vocabulary, or declared/dropped a palette.
2687
+ onlyInA: onlyIn(left, ta, onlyInA),
2688
+ onlyInB: onlyIn(right, tb, onlyInB),
2689
+ ...onlyInA.length || onlyInB.length ? { note: "Ids on one side only are either EXTENSIONS \u2014 vocabulary a layer of that system declared, listed with `declaredBy` \u2014 or come from declared palettes (their four roles, and the ref.palette tones some role needs). Neither is an error." } : {},
2690
+ ...group ? { group } : {},
2691
+ ...rest,
2692
+ changes: items
2693
+ };
2694
+ }
2695
+ async function validateLayerTool({ layer, layerFile, parents, dir, limit = 20 }) {
2696
+ if (!layer === !layerFile) throw new ToolError('Pass exactly one of "layer" (the JSON object) or "layerFile" (its path).');
2697
+ if (layerFile && (parents || dir)) throw new ToolError('"parents" and "dir" go with "layer". A layer FILE finds its parents next to itself.');
2698
+ const result = await validateLayer2({ layer, layerFile, parents, dir });
2699
+ const { warnings, ...rest } = result;
2700
+ if (!result.valid) return { ...rest, next: "Fix the problems and validate again. Nothing is built from an invalid layer." };
2701
+ return {
2702
+ ...rest,
2703
+ // Thresholds are constants — for extensions too. In a product layer a violation warns; it is printed by `tanrei build` and stamped into every generated file.
2704
+ warnings: { total: warnings.length, severity: "warning", first: leadWithStructure(warnings).slice(0, limit) },
2705
+ next: "Run `tanrei build` to regenerate every platform from this layer."
2706
+ };
2707
+ }
2708
+ var RATIONALE2 = "<why this design system or product needs it \u2014 8+ characters>";
2709
+ var REASON2 = "<why this value is pinned \u2014 8+ characters>";
2710
+ var STAND_IN = "Stand-in text for a trial build; it is never written anywhere.";
2711
+ var parentOf = (id) => id.split(".").slice(0, -1).join(".");
2712
+ function checkNames(id, segments2) {
2713
+ for (const segment of segments2) if (!SEGMENT.test(segment)) throw new ToolError(`${id}: "${segment}" is not a valid name. Every segment is lowercase letters, digits and hyphens, starting with a letter or a digit (${SEGMENT.source}).`);
2714
+ }
2715
+ function refuseExisting(ctx, id, token, what) {
2716
+ const declaredBy = (token && ctx.extensionOf(token)?.declaredBy) ?? ctx.extensions.find((e) => e.id === id)?.declaredBy;
2717
+ throw new ToolError(`${id} already exists in "${ctx.id}" \u2014 ${declaredBy ? `layer "${declaredBy}" declared it` : "it is core vocabulary"}. Declaring it again is an error (extensions are additive, declared once). ${what}`, {
2718
+ exists: { id, declaredBy: declaredBy ?? "core" },
2719
+ ...token ? { howToChange: legalOperations2(descriptorOf(ctx, token, kindAndRule(ctx, token))) } : {}
2720
+ });
2721
+ }
2722
+ function briefValue(token) {
2723
+ const value = formatValue(token.$value);
2724
+ if (typeof value !== "object" || value === null) return value;
2725
+ if (choiceOf2(token)) return choiceOf2(token).value;
2726
+ if (token.$type === "typography") return `typography ${value.fontSize} / ${value.lineHeight} / ${value.fontWeight}${token.aliasChain?.length ? ` = {${token.aliasChain[0]}}` : ""}`;
2727
+ return `${token.$type}${token.aliasChain?.length ? ` = {${token.aliasChain[0]}}` : " (composite; use resolve)"}`;
2728
+ }
2729
+ function definitionLike(ctx, near, tokens) {
2730
+ const { kind, rule } = kindAndRule(ctx, near);
2731
+ if (near.id.startsWith(SYS_COLOR3)) {
2732
+ const role = near.id.slice(SYS_COLOR3.length);
2733
+ const onRole = tokens[`${SYS_COLOR3}on-${role}`] ? `${SYS_COLOR3}on-${role}` : `${SYS_COLOR3}on-surface`;
2734
+ return { derive: rule?.fn ? rule : { fn: "tone", palette: rule?.palette ?? "<palette>", tone: { light: [90], dark: [30] } }, onRole };
2735
+ }
2736
+ if (kind === "alias") return { $value: `{${near.aliasChain[0]}}` };
2737
+ if (kind === "derived" && rule?.fn === "mul") return { derive: { ...rule, by: `<coefficient \u2014 ${near.id.split(".").at(-1)} is ${rule.by}>` } };
2738
+ if (near.$type === "typography") return { $value: "<a full text style, or an alias to another typescale role>" };
2739
+ return { $value: near.$value, reason: REASON2 };
2740
+ }
2741
+ async function proposeExtension({ kind, near, component, axis, from, value, scale, id, $type, definition, layerId, ...reference }) {
2742
+ const { reference: described, chain } = readLayers(reference);
2743
+ const into = described.kind === "shipped" ? null : chain.at(-1);
2744
+ if (into && layerId && layerId !== into.id) throw new ToolError(`"layerId" (${layerId}) is not the id of ${reference.layerFile ?? reference.system} (${into.id}). Pass one of them.`);
2745
+ const layer = into?.id ?? layerId ?? null;
2746
+ if (layer !== null && !into && (shippedSystems().includes(layer) || !/^[a-z][a-z0-9-]*$/.test(layer))) throw new ToolError(`"${layer}" cannot be a product layer's id: lowercase letters, digits and hyphens, and not a shipped system (${shippedSystems().join(", ")}).`);
2747
+ const ctx = await loadContext(reference);
2748
+ const tokens = ctx.tokens("light");
2749
+ const nearToken = near ? requireToken(ctx, near) : null;
2750
+ const fragment = { vocabulary: {} };
2751
+ const notes = [];
2752
+ let declaration;
2753
+ if (kind === "axis-value") {
2754
+ const located = nearToken && ctx.axisOf(near);
2755
+ if (near && !located) throw new ToolError(`${near} is not on a component axis, so there is no size or variant to add next to it. Pass "component" and "axis", or use kind "step" / "own-token".`, { components: Object.fromEntries(Object.entries(ctx.components).map(([name, c]) => [name, Object.keys(c.axes)])) });
2756
+ const [componentName, axisName] = located ? located.id.split(".").slice(-2) : [component, axis];
2757
+ const declared = ctx.components[componentName];
2758
+ if (!declared) {
2759
+ const what = !componentName ? 'Pass "component" and "axis" (or "near": a token on the axis)' : ctx.componentNames.includes(componentName) ? `${NS2}.comp.${componentName} declares no axis, so there is no size or variant to add a value to; a layer adds VALUES to an axis, not axes` : `"${componentName}" is not a component of this system`;
2760
+ throw new ToolError(`${what}. Components with an axis: ${Object.keys(ctx.components).join(", ")}.`);
2761
+ }
2762
+ const onAxis = declared.axes[axisName];
2763
+ if (!onAxis) throw new ToolError(`${declared.id} has no axis "${axisName}". Its axes: ${Object.keys(declared.axes).join(", ")}. Axes are declared by the component; a layer adds VALUES to an axis, not axes.`);
2764
+ if (!value) throw new ToolError(`Pass "value": the name of the new ${axisName} (e.g. "3x", "danger").`);
2765
+ checkNames(`${declared.id}.${axisName}.${value}`, [value]);
2766
+ if (declared.states.includes(value)) throw new ToolError(`"${value}" is an interaction state. States are not extensible: ${declared.states.join(", ")} are bound to platform behaviour, not to values. How a state LOOKS is a value \u2014 see explain_token on ${declared.id}.<variant>.${value}.container.color, or a pattern rule.`);
2767
+ declaration = `${declared.id}.${axisName}.${value}`;
2768
+ if (onAxis.values.includes(value)) refuseExisting(ctx, declaration, null, `Value its tokens under "tokens": search_tokens "${onAxis.members ? `${declared.id}.**.${value}` : `${declared.id}.${value}.**`}".`);
2769
+ const source = from ?? located?.key ?? onAxis.default;
2770
+ if (!onAxis.values.includes(source)) throw new ToolError(`"from" must be an existing ${axisName} of ${componentName} (${onAxis.values.join(", ")}), not "${source}".`);
2771
+ if (scale !== void 0 && !onAxis.members) throw new ToolError(`"scale" applies to a size-like axis, whose members are numeric. A ${axisName} is cloned as it is; give its resting tokens values under "tokens".`);
2772
+ fragment.vocabulary[declaration] = { from: source, ...scale !== void 0 ? { scale } : {}, rationale: RATIONALE2 };
2773
+ if (onAxis.members) notes.push(`One line values every member of the axis (${onAxis.members.join(", ")}) from "${source}"${scale !== void 0 ? ", scaled and still following the dials" : ""}. Override a single member under "tokens", e.g. "${declared.id}.${onAxis.members[0]}.${value}".`);
2774
+ else {
2775
+ const prefix = `${declared.id}.${source}.`;
2776
+ const resting = Object.values(tokens).filter((t) => t.id.startsWith(prefix) && !t.$extensions?.[STATE] && t.$type === "color" && t.aliasChain?.length && !t.aliasChain[0].startsWith(prefix));
2777
+ if (resting.length) fragment.tokens = Object.fromEntries(resting.map((t) => [`${declared.id}.${value}.${t.id.slice(prefix.length)}`, { $value: `{${t.aliasChain[0]}}` }]));
2778
+ notes.push(`"tokens" holds the resting colors of "${value}", as cloned from "${source}": re-point the ones that make it a distinct ${axisName} and delete the rest. Its ${declared.states.join(", ")} tokens are valued by the system's pattern rules.`);
2779
+ }
2780
+ } else {
2781
+ declaration = id ?? (nearToken && value ? `${parentOf(near)}.${value}` : null);
2782
+ if (!declaration) throw new ToolError(kind === "step" ? 'Pass "id" (the full id of the new token), or "near" (a token of the series) with "value" (the name of the new step).' : `Pass "id": the full id of the new token, in the layer's own namespace.`);
2783
+ const segments2 = declaration.split(".");
2784
+ if (kind === "own-token") {
2785
+ if (!layer) throw new ToolError(`A layer's own tokens live in the namespace of its id: pass "layerFile" (the product's layer) or "layerId".`);
2786
+ if (segments2[0] === NS2) throw new ToolError(`${declaration} is inside Tanrei's tree; that is kind "step". A layer's own token is "${layer}.comp.<your-component>.<part>".`);
2787
+ if (segments2[0] !== layer) throw new ToolError(`${declaration}: a layer's own tokens live in its own namespace \u2014 "${layer}.\u2026", not "${segments2[0]}.\u2026". Did you mean "${[layer, ...segments2.slice(1)].join(".")}"?`);
2788
+ } else if (segments2[0] !== NS2) throw new ToolError(`${declaration}: a step in a series is inside Tanrei's tree ("${NS2}.sys.\u2026"). For a token of your own namespace use kind "own-token".`);
2789
+ if (!["sys", "comp"].includes(segments2[1]) || segments2.length < 4) throw new ToolError(`${declaration}: declare tokens under "${segments2[0]}.sys.<group>.\u2026" or "${segments2[0]}.comp.<component>.\u2026". Dials and the reference tier are not extensible; a color family is a palette ("palettes" with "roles": "intent").`);
2790
+ checkNames(declaration, segments2.slice(1));
2791
+ if (tokens[declaration]) refuseExisting(ctx, declaration, tokens[declaration], "Change its value instead \u2014 `howToChange` lists the legal operations.");
2792
+ const type = $type ?? nearToken?.$type;
2793
+ if (!type) throw new ToolError('Pass "$type" (color, dimension, number, duration, typography, shadow, cubicBezier, fontFamily, fontWeight), or "near": a token whose type and rule the new one takes after.');
2794
+ if (kind === "step" && !Object.keys(tokens).some((other) => other.startsWith(`${parentOf(declaration)}.`))) notes.push(`${parentOf(declaration)} has no tokens yet: this starts a NEW group inside Tanrei's tree rather than adding a step to a series. The engine accepts it, but what only your product has is better declared in your own namespace (kind "own-token").`);
2795
+ const value_ = definition ?? (nearToken ? kind === "own-token" ? { $value: `{${near}}` } : definitionLike(ctx, nearToken, tokens) : { $value: '<an alias "{tanrei.sys.\u2026}", or a literal with a "reason">' });
2796
+ fragment.vocabulary[declaration] = { $type: type, rationale: RATIONALE2, ...value_ };
2797
+ if (kind === "own-token") notes.push(`Emitted as ${idToVar(declaration)} on the web and as a typed object next to your system on the native platforms. It may reference any ${NS2}.* token; nothing in ${NS2}.* may reference it.`);
2798
+ }
2799
+ const fill = [`vocabulary["${declaration}"].rationale \u2014 why this design system or product needs it. validate_layer refuses the placeholder; so should you.`];
2800
+ const standIn = JSON.parse(JSON.stringify(fragment), (key, v) => (key === "rationale" || key === "reason") && isPlaceholder(v) ? STAND_IN : v);
2801
+ if (isPlaceholder(fragment.vocabulary[declaration].reason)) fill.push(`vocabulary["${declaration}"].reason \u2014 why the value is pinned.`);
2802
+ const open = JSON.stringify(standIn).match(/<[^<>"]*>/g) ?? [];
2803
+ fill.push(...open.map((text2) => `${text2} \u2014 replace it`));
2804
+ let verified;
2805
+ if (open.length) verified = { built: false, because: `The fragment still has ${open.length === 1 ? "a placeholder" : "placeholders"} only you can fill (${open.join(", ")}). Pass "definition" ({ "$value" | "derive", "reason"? }) to have the proposal built and its values reported, or fill it and run validate_layer.` };
2806
+ else {
2807
+ const base = into ?? { id: layer ?? "proposal", name: "Proposal", extends: ctx.id };
2808
+ const merged = { ...base, vocabulary: { ...base.vocabulary, ...standIn.vocabulary }, ...standIn.tokens ? { tokens: { ...standIn.tokens, ...base.tokens } } : {} };
2809
+ try {
2810
+ const trial = await trialBuild([...into ? chain.slice(0, -1) : chain, merged]);
2811
+ const after = trial.tokens("light");
2812
+ const added = Object.keys(after).filter((other) => !(other in tokens)).sort();
2813
+ const before = new Set(await ctx.warnings());
2814
+ verified = {
2815
+ built: true,
2816
+ how: `Built "${ctx.id}" + this fragment with the real pipeline (a stand-in for the rationale). Nothing was written.`,
2817
+ newTokens: { total: added.length, values: Object.fromEntries(added.slice(0, 40).map((other) => [other, briefValue(after[other])])) },
2818
+ ...trial.system.notices?.length ? { notices: trial.system.notices } : {},
2819
+ // The parent is resolved once per chain digest and kept; the trial's warnings read its light tokens and role colors only.
2820
+ newWarnings: (await trial.warnings()).filter((warning) => !before.has(warning))
2821
+ };
2822
+ } catch (error) {
2823
+ if (!(error instanceof ToolError)) throw error;
2824
+ verified = { built: false, error: error.message, ...error.details ?? {} };
2825
+ }
2826
+ }
2827
+ return {
2828
+ kind,
2829
+ declares: declaration,
2830
+ system: ctx.id,
2831
+ layer: layer ?? "<the product layer that will declare it>",
2832
+ write: fragment,
2833
+ fill,
2834
+ ...notes.length ? { notes } : {},
2835
+ verified,
2836
+ next: `Merge \`write\` into ${into ? reference.layerFile ?? reference.system : "the product's <id>.system.json"}, fill the rationale, run validate_layer, then \`tanrei build\`. \`vocabulary\` says the token exists; change its value later under "tokens", like any core token.`
2837
+ };
2838
+ }
2839
+ var registry;
2840
+ function gapsRegistry() {
2841
+ registry ??= JSON.parse(fs7.readFileSync(path8.join(REPO_ROOT, "docs/governance/mimicry-gaps.json"), "utf8"));
2842
+ return registry;
2843
+ }
2844
+ function mimicryGaps({ status, kind, system, id, limit = 10, offset = 0 }) {
2845
+ const { gaps } = gapsRegistry();
2846
+ const needle = system?.toLowerCase();
2847
+ const found = gaps.filter((gap) => (!id || gap.id === id) && (!status || gap.status === status) && (!kind || gap.kind === kind) && (!needle || gap.systems.some((s) => s.toLowerCase().includes(needle))));
2848
+ const count = (key) => found.reduce((acc, gap) => ({ ...acc, [gap[key]]: (acc[gap[key]] ?? 0) + 1 }), {});
2849
+ const { items, ...rest } = page(found, { offset, limit });
2850
+ return {
2851
+ about: `Traits of other design systems that Tanrei cannot reproduce yet. A shipped preset's accessibility measurements are not gaps: Tanrei's accessibility criteria do not apply to an imitation preset. MISSING VOCABULARY IS NOT A GAP any more: a size, a variant, a step, a color role or a product's own token is declared by the layer under "vocabulary" (propose_extension). What stays here is what no token can express \u2014 behaviours and mechanisms (ripple, continuous corners, materials) \u2014 each a defect in Tanrei, resolved by a new token TYPE, a small enumerated behaviour token, or a component composition option.`,
2852
+ byStatus: count("status"),
2853
+ byKind: count("kind"),
2854
+ ...rest,
2855
+ gaps: items
2856
+ };
2857
+ }
2858
+ var object = (properties, required = []) => ({ type: "object", additionalProperties: false, properties, required });
2859
+ var TOOLS = [
2860
+ {
2861
+ name: "list_systems",
2862
+ description: "The design systems that ship with Tanrei (the root `tanrei` and the presets that extend it) and, with `layerFile`, a product's own layer chain. A system is a LAYER: it changes values of a small shared core vocabulary, and may EXTEND it under `vocabulary` \u2014 each system lists its extensions with the layer that declared them, and a preset measured against the published system it reproduces lists its `fidelity` (equal / measured reference tokens, how many differ or have no counterpart, and the reference). Start here.",
2863
+ inputSchema: object({
2864
+ layerFile: systemProperties.layerFile,
2865
+ warnings: { type: "boolean", default: true, description: "Count accessibility/structure warnings per system (builds each system once; cached). For an imitation preset the count is of contrast measurements that do not apply to it, under `accessibility`." }
2866
+ }),
2867
+ handler: listSystemsTool
2868
+ },
2869
+ {
2870
+ name: "search_tokens",
2871
+ description: `Find tokens of the vocabulary by id. \`query\` is a case-insensitive substring, or a glob when it contains \`*\`: \`*\` matches within one segment, \`**\` any number of segments (e.g. \`${NS2}.comp.button.*.hovered.*\`, \`sys.color.on-*\`, \`**.opacity\`). A layer's own tokens are found by their namespace (\`acme.comp.*\`). Returns id, $type, kind (derived | fixed | alias | dial), \`extension: true\` + \`declaredBy\` for vocabulary a layer added, and a short description, paginated. A choice of kind (\`sys.behavior.*\`) shows the NAME it has and the names it may take. Search before concluding a token is missing; if it really is, propose_extension adds it.`,
2872
+ inputSchema: object({
2873
+ query: { type: "string", description: "Substring or glob over token ids. Omit to list by tier/type." },
2874
+ tier: { type: "string", enum: TIERS, description: "dial < ref < sys < comp. Components read comp tokens; comp aliases sys; sys derives from dials and palettes." },
2875
+ type: { type: "string", description: "DTCG $type: color, dimension, number, duration, typography, cubicBezier, shadow, fontFamily, fontWeight\u2026" },
2876
+ kind: { type: "string", enum: ["derived", "fixed", "alias", "dial"] },
2877
+ extensions: { type: "boolean", description: "true: only vocabulary that a layer of this system declared. false: only core vocabulary." },
2878
+ ...systemProperties,
2879
+ ...pagination(25, 200)
2880
+ }),
2881
+ handler: searchTokens
2882
+ },
2883
+ {
2884
+ name: "resolve",
2885
+ description: "The resolved value of one or more tokens in a system and scheme (a choice of kind \u2014 `sys.behavior.*` \u2014 as its NAME, with `choice: { name, index, of }`), with where it comes from: the alias chain, the derive rule and the current value of its inputs, which layer set it (and, for an extension, which layer declared it), and the CSS custom property name (`--tanrei-\u2026`; `--<namespace>-\u2026` for a layer's own tokens).",
2886
+ inputSchema: object({
2887
+ token: { type: "string", description: `One token id, e.g. ${NS2}.sys.shape.corner.small` },
2888
+ tokens: { type: "array", items: { type: "string" }, maxItems: 50 },
2889
+ ...systemProperties,
2890
+ scheme: schemeProperty,
2891
+ raw: { type: "boolean", default: false, description: "Also return the DTCG $value object (colors as components)." }
2892
+ }),
2893
+ handler: resolveTool
2894
+ },
2895
+ {
2896
+ name: "explain_token",
2897
+ description: 'Everything needed to change ONE token correctly: why it exists (the core rationale, or \u2014 for an extension \u2014 who declared it and why), usage guidance if the vocabulary carries any, which layers and pattern rules touch it (root first; every matching pattern rule says whether it `wins` and `because` \u2014 an explicit entry beats patterns, fewer wildcards beat more, the later layer wins a tie \u2014 and `winningRule` names the one that values the token), what follows it (`followers`), the operations a layer may legally write for it (`howToChange`; for a choice of kind: "choose", with the names; for a typeface: "set the font stack") and how to add vocabulary next to it (`howToExtend`: a step in its series, a size/variant on its axis, a token of your own). Every `write` is a ready-to-edit fragment of a layer. Call this before editing a layer.',
2898
+ inputSchema: object({ token: { type: "string" }, ...systemProperties, scheme: schemeProperty }, ["token"]),
2899
+ handler: explainToken
2900
+ },
2901
+ {
2902
+ name: "diff_systems",
2903
+ description: "Tokens whose resolved value differs between two systems in one scheme. Counts come first (by tier and by group such as `sys.color`, `comp.button`); details are paginated and can be narrowed with `group`. Ids that exist on one side only are reported apart: extensions (with `declaredBy`) and what declared palettes bring.",
2904
+ inputSchema: object(
2905
+ {
2906
+ a: { type: "string", description: "Shipped system id, or path of a <id>.system.json." },
2907
+ b: { type: "string", description: "Shipped system id, or path of a <id>.system.json." },
2908
+ scheme: schemeProperty,
2909
+ group: { type: "string", description: "A tier (`sys`) or a group from `byGroup` (`sys.shape`)." },
2910
+ ...pagination(20, 200)
2911
+ },
2912
+ ["a", "b"]
2913
+ ),
2914
+ handler: diffSystems
2915
+ },
2916
+ {
2917
+ name: "validate_layer",
2918
+ description: "Check a product layer before it is saved or built: JSON Schema; then every problem at once, with the way out \u2014 `vocabulary` declarations as the engine judges them (a rationale, the layer's own namespace, declared once, an existing axis and `from`, never an interaction state), ids under `tokens`/`rules` that are neither core nor declared (declare them, or use the token that exists), a pinned literal without a `reason`, a `$type` change, leftover placeholders; then the real build, which is the final authority. If valid, returns the accessibility/structure warnings `tanrei build` would print. Writes nothing.",
2919
+ inputSchema: object({
2920
+ layer: { type: "object", description: 'The layer as JSON: { "id", "extends", "vocabulary", "palettes", "tokens", "rules" }. It may extend a shipped system, a layer passed in "parents", or a layer file in "dir".' },
2921
+ parents: { type: "array", items: { type: "object" }, maxItems: 8, description: 'With "layer": other layers that exist only in this request and that the layer (or another parent) extends \u2014 a product that stacks its own layers. Any order; each needs an "id". They are validated too.' },
2922
+ dir: { type: "string", description: `With "layer": the directory that holds the product's other <id>.system.json files, where "extends" is looked up after "parents" and before the shipped systems. The layer itself shadows a file of the same id, so this validates what WOULD be written. "extends" is an id, never a path: only <dir>/<id>.system.json \u2014 a regular file inside the directory \u2014 is read.` },
2923
+ layerFile: systemProperties.layerFile,
2924
+ limit: { type: "integer", minimum: 1, maximum: 200, default: 20, description: "How many warnings to return." }
2925
+ }),
2926
+ handler: validateLayerTool
2927
+ },
2928
+ {
2929
+ name: "propose_extension",
2930
+ description: `Write the \`vocabulary\` declaration that ADDS something to a system, checked and \u2014 where possible \u2014 built. Three kinds: "step" (a token inside Tanrei's tree: one more step of a series, or a single color role), "axis-value" (a size or variant of a component: one line values every member, e.g. button size "3x" from "large" \xD7 1.5), "own-token" (a token of the product's own components, in the layer's namespace). Refuses what the engine would refuse \u2014 an id that already exists (change its value under \`tokens\` instead), an invalid name, a foreign namespace, an unknown axis or \`from\`, an interaction state \u2014 and returns \`write\` (a layer fragment with a rationale placeholder YOU must fill; validate_layer rejects the placeholder) plus \`verified\`: the new token ids and their values from a trial build, and any new warnings. Writes nothing.`,
2931
+ inputSchema: object(
2932
+ {
2933
+ kind: { type: "string", enum: ["step", "axis-value", "own-token"] },
2934
+ near: { type: "string", description: "An existing token id the new thing sits next to. step: a token of the series (gives the group, $type and the shape of the rule). axis-value: a token on the axis (gives component, axis and `from`). own-token: the token it references." },
2935
+ id: { type: "string", description: `step / own-token: the full id of the new token, e.g. ${NS2}.sys.space.space1200 or acme.comp.rating.star.size. A step may pass "near" + "value" instead.` },
2936
+ value: { type: "string", description: 'axis-value: the name of the new size or variant ("3x", "danger"). step: the name of the new step, next to "near".' },
2937
+ component: { type: "string", description: 'axis-value: the component, e.g. "button".' },
2938
+ axis: { type: "string", description: 'axis-value: the axis, e.g. "size" or "variant".' },
2939
+ from: { type: "string", description: "axis-value: the existing value to clone. Defaults to the value of `near`, or the axis's default." },
2940
+ scale: { description: 'axis-value on a size-like axis: multiply the numeric members \u2014 a number, or a map of member \u2192 number ({"container.height": 1.5}).', oneOf: [{ type: "number", exclusiveMinimum: 0 }, { type: "object", additionalProperties: { type: "number", exclusiveMinimum: 0 } }] },
2941
+ $type: { type: "string", description: "step / own-token: the DTCG $type. Defaults to the $type of `near`." },
2942
+ definition: { type: "object", description: 'step / own-token: the value, exactly as the declaration takes it \u2014 { "$value": "{tanrei.sys.\u2026}" } | { "$value": <literal>, "reason": "\u2026" } | { "derive": {\u2026} }, plus "onRole" for a color role. Without it the proposal takes after `near` and may leave a placeholder.' },
2943
+ ...systemProperties,
2944
+ layerId: { type: "string", description: "The id of the product layer that will declare it, when there is no file yet. It is the namespace of the layer's own tokens." }
2945
+ },
2946
+ ["kind"]
2947
+ ),
2948
+ handler: proposeExtension
2949
+ },
2950
+ {
2951
+ name: "mimicry_gaps",
2952
+ description: "Tanrei's registry of traits it cannot reproduce yet (ripple, continuous corners, backdrop materials\u2026). Missing VOCABULARY is not a gap \u2014 a layer declares it (propose_extension). Check this when a trait is a behaviour or a mechanism that no token value can express.",
2953
+ inputSchema: object({
2954
+ status: { type: "string", enum: ["open", "planned", "resolved", "wont-fix"] },
2955
+ kind: { type: "string", description: "behavior | mechanism | vocabulary | anatomy" },
2956
+ system: { type: "string", description: 'Substring of the imitated system, e.g. "Material", "HIG", "cupertino".' },
2957
+ id: { type: "string" },
2958
+ ...pagination(10, 100)
2959
+ }),
2960
+ handler: mimicryGaps
2961
+ }
2962
+ ];
2963
+
2964
+ // src/server.js
2965
+ var VERSION = JSON.parse(fs8.readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
2966
+ var ajv = new Ajv20202({ allErrors: true, strict: false, useDefaults: true });
2967
+ var tools = new Map(TOOLS.map((tool) => [tool.name, { ...tool, validate: ajv.compile(tool.inputSchema) }]));
2968
+ var text = (value, isError = false) => ({ content: [{ type: "text", text: JSON.stringify(value) }], ...isError ? { isError: true } : {} });
2969
+ async function callTool(name, args = {}) {
2970
+ const tool = tools.get(name);
2971
+ if (!tool) throw new McpError(ErrorCode.InvalidParams, `unknown tool "${name}". Tools: ${[...tools.keys()].join(", ")}`);
2972
+ const input = structuredClone(args);
2973
+ if (!tool.validate(input)) return text({ error: "invalid arguments", problems: tool.validate.errors.map((e) => `${e.instancePath || "/"} ${e.message}${e.params?.additionalProperty ? ` ("${e.params.additionalProperty}")` : ""}${e.params?.allowedValues ? `: ${e.params.allowedValues.join(", ")}` : ""}`) }, true);
2974
+ try {
2975
+ return text(await tool.handler(input));
2976
+ } catch (error) {
2977
+ if (error instanceof ToolError) return text({ error: error.message, ...error.details }, true);
2978
+ return text({ error: `${name} failed: ${error.message}` }, true);
2979
+ }
2980
+ }
2981
+ function createServer() {
2982
+ const server = new Server({ name: "tanrei", title: "Tanrei design system", version: VERSION }, { capabilities: { tools: {}, resources: {} }, instructions: INSTRUCTIONS });
2983
+ server.setRequestHandler(ListToolsRequestSchema, async () => ({
2984
+ tools: TOOLS.map(({ name, description, inputSchema }) => ({ name, description, inputSchema, annotations: { readOnlyHint: true, idempotentHint: true, openWorldHint: false } }))
2985
+ }));
2986
+ server.setRequestHandler(CallToolRequestSchema, async (request) => callTool(request.params.name, request.params.arguments));
2987
+ server.setRequestHandler(ListResourcesRequestSchema, async () => ({ resources: listResources() }));
2988
+ server.setRequestHandler(ListResourceTemplatesRequestSchema, async () => ({
2989
+ resourceTemplates: [{ uriTemplate: "tanrei://systems/{id}", name: "System layer", description: "The layer file of a shipped system, as authored.", mimeType: "application/json" }]
2990
+ }));
2991
+ server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
2992
+ try {
2993
+ return { contents: [readResource(request.params.uri)] };
2994
+ } catch (error) {
2995
+ throw new McpError(ErrorCode.InvalidParams, error.message);
2996
+ }
2997
+ });
2998
+ return server;
2999
+ }
3000
+ async function main() {
3001
+ console.log = console.info = console.debug = (...args) => console.error(...args);
3002
+ await createServer().connect(new StdioServerTransport());
3003
+ }
3004
+ export {
3005
+ callTool,
3006
+ createServer,
3007
+ main
3008
+ };