@cagov/ca-ds 1.0.0 → 1.2.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 (101) hide show
  1. package/README.md +43 -26
  2. package/THIRD-PARTY-LICENSES.txt +690 -0
  3. package/ca-ds.js +48390 -0
  4. package/package.json +5 -31
  5. package/bin/ca-ds.js +0 -5
  6. package/src/cli/add.js +0 -134
  7. package/src/cli/build.js +0 -15
  8. package/src/cli/diff.js +0 -39
  9. package/src/cli/eject.js +0 -112
  10. package/src/cli/exit.js +0 -22
  11. package/src/cli/format.js +0 -52
  12. package/src/cli/init.js +0 -148
  13. package/src/cli/install.js +0 -178
  14. package/src/cli/items.js +0 -10
  15. package/src/cli/login.js +0 -331
  16. package/src/cli/main.js +0 -108
  17. package/src/cli/new.js +0 -230
  18. package/src/cli/outdated.js +0 -74
  19. package/src/cli/pack.js +0 -75
  20. package/src/cli/preview.js +0 -31
  21. package/src/cli/publish.js +0 -295
  22. package/src/cli/pull.js +0 -208
  23. package/src/cli/remote.js +0 -52
  24. package/src/cli/remove.js +0 -69
  25. package/src/cli/update.js +0 -223
  26. package/src/cli/validate.js +0 -131
  27. package/src/lib/browser.js +0 -12
  28. package/src/lib/build.js +0 -249
  29. package/src/lib/bundle.js +0 -148
  30. package/src/lib/catalog.js +0 -44
  31. package/src/lib/checks.js +0 -31
  32. package/src/lib/collection.js +0 -65
  33. package/src/lib/emblem.js +0 -29
  34. package/src/lib/fixtures.js +0 -59
  35. package/src/lib/floor.js +0 -79
  36. package/src/lib/glyph.js +0 -148
  37. package/src/lib/image.js +0 -138
  38. package/src/lib/json-text.js +0 -213
  39. package/src/lib/keys.js +0 -322
  40. package/src/lib/links.js +0 -321
  41. package/src/lib/markdown.js +0 -408
  42. package/src/lib/merge.js +0 -93
  43. package/src/lib/pack.js +0 -30
  44. package/src/lib/page-schema.js +0 -368
  45. package/src/lib/page.js +0 -372
  46. package/src/lib/patch.js +0 -9
  47. package/src/lib/regions.js +0 -173
  48. package/src/lib/registry.js +0 -371
  49. package/src/lib/release.js +0 -119
  50. package/src/lib/repoints.js +0 -120
  51. package/src/lib/resolve.js +0 -32
  52. package/src/lib/schema.js +0 -28
  53. package/src/lib/serial.js +0 -4
  54. package/src/lib/serialize.js +0 -444
  55. package/src/lib/structured.js +0 -72
  56. package/src/lib/system.js +0 -13
  57. package/src/lib/targets.js +0 -85
  58. package/src/lib/terms.js +0 -11
  59. package/src/lib/token-view.js +0 -289
  60. package/src/lib/tokens.js +0 -247
  61. package/src/lib/version.js +0 -34
  62. package/src/preview/frame.js +0 -75
  63. package/src/preview/pages.js +0 -128
  64. package/src/preview/screenshots.js +0 -72
  65. package/src/preview/server.js +0 -378
  66. package/src/preview/shell.js +0 -153
  67. package/src/schema/a11y.schema.json +0 -56
  68. package/src/schema/collection.lock.schema.json +0 -58
  69. package/src/schema/collection.schema.json +0 -65
  70. package/src/schema/composition.schema.json +0 -98
  71. package/src/schema/contract.schema.json +0 -116
  72. package/src/schema/interface.schema.json +0 -257
  73. package/src/schema/item.schema.json +0 -362
  74. package/src/schema/release.schema.json +0 -39
  75. package/src/schema/system.schema.json +0 -75
  76. package/src/schema/variants.schema.json +0 -60
  77. package/src/validate/collection.js +0 -19
  78. package/src/validate/collisions.js +0 -124
  79. package/src/validate/context.js +0 -357
  80. package/src/validate/facts.js +0 -253
  81. package/src/validate/files.js +0 -103
  82. package/src/validate/findings.js +0 -19
  83. package/src/validate/glyphs.js +0 -126
  84. package/src/validate/html.js +0 -215
  85. package/src/validate/imports.js +0 -29
  86. package/src/validate/index.js +0 -75
  87. package/src/validate/item.js +0 -47
  88. package/src/validate/links.js +0 -113
  89. package/src/validate/manifest.js +0 -147
  90. package/src/validate/media.js +0 -65
  91. package/src/validate/page.js +0 -74
  92. package/src/validate/prefixes.js +0 -58
  93. package/src/validate/relations.js +0 -310
  94. package/src/validate/release.js +0 -109
  95. package/src/validate/skill.js +0 -122
  96. package/src/validate/structured.js +0 -335
  97. package/src/validate/tasc.js +0 -80
  98. package/src/validate/template.js +0 -129
  99. package/src/validate/tokens.js +0 -154
  100. package/src/validate/zip.js +0 -40
  101. /package/{src/preview/preview.css → preview.css} +0 -0
