@designtools/tokens 0.14.0 → 0.16.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.
package/dist/cli.js CHANGED
@@ -2,12 +2,15 @@
2
2
  import {
3
3
  APCAUnavailableError,
4
4
  DEFAULT_NEUTRAL_COLOR,
5
+ LOCAL_TEMPLATE,
6
+ OFF_SCALE_ADVICE,
5
7
  SECTIONED_FORMATS,
6
8
  SHADE_PRESETS,
7
9
  TOKEN_SECTIONS,
8
10
  VALID_SHADES,
9
11
  applyScaleOverrides,
10
12
  bridgeShade,
13
+ checkLocalOverrides,
11
14
  checkRampChroma,
12
15
  checkSemanticContrast,
13
16
  checkSemanticContrastAPCA,
@@ -24,11 +27,15 @@ import {
24
27
  getContrastRatio,
25
28
  isAPCAAvailable,
26
29
  isInGamut,
30
+ isOwnedScale,
27
31
  mergeSlice,
32
+ offScaleReason,
28
33
  overrideContract,
34
+ ownedScaleHeader,
29
35
  parseProvenance,
30
36
  parseToOklch,
31
37
  provenanceComment,
38
+ reservedColorReason,
32
39
  resolveShades,
33
40
  ringBridgeShade,
34
41
  seedFingerprint,
@@ -39,17 +46,22 @@ import {
39
46
  suggestStep,
40
47
  tokenFamilies,
41
48
  usageReport,
49
+ verifyScale,
42
50
  withJsonProvenance
43
- } from "./chunk-7PQDEFU6.js";
51
+ } from "./chunk-PG4SXPRL.js";
44
52
 
45
53
  // src/cli.ts
46
54
  import { parseArgs as parseArgs2 } from "util";
47
- import { mkdirSync as mkdirSync2, writeFileSync as writeFileSync2, readFileSync as readFileSync2, statSync } from "fs";
48
- import { join as join2, dirname } from "path";
55
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync3, readFileSync as readFileSync3, statSync } from "fs";
56
+ import { join as join3, dirname as dirname2 } from "path";
49
57
  import { fileURLToPath } from "url";
50
58
 
