@designtools/tokens 0.1.6 → 0.1.7

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
@@ -1,42 +1,146 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  DEFAULT_NEUTRAL_COLOR,
4
+ SECTIONED_FORMATS,
5
+ SHADE_PRESETS,
6
+ TOKEN_SECTIONS,
7
+ VALID_SHADES,
8
+ checkSemanticContrast,
9
+ checkSemanticContrastAPCA,
10
+ computeAccessibilityScore,
4
11
  exportTokens,
5
12
  generateTokens,
6
- parseToOklch
7
- } from "./chunk-G6P25B5W.js";
13
+ parseToOklch,
14
+ resolveShades,
15
+ selectTokenSections,
16
+ snapShade
17
+ } from "./chunk-T62MMGGQ.js";
8
18
 
9
19
  // src/cli.ts
10
20
  import { parseArgs } from "util";
11
21
  import { mkdirSync, writeFileSync, readFileSync, statSync } from "fs";
12
- import { join } from "path";
22
+ import { join, dirname } from "path";
23
+ import { fileURLToPath } from "url";
24
+
25
+ // src/seed.ts
26
+ var GENERATOR_NAME = "@designtools/tokens";
27
+ function stableStringify(value) {
28
+ if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
29
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
30
+ const entries = Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${stableStringify(v)}`);
31
+ return `{${entries.join(",")}}`;
32
+ }
33
+ function fingerprint(input) {
34
+ let h = 2166136261;
35
+ for (let i = 0; i < input.length; i++) {
36
+ h ^= input.charCodeAt(i);
37
+ h = Math.imul(h, 16777619) >>> 0;
38
+ }
39
+ return h.toString(16).padStart(8, "0");
40
+ }
41
+ function seedFingerprint(config) {
42
+ return fingerprint(stableStringify(config));
43
+ }
44
+ function provenanceComment(p) {
45
+ return `/* Generated by ${GENERATOR_NAME} v${p.version} (seed ${p.seed}) - do not edit by hand */`;
46
+ }
47
+ var PROVENANCE_RE = new RegExp(
48
+ `${GENERATOR_NAME.replace("/", "\\/")} v(\\S+) \\(seed ([0-9a-f]{8})\\)`
49
+ );
50
+ function parseProvenance(text) {
51
+ const comment = PROVENANCE_RE.exec(text);
52
+ if (comment) return { version: comment[1], seed: comment[2] };
53
+ const json = /"\$designtools"\s*:\s*\{[^}]*"version"\s*:\s*"([^"]+)"[^}]*"seed"\s*:\s*"([0-9a-f]{8})"/.exec(text);
54
+ if (json) return { version: json[1], seed: json[2] };
55
+ return null;
56
+ }
57
+ function withJsonProvenance(json, p) {
58
+ const parsed = JSON.parse(json);
59
+ const stamped = {
60
+ $designtools: { generator: GENERATOR_NAME, version: p.version, seed: p.seed },
61
+ ...parsed
62
+ };
63
+ return JSON.stringify(stamped, null, 2);
64
+ }
65
+
66
+ // src/cli.ts
13
67
  var HELP = `generate-tokens \u2014 brand colour in, design tokens out
14
68
 
15
69
  Usage:
16
70
  generate-tokens --primary <colour> [options]
17
71
 
18
72
  Seeds:
19
- --primary <colour> Brand colour (hex, rgb(), hsl(), oklch(), named). Required.
73
+ --primary <colour> Brand colour (hex, rgb(), hsl(), oklch(), named). Required
74
+ unless supplied by --seed.
20
75
  --neutral <colour> Neutral seed. Default: ${DEFAULT_NEUTRAL_COLOR}
21
76
  --color <name>=<colour> Additional brand colour scale. Repeatable.
77
+ --seed <file.json> Replay a saved configuration (the shape the web tool
78
+ persists). Any flag given alongside it wins, so a seed
79
+ file is a set of defaults rather than a lock.
22
80
 
23
81
  Generation options:
24
82
  --contrast <wcag|apca> Contrast algorithm for foreground selection. Default: wcag
25
83
  --target <aa-large|aa|aaa> Contrast target level. Default: aa
26
84
  --lightness <fixed|perceptual> Lightness distribution strategy. Default: fixed
85
+ --seed-shade <25..950> Which step the seed colour lands on. Default: 500.
86
+ Brand colours arrive as whatever they are; a deep
87
+ navy or a pale tint forced onto 500 leaves no
88
+ headroom on one side and wrecks the ramp.
89
+ --shades <list|preset> Which steps to emit. Default: all twelve (25-950).
90
+ Presets: tailwind (50-950, matching Tailwind's
91
+ stock ramps) and full. Or a list: 50,100,500,900.
92
+ Tokens naming a dropped step snap to the nearest
93
+ emitted one, reported on stderr.
27
94
  --overrides <file.json> JSON file with { shadeOverrides, surfaceShadeOverrides,
28
95
  utilityShadeOverrides } (same shape as the web tool).
29
96
 
97
+ Selection:
98
+ --only <sections> Emit only these slices, comma-separated or repeated:
99
+ ramp the twelve-step colour ramps alone
100
+ primitives the ramps plus black and white
101
+ semantic intent tokens (primary, destructive, muted, \u2026)
102
+ surface canvas / surface / overlay
103
+ utility border / input / ring / shadow
104
+ Keeps generated colour separable from hand-tuned files,
105
+ so a re-theme does not clobber them. Supported by the
106
+ css, tailwind-v4 and json formats.
107
+ Note a partial slice is not self-contained: --only semantic
108
+ emits var(--color-*) references to primitives it does not
109
+ itself define, so ship it alongside the primitive slice.
110
+
30
111
  Output:
31
- --format <fmt> css | tailwind-v4 | tailwind-v3 | dtcg | lovable | json | all
112
+ --format <fmt> css | tailwind-v4 | tailwind-v3 | dtcg | json | all
32
113
  Default: css (CSS custom properties, the lead format)
33
114
  --color-format <fmt> oklch | hex | rgb | hsl \u2014 how literal colour values are printed.
34
115
  Default: oklch
35
116
  --out <path> File to write (or directory when --format all).
36
117
  Omit to print to stdout.
37
- --vanilla Omit the shadcn/ui compatibility aliases (--background,
38
- --card, --secondary, --sidebar-*) from css and tailwind-v4.
39
- Use for Base UI / vanilla-CSS projects. Default: aliases on.
118
+ --vanilla Accepted and ignored. The shadcn/ui aliases it used to
119
+ switch off are gone in 0.2, so vanilla is now the only
120
+ behaviour. Kept for one version so existing calls do not
121
+ break; it will be removed in 0.3.
122
+ --replace-palette tailwind-v4 only: clear Tailwind's stock colour palette
123
+ (--color-*: initial), so a colour class this tool does not
124
+ define fails to compile instead of compiling off-brand.
125
+ Breaks existing Tailwind codebases. Default: off.
126
+ --no-provenance Omit the "Generated by \u2026" header. The header is what
127
+ makes --check able to distinguish a generator upgrade
128
+ from a hand edit, so dropping it costs you that.
129
+
130
+ Verification:
131
+ --check Regenerate in memory and compare against what is already
132
+ at --out. Writes nothing. Exit 0 if identical, 1 if it
133
+ differs, and reports a version mismatch distinctly from
134
+ an edit. Requires --out.
135
+ --report Print the measured contrast of every semantic foreground
136
+ pairing to stderr, with an overall score against the
137
+ --contrast algorithm and --target level. Writes no files
138
+ and does not change the output.
139
+
140
+ Input:
141
+ --stdin Read a --seed JSON document from standard input. Flags
142
+ still win over it, as with --seed.
143
+
40
144
  --help Show this help.
41
145
  `;
42
146
  var FILE_NAMES = {
@@ -44,9 +148,16 @@ var FILE_NAMES = {
44
148
  "tailwind-v4": "tailwind.css",
45
149
  "tailwind-v3": "tailwind.config.js",
46
150
  dtcg: "tokens.dtcg.json",
47
- lovable: "lovable.css",
48
151
  json: "tokens.json"
49
152
  };
153
+ var VERSION = (() => {
154
+ try {
155
+ const here = dirname(fileURLToPath(import.meta.url));
156
+ return JSON.parse(readFileSync(join(here, "../package.json"), "utf8")).version;
157
+ } catch {
158
+ return "0.0.0";
159
+ }
160
+ })();
50
161
  function fail(message) {
51
162
  process.stderr.write(`generate-tokens: ${message}
52
163
  `);
@@ -62,11 +173,20 @@ try {
62
173
  contrast: { type: "string" },
63
174
  target: { type: "string" },
64
175
  lightness: { type: "string" },
176
+ "seed-shade": { type: "string" },
177
+ shades: { type: "string" },
65
178
  overrides: { type: "string" },
179
+ only: { type: "string", multiple: true },
66
180
  format: { type: "string" },
67
181
  "color-format": { type: "string" },
68
182
  out: { type: "string" },
69
183
  vanilla: { type: "boolean" },
184
+ "replace-palette": { type: "boolean" },
185
+ seed: { type: "string" },
186
+ check: { type: "boolean" },
187
+ report: { type: "boolean" },
188
+ stdin: { type: "boolean" },
189
+ "no-provenance": { type: "boolean" },
70
190
  help: { type: "boolean" }
71
191
  }
72
192
  }));
@@ -77,7 +197,25 @@ if (values.help) {
77
197
  process.stdout.write(HELP);
78
198
  process.exit(0);
79
199
  }
80
- if (!values.primary) fail("--primary is required (try --help)");
200
+ var seed = {};
201
+ if (values.stdin) {
202
+ try {
203
+ seed = JSON.parse(readFileSync(0, "utf8"));
204
+ } catch (err) {
205
+ fail(`could not read seed from stdin: ${err instanceof Error ? err.message : String(err)}`);
206
+ }
207
+ }
208
+ if (values.seed) {
209
+ try {
210
+ seed = JSON.parse(readFileSync(values.seed, "utf8"));
211
+ } catch (err) {
212
+ fail(`could not read --seed file: ${err instanceof Error ? err.message : String(err)}`);
213
+ }
214
+ }
215
+ if (values.check && !values.out) fail("--check needs --out to compare against");
216
+ if (!values.primary && !seed.primaryColor) {
217
+ fail("--primary is required, either as a flag or in --seed (try --help)");
218
+ }
81
219
  function validateChoice(name, value, choices, fallback) {
82
220
  if (value === void 0) return fallback;
83
221
  if (!choices.includes(value)) {
@@ -93,9 +231,15 @@ function validateColor(name, value) {
93
231
  }
94
232
  return value;
95
233
  }
96
- var primary = validateColor("primary", values.primary);
97
- var neutral = validateColor("neutral", values.neutral ?? DEFAULT_NEUTRAL_COLOR);
234
+ var primary = validateColor("primary", values.primary ?? seed.primaryColor);
235
+ var neutral = validateColor(
236
+ "neutral",
237
+ values.neutral ?? seed.neutralColor ?? DEFAULT_NEUTRAL_COLOR
238
+ );
98
239
  var additionalColors = {};
240
+ for (const { name, color } of seed.additionalColors ?? []) {
241
+ additionalColors[name] = validateColor(`seed colour ${name}`, color);
242
+ }
99
243
  for (const entry of values.color ?? []) {
100
244
  const eq = entry.indexOf("=");
101
245
  if (eq === -1) fail(`--color expects name=colour (got "${entry}")`);
@@ -106,17 +250,54 @@ for (const entry of values.color ?? []) {
106
250
  }
107
251
  additionalColors[name] = validateColor(`color ${name}`, colour);
108
252
  }
109
- var contrastAlgorithm = validateChoice("contrast", values.contrast, ["wcag", "apca"], "wcag");
110
- var contrastTarget = validateChoice("target", values.target, ["aa-large", "aa", "aaa"], "aa");
111
- var lightnessStrategy = validateChoice("lightness", values.lightness, ["fixed", "perceptual"], "fixed");
253
+ var contrastAlgorithm = validateChoice("contrast", values.contrast ?? seed.contrastAlgorithm, ["wcag", "apca"], "wcag");
254
+ var contrastTarget = validateChoice("target", values.target ?? seed.contrastTarget, ["aa-large", "aa", "aaa"], "aa");
255
+ var lightnessStrategy = validateChoice("lightness", values.lightness ?? seed.lightnessStrategy, ["fixed", "perceptual"], "fixed");
112
256
  var format = validateChoice(
113
257
  "format",
114
258
  values.format,
115
- ["css", "tailwind-v4", "tailwind-v3", "dtcg", "lovable", "json", "all"],
259
+ ["css", "tailwind-v4", "tailwind-v3", "dtcg", "json", "all"],
116
260
  "css"
117
261
  );
118
- var colorFormat = validateChoice("color-format", values["color-format"], ["oklch", "hex", "rgb", "hsl"], "oklch");
119
- var overrides = {};
262
+ var colorFormat = validateChoice("color-format", values["color-format"] ?? seed.colorFormat, ["oklch", "hex", "rgb", "hsl"], "oklch");
263
+ function parseShade(flag, raw) {
264
+ const n = Number(raw.trim());
265
+ if (!VALID_SHADES.includes(n)) {
266
+ fail(`--${flag} must be one of: ${VALID_SHADES.join(", ")} (got "${raw}")`);
267
+ }
268
+ return n;
269
+ }
270
+ var shadesInput = values.shades ?? (seed.shades ? seed.shades.join(",") : void 0);
271
+ var shades;
272
+ if (shadesInput !== void 0) {
273
+ const preset = SHADE_PRESETS[shadesInput.trim()];
274
+ shades = preset ? [...preset] : resolveShades(shadesInput.split(",").map((v) => parseShade("shades", v)));
275
+ if (shades.length < 3) fail(`--shades needs at least 3 steps (got ${shades.length})`);
276
+ }
277
+ var seedShade = values["seed-shade"] !== void 0 ? parseShade("seed-shade", values["seed-shade"]) : seed.seedShade;
278
+ if (seedShade !== void 0 && shades !== void 0 && !shades.includes(seedShade)) {
279
+ const emitted = shades;
280
+ fail(`--seed-shade ${seedShade} is not in --shades (${emitted.join(", ")})`);
281
+ }
282
+ var sections = (values.only ?? []).flatMap((entry) => entry.split(",")).map((s) => s.trim()).filter((s) => s.length > 0).map((s) => {
283
+ if (!TOKEN_SECTIONS.includes(s)) {
284
+ fail(`--only must be one of: ${TOKEN_SECTIONS.join(", ")} (got "${s}")`);
285
+ }
286
+ return s;
287
+ });
288
+ if (sections.length > 0) {
289
+ const sectionable = [...SECTIONED_FORMATS, "json"];
290
+ const targets = format === "all" ? SECTIONED_FORMATS : [format];
291
+ const unsupported = targets.filter((f) => !sectionable.includes(f));
292
+ if (unsupported.length > 0) {
293
+ fail(`--only is not supported by --format ${unsupported.join(", ")} (supported: ${sectionable.join(", ")})`);
294
+ }
295
+ }
296
+ var overrides = {
297
+ shadeOverrides: seed.shadeOverrides,
298
+ surfaceShadeOverrides: seed.surfaceShadeOverrides,
299
+ utilityShadeOverrides: seed.utilityShadeOverrides
300
+ };
120
301
  if (values.overrides) {
121
302
  try {
122
303
  overrides = JSON.parse(readFileSync(values.overrides, "utf8"));
@@ -133,24 +314,158 @@ var options = {
133
314
  contrastAlgorithm,
134
315
  contrastTarget,
135
316
  lightnessStrategy,
317
+ seedShade,
318
+ shades,
136
319
  shadeOverrides: overrides.shadeOverrides ?? {},
137
320
  surfaceShadeOverrides: overrides.surfaceShadeOverrides,
138
321
  utilityShadeOverrides: overrides.utilityShadeOverrides
139
322
  };
140
323
  var tokens = generateTokens(brandColors, options);
141
- var compat = !values.vanilla;
324
+ if (shades) {
325
+ const named = [
326
+ ["muted (light)", 25],
327
+ ["muted-foreground (light)", 500],
328
+ ["muted (dark)", 800],
329
+ ["muted-foreground (dark)", 200],
330
+ ["canvas (light)", 25],
331
+ ["canvas (dark)", 950],
332
+ ["semantic DEFAULT (light)", 500],
333
+ ["semantic subdued (light)", 50],
334
+ ["semantic highlight (light)", 700],
335
+ ["semantic DEFAULT (dark)", 600],
336
+ ["semantic subdued (dark)", 200],
337
+ ["semantic highlight (dark)", 400],
338
+ ["border/input (light)", 200],
339
+ ["ring (light)", 400],
340
+ ["border/input (dark)", 800],
341
+ ["ring (dark)", 700],
342
+ ["shadow", 950]
343
+ ];
344
+ const moved = named.map(([label, want]) => [label, want, snapShade(want, shades)]).filter(([, want, got]) => want !== got);
345
+ if (moved.length > 0) {
346
+ process.stderr.write(`--shades ${shades.join(",")} drops steps some tokens name; snapped to nearest:
347
+ `);
348
+ for (const [label, want, got] of moved) {
349
+ process.stderr.write(` ${label}: ${want} -> ${got}
350
+ `);
351
+ }
352
+ }
353
+ }
354
+ var replacePalette = values["replace-palette"] === true;
355
+ var resolvedSeed = {
356
+ primaryColor: primary,
357
+ neutralColor: neutral,
358
+ additionalColors: Object.entries(additionalColors).map(([name, color]) => ({ name, color })),
359
+ colorFormat,
360
+ contrastAlgorithm,
361
+ contrastTarget,
362
+ lightnessStrategy,
363
+ seedShade,
364
+ shades,
365
+ shadeOverrides: options.shadeOverrides ?? {},
366
+ surfaceShadeOverrides: options.surfaceShadeOverrides,
367
+ utilityShadeOverrides: options.utilityShadeOverrides
368
+ };
369
+ var provenance = {
370
+ version: VERSION,
371
+ seed: seedFingerprint(resolvedSeed)
372
+ };
373
+ var stampProvenance = values["no-provenance"] !== true;
374
+ var JSON_FORMATS = ["json", "dtcg"];
142
375
  function serialise(fmt) {
143
- if (fmt === "json") return JSON.stringify(tokens, null, 2);
144
- return exportTokens(tokens, fmt, {
376
+ const body = fmt === "json" ? JSON.stringify(selectTokenSections(tokens, sections), null, 2) : exportTokens(tokens, fmt, {
145
377
  colorFormat,
146
378
  shadeOverrides: options.shadeOverrides,
147
- compat
379
+ replacePalette,
380
+ // `--format all` writes every format; only the sectionable ones get filtered.
381
+ sections: SECTIONED_FORMATS.includes(fmt) ? sections : void 0,
382
+ shades
148
383
  });
384
+ if (!stampProvenance) return body;
385
+ return JSON_FORMATS.includes(fmt) ? withJsonProvenance(body, provenance) : `${provenanceComment(provenance)}
386
+ ${body}`;
387
+ }
388
+ function targetPath(fmt, out) {
389
+ try {
390
+ if (statSync(out).isDirectory()) return join(out, FILE_NAMES[fmt]);
391
+ } catch {
392
+ }
393
+ return out;
149
394
  }
150
- if (format === "all") {
395
+ function check(fmt, target) {
396
+ let existing;
397
+ try {
398
+ existing = readFileSync(target, "utf8");
399
+ } catch {
400
+ process.stderr.write(`check: ${target} does not exist
401
+ `);
402
+ return false;
403
+ }
404
+ const expected = serialise(fmt) + "\n";
405
+ if (existing === expected) {
406
+ process.stderr.write(`check: ${target} up to date
407
+ `);
408
+ return true;
409
+ }
410
+ const found = parseProvenance(existing);
411
+ if (found && found.version !== provenance.version) {
412
+ process.stderr.write(
413
+ `check: ${target} differs \u2014 generated by v${found.version}, running v${provenance.version}. Expected after a generator upgrade; regenerate to adopt it.
414
+ `
415
+ );
416
+ } else if (found && found.seed !== provenance.seed) {
417
+ process.stderr.write(
418
+ `check: ${target} differs \u2014 seed ${found.seed} on disk, ${provenance.seed} now. The inputs changed; regenerate.
419
+ `
420
+ );
421
+ } else {
422
+ process.stderr.write(
423
+ `check: ${target} differs \u2014 same generator and seed, so the file was edited by hand.
424
+ `
425
+ );
426
+ }
427
+ return false;
428
+ }
429
+ function report() {
430
+ const width = 34;
431
+ for (const mode of ["light", "dark"]) {
432
+ const semantic = tokens.semantic[mode];
433
+ process.stderr.write(`
434
+ ${mode} mode (${contrastAlgorithm}, target ${contrastTarget})
435
+ `);
436
+ if (contrastAlgorithm === "wcag") {
437
+ for (const [pair, r] of Object.entries(checkSemanticContrast(semantic))) {
438
+ const mark = r.passesAAA ? "AAA" : r.passesAA ? "AA " : "- ";
439
+ process.stderr.write(` ${mark} ${pair.padEnd(width)} ${r.ratio.toFixed(2)}:1
440
+ `);
441
+ }
442
+ } else {
443
+ for (const [pair, r] of Object.entries(checkSemanticContrastAPCA(semantic))) {
444
+ process.stderr.write(
445
+ ` ${r.level.padEnd(10)} ${pair.padEnd(width)} Lc ${r.lcValue.toFixed(1)}
446
+ `
447
+ );
448
+ }
449
+ }
450
+ const { score, passed, total } = computeAccessibilityScore(
451
+ semantic,
452
+ contrastAlgorithm,
453
+ contrastTarget
454
+ );
455
+ process.stderr.write(` score: ${score}% (${passed}/${total} pairings)
456
+ `);
457
+ }
458
+ }
459
+ if (values.report) report();
460
+ var formats = format === "all" ? Object.keys(FILE_NAMES) : [format];
461
+ if (values.check) {
462
+ const out = values.out;
463
+ const ok = formats.map((fmt) => check(fmt, format === "all" ? join(out, FILE_NAMES[fmt]) : targetPath(fmt, out)));
464
+ process.exit(ok.every(Boolean) ? 0 : 1);
465
+ } else if (format === "all") {
151
466
  const dir = values.out ?? ".";
152
467
  mkdirSync(dir, { recursive: true });
153
- for (const fmt of Object.keys(FILE_NAMES)) {
468
+ for (const fmt of formats) {
154
469
  const target = join(dir, FILE_NAMES[fmt]);
155
470
  writeFileSync(target, serialise(fmt) + "\n");
156
471
  process.stderr.write(`wrote ${target}
@@ -159,11 +474,7 @@ if (format === "all") {
159
474
  } else {
160
475
  const output = serialise(format) + "\n";
161
476
  if (values.out) {
162
- let target = values.out;
163
- try {
164
- if (statSync(target).isDirectory()) target = join(target, FILE_NAMES[format]);
165
- } catch {
166
- }
477
+ const target = targetPath(format, values.out);
167
478
  writeFileSync(target, output);
168
479
  process.stderr.write(`wrote ${target}
169
480
  `);