@@ -1,289 +0,0 @@
1
- // Names and values match what ./tokens.js emits; it imports the math from here, so the two share one copy.
2
- // A bare number in a dimension is a rem magnitude.
3
-
4
- // Viewport ends in px, and the px per rem.
5
- export const FLUID = { minVw: 400, maxVw: 1440, base: 16 };
6
-
7
- export const SCHEMES = ['light', 'dark'];
8
-
9
- export function fluidClamp(min, max) {
10
- const { minVw, maxVw, base } = FLUID;
11
- const minPx = min * base;
12
- const maxPx = max * base;
13
- const slopePxPerPx = (maxPx - minPx) / (maxVw - minVw);
14
- const slopeVw = slopePxPerPx * 100;
15
- const interceptRem = (minPx - slopePxPerPx * minVw) / base;
16
- const r = (n) => +n.toFixed(3);
17
- return `clamp(${min}rem, ${r(slopeVw)}vw + ${r(interceptRem)}rem, ${max}rem)`;
18
- }
19
-
20
- export function shadowCss(value) {
21
- const px = (n) => (n === 0 ? '0' : `${n * FLUID.base}px`);
22
- const layer = (s) => `${px(s.offsetX)} ${px(s.offsetY)} ${px(s.blur)} ${px(s.spread)} ${s.color}`;
23
- return Array.isArray(value) ? value.map(layer).join(', ') : layer(value);
24
- }
25
-
26
- // Splits as Style Dictionary's name/kebab transform does.
27
- const words = (s) =>
28
- String(s)
29
- .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
30
- .replace(/([A-Z])([A-Z][a-z])/g, '$1 $2')
31
- .split(/[^A-Za-z0-9]+/)
32
- .filter(Boolean)
33
- .map((w) => w.toLowerCase());
34
-
35
- export function cssName(path) {
36
- const segments = Array.isArray(path) ? path : String(path).split('.');
37
- return `--${['ca', ...segments].flatMap(words).join('-')}`;
38
- }
39
-
40
- export const anchorOf = (path) => cssName(path).slice(2);
41
-
42
- export function layerOf(manifest, filePath) {
43
- if (manifest?.kind !== 'tokens') return 'component';
44
- const slash = String(filePath).indexOf('/');
45
- return slash > 0 ? filePath.slice(0, slash) : 'tokens';
46
- }
47
-
48
- const isToken = (node) => node !== null && typeof node === 'object' && !Array.isArray(node) && '$value' in node;
49
- const children = (node) => Object.entries(node).filter(([key, value]) => !key.startsWith('$') && value !== null && typeof value === 'object');
50
-
51
- function walk(json, visit, path = [], type = null, groups = null) {
52
- for (const [key, node] of children(json)) {
53
- const at = [...path, key];
54
- if (isToken(node)) visit(at, node, node.$type ?? type);
55
- else {
56
- groups?.(at, node);
57
- walk(node, visit, at, node.$type ?? type, groups);
58
- }
59
- }
60
- }
61
-
62
- // The group under a file's top-level key is implicit, label null; a deeper group's label is its path past that key.
63
- export function parseTokens(json) {
64
- const groups = new Map();
65
- const descriptions = new Map();
66
- walk(
67
- json ?? {},
68
- (segments, node, type) => {
69
- const parent = segments.slice(0, -1);
70
- const key = parent.join('.');
71
- if (!groups.has(key)) {
72
- groups.set(key, {
73
- path: key,
74
- label: parent.length > 1 ? parent.slice(1).join('.') : null,
75
- description: descriptions.get(key) ?? null,
76
- records: [],
77
- });
78
- }
79
- const path = segments.join('.');
80
- groups.get(key).records.push({
81
- path,
82
- cssName: cssName(segments),
83
- anchor: anchorOf(segments),
84
- type,
85
- value: node.$value,
86
- description: typeof node.$description === 'string' ? node.$description : null,
87
- });
88
- },
89
- [],
90
- null,
91
- (segments, node) => {
92
- if (typeof node.$description === 'string') descriptions.set(segments.join('.'), node.$description);
93
- },
94
- );
95
- return { groups: [...groups.values()] };
96
- }
97
-
98
- // The first file to define a path holds it, since the validator refuses a set where two do.
99
- export function tokenIndex(files) {
100
- const index = new Map();
101
- for (const { item = null, file = null, layer = null, json } of files) {
102
- walk(json ?? {}, (segments, node, type) => {
103
- const path = segments.join('.');
104
- if (index.has(path)) return;
105
- index.set(path, { path, cssName: cssName(segments), anchor: anchorOf(segments), type, value: node.$value, item, file, layer });
106
- });
107
- }
108
- return index;
109
- }
110
-
111
- const REF = /\{([^{}]+)\}/g;
112
- const WHOLE_REF = /^\{([^{}]+)\}$/;
113
-
114
- const pick = (type, value, scheme) => (type === 'colorScheme' && value && typeof value === 'object' && !Array.isArray(value) ? value[scheme] : value);
115
-
116
- const stepOf = (entry) => ({ path: entry.path, cssName: entry.cssName, anchor: entry.anchor, type: entry.type, item: entry.item, file: entry.file, layer: entry.layer });
117
-
118
- // A reference back into its own chain breaks it, as a missing one does.
119
- function follow(path, scheme, index, state) {
120
- const steps = [];
121
- const seen = new Set();
122
- let at = path;
123
- for (;;) {
124
- const entry = index.get(at);
125
- if (!entry || seen.has(at)) {
126
- state.missing.add(at);
127
- return { steps, value: null, type: null, missing: at };
128
- }
129
- seen.add(at);
130
- steps.push(stepOf(entry));
131
- const value = pick(entry.type, entry.value, scheme);
132
- const ref = typeof value === 'string' ? WHOLE_REF.exec(value) : null;
133
- if (ref) {
134
- at = ref[1].trim();
135
- continue;
136
- }
137
- const type = entry.type === 'colorScheme' ? 'color' : entry.type;
138
- return { steps, value: substitute(value, scheme, index, state), type, missing: null };
139
- }
140
- }
141
-
142
- function substitute(value, scheme, index, state) {
143
- if (typeof value === 'string') {
144
- const whole = WHOLE_REF.exec(value);
145
- if (whole) return follow(whole[1].trim(), scheme, index, state).value;
146
- return value.replace(REF, (match, path) => {
147
- const end = follow(path.trim(), scheme, index, state).value;
148
- return end === null || typeof end === 'object' ? match : String(end);
149
- });
150
- }
151
- if (Array.isArray(value)) return value.map((v) => substitute(v, scheme, index, state));
152
- if (value !== null && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, substitute(v, scheme, index, state)]));
153
- return value;
154
- }
155
-
156
- // A chain's branch is the key path to its reference inside the value, or null for a whole-value reference.
157
- function resolveUnder(record, scheme, index, state) {
158
- const chains = [];
159
- const visit = (value, branch) => {
160
- if (typeof value === 'string') {
161
- const whole = WHOLE_REF.exec(value);
162
- if (whole) {
163
- const end = follow(whole[1].trim(), scheme, index, state);
164
- chains.push({ branch: branch.length ? branch.join('.') : null, steps: end.steps, value: end.value, type: end.type, missing: end.missing });
165
- return end.value;
166
- }
167
- return substitute(value, scheme, index, state);
168
- }
169
- if (Array.isArray(value)) return value.map((v, i) => visit(v, [...branch, String(i)]));
170
- if (value !== null && typeof value === 'object') return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, visit(v, [...branch, k])]));
171
- return value;
172
- };
173
- const value = visit(pick(record.type, record.value, scheme), []);
174
- return { value, chains };
175
- }
176
-
177
- const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
178
-
179
- // Every record resolves once per scheme, since a colorScheme anywhere in its chain takes the scheme's value.
180
- // A broken reference leaves its value null and lands in missing, never thrown.
181
- export function resolveToken(record, index) {
182
- const state = { missing: new Set() };
183
- const light = resolveUnder(record, 'light', index, state);
184
- const dark = resolveUnder(record, 'dark', index, state);
185
- const schemed = record.type === 'colorScheme' || !same(light, dark);
186
- const chains = schemed
187
- ? SCHEMES.flatMap((scheme) => (scheme === 'light' ? light : dark).chains.map((c) => ({ ...c, scheme })))
188
- : light.chains.map((c) => ({ ...c, scheme: null }));
189
- const resolved = schemed ? { light: light.value, dark: dark.value } : light.value;
190
- return { ...record, schemed, resolved, chains, display: formatValue(schemed ? 'colorScheme' : record.type, resolved), missing: [...state.missing] };
191
- }
192
-
193
- // Without repoints a record carries no repointedBy, as the tokens item's, which holds no CSS.
194
- export function tokenView({ item = null, file = null, layer = null, json }, index, { repoints = null } = {}) {
195
- const { groups } = parseTokens(json);
196
- const withRepoints = (r) => (repoints ? { ...r, repointedBy: repoints.get(r.cssName) ?? [] } : r);
197
- return { item, file, layer, groups: groups.map((g) => ({ ...g, records: g.records.map((r) => withRepoints(resolveToken(r, index))) })) };
198
- }
199
-
200
- export const LAYERS = ['primitive', 'semantic', 'component'];
201
-
202
- export function tokenLayerViews(files, index = tokenIndex(files)) {
203
- const layers = new Map();
204
- for (const f of files) {
205
- if (!layers.has(f.layer)) layers.set(f.layer, []);
206
- layers.get(f.layer).push(tokenView(f, index));
207
- }
208
- const rank = (layer) => (LAYERS.includes(layer) ? LAYERS.indexOf(layer) : LAYERS.length);
209
- return [...layers.entries()].sort(([a], [b]) => rank(a) - rank(b)).map(([layer, views]) => ({ layer, files: views }));
210
- }
211
-
212
- const trim = (n) => +n.toFixed(3);
213
-
214
- export function formatDimension(value) {
215
- let rem = null;
216
- if (typeof value === 'number') rem = value;
217
- else if (typeof value === 'string') {
218
- const m = /^(-?\d*\.?\d+)(rem|px)$/.exec(value.trim());
219
- if (m && m[2] === 'rem') rem = Number(m[1]);
220
- else if (m) {
221
- const px = Number(m[1]);
222
- return px === 0 ? { text: '0', rem: null, px: null } : { text: `${px}px`, rem: null, px: `${px}px` };
223
- }
224
- }
225
- if (rem === null) return { text: value === null || value === undefined ? '' : String(value), rem: null, px: null };
226
- if (rem === 0) return { text: '0', rem: null, px: null };
227
- const remText = `${rem}rem`;
228
- const pxText = `${trim(rem * FLUID.base)}px`;
229
- return { text: `${remText} (${pxText})`, rem: remText, px: pxText };
230
- }
231
-
232
- const fontFamilyCss = (value) =>
233
- (Array.isArray(value) ? value : [value]).map((name) => (/\s/.test(name) && !/^['"]/.test(name) ? `'${name}'` : String(name))).join(', ');
234
-
235
- export function formatValue(type, value) {
236
- if (value === null || value === undefined) return { text: '' };
237
- if (type === 'colorScheme' && typeof value === 'object' && !Array.isArray(value)) {
238
- const light = formatValue('color', value.light);
239
- const dark = formatValue('color', value.dark);
240
- return { text: `light: ${light.text}, dark: ${dark.text}`, light, dark };
241
- }
242
- if (type === 'dimensionFluid' || (type === 'dimension' && typeof value === 'object' && 'min' in value && 'max' in value)) {
243
- if (typeof value !== 'object') return formatDimension(value);
244
- const min = formatDimension(value.min);
245
- const max = formatDimension(value.max);
246
- const clamp = typeof value.min === 'number' && typeof value.max === 'number' ? fluidClamp(value.min, value.max) : null;
247
- return { text: clamp ?? `${min.text} to ${max.text}`, min, max, clamp };
248
- }
249
- if (type === 'dimension') return formatDimension(value);
250
- if (type === 'shadow' && typeof value === 'object') return { text: shadowCss(value) };
251
- if (type === 'fontFamily') return { text: fontFamilyCss(value) };
252
- return { text: typeof value === 'object' ? JSON.stringify(value) : String(value) };
253
- }
254
-
255
- export function isLineHeight(record) {
256
- if (record?.type !== 'number') return false;
257
- return String(record.path).split('.').some((s) => s === 'line-height' || s === 'lineHeight');
258
- }
259
-
260
- export function isRadius(record) {
261
- if (record?.type !== 'dimension') return false;
262
- return String(record.path).split('.').some((s) => s === 'radius' || s.endsWith('-radius') || s.endsWith('Radius'));
263
- }
264
-
265
- export function tokenJson(record, group = null) {
266
- const chains = record.chains.map((c) => {
267
- const out = {};
268
- if (c.scheme) out.scheme = c.scheme;
269
- if (c.branch) out.branch = c.branch;
270
- out.steps = c.steps.map((s) => s.path);
271
- out.value = c.missing ? null : formatValue(c.type, c.value).text;
272
- if (c.missing) out.missing = c.missing;
273
- return out;
274
- });
275
- return {
276
- path: record.path,
277
- cssName: record.cssName,
278
- type: record.type,
279
- group: group?.label ?? null,
280
- value: record.value,
281
- display: record.display.text,
282
- description: record.description,
283
- ...(record.repointedBy ? { repointedBy: record.repointedBy } : {}),
284
- chains,
285
- ...(record.missing.length ? { missing: record.missing } : {}),
286
- };
287
- }
288
-
289
- export const tokensJson = (view) => view.groups.flatMap((g) => g.records.map((r) => tokenJson(r, g)));
package/src/lib/tokens.js DELETED
@@ -1,247 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import { join, posix } from 'node:path';
3
- import StyleDictionary from 'style-dictionary';
4
- import { resolveReferences } from 'style-dictionary/utils';
5
- import { loadItems } from './catalog.js';
6
- import { FLUID, fluidClamp, shadowCss } from './token-view.js';
7
-
8
- // The layers come from manifests, never from paths.
9
- // Mutating $value in place is safe, since each instance re-parses its source. The ds.mode marker lets the dark build
10
- // emit only the mode roles, not the scale they share a file with.
11
- const pickMode = (mode) => (tokens) => {
12
- const walk = (node) => {
13
- if (!node || typeof node !== 'object') return;
14
- if (node.$type === 'colorScheme' && node.$value && typeof node.$value === 'object') {
15
- node.$value = node.$value[mode];
16
- node.$type = 'color';
17
- node.$extensions = { ...node.$extensions, 'ds.mode': true };
18
- return;
19
- }
20
- for (const key of Object.keys(node)) walk(node[key]);
21
- };
22
- walk(tokens);
23
- return tokens;
24
- };
25
- StyleDictionary.registerPreprocessor({ name: 'mode/light', preprocessor: pickMode('light') });
26
- StyleDictionary.registerPreprocessor({ name: 'mode/dark', preprocessor: pickMode('dark') });
27
-
28
- // Style Dictionary resolves references only in string $values, so an endpoint reference inside
29
- // dimensionFluid's { min, max } would reach the clamp unresolved and compute to NaN.
30
- StyleDictionary.registerPreprocessor({
31
- name: 'fluid/resolveEndpoints',
32
- preprocessor: (tokens) => {
33
- const walk = (node) => {
34
- if (!node || typeof node !== 'object') return;
35
- const v = node.$value;
36
- if (node.$type === 'dimensionFluid' && v && typeof v === 'object') {
37
- for (const k of ['min', 'max']) {
38
- if (typeof v[k] === 'string') v[k] = resolveReferences(v[k], tokens, { usesDtcg: true });
39
- }
40
- return;
41
- }
42
- for (const key of Object.keys(node)) walk(node[key]);
43
- };
44
- walk(tokens);
45
- return tokens;
46
- },
47
- });
48
-
49
- StyleDictionary.registerTransform({
50
- name: 'size/fluidClamp/css',
51
- type: 'value',
52
- transitive: true,
53
- filter: (token) => token.$type === 'dimensionFluid',
54
- transform: (token) => {
55
- // A whole-value alias is left to outputReferences, which emits var().
56
- if (token.$value === null || typeof token.$value !== 'object') return token.$value;
57
- return fluidClamp(token.$value.min, token.$value.max);
58
- },
59
- });
60
-
61
- // Shadow geometry is stored in rem magnitudes and written back as px, so shadows stay fixed-size.
62
- StyleDictionary.registerTransform({
63
- name: 'shadow/css/fromRem',
64
- type: 'value',
65
- filter: (token) => token.$type === 'shadow',
66
- transform: (token) => shadowCss(token.$value),
67
- });
68
-
69
- const cssTransforms = [
70
- ...StyleDictionary.hooks.transformGroups.css.filter((n) => n !== 'shadow/css/shorthand'),
71
- 'shadow/css/fromRem',
72
- 'size/fluidClamp/css',
73
- ];
74
-
75
- const platform = (destination, selector, filter) => ({
76
- css: {
77
- transforms: cssTransforms,
78
- prefix: 'ca',
79
- // The dark platform references tokens filtered from its own output, so format warnings stay non-fatal.
80
- log: { warnings: 'warn' },
81
- files: [
82
- {
83
- destination,
84
- format: 'css/variables',
85
- filter,
86
- options: { outputReferences: true, selector },
87
- },
88
- ],
89
- },
90
- });
91
-
92
- // A tokens item that isn't shared joins the component layer, so its names reach only the items that depend on it.
93
- export function tokenLayers(entries, { shared = () => true } = {}) {
94
- const categories = [];
95
- const components = [];
96
- for (const { base, manifest, json } of entries) {
97
- const files = Array.isArray(manifest?.files) ? manifest.files : [];
98
- for (const f of files.filter((x) => x?.role === 'tokens' && typeof x.path === 'string')) {
99
- const data = json(f.path);
100
- if (data == null) continue;
101
- const source = { path: posix.join(base, f.path), json: data };
102
- (manifest.kind === 'tokens' && shared(manifest) ? categories : components).push(source);
103
- }
104
- }
105
- const byPath = (a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
106
- return { categories: categories.sort(byPath), components: components.sort(byPath) };
107
- }
108
-
109
- export function readTokenSources(root = process.cwd()) {
110
- return tokenLayers(
111
- loadItems(root).map(({ dir, manifest }) => ({
112
- base: dir,
113
- manifest,
114
- json: (path) => JSON.parse(readFileSync(join(root, dir, path), 'utf8')),
115
- })),
116
- );
117
- }
118
-
119
- // mergeTokens catches leaf collisions alone, which miss a component claiming another layer's first segment.
120
- function checkNamespaceCollisions({ categories, components }) {
121
- const firstSegment = (files) => {
122
- const owners = new Map();
123
- for (const { path, json } of files) {
124
- for (const key of Object.keys(json)) {
125
- if (!owners.has(key)) owners.set(key, new Set());
126
- owners.get(key).add(path);
127
- }
128
- }
129
- return owners;
130
- };
131
-
132
- const categoryOwners = firstSegment(categories);
133
- const componentOwners = firstSegment(components);
134
-
135
- for (const [segment, files] of componentOwners) {
136
- const claimants = new Set([...(categoryOwners.get(segment) ?? []), ...files]);
137
- if (claimants.size > 1) {
138
- throw new Error(
139
- `Token namespace collision on "${segment}": claimed by ${[...claimants].join(', ')}. ` +
140
- `Each component file's top-level key must be unique across all token layers.`,
141
- );
142
- }
143
- }
144
- }
145
-
146
- // Merges as Style Dictionary does: a group's $-keys take the last file's value, and a repeated token path throws.
147
- function mergeTokens(files) {
148
- const tree = {};
149
- const owners = new Map();
150
- const isToken = (node) => node && typeof node === 'object' && '$value' in node;
151
- const merge = (node, target, path, file) => {
152
- for (const [key, value] of Object.entries(node)) {
153
- const at = [...path, key].join('.');
154
- if (key.startsWith('$')) {
155
- target[key] = structuredClone(value);
156
- } else if (isToken(value) || isToken(target[key])) {
157
- if (key in target) throw new Error(`Token collision on "${at}": defined by ${owners.get(at) ?? 'a group'} and ${file}.`);
158
- target[key] = structuredClone(value);
159
- owners.set(at, file);
160
- } else if (value && typeof value === 'object') {
161
- merge(value, (target[key] ??= {}), [...path, key], file);
162
- }
163
- }
164
- };
165
- for (const { path, json } of files) merge(json, tree, [], path);
166
- return tree;
167
- }
168
-
169
- // Each instance gets its own copy, since the mode preprocessors rewrite $value in place.
170
- function instances(tree) {
171
- const light = new StyleDictionary({
172
- tokens: structuredClone(tree),
173
- preprocessors: ['fluid/resolveEndpoints', 'mode/light'],
174
- platforms: platform('_root.css', ':root'),
175
- log: { verbosity: 'silent', warnings: 'error' },
176
- });
177
-
178
- // Every token is source, so references resolve, but only mode roles are output.
179
- const dark = new StyleDictionary({
180
- tokens: structuredClone(tree),
181
- preprocessors: ['fluid/resolveEndpoints', 'mode/dark'],
182
- platforms: platform('_dark.css', ':root', (token) => token.$extensions?.['ds.mode']),
183
- log: { verbosity: 'silent', warnings: 'error' },
184
- });
185
-
186
- return { light, dark };
187
- }
188
-
189
- export function declarations(css) {
190
- const decls = new Map();
191
- const bare = String(css).replace(/\/\*[\s\S]*?\*\//g, '');
192
- for (const m of bare.matchAll(/(--ca-[\w-]+)\s*:\s*([^;]+);/g)) decls.set(m[1], m[2].trim());
193
- return decls;
194
- }
195
-
196
- // A browser without light-dark() skips the block and keeps :root's light values.
197
- export const SCHEME_SUPPORTS = '@supports (color: light-dark(#000, #fff))';
198
-
199
- // light-dark() resolves against the color-scheme of the element that uses the role; an identical pair stays flat.
200
- export async function buildTokens({ sources = null } = {}) {
201
- sources ??= readTokenSources();
202
- checkNamespaceCollisions(sources);
203
- const { light, dark } = instances(mergeTokens([...sources.categories, ...sources.components]));
204
-
205
- const [{ output: rootCss }] = await light.formatPlatform('css');
206
- const [{ output: darkCss }] = await dark.formatPlatform('css');
207
-
208
- // A platform whose filter keeps no token formats to nothing.
209
- const root = declarations(rootCss ?? '');
210
- const pairs = [...declarations(darkCss ?? '')]
211
- .filter(([name, value]) => root.get(name) !== value)
212
- .map(([name, value]) => ` ${name}: light-dark(${root.get(name)}, ${value});`);
213
- const blocks = rootCss ? [String(rootCss).trimEnd()] : [];
214
- if (pairs.length) blocks.push(`${SCHEME_SUPPORTS} {\n :root {\n${pairs.join('\n')}\n }\n}`);
215
- return blocks.join('\n\n') + '\n';
216
- }
217
-
218
- // Many email clients read neither rem nor custom properties. A fluid token stays an object, which emailTokens skips.
219
- StyleDictionary.registerTransform({
220
- name: 'size/email/px',
221
- type: 'value',
222
- filter: (token) => token.$type === 'dimension' && typeof token.$value === 'number',
223
- transform: (token) => (token.$value === 0 ? '0' : `${+(token.$value * FLUID.base).toFixed(3)}px`),
224
- });
225
-
226
- const emailTransforms = [
227
- ...cssTransforms.filter((n) => n !== 'size/rem' && n !== 'size/fluidClamp/css'),
228
- 'size/email/px',
229
- ];
230
-
231
- export async function emailTokens({ sources = null } = {}) {
232
- sources ??= readTokenSources();
233
- checkNamespaceCollisions(sources);
234
- const sd = new StyleDictionary({
235
- tokens: mergeTokens([...sources.categories, ...sources.components]),
236
- preprocessors: ['fluid/resolveEndpoints', 'mode/light'],
237
- platforms: { email: { transforms: emailTransforms, prefix: 'ca' } },
238
- log: { verbosity: 'silent', warnings: 'error' },
239
- });
240
- const { allTokens } = await sd.getPlatformTokens('email');
241
- const values = new Map();
242
- for (const token of allTokens) {
243
- const value = token.$value ?? token.value;
244
- if (typeof value === 'string' || typeof value === 'number') values.set(`--${token.name}`, String(value));
245
- }
246
- return values;
247
- }
@@ -1,34 +0,0 @@
1
- // The registry validates and mints with its own @cagov/ca-ds, so a different version here may judge an item
2
- // otherwise. 1.0.0 gave an upload's version its meaning as the base, so a 0.x CLI meets the major outcome.
3
-
4
- import { readFileSync } from 'node:fs';
5
- import semver from 'semver';
6
-
7
- export const PACKAGE = '@cagov/ca-ds';
8
-
9
- export const VERSION = JSON.parse(readFileSync(new URL('../../package.json', import.meta.url), 'utf8')).version;
10
-
11
- export function handshake(url, theirs, ours = VERSION) {
12
- const at = `The registry at ${url}`;
13
- if (typeof theirs !== 'string' || !semver.valid(theirs)) {
14
- return { ours, theirs: null, outcome: 'unknown', message: `${at} reports no ${PACKAGE} version, so its validator may judge an item otherwise than ca-ds ${ours}.` };
15
- }
16
- if (theirs === ours) return { ours, theirs, outcome: 'match', message: null };
17
- if (semver.major(theirs) !== semver.major(ours)) {
18
- return {
19
- ours,
20
- theirs,
21
- outcome: 'major',
22
- message: `${at} runs ${PACKAGE} ${theirs}, and this is ca-ds ${ours}. A different major version validates differently, so run ca-ds ${semver.major(theirs)}.x against it.`,
23
- };
24
- }
25
- const older = semver.lt(theirs, ours);
26
- return {
27
- ours,
28
- theirs,
29
- outcome: older ? 'registry-older' : 'local-older',
30
- message: older
31
- ? `${at} runs ${PACKAGE} ${theirs}, older than this ca-ds ${ours}, so its dry run may judge an item otherwise than ca-ds validate.`
32
- : `${at} runs ${PACKAGE} ${theirs}, newer than this ca-ds ${ours}, so its dry run may judge an item otherwise than ca-ds validate. Update ca-ds to match.`,
33
- };
34
- }
@@ -1,75 +0,0 @@
1
- const esc = (s) =>
2
- String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
3
-
4
- const STOCK_HEADER = `<header>
5
- <ca-masthead>
6
- <ca-org>
7
- <a href="/">
8
- <span slot="org-dept">Department of Example Services</span>
9
- </a>
10
- </ca-org>
11
- <nav id="site-nav" slot="masthead-navigation" aria-label="Main navigation">
12
- <ca-navigation>
13
- <ul>
14
- <li><a href="/" aria-current="page">Home</a></li>
15
- <li><a href="/services">Services</a></li>
16
- <li><a href="/about">About</a></li>
17
- </ul>
18
- </ca-navigation>
19
- </nav>
20
- </ca-masthead>
21
- </header>
22
- `;
23
- const STOCK_MAIN = `<ca-container class="ca-prose">
24
- <h1>Department of Example Services</h1>
25
- <p>Services, programs, and news from the department.</p>
26
- </ca-container>
27
- `;
28
- const STOCK_FOOTER = `<footer>
29
- <ca-container class="ca-prose">
30
- <p>Department of Example Services</p>
31
- </ca-container>
32
- </footer>
33
- `;
34
-
35
- export function framedBody(body, frame) {
36
- if (!frame) return body;
37
- const format = frame.format ? ` format="${esc(frame.format)}"` : '';
38
- const indent = (s, n) => s.replace(/\n$/, '').replace(/^(?=.)/gm, ' '.repeat(n));
39
- const at = frame.placement;
40
- const layout = at === 'layout' ? `${indent(body, 2)}\n` : '';
41
- const header = indent(at === 'header' ? body : STOCK_HEADER, 2);
42
- const main = indent(at === 'main' ? body : STOCK_MAIN, 4);
43
- const footer = indent(at === 'footer' ? body : STOCK_FOOTER, 2);
44
- return `<div id="top" tabindex="-1"></div>
45
- <ca-layout${format}>
46
- ${layout}${header}
47
- <main>
48
- ${main}
49
- </main>
50
- ${footer}
51
- </ca-layout>
52
- `;
53
- }
54
-
55
- export function renderFrame(page) {
56
- const sheets = page.styles ?? ['/assets/bundle.css'];
57
- const links = ['/assets/tokens.css', ...sheets, '/assets/preview.css']
58
- .map((href) => ` <link rel="stylesheet" href="${esc(href)}">`)
59
- .join('\n');
60
-
61
- return `<!doctype html>
62
- <html lang="en">
63
- <head>
64
- <meta charset="utf-8">
65
- <meta name="viewport" content="width=device-width, initial-scale=1">
66
- <title>${esc(page.title)}</title>
67
- ${links}
68
- </head>
69
- <body${page.inset ? ' data-preview-inset' : ''}${page.kind === 'example' ? ' data-preview-example' : ''}>
70
- ${page.body}
71
- <script type="module" src="/assets/bundle.js"></script>
72
- </body>
73
- </html>
74
- `;
75
- }