59
+ // src/init.ts
60
+ import { existsSync as existsSync2, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
61
+ import { dirname, join as join2, relative } from "path";
62
+
51
63
  // src/scale-cli.ts
52
- import { mkdirSync, readFileSync, writeFileSync } from "fs";
64
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "fs";
53
65
  import { join } from "path";
54
66
  import { parseArgs } from "util";
55
67
  var FORMATS = ["css", "tailwind-v4", "tailwind-v3", "dtcg", "json"];
@@ -60,26 +72,84 @@ var FILE_NAMES = {
60
72
  dtcg: "scale.dtcg.json",
61
73
  json: "scale.json"
62
74
  };
63
- var SCALE_HELP = `generate-tokens scale: the non-colour scale, from defaults and your overrides
75
+ var SCALE_HELP = `generate-tokens scale: the non-colour scale, scaffolded once and then the project's own
64
76
 
65
- generate-tokens scale --format tailwind-v4 --out app/styles/scale.css
66
- generate-tokens scale --format css --overrides scale.overrides.json --out src/scale.css
67
- generate-tokens scale --format all --out ./tokens
77
+ generate-tokens scale --init --format tailwind-v4 --out app/styles/scale.css
78
+ generate-tokens scale --verify app/styles/scale.css
68
79
 
69
80
  Space (--spacing), size (--size-*), type sizes with their line height and tracking (--text-*,
70
81
  --leading-*, --tracking-*, --font-weight-*), corners (--radius-*), elevation (--shadow-*),
71
82
  motion (--duration-*, --ease-*), screen sizes (--breakpoint-*) and widths (--container-*).
72
- The names are the contract; retune the values with --overrides, never by editing the file.
73
83
 
84
+ The scale is art direction, so it is written once and then edited by hand: nothing regenerates
85
+ it, and no overrides file tracks it. The names are the contract. Keep every one. A new name in
86
+ the type tiers is a step of that tier, never a use:
87
+ --text-* 3xs, 2xs, xs, sm, base, lg, xl, 2xl to 9xl (with --line-height,
88
+ --letter-spacing and --font-weight companions)
89
+ --leading-* none, tightest, tighter, tight, snug, medium, normal, relaxed, loose, looser, loosest
90
+ --tracking-* tightest, tighter, tight, normal, wide, wider, widest
91
+ --font-weight-* thin, extralight, light, normal, medium, semibold, bold, extrabold, black
92
+ A size that changes by screen is set in the component (text-5xl lg:text-8xl); a role a page uses
93
+ (display, headline, label) is a step, mapped in the docs config's type.hierarchy. The other tiers
94
+ take a project's own names inside their namespace (--spacing-section, --container-measure).
95
+ --verify (and designtools-manifest check) holds you to it.
96
+
97
+ --init Write the scale once. Refuses if the file exists: it is the project's.
98
+ --force With --init, write over an existing scale, after showing what changes.
99
+ --verify <file> Check a scale file's names against the contract. Exit 1 on a missing name,
100
+ one outside every tier, or one in a type tier that is no step of it.
101
+ Values are never compared.
74
102
  --format <fmt> css | tailwind-v4 | tailwind-v3 | dtcg | json | all. Default: css.
75
103
  css writes screen sizes as @custom-media too, since a variable can't go in @media.
76
- --overrides <file> JSON, by token name: { "--radius-md": "0.5rem", "--text-5xl": { "value":
77
- "3rem", "description": "48px: page titles" }, "--leading-relaxed": null }.
78
- A new name joins the tier its prefix belongs to; null removes a token.
104
+ --overrides <file> JSON, by token name, to start --init from other values than the defaults:
105
+ { "--radius-md": "0.5rem", "--text-5xl": { "value": "3rem", "description":
106
+ "48px: page titles" } }. A new name joins the tier its prefix belongs to.
79
107
  --out <path> File to write, or a directory with --format all. Default: stdout.
80
- --check Compare against the file at --out instead of writing it. Exit 1 if it differs.
81
- --no-provenance Leave out the "Generated by" header.
108
+
109
+ Without --init, writing over a scale and --check still work, for projects that adopted the
110
+ scale before 0.14; both warn. Move to an owned scale: run --init --force once, delete the
111
+ overrides file, and drop the check.
82
112
  `;
113
+ function valuesOf(css) {
114
+ return new Map([...css.matchAll(/(?:^|[;{\s])(--[\w-]+)\s*:\s*([^;]+);/g)].map((m) => [m[1], m[2].trim()]));
115
+ }
116
+ function describeChange(before, after) {
117
+ const was = valuesOf(before);
118
+ const now = valuesOf(after);
119
+ const lines = [];
120
+ for (const [name, value] of now) {
121
+ const old = was.get(name);
122
+ if (old === void 0) lines.push(` + ${name}: ${value}`);
123
+ else if (old !== value) lines.push(` ~ ${name}: ${old} -> ${value}`);
124
+ }
125
+ for (const name of was.keys()) if (!now.has(name)) lines.push(` - ${name}`);
126
+ return lines;
127
+ }
128
+ function verify(file, fail2) {
129
+ let css;
130
+ try {
131
+ css = readFileSync(file, "utf8");
132
+ } catch {
133
+ return fail2(`can't read ${file}`);
134
+ }
135
+ const { missing, strays, offScale, own } = verifyScale(css);
136
+ if (!isOwnedScale(css)) {
137
+ process.stderr.write(`verify: ${file} is not an owned scale yet; run generate-tokens scale --init --force once to adopt it
138
+ `);
139
+ }
140
+ for (const name of missing) process.stderr.write(`verify: ${file} is missing ${name}, a name the scale promises
141
+ `);
142
+ for (const name of strays) process.stderr.write(`verify: ${file} declares ${name}, which belongs to no tier of the scale
143
+ `);
144
+ for (const name of offScale) process.stderr.write(`verify: ${file} declares ${name}, which ${offScaleReason(name)}
145
+ `);
146
+ if (offScale.length) process.stderr.write(`verify: ${OFF_SCALE_ADVICE}
147
+ `);
148
+ if (missing.length || strays.length || offScale.length) return 1;
149
+ process.stderr.write(`verify: ${file} keeps the scale's names${own.length ? `, with ${own.length} of its own inside the tiers` : ""}
150
+ `);
151
+ return 0;
152
+ }
83
153
  function runScale(argv, version) {
84
154
  const fail2 = (message) => {
85
155
  process.stderr.write(`generate-tokens scale: ${message}
@@ -95,6 +165,9 @@ function runScale(argv, version) {
95
165
  overrides: { type: "string" },
96
166
  out: { type: "string" },
97
167
  check: { type: "boolean" },
168
+ init: { type: "boolean" },
169
+ force: { type: "boolean" },
170
+ verify: { type: "string" },
98
171
  "no-provenance": { type: "boolean" },
99
172
  help: { type: "boolean", short: "h" }
100
173
  }
@@ -106,9 +179,12 @@ function runScale(argv, version) {
106
179
  process.stdout.write(SCALE_HELP);
107
180
  return 0;
108
181
  }
182
+ if (values2.verify) return verify(values2.verify, fail2);
109
183
  const format2 = values2.format ?? "css";
110
184
  if (format2 !== "all" && !FORMATS.includes(format2)) return fail2(`--format must be one of ${[...FORMATS, "all"].join(", ")}`);
111
185
  if (values2.check && !values2.out) return fail2("--check needs --out to compare against");
186
+ if (values2.force && !values2.init) return fail2("--force goes with --init");
187
+ if (values2.init && values2.check) return fail2("an owned scale has nothing to check against; use --verify");
112
188
  let overrides2 = {};
113
189
  if (values2.overrides) {
114
190
  try {
@@ -123,10 +199,18 @@ function runScale(argv, version) {
123
199
  } catch (err) {
124
200
  return fail2(err instanceof Error ? err.message : String(err));
125
201
  }
126
- const header = values2["no-provenance"] ? void 0 : `/* Generated by @designtools/tokens v${version} (scale${values2.overrides ? `, overrides ${values2.overrides}` : ""}) - retune with --overrides, do not edit by hand */`;
202
+ if (values2.init) {
203
+ const { offScale } = verifyScale(exportScale(tiers, "css"));
204
+ if (offScale.length) return fail2(`${offScale.map((name) => `--overrides ${name} ${offScaleReason(name)}`).join("; ")}: ${OFF_SCALE_ADVICE}`);
205
+ }
206
+ const header = values2["no-provenance"] ? void 0 : values2.init ? ownedScaleHeader(version) : `/* Generated by @designtools/tokens v${version} (scale${values2.overrides ? `, overrides ${values2.overrides}` : ""}) - retune with --overrides, do not edit by hand */`;
127
207
  const formats2 = format2 === "all" ? FORMATS.filter((f) => f !== "tailwind-v4") : [format2];
128
208
  const target = (f) => format2 === "all" ? join(values2.out ?? ".", FILE_NAMES[f]) : values2.out;
209
+ const legacy = () => process.stderr.write(
210
+ "generate-tokens scale: regenerating the scale is deprecated; scaffold it once with --init and own the file (see --help)\n"
211
+ );
129
212
  if (values2.check) {
213
+ legacy();
130
214
  let ok = true;
131
215
  for (const f of formats2) {
132
216
  const want = exportScale(tiers, f, header);
@@ -147,20 +231,107 @@ function runScale(argv, version) {
147
231
  process.stdout.write(exportScale(tiers, formats2[0], header));
148
232
  return 0;
149
233
  }
234
+ if (values2.init) {
235
+ for (const f of formats2) {
236
+ const path = target(f);
237
+ if (!existsSync(path)) continue;
238
+ const existing = readFileSync(path, "utf8");
239
+ if (!values2.force) {
240
+ return fail2(`${path} exists and is the project's own: edit it by hand, or pass --force to write over it`);
241
+ }
242
+ const changes = describeChange(existing, exportScale(tiers, f, header));
243
+ process.stderr.write(
244
+ changes.length ? `rewriting ${path}:
245
+ ${changes.join("\n")}
246
+ ` : `rewriting ${path}: the same names and values, now an owned scale
247
+ `
248
+ );
249
+ }
250
+ } else {
251
+ legacy();
252
+ }
150
253
  if (format2 === "all") mkdirSync(values2.out, { recursive: true });
