@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
package/src/lib/page.js DELETED
@@ -1,372 +0,0 @@
1
- // checkPage, sanitizePage, and formatPage resolve elements to nodes the same way, so an editor-written page passes each unchanged.
2
- // A finding never quotes an attribute's value. A draft attachment's path passes only with draft: true, which no publish passes.
3
-
4
- import { parseFragment, serialize } from 'parse5';
5
- import { NODES, TOP, SERVER_VALUE } from './page-schema.js';
6
- import { mediaTarget } from './fixtures.js';
7
-
8
- // Block content becomes one part of the block group.
9
- const CONTENT = new Map(
10
- Object.entries(NODES).map(([name, node]) => {
11
- const except = node.except ?? [];
12
- if (Array.isArray(node.content)) return [name, { kind: 'parts', parts: node.content.map(part) }];
13
- if (node.content === 'block') return [name, { kind: 'parts', parts: [part({ group: 'block', max: null, except })] }];
14
- return [name, { kind: node.content, except }];
15
- }),
16
- );
17
- const TOP_CONTENT = { kind: 'parts', parts: TOP.map(part) };
18
-
19
- function part(p) {
20
- return { group: p.group ?? null, nodes: p.nodes ?? null, min: p.min ?? 1, max: p.max === undefined ? 1 : p.max, except: p.except ?? [] };
21
- }
22
-
23
- const GROUPS = new Map();
24
- for (const [name, node] of Object.entries(NODES)) {
25
- if (!node.group) continue;
26
- if (!GROUPS.has(node.group)) GROUPS.set(node.group, []);
27
- GROUPS.get(node.group).push(name);
28
- }
29
-
30
- const admits = (p) => (p.nodes ?? GROUPS.get(p.group) ?? []).filter((n) => !p.except.includes(n));
31
-
32
- function candidatesOf(content) {
33
- if (content.kind === 'parts') return [...new Set(content.parts.flatMap(admits))];
34
- if (content.kind === 'inline') return admits({ group: 'inline', except: content.except });
35
- if (content.kind === 'list-item') return [...admits({ group: 'inline', except: [] }), ...admits({ group: 'block', except: [] })];
36
- return [];
37
- }
38
-
39
- export const contentOf = (name) => (name === null ? TOP_CONTENT : CONTENT.get(name));
40
-
41
- const attrOf = (el, name) => el.attrs?.find((a) => a.name === name)?.value;
42
- const classesOf = (el) => (attrOf(el, 'class') ?? '').split(/\s+/).filter(Boolean);
43
- export const isElement = (node) => typeof node.tagName === 'string';
44
- const isText = (node) => node.nodeName === '#text';
45
- const isBlank = (node) => isText(node) && !/\S/.test(node.value);
46
-
47
- // A node with an identity class wins over a node of the same tag without one.
48
- export function resolve(el, content) {
49
- const slot = attrOf(el, 'slot') ?? null;
50
- const classes = classesOf(el);
51
- let found = null;
52
- for (const name of candidatesOf(content)) {
53
- const node = NODES[name];
54
- if (node.tag !== el.tagName || (node.slot ?? null) !== slot) continue;
55
- if (node.match && !classes.includes(node.match)) continue;
56
- if (!found || (node.match && !NODES[found].match)) found = name;
57
- }
58
- return found;
59
- }
60
-
61
- export function label(name) {
62
- const node = NODES[name];
63
- return `${node.tag}${node.match ? `.${node.match}` : ''}${node.slot ? `[slot="${node.slot}"]` : ''}`;
64
- }
65
-
66
- export const parsePage = (html) => parseFragment(html, { sourceCodeLocationInfo: true });
67
-
68
- // A browser drops white space and control characters from a URL's scheme, so a url is read without them.
69
- export function allowed(kind, value, { draft = false } = {}) {
70
- if (Array.isArray(kind)) return kind.includes(value);
71
- if (kind === 'boolean') return value === '';
72
- if (kind === 'integer') return /^-?\d+$/.test(value);
73
- if (kind === 'id') return /^[A-Za-z][\w-]*$/.test(value);
74
- if (kind === 'url') return !/^(javascript|data|vbscript):/i.test(value.replace(/[\u0000-\u0020\u007f]/g, ''));
75
- if (kind === 'media') {
76
- const target = mediaTarget(value);
77
- return target !== null && (target.kind !== 'draft' || draft);
78
- }
79
- if (kind === 'blank') return value === '';
80
- return true;
81
- }
82
-
83
- export const checkPage = (html, options = {}) => findingsOf(html, TOP_CONTENT, 'the page', options);
84
-
85
- // A run of blocks that replaces blocks of a page. A hero is no block, so a run never holds one.
86
- export const checkBlocks = (html, { except = [], draft = false } = {}) => findingsOf(html, { kind: 'parts', parts: [part({ group: 'block', max: null, except })] }, 'the run of blocks', { draft });
87
-
88
- function findingsOf(html, top, outer, options = {}) {
89
- const findings = [];
90
- const add = (path, node, message) => findings.push({ path: path.join(' > '), line: node.sourceCodeLocation?.startLine ?? null, message });
91
- const where = (path) => (path.length ? `\`${path.at(-1).replace(/:nth-child\(\d+\)$/, '')}\`` : outer);
92
-
93
- const visit = (parent, name, path, marks) => {
94
- const content = path.length ? contentOf(name) : top;
95
- const kids = parent.childNodes ?? [];
96
- const resolved = [];
97
- let index = 0;
98
- let phase = 'start';
99
- for (const kid of kids) {
100
- if (isText(kid)) {
101
- if (isBlank(kid)) continue;
102
- if (content.kind === 'parts') add(path, kid, `Text sits directly in ${where(path)}, which holds blocks alone.`);
103
- else if (content.kind === 'empty') add(path, kid, `${where(path)} holds text, and the allow-list keeps it empty.`);
104
- else if (content.kind === 'list-item' && phase === 'block') add(path, kid, `Text follows a block in ${where(path)}, which holds its text before its blocks.`);
105
- else if (content.kind === 'list-item') phase = 'inline';
106
- continue;
107
- }
108
- if (kid.nodeName === '#comment') {
109
- add(path, kid, `A comment sits in ${where(path)}, and the editor keeps none. A page's reasons belong in its notes.md.`);
110
- continue;
111
- }
112
- if (!isElement(kid)) continue;
113
- index += 1;
114
- const at = [...path, `${kid.tagName}:nth-child(${index})`];
115
- const child = content.kind === 'text' || content.kind === 'empty' ? null : resolve(kid, content);
116
- if (child === null) {
117
- const inside = path.length ? ` inside ${where(path)}` : '';
118
- add(at, kid, `\`<${kid.tagName}>\`${attrOf(kid, 'slot') ? ` in the slot \`${attrOf(kid, 'slot')}\`` : ''} is off the allow-list${inside}.`);
119
- continue;
120
- }
121
- const node = NODES[child];
122
- if (node.mark && marks.includes(child)) {
123
- add(at, kid, `\`<${node.tag}>\` nests inside another \`<${node.tag}>\`.`);
124
- continue;
125
- }
126
- if (content.kind === 'list-item') {
127
- const inline = node.group === 'inline';
128
- if (inline && phase === 'block') add(at, kid, `\`<${kid.tagName}>\` follows a block in ${where(path)}, which holds its text before its blocks.`);
129
- if (!inline) phase = 'block';
130
- else if (phase === 'start') phase = 'inline';
131
- }
132
- resolved.push({ el: kid, name: child, at });
133
- attributes(kid, child, at, add, options);
134
- visit(kid, child, at, node.mark ? [...marks, child] : marks);
135
- }
136
- if (content.kind === 'parts') sequence(content.parts, resolved, parent, path, add, where);
137
- };
138
- visit(parsePage(html), null, [], []);
139
- return findings;
140
- }
141
-
142
- function attributes(el, name, at, add, options) {
143
- const node = NODES[name];
144
- const listed = new Map((node.attrs ?? []).map((a) => [a.name, a]));
145
- const tag = `\`<${el.tagName}>\``;
146
- for (const { name: attr, value } of el.attrs ?? []) {
147
- if (attr === 'slot') continue;
148
- if (attr === 'class') {
149
- if (!node.match && !node.classes) add(at, el, `${tag} carries a class, and the allow-list holds none for it.`);
150
- continue;
151
- }
152
- const spec = listed.get(attr);
153
- if (!spec) add(at, el, `${tag} carries \`${attr}\`, an attribute the allow-list doesn't hold for it.`);
154
- else if (!allowed(spec.kind, value, options)) add(at, el, spec.kind === 'boolean' ? `${tag}'s \`${attr}\` takes no value.` : `${tag}'s \`${attr}\` takes a value the allow-list doesn't hold.`);
155
- }
156
- for (const spec of node.attrs ?? []) {
157
- if (spec.required && attrOf(el, spec.name) === undefined) add(at, el, `${tag} lacks \`${spec.name}\`, which the allow-list requires.`);
158
- }
159
- if (!node.match && !node.classes) return;
160
- const groups = node.classes ?? [];
161
- const seen = new Map();
162
- for (const c of classesOf(el)) {
163
- if (c === node.match) continue;
164
- const group = groups.findIndex((g) => g.includes(c));
165
- if (group === -1) {
166
- add(at, el, `${tag} carries the class \`.${c}\`, which the allow-list doesn't hold for it.`);
167
- } else if (seen.has(group)) {
168
- add(at, el, `${tag} carries \`.${seen.get(group)}\` and \`.${c}\`, two classes of one group, which takes one at most.`);
169
- } else {
170
- seen.set(group, c);
171
- }
172
- }
173
- }
174
-
175
- function sequence(parts, resolved, parent, path, add, where) {
176
- let i = 0;
177
- for (const p of parts) {
178
- const names = admits(p);
179
- let count = 0;
180
- while (i < resolved.length && (p.max === null || count < p.max) && names.includes(resolved[i].name)) {
181
- i += 1;
182
- count += 1;
183
- }
184
- if (count < p.min) {
185
- const what = p.nodes ? p.nodes.map((n) => `\`${label(n)}\``).join(' or ') : 'a block';
186
- add(path, parent, `${where(path)} lacks ${what}, which the allow-list requires${i < resolved.length ? ` before \`<${resolved[i].el.tagName}>\`` : ''}.`);
187
- }
188
- }
189
- for (const { el, at } of resolved.slice(i)) {
190
- add(at, el, `\`<${el.tagName}>\` is out of place in ${where(path)}: the allow-list takes its parts in a fixed order and count.`);
191
- }
192
- }
193
-
194
- // Sanitizer
195
-
196
- function keepAttributes(el, name, options) {
197
- const node = NODES[name];
198
- const listed = new Map((node.attrs ?? []).map((a) => [a.name, a]));
199
- const kept = [];
200
- for (const a of el.attrs ?? []) {
201
- if (a.name === 'slot') {
202
- if (node.slot) kept.push(a);
203
- } else if (a.name === 'class') {
204
- const groups = node.classes ?? [];
205
- const seen = new Set();
206
- const classes = classesOf(el).filter((c) => {
207
- if (c === node.match) return true;
208
- const group = groups.findIndex((g) => g.includes(c));
209
- if (group === -1 || seen.has(group)) return false;
210
- seen.add(group);
211
- return true;
212
- });
213
- if (classes.length) kept.push({ name: 'class', value: classes.join(' ') });
214
- } else if (listed.has(a.name) && allowed(listed.get(a.name).kind, a.value, options)) {
215
- kept.push(a);
216
- }
217
- }
218
- el.attrs = kept;
219
- }
220
-
221
- // An unresolved element drops with everything inside it. Part order, count, and required attributes go unenforced,
222
- // since none lets a page run anything; the validator holds them.
223
- export function sanitizePage(html, options = {}) {
224
- const visit = (parent, name, marks) => {
225
- const content = contentOf(name);
226
- const kids = parent.childNodes ?? [];
227
- for (let i = 0; i < kids.length; ) {
228
- const kid = kids[i];
229
- const drop = () => kids.splice(i, 1);
230
- if (isText(kid)) {
231
- if (content.kind === 'empty') drop();
232
- else i += 1;
233
- continue;
234
- }
235
- if (!isElement(kid)) {
236
- drop();
237
- continue;
238
- }
239
- const child = content.kind === 'text' || content.kind === 'empty' ? null : resolve(kid, content);
240
- if (child === null) {
241
- drop();
242
- continue;
243
- }
244
- const node = NODES[child];
245
- if (node.mark && marks.includes(child)) {
246
- const inner = kid.childNodes ?? [];
247
- for (const n of inner) n.parentNode = parent;
248
- kids.splice(i, 1, ...inner);
249
- continue;
250
- }
251
- keepAttributes(kid, child, options);
252
- visit(kid, child, node.mark ? [...marks, child] : marks);
253
- i += 1;
254
- }
255
- };
256
- const tree = parseFragment(html);
257
- visit(tree, null, []);
258
- return formatPage(serialize(tree));
259
- }
260
-
261
- // Canonical formatter. It keeps every byte of content even on a page checkPage rejects.
262
-
263
- const VOID = new Set(['area', 'br', 'col', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'source', 'track', 'wbr']);
264
- const INLINE_TAGS = new Set(['a', 'abbr', 'b', 'br', 'code', 'em', 'i', 'img', 'small', 'span', 'strong', 'sub', 'sup', 'ca-icon']);
265
-
266
- const escText = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/ /g, '&nbsp;');
267
- const escAttr = (s) => s.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/ /g, '&nbsp;');
268
-
269
- function openTag(el, name) {
270
- const node = name === null ? null : NODES[name];
271
- const attrs = [...(el.attrs ?? [])];
272
- const out = [];
273
- const take = (attrName) => {
274
- const at = attrs.findIndex((a) => a.name === attrName);
275
- return at === -1 ? null : attrs.splice(at, 1)[0];
276
- };
277
- const write = (a, bare) => out.push(bare && a.value === '' ? ` ${a.name}` : ` ${a.name}="${escAttr(a.value)}"`);
278
- const cls = take('class');
279
- if (cls) {
280
- const groups = node?.classes ?? [];
281
- const order = (c) => {
282
- if (c === node?.match) return -1;
283
- const g = groups.findIndex((x) => x.includes(c));
284
- return g === -1 ? groups.length : g;
285
- };
286
- const sorted = cls.value.split(/\s+/).filter(Boolean).map((c, i) => ({ c, i })).sort((a, b) => order(a.c) - order(b.c) || a.i - b.i).map((x) => x.c);
287
- out.push(` class="${escAttr(sorted.join(' '))}"`);
288
- }
289
- const slot = take('slot');
290
- if (slot) write(slot, false);
291
- for (const spec of node?.attrs ?? []) {
292
- const a = take(spec.name);
293
- if (a) write(a, spec.kind === 'boolean');
294
- }
295
- for (const a of attrs) write(a, true);
296
- return `<${el.tagName}${out.join('')}>`;
297
- }
298
-
299
- const closeTag = (el) => (VOID.has(el.tagName) ? '' : `</${el.tagName}>`);
300
-
301
- function isBlock(el, name) {
302
- const kids = el.childNodes ?? [];
303
- const text = kids.some((k) => isText(k) && !isBlank(k));
304
- if (name !== null) {
305
- const content = contentOf(name);
306
- if (content.kind === 'parts') return !text && kids.some(isElement);
307
- if (content.kind === 'list-item') return !text && kids.some(isElement) && !kids.some((k) => isElement(k) && NODES[resolve(k, content)]?.group === 'inline');
308
- return false;
309
- }
310
- return !text && kids.some((k) => isElement(k) && !INLINE_TAGS.has(k.tagName));
311
- }
312
-
313
- function inlineOf(node, content) {
314
- if (isText(node)) return escText(node.value.replace(/[ \t\n\r\f]+/g, ' '));
315
- if (node.nodeName === '#comment') return `<!--${node.data}-->`;
316
- if (!isElement(node)) return '';
317
- const name = content ? resolve(node, content) : null;
318
- const inner = name === null ? null : contentOf(name);
319
- const kids = (node.childNodes ?? []).map((k) => inlineOf(k, inner)).join('');
320
- return `${openTag(node, name)}${kids}${closeTag(node)}`;
321
- }
322
-
323
- function print(el, name, indent) {
324
- if (!isBlock(el, name)) {
325
- const content = name === null ? null : contentOf(name);
326
- let inner = (el.childNodes ?? []).map((k) => inlineOf(k, content)).join('');
327
- if (!VOID.has(el.tagName)) inner = inner.replace(/^ +/, '').replace(/ +$/, '');
328
- return `${indent}${openTag(el, name)}${inner}${closeTag(el)}`;
329
- }
330
- const content = name === null ? null : contentOf(name);
331
- const lines = children(el, content, `${indent} `);
332
- return `${indent}${openTag(el, name)}\n${lines.join('\n')}\n${indent}</${el.tagName}>`;
333
- }
334
-
335
- function children(parent, content, indent) {
336
- const lines = [];
337
- for (const kid of parent.childNodes ?? []) {
338
- if (isText(kid)) {
339
- if (!isBlank(kid)) lines.push(`${indent}${escText(kid.value.trim().replace(/[ \t\n\r\f]+/g, ' '))}`);
340
- } else if (kid.nodeName === '#comment') {
341
- lines.push(`${indent}<!--${kid.data}-->`);
342
- } else if (isElement(kid)) {
343
- lines.push(print(kid, content ? resolve(kid, content) : null, indent));
344
- }
345
- }
346
- return lines;
347
- }
348
-
349
- export function formatPage(html) {
350
- const lines = children(parsePage(html), TOP_CONTENT, '');
351
- return lines.length ? `${lines.join('\n')}\n` : '';
352
- }
353
-
354
- // Offsets come from the parse, so text or an attribute value that spells a value's markup is never one.
355
- export function valuesOf(html) {
356
- const out = [];
357
- const visit = (parent) => {
358
- for (const kid of parent.childNodes ?? []) {
359
- if (!isElement(kid)) continue;
360
- if (kid.tagName === SERVER_VALUE) {
361
- const { startOffset, endOffset } = kid.sourceCodeLocation;
362
- out.push({ name: attrOf(kid, 'name') ?? null, from: startOffset, to: endOffset });
363
- continue;
364
- }
365
- visit(kid);
366
- }
367
- };
368
- visit(parsePage(html));
369
- return out;
370
- }
371
-
372
- export const formatElement = (el, name) => print(el, name, '');
package/src/lib/patch.js DELETED
@@ -1,9 +0,0 @@
1
- import { createTwoFilesPatch, FILE_HEADERS_ONLY } from 'diff';
2
-
3
- const decoder = new TextDecoder();
4
-
5
- // A unified diff of one file, null standing for a side that lacks it.
6
- export function patchOf(path, before, after) {
7
- const text = (bytes) => (bytes === null ? '' : decoder.decode(bytes));
8
- return createTwoFilesPatch(before === null ? '/dev/null' : `a/${path}`, after === null ? '/dev/null' : `b/${path}`, text(before), text(after), undefined, undefined, { headerOptions: FILE_HEADERS_ONLY });
9
- }
@@ -1,173 +0,0 @@
1
- // An extension record never claims its element; a name it adds maps to its item beside the owner.
2
- // A name added under a borrowed key maps only inside an element of that key, so two families' remixes map apart.
3
-
4
- import { parseHtml } from './checks.js';
5
- import { interfaceRecords } from './structured.js';
6
- import { addedNames, elementCarries, extensionRecords, keyGraph, withinKey } from './keys.js';
7
- import { isSystemItem } from './system.js';
8
-
9
- const SURFACE = new Set(['element', 'class', 'property']);
10
-
11
- const DECLARED = /(?:^|;)\s*(--ca-[\w-]+)\s*:/g;
12
-
13
- const isElement = (node) => node.type === 'tag' || node.type === 'script' || node.type === 'style';
14
- const isBlank = (node) => node.type === 'text' && node.data.trim() === '';
15
- const isComment = (node) => node.type === 'comment' || node.type === 'directive';
16
-
17
- // standard's and the scope's own, so no third namespace's interface changes what a page depends on.
18
- export function interfacesFor(interfaces, scope) {
19
- return interfaces.filter((i) => isSystemItem(i.name) || (scope !== null && scope !== undefined && i.name.startsWith(`${scope}/`)));
20
- }
21
-
22
- // A name two items hold maps to the first. The map also carries .extensions, [{ item, names, key }].
23
- export function surfaceOwners(interfaces) {
24
- const owners = new Map();
25
- const byName = new Map();
26
- for (const { name, interface: iface, partOf, remixOf } of interfaces) {
27
- if (!byName.has(name)) byName.set(name, { manifest: { partOf, remixOf }, interfaces: [] });
28
- byName.get(name).interfaces.push(iface);
29
- for (const r of interfaceRecords(iface)) {
30
- if (r.kind === 'element' && typeof r.entry.extends === 'string') continue;
31
- if (SURFACE.has(r.kind) && !owners.has(r.id)) owners.set(r.id, name);
32
- }
33
- }
34
- const graph = keyGraph((name) => byName.get(name) ?? null);
35
- owners.extensions = [];
36
- for (const [name, { interfaces: held }] of byName) {
37
- const records = held.flatMap(extensionRecords);
38
- if (records.length === 0) continue;
39
- const names = addedNames([{ elements: Object.fromEntries(records.map(({ tag, record }) => [tag, record])) }], graph.ownerAttribute);
40
- if (names.length) owners.extensions.push({ item: name, names, key: [...graph.inherited(name).values()] });
41
- }
42
- return owners;
43
- }
44
-
45
- export const interfaceEntry = (name, manifest, iface) => ({ name, interface: iface, partOf: manifest?.partOf, remixOf: manifest?.remixOf });
46
-
47
- function extensionItems(el, owners) {
48
- const out = [];
49
- for (const { item, names, key } of owners.extensions ?? []) {
50
- if (names.some((n) => elementCarries(el, n)) && (key.length === 0 || withinKey(el, key))) out.push(item);
51
- }
52
- return out;
53
- }
54
-
55
- function ownSurface(el) {
56
- const out = [];
57
- if (el.name.startsWith('ca-')) out.push(el.name);
58
- for (const c of (el.attribs?.class ?? '').split(/\s+/)) if (c.startsWith('ca-')) out.push(`.${c}`);
59
- for (const m of (el.attribs?.style ?? '').matchAll(DECLARED)) out.push(m[1]);
60
- return out;
61
- }
62
-
63
- function treeSurface(node, owners, out = [], extended = []) {
64
- if (isElement(node)) {
65
- out.push(...ownSurface(node));
66
- extended.push(...extensionItems(node, owners));
67
- }
68
- for (const child of node.children ?? []) treeSurface(child, owners, out, extended);
69
- return { names: out, extended };
70
- }
71
-
72
- function mapped({ names, extended = [] }, owners, foundation) {
73
- const surface = [...new Set(names)];
74
- const items = new Set();
75
- const unmapped = [];
76
- for (const id of surface) {
77
- const owner = owners.get(id);
78
- if (owner === undefined) unmapped.push(id);
79
- else if (!foundation.has(owner)) items.add(owner);
80
- }
81
- for (const item of extended) if (!foundation.has(item)) items.add(item);
82
- return { surface, items: [...items], unmapped };
83
- }
84
-
85
- function topLevel(tree) {
86
- const html = tree.children.find((n) => isElement(n) && n.name === 'html');
87
- const body = html?.children.find((n) => isElement(n) && n.name === 'body');
88
- return body ? body.children : tree.children;
89
- }
90
-
91
- const layoutsUnder = (nodes) => nodes.flatMap((n) => (isElement(n) ? [...(n.name === 'ca-layout' ? [n] : []), ...layoutsUnder(n.children ?? [])] : []));
92
-
93
- // frame is the surface in no region: <ca-layout>, <main>, and an empty element beside the layout.
94
- // A page with problems still answers the regions found.
95
- export function deriveRegions(html, { owners, foundation = [] }) {
96
- const tree = typeof html === 'string' ? parseHtml(html) : html;
97
- const skip = new Set(foundation);
98
- const problems = [];
99
- const regions = [];
100
- const frame = [];
101
- const frameExtended = [];
102
- const framed = (node) => {
103
- frame.push(...ownSurface(node));
104
- frameExtended.push(...extensionItems(node, owners));
105
- };
106
-
107
- const top = topLevel(tree);
108
- const layouts = top.filter((n) => isElement(n) && n.name === 'ca-layout');
109
- if (layouts.length !== 1) {
110
- const nested = layoutsUnder(top).length - layouts.length;
111
- const where = nested > 0 ? ` It holds ${nested} below the top level, where no region is found.` : '';
112
- problems.push(`The page holds ${layouts.length} \`<ca-layout>\` at its top level, where the rule takes exactly one.${where}`);
113
- }
114
- const layout = layouts[0] ?? null;
115
-
116
- for (const node of top) {
117
- if (layouts.includes(node) || isBlank(node) || isComment(node)) continue;
118
- if (isElement(node) && (node.children ?? []).every((c) => isBlank(c) || isComment(c))) {
119
- framed(node);
120
- continue;
121
- }
122
- problems.push(isElement(node) ? `\`<${node.name}>\` sits outside \`<ca-layout>\`, in no region.` : 'Text sits outside `<ca-layout>`, in no region.');
123
- }
124
-
125
- if (layout) {
126
- framed(layout);
127
- const counts = { header: 0, main: 0, footer: 0 };
128
- for (const node of layout.children ?? []) {
129
- if (isBlank(node) || isComment(node)) continue;
130
- if (!isElement(node)) {
131
- problems.push('Text sits directly in `<ca-layout>`, in no region.');
132
- continue;
133
- }
134
- if (Object.hasOwn(counts, node.name)) counts[node.name] += 1;
135
- if (node.name === 'header' || node.name === 'footer') {
136
- regions.push({ kind: node.name, el: node });
137
- } else if (node.name === 'main') {
138
- framed(node);
139
- for (const child of node.children ?? []) {
140
- if (isBlank(child) || isComment(child)) continue;
141
- if (isElement(child)) regions.push({ kind: 'main', el: child });
142
- else problems.push('Text sits directly in `<main>`, in no region.');
143
- }
144
- } else if (node.attribs?.slot !== undefined) {
145
- regions.push({ kind: 'slot', el: node });
146
- } else {
147
- problems.push(`\`<${node.name}>\` is a child of \`<ca-layout>\` with no slot, and not its \`<header>\`, \`<main>\`, or \`<footer>\`.`);
148
- }
149
- }
150
- if (counts.main !== 1) problems.push(`\`<ca-layout>\` holds ${counts.main} \`<main>\`, where the rule takes exactly one.`);
151
- for (const tag of ['header', 'footer']) if (counts[tag] > 1) problems.push(`\`<ca-layout>\` holds ${counts[tag]} \`<${tag}>\`, where the rule takes one at most.`);
152
- }
153
-
154
- const out = regions.map(({ kind, el }) => ({ kind, tag: el.name, slot: el.attribs?.slot ?? null, ...mapped(treeSurface(el, owners), owners, skip) }));
155
- const around = mapped({ names: frame, extended: frameExtended }, owners, skip);
156
- const all = [...out, around];
157
- return {
158
- regions: out,
159
- frame: around,
160
- items: [...new Set(all.flatMap((r) => r.items))].sort(),
161
- unmapped: [...new Set(all.flatMap((r) => r.unmapped))].sort(),
162
- problems,
163
- };
164
- }
165
-
166
- export function pageSurface(html, { owners, foundation = [] }) {
167
- const tree = typeof html === 'string' ? parseHtml(html) : html;
168
- const names = [];
169
- const extended = [];
170
- for (const node of tree.children ?? []) treeSurface(node, owners, names, extended);
171
- const { surface, items, unmapped } = mapped({ names, extended }, owners, new Set(foundation));
172
- return { surface, items: [...items].sort(), unmapped: [...unmapped].sort() };
173
- }