@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,65 +0,0 @@
1
- import { closeSync, openSync, readSync } from 'node:fs';
2
- import { extname, join } from 'node:path';
3
- import { HEAD, READERS } from '../lib/image.js';
4
-
5
- export const check = 'media';
6
-
7
- // The registry serves a rendition under its extension's type, so each is a format a browser never runs.
8
- export const IMAGE_EXTENSIONS = ['.png', '.jpg', '.jpeg', '.webp', '.gif', '.avif', '.svg'];
9
-
10
- function withRead(path, fn) {
11
- const fd = openSync(path, 'r');
12
- try {
13
- return fn((at, length) => {
14
- const bytes = new Uint8Array(length);
15
- return bytes.subarray(0, readSync(fd, bytes, 0, length, at));
16
- });
17
- } finally {
18
- closeSync(fd);
19
- }
20
- }
21
-
22
- const isLfsPointer = (bytes) => new TextDecoder().decode(bytes).startsWith('version https://git-lfs.github.com/spec/');
23
-
24
- export async function run(item, ctx, { reject, warn }) {
25
- const m = item.manifest;
26
- if (m.kind !== 'media' || m.media === null || typeof m.media !== 'object') return;
27
-
28
- for (const r of Array.isArray(m.media.renditions) ? m.media.renditions : []) {
29
- if (typeof r?.file !== 'string') continue;
30
- const ext = extname(r.file).toLowerCase();
31
- if (!IMAGE_EXTENSIONS.includes(ext)) {
32
- reject('not-image', `\`${r.file}\` is a \`${ext || '(none)'}\` file, and a rendition is an image: ${IMAGE_EXTENSIONS.map((e) => `\`${e}\``).join(', ')}.`, { file: r.file });
33
- continue;
34
- }
35
- if (!item.present.has(r.file) || ext === '.svg') continue;
36
- const reader = READERS.get(ext);
37
- if (!reader) {
38
- warn('unchecked', `\`${r.file}\` is a \`${ext}\` file. The validator reads the size of PNG, WebP, and JPEG alone, so this rendition's width and height are unchecked.`, { file: r.file });
39
- continue;
40
- }
41
- const { size, pointer, orientation } = withRead(join(item.dir, r.file), (read) => {
42
- const found = reader.size(read);
43
- return {
44
- size: found,
45
- pointer: !found && isLfsPointer(read(0, HEAD)),
46
- orientation: found && reader.orientation ? reader.orientation(read) : null,
47
- };
48
- });
49
- if (!size) {
50
- const why = pointer ? ' The file is a Git LFS pointer, not the image.' : '';
51
- reject('header', `\`${r.file}\` has no ${reader.format} header to read its width and height from.${why}`, { file: r.file });
52
- } else if (size.width !== r.width || size.height !== r.height) {
53
- reject('dimensions', `\`${r.file}\` is ${size.width} by ${size.height}, and its rendition says ${r.width} by ${r.height}.`, { file: r.file });
54
- }
55
- if (size && orientation >= 5) {
56
- warn('orientation', `\`${r.file}\` carries EXIF orientation ${orientation}, so a browser shows it rotated, at ${size.height} by ${size.width}. Rotate the pixels upright and reset the orientation to 1 before packaging.`, { file: r.file });
57
- }
58
- }
59
-
60
- const origin = m.media.origin ?? {};
61
- const named = ['ai-generator', 'ai-prompt'].filter((f) => origin[f] !== undefined);
62
- if (named.length > 0 && origin['ai-generated'] !== true) {
63
- warn('ai-generated', `The origin names ${named.map((f) => `\`${f}\``).join(' and ')}, and \`ai-generated\` isn't \`true\`.`, { file: 'item.json' });
64
- }
65
- }
@@ -1,74 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { checkPage, formatPage } from '../lib/page.js';
4
- import { pageSurface } from '../lib/regions.js';
5
- import { linkedMediaItems } from '../lib/fixtures.js';
6
- import { interfaceOwners } from './context.js';
7
-
8
- export const check = 'page';
9
-
10
- const scopeOf = (name) => (typeof name === 'string' && name.includes('/') ? name.slice(0, name.indexOf('/')) : null);
11
-
12
- const SHOWN = 20;
13
-
14
- function firstDiff(a, b) {
15
- const x = a.split('\n');
16
- const y = b.split('\n');
17
- for (let i = 0; i < Math.max(x.length, y.length); i++) if (x[i] !== y[i]) return i + 1;
18
- return null;
19
- }
20
-
21
- export async function run(item, ctx, { reject, warn }) {
22
- const m = item.manifest;
23
- if (m.kind !== 'page') return;
24
- const base = typeof m.name === 'string' ? m.name.slice(m.name.indexOf('/') + 1) : null;
25
-
26
- // Unique within the namespace alone, since a site renders one namespace's pages.
27
- const scope = scopeOf(m.name);
28
- for (const field of ['slug', 'region']) {
29
- if (typeof m[field] !== 'string') continue;
30
- for (const [name, other] of ctx.catalog) {
31
- if (name === m.name || scopeOf(name) !== scope || other.manifest?.kind !== 'page' || other.manifest[field] !== m[field]) continue;
32
- const what = field === 'slug' ? (m.slug === '' ? 'the empty slug, the home page' : `the slug \`${m.slug}\``) : `the region \`${m.region}\``;
33
- reject(`${field}-taken`, `\`${name}\` also takes ${what}. A page's ${field} is unique among its namespace's pages.`, { file: 'item.json' });
34
- }
35
- }
36
-
37
- if (base !== null && m.doc !== `${base}.html`) {
38
- reject('doc', `A page's doc is \`${base}.html\`, its canonical HTML, and the manifest names \`${m.doc}\`.`, { file: 'item.json' });
39
- }
40
- if (typeof m.doc !== 'string' || !m.doc.endsWith('.html') || !item.present.has(m.doc)) return;
41
- const html = readFileSync(join(item.dir, m.doc), 'utf8');
42
-
43
- const found = checkPage(html);
44
- for (const f of found.slice(0, SHOWN)) {
45
- reject('allow-list', `${f.path ? `At \`${f.path}\`: ` : ''}${f.message}`, { file: m.doc, line: f.line });
46
- }
47
- if (found.length > SHOWN) {
48
- reject('allow-list', `${found.length - SHOWN} more elements, attributes, or classes are off the allow-list.`, { file: m.doc });
49
- }
50
-
51
- const formatted = formatPage(html);
52
- if (formatted !== html) {
53
- const line = firstDiff(html, formatted);
54
- reject('format', `The doc differs from its canonical format from line ${line}. A page's doc keeps the format the editor writes, so each edit diffs minimally.`, { file: m.doc, line });
55
- }
56
-
57
- const { items, unmapped } = pageSurface(html, { owners: interfaceOwners(ctx, scope), foundation: ctx.foundation });
58
- const media = linkedMediaItems(html);
59
- const declared = new Set(Object.keys(m.dependencies ?? {}));
60
- for (const name of items) {
61
- if (!declared.has(name)) reject('undeclared-dependency', `The page uses \`${name}\`'s surface, and \`dependencies\` leaves it out.`, { file: m.doc });
62
- }
63
- for (const name of media) {
64
- if (declared.has(name) || items.includes(name)) continue;
65
- if (ctx.purged?.has(name)) warn('purged-media', `The page links a file of \`${name}\`, which the registry purged, so the image shows nothing. Remove the image, or place another.`, { file: m.doc });
66
- else reject('undeclared-dependency', `The page links a file of \`${name}\`, and \`dependencies\` leaves it out.`, { file: m.doc });
67
- }
68
- for (const name of declared) {
69
- if (!items.includes(name) && !media.includes(name)) reject('extra-dependency', `\`dependencies\` names \`${name}\`, and the page uses none of its surface and links none of its files. A page's dependencies are the items its surface maps to and the media leaves it links.`, { file: 'item.json' });
70
- }
71
- if (unmapped.length > 0) {
72
- warn('unmapped-surface', `The page uses surface no interface holds, so no dependency covers it: ${unmapped.map((n) => `\`${n}\``).join(', ')}.`, { file: m.doc });
73
- }
74
- }
@@ -1,58 +0,0 @@
1
- import { walkHtml, components } from './facts.js';
2
- import { SERVER_VALUE } from '../lib/page-schema.js';
3
-
4
- export const check = 'prefixes';
5
-
6
- export const PROPERTY_PREFIXES = ['--ca-', '--_ca-'];
7
-
8
- export const systemProperty = (name) => PROPERTY_PREFIXES.some((p) => name.startsWith(p));
9
-
10
- const wanted = { 'custom-property': '`--ca-` or `--_ca-`', class: '`.ca-`', 'custom-element': '`ca-`' };
11
-
12
- export async function run(item, ctx, { reject }) {
13
- if (!item.manifest) return;
14
- const facts = await ctx.facts(item);
15
- const once = new Set();
16
- const flag = (kind, name, file, line) => {
17
- if (once.has(`${file}\0${kind}\0${name}`)) return;
18
- once.add(`${file}\0${kind}\0${name}`);
19
- reject(kind, `The ${kind.replace('-', ' ')} \`${name}\` lacks the ${wanted[kind]} prefix.`, { file, line });
20
- };
21
-
22
- for (const [path, css] of facts.css) {
23
- for (const rule of css.rules) {
24
- for (const s of rule.selectors) {
25
- for (const c of components(s)) {
26
- if (c.type === 'class' && !c.name.startsWith('ca-')) flag('class', `.${c.name}`, path, rule.line);
27
- if (c.type === 'type' && c.name.includes('-') && !c.name.startsWith('ca-')) flag('custom-element', c.name, path, rule.line);
28
- }
29
- }
30
- }
31
- for (const d of css.customDecls) if (!systemProperty(d.name)) flag('custom-property', d.name, path, d.line);
32
- for (const r of css.varRefs) if (!systemProperty(r.name)) flag('custom-property', r.name, path, r.line);
33
- }
34
-
35
- const page = item.manifest.kind === 'page';
36
- for (const [path, html] of facts.html) {
37
- for (const { node } of walkHtml(html.tree)) {
38
- if (page && path === item.manifest.doc && node.tagName === SERVER_VALUE) continue;
39
- if (node.tagName?.includes('-') && !node.tagName.startsWith('ca-')) {
40
- flag('custom-element', node.tagName, path, node.sourceCodeLocation?.startLine);
41
- }
42
- }
43
- }
44
-
45
- for (const [path, js] of facts.js) {
46
- for (const m of js.code.matchAll(/customElements\.define\(\s*(["'`])([^"'`]+)\1/g)) {
47
- if (!m[2].startsWith('ca-')) flag('custom-element', m[2], path, null);
48
- }
49
- for (const m of js.code.matchAll(/\.setProperty\(\s*(["'`])(--[^"'`]+)\1/g)) {
50
- if (!systemProperty(m[2])) flag('custom-property', m[2], path, null);
51
- }
52
- for (const m of js.code.matchAll(/classList\.(?:add|remove|toggle|replace)\(([^)]*)\)/g)) {
53
- for (const lit of m[1].matchAll(/(["'`])([^"'`]+)\1/g)) {
54
- if (!lit[2].startsWith('ca-')) flag('class', `.${lit[2]}`, path, null);
55
- }
56
- }
57
- }
58
- }
@@ -1,310 +0,0 @@
1
- import { readFileSync } from 'node:fs';
2
- import { join } from 'node:path';
3
- import { isDeepStrictEqual } from 'node:util';
4
- import { STRUCTURED } from '../lib/schema.js';
5
- import { structuredFiles } from '../lib/structured.js';
6
- import { addedNames, extensionRecords, keyGraph, keysMeet, nameId, ownedTags, scopedSubjectKeys, selectorNames } from '../lib/keys.js';
7
- import { runRules } from '../lib/checks.js';
8
- import { SYSTEM_NAMESPACE } from '../lib/system.js';
9
- import { elideValues } from './findings.js';
10
- import { styleRules } from './facts.js';
11
- import { declaredFiles } from './item.js';
12
- import { stateItem } from './context.js';
13
- import { contractsOf, failure, runnable } from './structured.js';
14
-
15
- export const check = 'relations';
16
-
17
- const scopeOf = (name) => (typeof name === 'string' && name.includes('/') ? name.slice(0, name.indexOf('/')) : null);
18
-
19
- const interfaceCache = new WeakMap();
20
- export function interfacesOf(item) {
21
- if (!item?.manifest) return [];
22
- if (!interfaceCache.has(item)) {
23
- const out = [];
24
- const path = structuredFiles(item.manifest).interface;
25
- if (path && item.present.has(path)) {
26
- try {
27
- const data = JSON.parse(readFileSync(join(item.dir, path), 'utf8'));
28
- if (STRUCTURED.interface(data)) out.push(data);
29
- } catch {
30
- // The files check reports it.
31
- }
32
- }
33
- interfaceCache.set(item, out);
34
- }
35
- return interfaceCache.get(item);
36
- }
37
-
38
- const rulesCache = new WeakMap();
39
- export function rulesOf(css) {
40
- if (!rulesCache.has(css)) rulesCache.set(css, styleRules(css.code));
41
- return rulesCache.get(css);
42
- }
43
-
44
- // item, when given, stands in for the state's item of its name.
45
- export function relations(ctx, item = null) {
46
- const stand = item?.manifest?.name ?? null;
47
- const lookup = (name) => (name === stand ? item : stateItem(ctx, name));
48
- const graph = keyGraph((name) => {
49
- const found = lookup(name);
50
- return found?.manifest ? { manifest: found.manifest, interfaces: interfacesOf(found) } : null;
51
- });
52
- return { lookup, ...graph };
53
- }
54
-
55
- function unquote(literal) {
56
- const body = literal.slice(1, -1);
57
- if (literal[0] === '"') return JSON.parse(literal);
58
- if (literal[0] === "'") return JSON.parse(`"${body.replace(/\\'/g, "'").replace(/"/g, '\\"')}"`);
59
- return body.replace(/\\`/g, '`');
60
- }
61
-
62
- const LITERAL = String.raw`("(?:[^"\\\n]|\\.)*"|'(?:[^'\\\n]|\\.)*'|` + '`(?:[^`\\\\$]|\\\\.)*`)';
63
- // A selector-taking call: its receiver when a chain of names, its first argument when a string literal.
64
- const QUERY = new RegExp(String.raw`(?:([\w$]+(?:\??\.[\w$]+)*)\s*)?\??\.(querySelectorAll|querySelector|closest|matches)\(\s*` + LITERAL + String.raw`\s*[,)]`, 'g');
65
- const DEFINE = new RegExp(String.raw`customElements\.define\(\s*` + LITERAL, 'g');
66
-
67
- function parseSelector(text) {
68
- const rules = styleRules(`${text} {}`);
69
- return rules.length === 1 && rules[0].selectors.length > 0 ? rules[0].selectors : null;
70
- }
71
-
72
- export async function run(item, ctx, { reject, warn }) {
73
- const m = item.manifest;
74
- const name = typeof m.name === 'string' ? m.name : null;
75
- if (!name) return;
76
- const rel = relations(ctx, item);
77
- const interfaces = interfacesOf(item);
78
- const facts = await ctx.facts(item);
79
- const contracts = contractsOf(item);
80
-
81
- // Extension records
82
- const interfaceFile = structuredFiles(m).interface ?? 'item.json';
83
- for (const iface of interfaces) {
84
- for (const { tag, record } of extensionRecords(iface)) {
85
- if (record.extends === name) {
86
- reject('extends-self', `The extension record of \`<${tag}>\` names the item itself. An extension record names the item that owns the element.`, { file: interfaceFile });
87
- continue;
88
- }
89
- const owner = rel.lookup(record.extends);
90
- if (!owner && item.authored == null && typeof m.partOf === 'string' && (rel.partChain(name).includes(record.extends) || rel.unresolved(name).length > 0)) {
91
- warn('extends-pending', `The extension record of \`<${tag}>\` names \`${record.extends}\`, which the registry doesn't hold yet, while the part's \`partOf\` chain is unpublished too, so the record goes unchecked. A first publish sends a part ahead of the parent that lists it.`, { file: interfaceFile });
92
- continue;
93
- }
94
- if (!owner || !interfacesOf(owner).some((o) => ownedTags(o).includes(tag))) {
95
- const why = owner ? `whose interface doesn't own \`<${tag}>\`` : 'which is no item in the state';
96
- reject('extends-owner', `The extension record of \`<${tag}>\` names \`${record.extends}\`, ${why}.`, { file: interfaceFile });
97
- continue;
98
- }
99
- for (const a of record.attributes ?? []) {
100
- const declared = rel.ownerAttribute(record.extends, tag, a.name);
101
- if (declared && !isDeepStrictEqual(declared.absent, a.absent)) {
102
- reject('extends-absent', `The extension record of \`<${tag}>\` gives \`${a.name}\` an \`absent\` other than its owner's. An attribute the owner declares keeps the owner's \`absent\`.`, { file: interfaceFile });
103
- }
104
- }
105
- }
106
- }
107
-
108
- const sheets = typeof m.partOf === 'string' || typeof m.remixOf === 'string' ? [...facts.css].map(([path, css]) => ({ path, rules: rulesOf(css) })) : [];
109
-
110
- if (typeof m.partOf === 'string') await checkPart(item, ctx, rel, sheets, reject, warn);
111
- if (typeof m.remixOf === 'string') checkRemix(item, rel, sheets, facts, interfaces, reject, warn);
112
-
113
- // Waivers
114
- const contractFile = structuredFiles(m).contract ?? 'item.json';
115
- const chain = rel.remixChain(name);
116
- const seen = new Set();
117
- for (const waiver of contracts.flatMap((c) => c.waives ?? [])) {
118
- if (scopeOf(name) === SYSTEM_NAMESPACE) {
119
- reject('waiver-standard', `The contract waives \`${waiver.rule}\`, and a \`${SYSTEM_NAMESPACE}\` item carries no waivers. A \`${SYSTEM_NAMESPACE}\` base's rules hold for every \`${SYSTEM_NAMESPACE}\` remix, or scope their checks to the base alone.`, { file: contractFile });
120
- continue;
121
- }
122
- if (seen.has(waiver.rule)) {
123
- reject('waiver-duplicate', `The contract waives \`${waiver.rule}\` twice.`, { file: contractFile });
124
- continue;
125
- }
126
- seen.add(waiver.rule);
127
- const at = waiver.rule.lastIndexOf('/');
128
- const owner = waiver.rule.slice(0, at);
129
- const id = waiver.rule.slice(at + 1);
130
- if (!chain.includes(owner)) {
131
- reject('waiver-chain', `The waiver of \`${waiver.rule}\` names \`${owner}\`, which is no item up the remix's \`remixOf\` chain. A remix waives its bases' rules alone.`, { file: contractFile });
132
- continue;
133
- }
134
- const target = rel.lookup(owner);
135
- if (target && !contractsOf(target).some((c) => c.rules.some((r) => r.id === id))) {
136
- reject('waiver-rule', `The waiver of \`${waiver.rule}\` names a rule \`${owner}\`'s contract doesn't hold.`, { file: contractFile });
137
- }
138
- }
139
- }
140
-
141
- function admittedTags(interfaces) {
142
- const out = new Set();
143
- for (const iface of interfaces) {
144
- for (const tag of ownedTags(iface)) {
145
- for (const child of iface.elements[tag].children ?? []) {
146
- for (const element of Array.isArray(child.element) ? child.element : []) {
147
- const match = /^<(ca-[a-z0-9-]+)[\s>]/.exec(element);
148
- if (match) out.add(match[1]);
149
- }
150
- }
151
- }
152
- }
153
- return out;
154
- }
155
-
156
- async function checkPart(item, ctx, rel, sheets, reject, warn) {
157
- const m = item.manifest;
158
- const at = { file: 'item.json' };
159
- if (m.partOf === m.name) {
160
- reject('part-self', 'The item names itself in `partOf`. A part names its parent.', at);
161
- return;
162
- }
163
- if (scopeOf(m.partOf) !== scopeOf(m.name)) {
164
- reject('part-namespace', `\`partOf\` names \`${m.partOf}\`, outside the \`${scopeOf(m.name)}\` namespace. A part shares its parent's namespace, and outside it, adding to a component is a remix.`, at);
165
- }
166
- const parent = rel.lookup(m.partOf);
167
- if (!parent?.manifest && item.authored == null) {
168
- warn('part-pending', `\`partOf\` names \`${m.partOf}\`, which the registry doesn't hold yet, so the part's scope and its properties go unchecked against it. A first publish sends a part ahead of the parent that lists it, and the parent's publish holds the two together.`, at);
169
- return;
170
- }
171
- if (!parent?.manifest) {
172
- reject('part-parent', `\`partOf\` names \`${m.partOf}\`, which is no item in the state.`, at);
173
- return;
174
- }
175
- if (parent.manifest.kind !== 'component') {
176
- reject('part-parent', `\`partOf\` names \`${m.partOf}\`, which is kind \`${parent.manifest.kind}\`. A part's parent is a component.`, at);
177
- }
178
- if (!Object.hasOwn(parent.manifest.dependencies ?? {}, m.name)) {
179
- if (item.authored != null) {
180
- reject('part-dependency', `The parent \`${m.partOf}\` leaves \`${m.name}\` out of its \`dependencies\`. A parent lists each of its parts, so a request for it brings them.`, at);
181
- } else {
182
- warn('part-pending', `The registry's \`${m.partOf}\` doesn't list \`${m.name}\` in its \`dependencies\` yet, so the part's scope and its properties go unchecked against it. A part that splits out of its parent publishes ahead of the parent version that lists it.`, at);
183
- return;
184
- }
185
- }
186
- const up = rel.partChain(m.name);
187
- if (rel.lookup(up.at(-1))?.manifest?.partOf === m.name) {
188
- reject('part-cycle', '`partOf` leads back to the item itself.', at);
189
- return;
190
- }
191
-
192
- // Scope
193
- const scope = new Map(rel.own(m.partOf).map((n) => [nameId(n), n]));
194
- if (rel.isRemix(m.partOf)) for (const n of rel.key(m.partOf)) scope.set(nameId(n), n);
195
- for (const iface of interfacesOf(item)) {
196
- for (const { tag, record } of extensionRecords(iface)) {
197
- if (!up.includes(record.extends)) continue;
198
- for (const n of addedNames([{ elements: { [tag]: record } }], rel.ownerAttribute)) scope.set(nameId(n), n);
199
- }
200
- }
201
- const admitted = admittedTags(interfacesOf(parent));
202
- for (const tag of interfacesOf(item).flatMap(ownedTags)) {
203
- if (admitted.has(tag)) scope.set(nameId({ kind: 'element', element: tag, name: tag }), { kind: 'element', element: tag, name: tag });
204
- }
205
- const names = [...scope.values()];
206
- if (names.length === 0 && sheets.some((s) => s.rules.length > 0)) {
207
- reject('part-scope', `The parent \`${m.partOf}\` adds no names, so no selector of the part can match only inside it.`, at);
208
- } else {
209
- for (const { path, rules } of sheets) {
210
- for (const rule of rules) {
211
- if (rule.selectors.every((s) => selectorNames(s, names))) continue;
212
- reject('part-scope', `The selector \`${elideValues(rule.prelude)}\` names nothing of the parent \`${m.partOf}\` as its subject or an ancestor, so it matches outside the parent's element. A part's selectors match only inside its parent.`, { file: path, line: rule.line });
213
- }
214
- }
215
- }
216
-
217
- // Properties the parent also sets
218
- const parentSets = new Map();
219
- for (const css of (await ctx.facts(parent)).css.values()) {
220
- for (const rule of rulesOf(css)) {
221
- for (const k of new Set(rule.selectors.flatMap(scopedSubjectKeys))) {
222
- if (!parentSets.has(k)) parentSets.set(k, new Set());
223
- for (const p of rule.properties) parentSets.get(k).add(p);
224
- }
225
- }
226
- }
227
- const reported = new Set();
228
- for (const { path, rules } of sheets) {
229
- for (const rule of rules) {
230
- for (const k of new Set(rule.selectors.flatMap(scopedSubjectKeys))) {
231
- for (const p of rule.properties) {
232
- if (reported.has(`${k}\0${p}`) || ![...parentSets].some(([pk, set]) => set.has(p) && keysMeet(k, pk))) continue;
233
- reported.add(`${k}\0${p}`);
234
- reject('part-overlap', `The part and its parent \`${m.partOf}\` both set \`${p}\` on \`${elideValues(k)}\`, so their load order decides it. A part and its parent never set the same property on the same subject.`, { file: path, line: rule.line });
235
- }
236
- }
237
- }
238
- }
239
- }
240
-
241
- function checkRemix(item, rel, sheets, facts, interfaces, reject, warn) {
242
- const m = item.manifest;
243
- const at = { file: 'item.json' };
244
- if (m.remixOf === m.name) {
245
- reject('remix-self', 'The item names itself in `remixOf`. A remix names its base.', at);
246
- return;
247
- }
248
- if (!Object.hasOwn(m.dependencies ?? {}, m.remixOf)) {
249
- reject('remix-dependency', `\`dependencies\` leaves out the base, \`${m.remixOf}\`. A remix depends on its base, so the base loads first and the remix's CSS wins the cascade.`, at);
250
- }
251
- const base = rel.lookup(m.remixOf);
252
- if (base?.manifest && base.manifest.kind !== 'component') {
253
- reject('remix-base', `\`remixOf\` names \`${m.remixOf}\`, which is kind \`${base.manifest.kind}\`. A remix's base is a component.`, at);
254
- }
255
- const chain = rel.remixChain(m.name);
256
- if (rel.lookup(chain.at(-1))?.manifest?.remixOf === m.name) {
257
- reject('remix-cycle', '`remixOf` leads back to the item itself.', at);
258
- return;
259
- }
260
- if (!structuredFiles(m).interface) {
261
- reject('remix-interface', "The remix has no interface. A remix's interface lists every name it adds, its key, in `<name>.interface.json`, declared with role `interface`.", at);
262
- return;
263
- }
264
-
265
- // A first publish can't read the key it borrows up an unheld partOf chain, so a miss warns.
266
- const key = rel.key(m.name);
267
- const pending = item.authored == null ? rel.partChain(m.name).filter((n) => !rel.lookup(n)) : [];
268
- const miss = pending.length > 0 ? (id, message, at) => warn(`${id}-pending`, `${message} The key it borrows from \`${pending[0]}\` goes unread, since the registry doesn't hold it yet. A first publish sends a part ahead of the parent that lists it.`, at) : reject;
269
- for (const { path, rules } of sheets) {
270
- for (const rule of rules) {
271
- if (rule.selectors.every((s) => selectorNames(s, key))) continue;
272
- miss('remix-key', `The selector \`${elideValues(rule.prelude)}\` names none of the remix's key as its subject or an ancestor. Every selector a remix ships names its key, so loading it changes no page that doesn't use the key.`, { file: path, line: rule.line });
273
- }
274
- }
275
-
276
- // Scripts, as far as their string literals reach
277
- const owned = new Set(interfaces.flatMap(ownedTags));
278
- for (const [path, js] of facts.js) {
279
- let definesOwn = false;
280
- for (const match of js.code.matchAll(DEFINE)) {
281
- const tag = unquote(match[1]);
282
- if (owned.has(tag)) definesOwn = true;
283
- else reject('remix-script', `\`${path}\` defines \`<${tag}>\`, which the remix's interface doesn't own. A remix's script defines its own elements alone.`, { file: path });
284
- }
285
- for (const match of js.code.matchAll(QUERY)) {
286
- const [, receiver, method, literal] = match;
287
- // In a script that defines an owned element, `this` is that element.
288
- if (definesOwn && method.startsWith('querySelector') && /^this\b/.test(receiver ?? '')) continue;
289
- const selectors = parseSelector(unquote(literal));
290
- if (!selectors || selectors.every((s) => selectorNames(s, key))) continue;
291
- miss('remix-script', `\`${path}\` passes \`${elideValues(unquote(literal))}\` to \`${method}\`, which names none of the remix's key. A remix's script queries only inside its key.`, { file: path });
292
- }
293
- }
294
-
295
- // A standard remix's examples against its bases' rules
296
- if (scopeOf(m.name) !== SYSTEM_NAMESPACE) return;
297
- const examples = declaredFiles(m).filter((f) => f.role === 'reference-html' && item.present.has(f.path));
298
- for (const above of chain) {
299
- const target = rel.lookup(above);
300
- if (!target?.manifest) continue;
301
- const rules = runnable(contractsOf(target).flatMap((c) => c.rules));
302
- if (rules.length === 0) continue;
303
- for (const f of examples) {
304
- const html = readFileSync(join(item.dir, f.path), 'utf8');
305
- for (const failed of runRules(rules, html).failed) {
306
- (failed.rule.severity === 'must' ? reject : warn)('rot', `Against its base, ${failure(above, failed).replace(/^The/, 'the')}`, { file: f.path });
307
- }
308
- }
309
- }
310
- }
@@ -1,109 +0,0 @@
1
- // A release validates as its own state, apart from the checkout it was packed from.
2
-
3
- import { cpSync, existsSync, mkdtempSync, readdirSync, readFileSync, rmSync } from 'node:fs';
4
- import { tmpdir } from 'node:os';
5
- import { join, posix } from 'node:path';
6
- import { recorder } from './findings.js';
7
- import { validateRepo } from './index.js';
8
- import { unpack } from './zip.js';
9
- import { validateReleaseManifest } from '../lib/schema.js';
10
- import { sha256 } from '../lib/pack.js';
11
-
12
- export const safeSource = (source) =>
13
- typeof source === 'string' && source === posix.normalize(source) && !posix.isAbsolute(source) && source !== '.' && !source.startsWith('..');
14
-
15
- export async function validateRelease(dir, { label = dir } = {}) {
16
- const findings = [];
17
- const { reject } = recorder(findings, 'release');
18
- const report = (results = [], tag = null) => ({
19
- tag,
20
- dir: label,
21
- rejections: findings.filter((f) => f.severity === 'reject'),
22
- warnings: findings.filter((f) => f.severity === 'warn'),
23
- results,
24
- });
25
-
26
- let release;
27
- try {
28
- release = JSON.parse(readFileSync(join(dir, 'release.json'), 'utf8'));
29
- } catch (err) {
30
- reject('manifest', `release.json is missing or not valid JSON: ${err.message}`, { file: 'release.json' });
31
- return report();
32
- }
33
- if (!validateReleaseManifest(release)) {
34
- for (const e of validateReleaseManifest.errors) {
35
- reject('schema', `${e.instancePath || '(root)'} ${e.message}.`, { file: 'release.json' });
36
- }
37
- return report([], typeof release?.tag === 'string' ? release.tag : null);
38
- }
39
-
40
- const listed = new Set();
41
- const names = new Set();
42
- for (const entry of release.items) {
43
- if (names.has(entry.name)) reject('duplicate', `${entry.name} is listed twice.`, { file: 'release.json' });
44
- names.add(entry.name);
45
- listed.add(entry.file);
46
- }
47
- for (const file of readdirSync(dir)) {
48
- if (file.endsWith('.zip') && !listed.has(file)) reject('unlisted', `\`${file}\` is in the release folder and not in release.json.`, { file });
49
- }
50
- for (const name of [...release.foundation, ...(release.fixtures ? [release.fixtures] : []), ...Object.values(release.presets).flatMap((p) => p.items)]) {
51
- if (!names.has(name)) reject('unknown-item', `system.json names ${name}, which the release doesn't hold.`, { file: 'release.json' });
52
- }
53
-
54
- const root = mkdtempSync(join(tmpdir(), 'ca-release-'));
55
- try {
56
- const sources = new Map();
57
- for (const entry of release.items) {
58
- const path = join(dir, entry.file);
59
- if (!existsSync(path)) {
60
- reject('missing', `\`${entry.file}\` is listed and missing from the release folder.`, { file: entry.file });
61
- continue;
62
- }
63
- if (sha256(readFileSync(path)) !== entry.sha256) {
64
- reject('hash', `\`${entry.file}\` doesn't match the hash release.json lists for it.`, { file: entry.file });
65
- continue;
66
- }
67
- let unpacked;
68
- try {
69
- unpacked = unpack(path);
70
- } catch (err) {
71
- reject('zip', `\`${entry.file}\` doesn't unpack: ${err.message}`, { file: entry.file });
72
- continue;
73
- }
74
- try {
75
- let manifest = null;
76
- try {
77
- manifest = JSON.parse(readFileSync(join(unpacked.dir, 'item.json'), 'utf8'));
78
- } catch {
79
- // Falls through to the listing rejection.
80
- }
81
- if (manifest?.name !== entry.name || manifest?.version !== entry.version) {
82
- const holds = manifest ? `${manifest.name} ${manifest.version}` : 'no readable item.json';
83
- reject('listing', `\`${entry.file}\` holds ${holds}, and release.json lists ${entry.name} ${entry.version}.`, { file: entry.file });
84
- continue;
85
- }
86
- if (!safeSource(manifest.source)) {
87
- reject('source', `${entry.name} has no \`source\` path inside the checkout to unpack to.`, { file: entry.file });
88
- continue;
89
- }
90
- if (sources.has(manifest.source)) {
91
- reject('source', `${entry.name} and ${sources.get(manifest.source)} both unpack to \`${manifest.source}\`.`, { file: entry.file });
92
- continue;
93
- }
94
- sources.set(manifest.source, entry.name);
95
- cpSync(unpacked.dir, join(root, manifest.source), { recursive: true });
96
- } finally {
97
- unpacked.cleanup();
98
- }
99
- }
100
-
101
- return report(await validateRepo(root, { foundation: release.foundation, fixtures: release.fixtures ?? null }), release.tag);
102
- } finally {
103
- rmSync(root, { recursive: true, force: true });
104
- }
105
- }
106
-
107
- export function isRelease(dir) {
108
- return existsSync(join(dir, 'release.json')) && !existsSync(join(dir, 'item.json'));
109
- }