151
254
  for (const f of formats2) {
152
255
  writeFileSync(target(f), exportScale(tiers, f, header));
153
- process.stderr.write(`wrote ${target(f)}
256
+ process.stderr.write(`wrote ${target(f)}${values2.init ? " (the project's now: edit it by hand)" : ""}
154
257
  `);
155
258
  }
156
259
  return 0;
157
260
  }
158
261
 
262
+ // src/init.ts
263
+ function take(args, flag) {
264
+ const i = args.findIndex((a) => a === flag || a.startsWith(`${flag}=`));
265
+ if (i === -1) return void 0;
266
+ const [arg] = args.splice(i, 1);
267
+ if (arg.includes("=")) return arg.slice(flag.length + 1);
268
+ return args.splice(i, 1)[0];
269
+ }
270
+ var ORDER = ["tokens.css", "tokens.local.css", "scale.css"];
271
+ function wire(entry, dir) {
272
+ const rel = (file) => {
273
+ const path = relative(dirname(entry), join2(dir, file)).replace(/\\/g, "/");
274
+ return path.startsWith(".") ? path : `./${path}`;
275
+ };
276
+ const imports = ORDER.map((file) => `@import "${rel(file)}";`);
277
+ let css = existsSync2(entry) ? readFileSync2(entry, "utf8") : '@import "tailwindcss";\n';
278
+ const missing = imports.filter((line) => !css.includes(line.slice(0, -1)));
279
+ if (!missing.length) {
280
+ process.stderr.write(`init: ${entry} already imports the tokens
281
+ `);
282
+ return;
283
+ }
284
+ const tailwind = /^@import\s+["']tailwindcss["'][^;\n]*;/m.exec(css);
285
+ const at = tailwind ? tailwind.index + tailwind[0].length : 0;
286
+ const rest = css.slice(at).replace(/^\n+/, "");
287
+ css = `${css.slice(0, at)}${at ? "\n\n" : ""}${missing.join("\n")}
288
+ ${rest ? `
289
+ ${rest}` : ""}`;
290
+ mkdirSync2(dirname(entry), { recursive: true });
291
+ writeFileSync2(entry, css);
292
+ process.stderr.write(`init: added ${missing.length} import${missing.length === 1 ? "" : "s"} to ${entry}
293
+ `);
294
+ }
295
+ function prepareInit(argv, version) {
296
+ const args = [...argv];
297
+ const dir = take(args, "--dir") ?? "app/styles";
298
+ const entry = take(args, "--entry");
299
+ mkdirSync2(dir, { recursive: true });
300
+ const scale = join2(dir, "scale.css");
301
+ if (existsSync2(scale)) {
302
+ process.stderr.write(`init: kept ${scale}: the scale is the project's own once written
303
+ `);
304
+ } else if (runScale(["--init", "--format", "tailwind-v4", "--out", scale], version) !== 0) {
305
+ return void 0;
306
+ }
307
+ const local = join2(dir, "tokens.local.css");
308
+ if (existsSync2(local)) process.stderr.write(`init: kept ${local}
309
+ `);
310
+ else {
311
+ writeFileSync2(local, LOCAL_TEMPLATE);
312
+ process.stderr.write(`wrote ${local} (empty: the overrides go here, checked on every run)
313
+ `);
314
+ }
315
+ if (entry) wire(entry, dir);
316
+ const has = (flag) => args.some((a) => a === flag || a.startsWith(`${flag}=`));
317
+ if (!has("--format")) args.push("--format", "tailwind-v4");
318
+ if (!has("--out")) args.push("--out", join2(dir, "tokens.css"));
319
+ if (!has("--local")) args.push("--local", local);
320
+ return args;
321
+ }
322
+
159
323
  // src/cli.ts
160
324
  var HELP = `generate-tokens \u2014 brand colour in, design tokens out
161
325
 
162
326
  Usage:
163
327
  generate-tokens --primary <colour> [options]
328
+ generate-tokens init --primary <colour> [options] [--dir <dir>] [--entry <stylesheet>]
329
+ Set a project up: the colour in tokens.css, the scale in
330
+ scale.css (written once, then the project's own) and an
331
+ empty tokens.local.css, in --dir (default app/styles).
332
+ --entry adds the three imports, in order, to a stylesheet.
333
+ generate-tokens scale --help
334
+ The non-colour scale.
164
335
 
165
336
  Seeds:
166
337
  --primary <colour> Brand colour (hex, rgb(), hsl(), oklch(), named). Required
@@ -171,7 +342,11 @@ Seeds:
171
342
  (--<name>, -foreground, -subdued, -hover, -active) for
172
343
  buttons, badges and text. Repeatable. Append @<shade> to
173
344
  anchor its seed on that step, as --seed-shade does for
174
- the primary: accent=#fde68a@200.
345
+ the primary: accent=#fde68a@200. Reserved, with or
346
+ without --aliases: green, red, yellow (the status
347
+ colours' second names: recolour warning with
348
+ --color warning=\u2026), canvas, surface, overlay,
349
+ foreground, border, input, ring, shadow, white, black.
175
350
  --decorative <name> Give a --color its ramp only, with no semantic slots (no
176
351
  --<name>, no bg-<name>), for an accent that must never be
177
352
  text or an action: --color sand=#e8d5b0 --decorative sand.
@@ -306,7 +481,7 @@ Selection:
306
481
  semantic intent tokens (primary, destructive, \u2026)
307
482
  surface canvas / surface / overlay, each with its text and secondary text
308
483
  utility border / input / ring / shadow
309
- grounds --on-<ground>-* and the data-surface scopes
484
+ grounds the [data-surface] scopes
310
485
  Keeps generated colour separable from hand-tuned files,
311
486
  so a re-theme does not clobber them. Supported by the
312
487
  css, tailwind-v4 and json formats.
@@ -342,6 +517,22 @@ Output:
342
517
  makes --check able to distinguish a generator upgrade
343
518
  from a hand edit, so dropping it costs you that.
344
519
 
520
+ Overrides:
521
+ --local <file> The project's overrides of the generated colour, loaded
522
+ after tokens.css: the one place for a value no flag or the
523
+ seed can say. Checked on every run, with or without
524
+ --check: only the generator's selectors (:root,
525
+ [data-theme], .dark, [data-surface="<ground>"], and the
526
+ system-dark block as tokens.css writes it), only its
527
+ token names (never a --color- alias or a ramp step), a
528
+ dark override set to the same value under the toggle and
529
+ under system dark, so it reaches every dark reader, and
530
+ values that point at the system (var(), or a ramp step
531
+ nudged with oklch(from \u2026)), never a literal colour. Each
532
+ override is listed as pinned by hand, and each pair it
533
+ touches is re-checked for contrast at --target. Exit 1 on
534
+ any problem.
535
+
345
536
  Verification:
346
537
  --check Regenerate in memory and compare against what is already
347
538
  at --out. Writes nothing. Exit 0 if identical, 1 if it
@@ -377,13 +568,18 @@ var FILE_NAMES2 = {
377
568
  };
378
569
  var VERSION = (() => {
379
570
  try {
380
- const here = dirname(fileURLToPath(import.meta.url));
381
- return JSON.parse(readFileSync2(join2(here, "../package.json"), "utf8")).version;
571
+ const here = dirname2(fileURLToPath(import.meta.url));
572
+ return JSON.parse(readFileSync3(join3(here, "../package.json"), "utf8")).version;
382
573
  } catch {
383
574
  return "0.0.0";
384
575
  }
385
576
  })();
386
577
  if (process.argv[2] === "scale") process.exit(runScale(process.argv.slice(3), VERSION));
578
+ if (process.argv[2] === "init") {
579
+ const colour = prepareInit(process.argv.slice(3), VERSION);
580
+ if (colour === void 0) process.exit(1);
581
+ process.argv.splice(2, process.argv.length - 2, ...colour);
582
+ }
387
583
  function fail(message) {
388
584
  process.stderr.write(`generate-tokens: ${message}
389
585
  `);
@@ -402,6 +598,7 @@ try {
402
598
  overlay: { type: "string" },
403
599
  background: { type: "string", multiple: true },
404
600
  usage: { type: "string" },
601
+ local: { type: "string" },
405
602
  contrast: { type: "string" },
406
603
  target: { type: "string" },
407
604
  lightness: { type: "string" },
@@ -457,14 +654,14 @@ if (values.help) {
457
654
  var seed = {};
458
655
  if (values.stdin) {
459
656
  try {
460
- seed = JSON.parse(readFileSync2(0, "utf8"));
657
+ seed = JSON.parse(readFileSync3(0, "utf8"));
461
658
  } catch (err) {
462
659
  fail(`could not read seed from stdin: ${err instanceof Error ? err.message : String(err)}`);
463
660
  }
464
661
  }
465
662
  if (values.seed) {
466
663
  try {
467
- seed = JSON.parse(readFileSync2(values.seed, "utf8"));
664
+ seed = JSON.parse(readFileSync3(values.seed, "utf8"));
468
665
  } catch (err) {
469
666
  fail(`could not read --seed file: ${err instanceof Error ? err.message : String(err)}`);
470
667
  }
@@ -497,6 +694,8 @@ var additionalColors = {};
497
694
  var additionalAnchors = {};
498
695
  var decorative = /* @__PURE__ */ new Set();
499
696
  for (const { name, color, seedShade: anchor, decorative: d } of seed.additionalColors ?? []) {
697
+ const reserved = reservedColorReason(name);
698
+ if (reserved) fail(`seed additionalColors ${name}: ${reserved}`);
500
699
  if (d) decorative.add(name);
501
700
  additionalColors[name] = validateColor(`seed colour ${name}`, color);
502
701
  if (anchor !== void 0) additionalAnchors[name] = { flag: `seed (additionalColors ${name})`, raw: anchor };
@@ -509,6 +708,8 @@ for (const entry of values.color ?? []) {
509
708
  if (!/^[a-z][a-z0-9-]*$/i.test(name)) {
510
709
  fail(`--color name must be alphanumeric/kebab-case (got "${name}")`);
511
710
  }
711
+ const reserved = reservedColorReason(name);
712
+ if (reserved) fail(`--color ${name}: ${reserved}`);
512
713
  const at = /^(.*)@(\d+)$/.exec(colour);
513
714
  if (at) {
514
715
  colour = at[1].trim();
@@ -752,7 +953,7 @@ var overrides = {
752
953
  };
753
954
  if (values.overrides) {
754
955
  try {
755
- overrides = JSON.parse(readFileSync2(values.overrides, "utf8"));
956
+ overrides = JSON.parse(readFileSync3(values.overrides, "utf8"));
756
957
  } catch (err) {
757
958
  fail(`could not read --overrides file: ${err instanceof Error ? err.message : String(err)}`);
758
959
  }
@@ -938,7 +1139,7 @@ ${body}`;
938
1139
  }
939
1140
  function targetPath(fmt, out) {
940
1141
  try {
941
- if (statSync(out).isDirectory()) return join2(out, FILE_NAMES2[fmt]);
1142
+ if (statSync(out).isDirectory()) return join3(out, FILE_NAMES2[fmt]);
942
1143
  } catch {
943
1144
  }
944
1145
  return out;
@@ -946,7 +1147,7 @@ function targetPath(fmt, out) {
946
1147
  function check(fmt, target) {
947
1148
  let existing;
948
1149
  try {
949
- existing = readFileSync2(target, "utf8");
1150
+ existing = readFileSync3(target, "utf8");
950
1151
  } catch {
951
1152
  process.stderr.write(`check: ${target} does not exist
952
1153
  `);
@@ -1202,7 +1403,7 @@ function reportExternalReferences(css, merged) {
1202
1403
  function checkSlice(target, slice) {
1203
1404
  let existing;
1204
1405
  try {
1205
- existing = readFileSync2(target, "utf8");
1406
+ existing = readFileSync3(target, "utf8");
1206
1407
  } catch {
1207
1408
  process.stderr.write(`check: ${target} does not exist
1208
1409
  `);
@@ -1236,7 +1437,7 @@ function checkUsage() {
1236
1437
  if (!values.usage) return true;
1237
1438
  let existing = "";
1238
1439
  try {
1239
- existing = readFileSync2(values.usage, "utf8");
1440
+ existing = readFileSync3(values.usage, "utf8");
1240
1441
  } catch {
1241
1442
  process.stderr.write(`check: ${values.usage} is missing
1242
1443
  `);
@@ -1251,18 +1452,45 @@ function checkUsage() {
1251
1452
  `);
1252
1453
  return false;
1253
1454
  }
1455
+ function checkLocal() {
1456
+ if (!values.local) return true;
1457
+ if (isSlice) {
1458
+ process.stderr.write(`local: ${values.local} is checked on a full run, not a partial one
1459
+ `);
1460
+ return true;
1461
+ }
1462
+ let local = "";
1463
+ try {
1464
+ local = readFileSync3(values.local, "utf8");
1465
+ } catch {
1466
+ process.stderr.write(`local: ${values.local} is missing
1467
+ `);
1468
+ return false;
1469
+ }
1470
+ const generated = serialise(SECTIONED_FORMATS.includes(format) ? format : "css");
1471
+ const { overrides: overrides2, problems } = checkLocalOverrides(generated, local, contrastTarget);
1472
+ for (const o of overrides2) process.stderr.write(`local: pinned by hand: ${o.name} in ${o.selector}
1473
+ `);
1474
+ for (const p of problems) process.stderr.write(`local: ${values.local}: ${p.message}
1475
+ `);
1476
+ if (!problems.length) process.stderr.write(`local: ${values.local} keeps to the system (${overrides2.length} pinned)
1477
+ `);
1478
+ return problems.length === 0;
1479
+ }
1254
1480
  if (values.check) {
1255
1481
  const out = values.out;
1256
1482
  if (isSlice) {
1257
- process.exit(checkSlice(targetPath(format, out), serialise(format)) && checkUsage() ? 0 : 1);
1483
+ process.exit(
1484
+ checkSlice(targetPath(format, out), serialise(format)) && checkUsage() && checkLocal() ? 0 : 1
1485
+ );
1258
1486
  }
1259
- const ok = formats.map((fmt) => check(fmt, format === "all" ? join2(out, FILE_NAMES2[fmt]) : targetPath(fmt, out)));
1260
- process.exit(ok.every(Boolean) && checkUsage() ? 0 : 1);
1487
+ const ok = formats.map((fmt) => check(fmt, format === "all" ? join3(out, FILE_NAMES2[fmt]) : targetPath(fmt, out)));
1488
+ process.exit(ok.every(Boolean) && checkUsage() && checkLocal() ? 0 : 1);
1261
1489
  } else if (values.merge) {
1262
1490
  const target = targetPath(format, values.out);
1263
1491
  let existing;
1264
1492
  try {
1265
- existing = readFileSync2(target, "utf8");
1493
+ existing = readFileSync3(target, "utf8");
1266
1494
  } catch (err) {
1267
1495
  fail(`--merge needs an existing file at ${target}: ${err instanceof Error ? err.message : String(err)}`);
1268
1496
  }
@@ -1273,7 +1501,7 @@ if (values.check) {
1273
1501
  `--merge cannot place ${result.missingBlocks.length} block(s) absent from ${target}: ` + result.missingBlocks.join(", ")
1274
1502
  );
1275
1503
  }
1276
- writeFileSync2(target, result.css);
1504
+ writeFileSync3(target, result.css);
1277
1505
  process.stderr.write(
1278
1506
  `merged into ${target}: ${result.updated.length} updated, ${result.added.length} added, ${result.unchanged.length} already current
1279
1507
  `
@@ -1281,10 +1509,10 @@ if (values.check) {
1281
1509
  reportExternalReferences(slice, { target, css: result.css });
1282
1510
  } else if (format === "all") {
1283
1511
  const dir = values.out ?? ".";
1284
- mkdirSync2(dir, { recursive: true });
1512
+ mkdirSync3(dir, { recursive: true });
1285
1513
  for (const fmt of formats) {
1286
- const target = join2(dir, FILE_NAMES2[fmt]);
1287
- writeFileSync2(target, serialise(fmt) + "\n");
1514
+ const target = join3(dir, FILE_NAMES2[fmt]);
1515
+ writeFileSync3(target, serialise(fmt) + "\n");
1288
1516
  process.stderr.write(`wrote ${target}
1289
1517
  `);
1290
1518
  }
@@ -1292,7 +1520,7 @@ if (values.check) {
1292
1520
  const output = serialise(format) + "\n";
1293
1521
  if (values.out) {
1294
1522
  const target = targetPath(format, values.out);
1295
- writeFileSync2(target, output);
1523
+ writeFileSync3(target, output);
1296
1524
  process.stderr.write(`wrote ${target}
1297
1525
  `);
1298
1526
  } else {
@@ -1301,7 +1529,8 @@ if (values.check) {
1301
1529
  if (isSlice && SECTIONED_FORMATS.includes(format)) reportExternalReferences(output);
1302
1530
  }
1303
1531
  if (values.usage && !values.check) {
1304
- writeFileSync2(values.usage, usageText);
1532
+ writeFileSync3(values.usage, usageText);
1305
1533
  process.stderr.write(`wrote ${values.usage}
1306
1534
  `);
1307
1535
  }
1536
+ if (!values.check && !checkLocal()) process.exit(1);
package/dist/index.d.ts CHANGED
@@ -1192,6 +1192,14 @@ interface View {
1192
1192
  declare function groundTokenNames(colors: readonly string[]): string[];
1193
1193
  /** The page tokens a page surface's name can't take: it is emitted as `--<name>` beside them */
1194
1194
  declare function reservedSurfaceNames(colors: readonly string[]): string[];
1195
+ /**
1196
+ * The names an added colour (`--color <name>=…`) can't take, whether or not `--aliases` is on: a
1197
+ * status colour's second name (`yellow` is warning's), a fixed colour, or a page token. Each is a name
1198
+ * the generator already writes or deletes, so a colour given one would vanish or collide.
1199
+ */
1200
+ declare const RESERVED_COLOR_NAMES: readonly string[];
1201
+ /** Why an added colour can't take a name, or undefined when it can. */
1202
+ declare function reservedColorReason(name: string): string | undefined;
1195
1203
  /**
1196
1204
  * The step a colour lands on by its lightness, on a ramp anchored where the system anchors by
1197
1205
  * default: a deep green near 900, a pale blue-grey near 200. What `--color name=colour@step`
@@ -1264,6 +1272,51 @@ interface ContractBreak {
1264
1272
  /** Every step whose promise differs between colours, light to dark. Empty when every step means the same everywhere. */
1265
1273
  declare function stepContract(palette: PrimitivePalette): ContractBreak[];
1266
1274
 
1275
+ /**
1276
+ * The one sanctioned place to override the generated colour: a project's `tokens.local.css`, loaded
1277
+ * straight after `tokens.css`. It exists for the few values a flag or the seed can't say, and it is held
1278
+ * to the system's own terms, so every project overrides the same way:
1279
+ *
1280
+ * - selectors are the generator's own: `:root`, `[data-theme="light"]`, `[data-theme="dark"]`, `.dark`,
1281
+ * and `[data-surface="<ground>"]` (or `"canvas"`, the page), alone or in a list, plus the system-dark
1282
+ * block exactly as the generator writes it; no other at-rule;
1283
+ * - a dark override reaches every dark reader: set under `[data-theme="dark"]` or `.dark`, it is set to
1284
+ * the same value under system dark too, and the other way round, or a visitor whose system is dark
1285
+ * (or who toggled dark on a light system) keeps the generated value;
1286
+ * - names are tokens the generator writes; never a `--color-*` alias or ramp step (a ramp step is moved
1287
+ * with shade overrides, a token by setting the token itself), and never a new name;
1288
+ * - values point at the system: `var()` references, a ramp step nudged with relative colour
1289
+ * (`oklch(from var(--color-…) …)`) or mixed (`color-mix()`); never a literal colour.
1290
+ *
1291
+ * `checkLocalOverrides` reports every override as pinned by hand and re-checks contrast for each pair an
1292
+ * override touches, so a pinned surface can't quietly fail its text.
1293
+ */
1294
+ interface LocalOverride {
1295
+ selector: string;
1296
+ name: string;
1297
+ value: string;
1298
+ }
1299
+ interface LocalProblem {
1300
+ kind: "selector" | "name" | "value" | "dark" | "contrast" | "syntax";
1301
+ message: string;
1302
+ }
1303
+ interface LocalReport {
1304
+ overrides: LocalOverride[];
1305
+ problems: LocalProblem[];
1306
+ }
1307
+ declare const TARGETS: {
1308
+ readonly "aa-large": 3;
1309
+ readonly aa: 4.5;
1310
+ readonly aaa: 7;
1311
+ };
1312
+ /**
1313
+ * Check a project's overrides against the system and against contrast. `generated` is the tokens file
1314
+ * the generator writes (css or tailwind-v4); `local` is the override file.
1315
+ */
1316
+ declare function checkLocalOverrides(generated: string, local: string, target?: keyof typeof TARGETS): LocalReport;
1317
+ /** The file `init` writes: empty, with its rules at the head. */
1318
+ declare const LOCAL_TEMPLATE = "/* tokens.local.css: the project's overrides of the generated colour, loaded after tokens.css.\n Most changes are an input instead (a flag, the seed, shade overrides): use this only for a value\n the generator can't say. generate-tokens --local checks it against the system:\n - selectors: :root, [data-theme=\"light\"], [data-theme=\"dark\"], .dark, [data-surface=\"<ground>\"];\n - a dark override is set twice, to the same value, so it reaches every dark reader: in\n [data-theme=\"dark\"], .dark { \u2026 } and in the system-dark block, which outranks the toggle:\n @media (prefers-color-scheme: dark) { :root:not([data-theme=\"light\"]):not(.light) { \u2026 } }\n - names: tokens the generator writes (never a --color- alias or ramp step, never a new name);\n - values: var() references, or a ramp step nudged with oklch(from var(--color-\u2026) \u2026); never a literal colour.\n Each override is reported as pinned by hand, and the pairs it touches are re-checked for contrast. */\n";
1319
+
1267
1320
  /**
1268
1321
  * The non-colour scale: space, size, type, radius, shadow, motion, screen sizes and widths. The colour
1269
1322
  * generator works a palette out from a seed; the scale has no seed, so this is a set of defaults, written
@@ -1305,5 +1358,49 @@ type ScaleOverride = string | {
1305
1358
  declare function applyScaleOverrides(tiers: ScaleTier[], overrides: Record<string, ScaleOverride>): ScaleTier[];
1306
1359
  type ScaleFormat = "css" | "tailwind-v4" | "tailwind-v3" | "dtcg" | "json";
1307
1360
  declare function exportScale(tiers: ScaleTier[], format: ScaleFormat, header?: string): string;
1361
+ /**
1362
+ * The mark an owned scale carries: written once by `generate-tokens scale --init` (or `init`), then the
1363
+ * project's file, edited by hand and never regenerated. The values are the project's; the names are the
1364
+ * contract, which `verifyScale` checks.
1365
+ */
1366
+ declare const OWNED_SCALE_MARK = "@designtools/tokens scale";
1367
+ /** The header an owned scale opens with. */
1368
+ declare function ownedScaleHeader(version: string): string;
1369
+ /** Whether a stylesheet is an owned scale. */
1370
+ declare function isOwnedScale(css: string): boolean;
1371
+ /**
1372
+ * The words a type tier's steps are made of: places on the scale, never uses. A tier is a scale, so a
1373
+ * name in it says where a step sits (`--text-5xl`, `--leading-loose`), and a role a page gives it
1374
+ * (display, headline, label) is mapped onto a step elsewhere. Tailwind's own words, plus the ones that
1375
+ * name a position between two of them (`--leading-medium`, between snug and normal).
1376
+ */
1377
+ declare const TYPE_STEPS: {
1378
+ text: string[];
1379
+ leading: string[];
1380
+ tracking: string[];
1381
+ "font-weight": string[];
1382
+ };
1383
+ /** Why a name in a type tier is refused, naming the tier's steps: "is not a step of the type sizes (xs, sm, …)". */
1384
+ declare function offScaleReason(name: string): string;
1385
+ /** What to do instead of naming a use in a type tier, said once after the names. */
1386
+ declare const OFF_SCALE_ADVICE = "a type step names a place on the scale, never a use. A size that changes by screen is set in the component (text-5xl lg:text-8xl); a role a page uses (display, headline, label) is a step, mapped in the docs config's type.hierarchy.";
1387
+ interface ScaleVerdict {
1388
+ /** Names the scale promises that the file no longer has. */
1389
+ missing: string[];
1390
+ /** Names that belong to no tier: a second system beside the scale. */
1391
+ strays: string[];
1392
+ /** Names in a type tier (text, leading, tracking, weight) that are no step of it: a use, such as `--text-display`. */
1393
+ offScale: string[];
1394
+ /** Names the project added inside a tier: its own steps, which are fine. */
1395
+ own: string[];
1396
+ }
1397
+ /**
1398
+ * Check a scale file's names against the contract: every default name is still there, and every
1399
+ * name the project added sits inside a tier's namespace. In the type tiers it must also be a step of
1400
+ * the tier's own vocabulary (`TYPE_STEPS`); the other tiers take any name inside their namespace.
1401
+ * Values are never compared; they are the project's. Reads the custom properties declared anywhere
1402
+ * in the file.
1403
+ */
1404
+ declare function verifyScale(css: string): ScaleVerdict;
1308
1405
 
1309
- export { ALIAS_PAIRS, type APCAContrastResult, APCAUnavailableError, type BrandColors, type CVDType, type ChromaProfile, type ChromaShape, type ColorFormat, type ColorScale, type ContractBreak, type ContrastAlgorithm, type ContrastTarget, DEFAULT_NEUTRAL_COLOR, DEFAULT_SEED_SHADE, type Declaration, type ExportFormat, type ExportOptions, type ExtendedSemanticColor, type FamilyShape, type ForegroundRef, GENERATOR_NAME, GROUND_BASE_TOKENS, GROUND_COLOR_PARTS, GROUND_SELECTOR, type Gamut, type GamutTokens, type GenerationOptions, type GroundAction, type GroundColour, type GroundFill, type GroundRef, type GroundSpec, type GroundTokens, type HueDrift, type LightnessStrategy, type MergeResult, type PageContrast, type PageSurface, type PaletteOptions, type PrimitivePalette, type Provenance, SECTIONED_FORMATS, SHADE_PRESETS, type SavedConfig, type ScaleFormat, type ScaleOptions, type ScaleOverride, type ScaleTier, type ScaleTierId, type ScaleToken, type SeedFile, type SelectedTokens, type SemanticColorPair, type SemanticGamuts, type SemanticShadeOverrides, type SemanticTokens, type ShadeNumber, type SliceDiff, type SurfaceRef, type SurfaceShadeOverrides, type SurfaceTokens, TAILWIND_SHADES, TOKEN_SECTIONS, type TokenSection, type TokenSystem, type UsageReport, type UsageVerdict, type UtilityShadeOverrides, type UtilityTokens, VALID_SHADES, type VariantShadeOverrides, type WCAGContrastResult, WIDE_GAMUT_QUERY, adjustChroma, adjustLightness, aliasOf, applyScaleOverrides, checkRampChroma, checkSemanticContrast, checkSemanticContrastAPCA, checkSurfaceContrast, chromaShadeFor, classifyAPCALevel, computeAccessibilityScore, defaultScale, diffSlice, exportScale, exportToCss, exportToDtcg, exportToTailwindV3, exportToTailwindV4, exportTokens, externalReferences, familiesOf, familySeedShade, findContrastingColorAPCA, fingerprint, formatColorAs, formatColorShort, formatOklchInGamut, generateColorScale, generateColorScaleAPCA, generateGroundTokens, generatePrimitivePalette, generateSemanticTokens, generateSurfaceTokens, generateTokens, generateUtilityTokens, getAPCAContrast, getContrastRatio, getOklchString, getRelativeLuminance, getShade, groundTokenNames, isAPCAAvailable, isInGamut, meetsWCAG_AA, meetsWCAG_AAA, mergeSlice, modeSelectors, oklchToHex, parseProvenance, parseToOklch, provenanceComment, rangeOf, readDeclarations, reanchorFactors, reservedSurfaceNames, resolveShades, seedFingerprint, selectTokenSections, serialiseUsage, simulateCVD, snapShade, stableStringify, stepContract, suggestStep, tokenFamilies, usageReport, withJsonProvenance };
1406
+ export { ALIAS_PAIRS, type APCAContrastResult, APCAUnavailableError, type BrandColors, type CVDType, type ChromaProfile, type ChromaShape, type ColorFormat, type ColorScale, type ContractBreak, type ContrastAlgorithm, type ContrastTarget, DEFAULT_NEUTRAL_COLOR, DEFAULT_SEED_SHADE, type Declaration, type ExportFormat, type ExportOptions, type ExtendedSemanticColor, type FamilyShape, type ForegroundRef, GENERATOR_NAME, GROUND_BASE_TOKENS, GROUND_COLOR_PARTS, GROUND_SELECTOR, type Gamut, type GamutTokens, type GenerationOptions, type GroundAction, type GroundColour, type GroundFill, type GroundRef, type GroundSpec, type GroundTokens, type HueDrift, LOCAL_TEMPLATE, type LightnessStrategy, type LocalOverride, type LocalProblem, type LocalReport, type MergeResult, OFF_SCALE_ADVICE, OWNED_SCALE_MARK, type PageContrast, type PageSurface, type PaletteOptions, type PrimitivePalette, type Provenance, RESERVED_COLOR_NAMES, SECTIONED_FORMATS, SHADE_PRESETS, type SavedConfig, type ScaleFormat, type ScaleOptions, type ScaleOverride, type ScaleTier, type ScaleTierId, type ScaleToken, type ScaleVerdict, type SeedFile, type SelectedTokens, type SemanticColorPair, type SemanticGamuts, type SemanticShadeOverrides, type SemanticTokens, type ShadeNumber, type SliceDiff, type SurfaceRef, type SurfaceShadeOverrides, type SurfaceTokens, TAILWIND_SHADES, TOKEN_SECTIONS, TYPE_STEPS, type TokenSection, type TokenSystem, type UsageReport, type UsageVerdict, type UtilityShadeOverrides, type UtilityTokens, VALID_SHADES, type VariantShadeOverrides, type WCAGContrastResult, WIDE_GAMUT_QUERY, adjustChroma, adjustLightness, aliasOf, applyScaleOverrides, checkLocalOverrides, checkRampChroma, checkSemanticContrast, checkSemanticContrastAPCA, checkSurfaceContrast, chromaShadeFor, classifyAPCALevel, computeAccessibilityScore, defaultScale, diffSlice, exportScale, exportToCss, exportToDtcg, exportToTailwindV3, exportToTailwindV4, exportTokens, externalReferences, familiesOf, familySeedShade, findContrastingColorAPCA, fingerprint, formatColorAs, formatColorShort, formatOklchInGamut, generateColorScale, generateColorScaleAPCA, generateGroundTokens, generatePrimitivePalette, generateSemanticTokens, generateSurfaceTokens, generateTokens, generateUtilityTokens, getAPCAContrast, getContrastRatio, getOklchString, getRelativeLuminance, getShade, groundTokenNames, isAPCAAvailable, isInGamut, isOwnedScale, meetsWCAG_AA, meetsWCAG_AAA, mergeSlice, modeSelectors, offScaleReason, oklchToHex, ownedScaleHeader, parseProvenance, parseToOklch, provenanceComment, rangeOf, readDeclarations, reanchorFactors, reservedColorReason, reservedSurfaceNames, resolveShades, seedFingerprint, selectTokenSections, serialiseUsage, simulateCVD, snapShade, stableStringify, stepContract, suggestStep, tokenFamilies, usageReport, verifyScale, withJsonProvenance };