create-kerf-component 5.0.0-beta.11 → 5.0.0-beta.111

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/catalog.js ADDED
@@ -0,0 +1,1219 @@
1
+ #!/usr/bin/env node
2
+
3
+ import {
4
+ existsSync,
5
+ readFileSync,
6
+ realpathSync,
7
+ readdirSync,
8
+ statSync,
9
+ writeFileSync,
10
+ } from 'node:fs';
11
+ import { dirname, join, relative, resolve, sep } from 'node:path';
12
+ import process from 'node:process';
13
+ import { createRequire } from 'node:module';
14
+ import { fileURLToPath } from 'node:url';
15
+
16
+ const CONFIG_KEY = 'kerfComponentCatalog';
17
+ const ignoredDirectories = new Set(['.git', 'dist', 'node_modules']);
18
+ const scriptRoot = dirname(fileURLToPath(import.meta.url));
19
+ const metadataSchema = JSON.parse(
20
+ readFileSync(join(scriptRoot, 'component-metadata.schema.json'), 'utf8'),
21
+ );
22
+ const catalogSchema = JSON.parse(
23
+ readFileSync(join(scriptRoot, 'component-composition.schema.json'), 'utf8'),
24
+ );
25
+ const selectionSchema = JSON.parse(
26
+ readFileSync(
27
+ join(scriptRoot, 'component-catalog-extension.schema.json'),
28
+ 'utf8',
29
+ ),
30
+ );
31
+
32
+ export class CatalogError extends Error {
33
+ constructor(diagnostics) {
34
+ super(diagnostics.join('\n'));
35
+ this.name = 'CatalogError';
36
+ this.diagnostics = diagnostics;
37
+ }
38
+ }
39
+
40
+ function readJson(path, label, diagnostics) {
41
+ try {
42
+ return JSON.parse(readFileSync(path, 'utf8'));
43
+ } catch (error) {
44
+ diagnostics.push(`${label}: ${error.message}`);
45
+ return null;
46
+ }
47
+ }
48
+
49
+ function schemaReference(rootSchema, reference) {
50
+ if (!reference.startsWith('#/'))
51
+ throw new Error(`unsupported schema reference ${reference}`);
52
+ return reference
53
+ .slice(2)
54
+ .split('/')
55
+ .map((part) => part.replaceAll('~1', '/').replaceAll('~0', '~'))
56
+ .reduce((value, part) => value?.[part], rootSchema);
57
+ }
58
+
59
+ function schemaTypeMatches(value, type) {
60
+ if (type === 'array') return Array.isArray(value);
61
+ if (type === 'object')
62
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
63
+ if (type === 'integer') return Number.isInteger(value);
64
+ return typeof value === type;
65
+ }
66
+
67
+ function validateSchemaValue(value, rule, path, rootSchema, diagnostics) {
68
+ if (rule.$ref) {
69
+ const referenced = schemaReference(rootSchema, rule.$ref);
70
+ if (!referenced) {
71
+ diagnostics.push(`${path}: schema reference ${rule.$ref} does not exist`);
72
+ return;
73
+ }
74
+ validateSchemaValue(value, referenced, path, rootSchema, diagnostics);
75
+ return;
76
+ }
77
+ if (rule.allOf) {
78
+ for (const candidate of rule.allOf)
79
+ validateSchemaValue(value, candidate, path, rootSchema, diagnostics);
80
+ }
81
+ if (rule.anyOf) {
82
+ const alternatives = rule.anyOf.map((candidate) => {
83
+ const failures = [];
84
+ validateSchemaValue(value, candidate, path, rootSchema, failures);
85
+ return failures;
86
+ });
87
+ if (alternatives.every((failures) => failures.length)) {
88
+ // A union of bare types (a prop condition's `equals`) names the types.
89
+ const types = rule.anyOf.every(
90
+ (candidate) =>
91
+ Object.keys(candidate).length === 1 &&
92
+ typeof candidate.type === 'string',
93
+ )
94
+ ? rule.anyOf.map((candidate) => candidate.type)
95
+ : null;
96
+ diagnostics.push(
97
+ types
98
+ ? `${path}: expected ${types.join(' or ')}`
99
+ : `${path}: does not match any allowed schema variant`,
100
+ );
101
+ }
102
+ return;
103
+ }
104
+ if (rule.const !== undefined && value !== rule.const)
105
+ diagnostics.push(`${path}: expected ${JSON.stringify(rule.const)}`);
106
+ if (rule.enum && !rule.enum.includes(value))
107
+ diagnostics.push(
108
+ `${path}: expected one of ${rule.enum.map((item) => JSON.stringify(item)).join(', ')}`,
109
+ );
110
+ if (rule.type && !schemaTypeMatches(value, rule.type)) {
111
+ diagnostics.push(`${path}: expected ${rule.type}`);
112
+ return;
113
+ }
114
+ if (typeof value === 'string') {
115
+ if (rule.minLength !== undefined && value.length < rule.minLength)
116
+ diagnostics.push(
117
+ `${path}: expected at least ${rule.minLength} character(s)`,
118
+ );
119
+ if (rule.pattern && !new RegExp(rule.pattern).test(value))
120
+ diagnostics.push(`${path}: must match ${rule.pattern}`);
121
+ }
122
+ if (typeof value === 'number' && rule.minimum !== undefined) {
123
+ if (value < rule.minimum)
124
+ diagnostics.push(`${path}: expected a value >= ${rule.minimum}`);
125
+ }
126
+ if (Array.isArray(value)) {
127
+ if (rule.minItems !== undefined && value.length < rule.minItems)
128
+ diagnostics.push(`${path}: expected at least ${rule.minItems} item(s)`);
129
+ if (rule.uniqueItems) {
130
+ const serialized = value.map((item) => JSON.stringify(item));
131
+ if (new Set(serialized).size !== serialized.length)
132
+ diagnostics.push(`${path}: expected unique items`);
133
+ }
134
+ if (rule.items)
135
+ value.forEach((item, index) =>
136
+ validateSchemaValue(
137
+ item,
138
+ rule.items,
139
+ `${path}[${index}]`,
140
+ rootSchema,
141
+ diagnostics,
142
+ ),
143
+ );
144
+ }
145
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
146
+ for (const key of rule.required ?? [])
147
+ if (!(key in value)) diagnostics.push(`${path}.${key}: is required`);
148
+ const properties = rule.properties ?? {};
149
+ for (const [key, item] of Object.entries(value)) {
150
+ if (key in properties)
151
+ validateSchemaValue(
152
+ item,
153
+ properties[key],
154
+ `${path}.${key}`,
155
+ rootSchema,
156
+ diagnostics,
157
+ );
158
+ else if (rule.additionalProperties === false)
159
+ diagnostics.push(`${path}.${key}: additional property is not allowed`);
160
+ }
161
+ }
162
+ }
163
+
164
+ export function validateDocumentAgainstSchema(value, schema, path) {
165
+ const diagnostics = [];
166
+ validateSchemaValue(value, schema, path, schema, diagnostics);
167
+ return diagnostics;
168
+ }
169
+
170
+ function expandWorkspace(root, pattern) {
171
+ const normalized = pattern.replaceAll('/', sep);
172
+ if (!normalized.includes('*')) return [resolve(root, normalized)];
173
+ const star = normalized.indexOf('*');
174
+ const parent = resolve(root, normalized.slice(0, star));
175
+ const suffix = normalized.slice(star + 1);
176
+ if (!existsSync(parent)) return [];
177
+ return readdirSync(parent, { withFileTypes: true })
178
+ .filter(
179
+ (entry) => entry.isDirectory() && !ignoredDirectories.has(entry.name),
180
+ )
181
+ .map((entry) => resolve(parent, entry.name + suffix))
182
+ .filter((path) => existsSync(path) && statSync(path).isDirectory());
183
+ }
184
+
185
+ function configuredPackages(root, diagnostics) {
186
+ const rootPackagePath = join(root, 'package.json');
187
+ const rootPackage = readJson(rootPackagePath, rootPackagePath, diagnostics);
188
+ if (!rootPackage) return [];
189
+ const packages = rootPackage[CONFIG_KEY] ? [root] : [];
190
+ const workspacePatterns = Array.isArray(rootPackage.workspaces)
191
+ ? rootPackage.workspaces
192
+ : (rootPackage.workspaces?.packages ?? []);
193
+ for (const pattern of workspacePatterns) {
194
+ for (const packageRoot of expandWorkspace(root, pattern)) {
195
+ const packagePath = join(packageRoot, 'package.json');
196
+ if (!existsSync(packagePath)) continue;
197
+ const packageJson = readJson(packagePath, packagePath, diagnostics);
198
+ if (packageJson?.[CONFIG_KEY]) packages.push(packageRoot);
199
+ }
200
+ }
201
+ return [...new Set(packages)].sort();
202
+ }
203
+
204
+ function valueAt(value, path) {
205
+ return path.split('.').reduce((current, part) => current?.[part], value);
206
+ }
207
+
208
+ // Paths where an explicit `null` is itself the author's decision: a component
209
+ // whose root element belongs to another catalog (a `rendersAs` wrapper) or that
210
+ // exposes no public root class.
211
+ const NULLABLE_DECISIONS = new Set(['boundaries.rootClass']);
212
+
213
+ function requireDecision(component, path, at, diagnostics) {
214
+ const value = valueAt(component, path);
215
+ const explicitNull =
216
+ value === null &&
217
+ NULLABLE_DECISIONS.has(path) &&
218
+ Object.hasOwn(
219
+ valueAt(component, path.slice(0, path.lastIndexOf('.'))) ?? {},
220
+ path.slice(path.lastIndexOf('.') + 1),
221
+ );
222
+ if (explicitNull) return;
223
+ if (value === undefined || value === null || value === '') {
224
+ diagnostics.push(
225
+ `${at}.${path}: author decision required; the generator does not infer semantics or geometry from rendered appearance`,
226
+ );
227
+ }
228
+ }
229
+
230
+ let typescript;
231
+
232
+ function typescriptApi() {
233
+ if (typescript) return typescript;
234
+ try {
235
+ typescript = createRequire(import.meta.url)('typescript');
236
+ return typescript;
237
+ } catch {
238
+ throw new Error(
239
+ 'TypeScript is required for syntax-aware export verification; run npm install before catalog generation.',
240
+ );
241
+ }
242
+ }
243
+
244
+ function hasModifier(ts, node, kind) {
245
+ return Boolean(node.modifiers?.some((modifier) => modifier.kind === kind));
246
+ }
247
+
248
+ function bindingNames(ts, name, names) {
249
+ if (ts.isIdentifier(name)) names.add(name.text);
250
+ else
251
+ for (const element of name.elements ?? [])
252
+ if (!ts.isOmittedExpression(element))
253
+ bindingNames(ts, element.name, names);
254
+ }
255
+
256
+ export function exportedNamesFromSource(source, fileName = 'component.tsx') {
257
+ const ts = typescriptApi();
258
+ const sourceFile = ts.createSourceFile(
259
+ fileName,
260
+ source,
261
+ ts.ScriptTarget.Latest,
262
+ true,
263
+ fileName.endsWith('.tsx') || fileName.endsWith('.jsx')
264
+ ? ts.ScriptKind.TSX
265
+ : ts.ScriptKind.TS,
266
+ );
267
+ if (sourceFile.parseDiagnostics.length) {
268
+ const diagnostic = sourceFile.parseDiagnostics[0];
269
+ const point = sourceFile.getLineAndCharacterOfPosition(
270
+ diagnostic.start ?? 0,
271
+ );
272
+ throw new Error(
273
+ `${fileName}:${point.line + 1}:${point.character + 1}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}`,
274
+ );
275
+ }
276
+ const names = new Set();
277
+ for (const statement of sourceFile.statements) {
278
+ if (ts.isExportDeclaration(statement)) {
279
+ if (!statement.exportClause) continue;
280
+ if (ts.isNamedExports(statement.exportClause))
281
+ for (const element of statement.exportClause.elements)
282
+ names.add(element.name.text);
283
+ continue;
284
+ }
285
+ if (
286
+ !hasModifier(ts, statement, ts.SyntaxKind.ExportKeyword) ||
287
+ hasModifier(ts, statement, ts.SyntaxKind.DefaultKeyword)
288
+ )
289
+ continue;
290
+ if (ts.isVariableStatement(statement)) {
291
+ for (const declaration of statement.declarationList.declarations)
292
+ bindingNames(ts, declaration.name, names);
293
+ } else if (
294
+ (ts.isFunctionDeclaration(statement) ||
295
+ ts.isClassDeclaration(statement) ||
296
+ ts.isEnumDeclaration(statement) ||
297
+ ts.isModuleDeclaration(statement) ||
298
+ ts.isInterfaceDeclaration(statement) ||
299
+ ts.isTypeAliasDeclaration(statement)) &&
300
+ statement.name
301
+ )
302
+ names.add(statement.name.text);
303
+ }
304
+ return names;
305
+ }
306
+
307
+ function exportedNamesFromFile(path) {
308
+ return exportedNamesFromSource(readFileSync(path, 'utf8'), path);
309
+ }
310
+
311
+ function sourceEntryForExport(packageRoot, definition) {
312
+ const target =
313
+ typeof definition === 'string'
314
+ ? definition
315
+ : (definition?.import ?? definition?.default);
316
+ if (typeof target !== 'string' || !target.startsWith('./dist/')) return null;
317
+ const stem = target.slice('./dist/'.length).replace(/\.(?:mjs|cjs|js)$/, '');
318
+ for (const extension of ['.ts', '.tsx', '.mts', '.js', '.jsx', '.mjs']) {
319
+ const candidate = join(packageRoot, 'src', `${stem}${extension}`);
320
+ if (existsSync(candidate)) return candidate;
321
+ }
322
+ return null;
323
+ }
324
+
325
+ function validateStringList(value, at, diagnostics, { nonempty = false } = {}) {
326
+ if (
327
+ !Array.isArray(value) ||
328
+ (nonempty && value.length === 0) ||
329
+ value.some((item) => typeof item !== 'string' || item.length === 0) ||
330
+ new Set(value).size !== value.length
331
+ )
332
+ diagnostics.push(
333
+ `${at}: expected a${nonempty ? ' non-empty' : ''} unique string list`,
334
+ );
335
+ }
336
+
337
+ function validateComposition(component, at, diagnostics, packageRoot) {
338
+ const composition = component.composition ?? {};
339
+ if (!['any', 'root', 'listed'].includes(composition.parents?.mode))
340
+ diagnostics.push(`${at}.composition.parents.mode: invalid parent mode`);
341
+ validateStringList(
342
+ composition.parents?.entries,
343
+ `${at}.composition.parents.entries`,
344
+ diagnostics,
345
+ { nonempty: composition.parents?.mode === 'listed' },
346
+ );
347
+ validateStringList(
348
+ composition.contexts,
349
+ `${at}.composition.contexts`,
350
+ diagnostics,
351
+ );
352
+ if (!Array.isArray(composition.zones))
353
+ diagnostics.push(`${at}.composition.zones: expected an array`);
354
+ const zoneIds = new Set();
355
+ const zoneProps = new Set();
356
+ for (const zone of composition.zones ?? []) {
357
+ const zoneAt = `${at}.composition.zones.${zone?.id ?? '<unknown>'}`;
358
+ if (!zone?.id || zoneIds.has(zone.id))
359
+ diagnostics.push(`${zoneAt}.id: expected a unique non-empty id`);
360
+ zoneIds.add(zone?.id);
361
+ const prop = zone?.jsx?.prop;
362
+ if (prop !== undefined) {
363
+ if (zoneProps.has(prop))
364
+ diagnostics.push(
365
+ `${zoneAt}.jsx.prop: ${prop} already fills another zone`,
366
+ );
367
+ zoneProps.add(prop);
368
+ }
369
+ validateStringList(zone?.accepts, `${zoneAt}.accepts`, diagnostics, {
370
+ nonempty: true,
371
+ });
372
+ const { min, max } = zone?.cardinality ?? {};
373
+ if (!Number.isInteger(min) || min < 0)
374
+ diagnostics.push(
375
+ `${zoneAt}.cardinality.min: expected a non-negative integer`,
376
+ );
377
+ if (max !== 'unbounded' && (!Number.isInteger(max) || max < 1 || max < min))
378
+ diagnostics.push(
379
+ `${zoneAt}.cardinality.max: expected unbounded or an integer >= min`,
380
+ );
381
+ validateStringList(
382
+ zone?.exclusiveWith,
383
+ `${zoneAt}.exclusiveWith`,
384
+ diagnostics,
385
+ );
386
+ }
387
+ for (const zone of composition.zones ?? [])
388
+ for (const other of zone?.exclusiveWith ?? [])
389
+ if (other === zone.id || !zoneIds.has(other))
390
+ diagnostics.push(
391
+ `${at}.composition.zones.${zone.id}.exclusiveWith: unknown or self-referential zone ${other}`,
392
+ );
393
+
394
+ if (!['any', 'none', 'listed'].includes(composition.children?.mode))
395
+ diagnostics.push(`${at}.composition.children.mode: invalid child mode`);
396
+ validateStringList(
397
+ composition.children?.concepts,
398
+ `${at}.composition.children.concepts`,
399
+ diagnostics,
400
+ { nonempty: composition.children?.mode === 'listed' },
401
+ );
402
+ validateStringList(
403
+ composition.children?.requiredConcepts,
404
+ `${at}.composition.children.requiredConcepts`,
405
+ diagnostics,
406
+ );
407
+ for (const required of composition.children?.requiredConcepts ?? [])
408
+ if (!composition.children.concepts?.includes(required))
409
+ diagnostics.push(
410
+ `${at}.composition.children.requiredConcepts: ${required} is not an allowed concept`,
411
+ );
412
+
413
+ if (!Array.isArray(composition.state))
414
+ diagnostics.push(`${at}.composition.state: expected an array`);
415
+ const stateIds = new Set();
416
+ for (const state of composition.state ?? []) {
417
+ if (!state?.id || stateIds.has(state.id))
418
+ diagnostics.push(
419
+ `${at}.composition.state: state ids must be unique and non-empty`,
420
+ );
421
+ stateIds.add(state?.id);
422
+ if (!['application', 'controlled', 'component'].includes(state?.owner))
423
+ diagnostics.push(
424
+ `${at}.composition.state.${state?.id}.owner: invalid owner`,
425
+ );
426
+ if (typeof state?.required !== 'boolean')
427
+ diagnostics.push(
428
+ `${at}.composition.state.${state?.id}.required: expected boolean`,
429
+ );
430
+ }
431
+ if (typeof composition.wiring?.required !== 'boolean')
432
+ diagnostics.push(`${at}.composition.wiring.required: expected boolean`);
433
+ validateStringList(
434
+ composition.wiring?.helpers,
435
+ `${at}.composition.wiring.helpers`,
436
+ diagnostics,
437
+ );
438
+ if ('actions' in (composition.wiring ?? {}))
439
+ validateStringList(
440
+ composition.wiring.actions,
441
+ `${at}.composition.wiring.actions`,
442
+ diagnostics,
443
+ );
444
+ // Required wiring names something the app must do: a helper to call, or a
445
+ // root-delegated data-action to handle.
446
+ if (
447
+ composition.wiring?.required === true &&
448
+ Array.isArray(composition.wiring.helpers) &&
449
+ !composition.wiring.helpers.length &&
450
+ !composition.wiring.actions?.length
451
+ )
452
+ diagnostics.push(
453
+ `${at}.composition.wiring: required wiring names at least one helper or action`,
454
+ );
455
+ validateStringList(
456
+ composition.wiring?.obligations,
457
+ `${at}.composition.wiring.obligations`,
458
+ diagnostics,
459
+ );
460
+ const helperSourcesSeen = new Set();
461
+ for (const helperSource of composition.wiring?.sources ?? []) {
462
+ const sourceAt = `${at}.composition.wiring.sources.${helperSource?.export}`;
463
+ if (helperSourcesSeen.has(helperSource?.export))
464
+ diagnostics.push(`${sourceAt}: declared more than once`);
465
+ helperSourcesSeen.add(helperSource?.export);
466
+ if (!composition.wiring.helpers?.includes(helperSource?.export))
467
+ diagnostics.push(
468
+ `${sourceAt}: ${helperSource?.export} is not listed in composition.wiring.helpers`,
469
+ );
470
+ const file = resolve(packageRoot, helperSource?.source ?? '');
471
+ if (!helperSource?.source || !existsSync(file))
472
+ diagnostics.push(
473
+ `${sourceAt}.source: file does not exist: ${helperSource?.source}`,
474
+ );
475
+ else if (!exportedNamesFromFile(file).has(helperSource.export))
476
+ diagnostics.push(
477
+ `${sourceAt}: ${helperSource.export} is not exported by ${helperSource.source}`,
478
+ );
479
+ }
480
+ const stateAttributes = composition.wiring?.stateAttributes;
481
+ if (stateAttributes !== undefined && !Array.isArray(stateAttributes))
482
+ diagnostics.push(
483
+ `${at}.composition.wiring.stateAttributes: expected an array`,
484
+ );
485
+ const stateAttributeNames = new Set();
486
+ for (const attribute of Array.isArray(stateAttributes)
487
+ ? stateAttributes
488
+ : []) {
489
+ const name = attribute?.name;
490
+ const attributeAt = `${at}.composition.wiring.stateAttributes.${name}`;
491
+ if (typeof name !== 'string' || !/^data-[a-z0-9]+(-[a-z0-9]+)*$/.test(name))
492
+ diagnostics.push(`${attributeAt}.name: expected a data-* attribute name`);
493
+ if (stateAttributeNames.has(name))
494
+ diagnostics.push(`${attributeAt}.name: declared more than once`);
495
+ stateAttributeNames.add(name);
496
+ for (const field of ['on', 'meaning'])
497
+ if (typeof attribute?.[field] !== 'string' || !attribute[field])
498
+ diagnostics.push(
499
+ `${attributeAt}.${field}: expected a non-empty string`,
500
+ );
501
+ if (!composition.wiring.helpers?.includes(attribute?.helper))
502
+ diagnostics.push(
503
+ `${attributeAt}.helper: ${attribute?.helper} is not listed in composition.wiring.helpers`,
504
+ );
505
+ }
506
+ if (
507
+ !['application', 'component', 'shared', 'not-applicable'].includes(
508
+ composition.responsive?.owner,
509
+ )
510
+ )
511
+ diagnostics.push(`${at}.composition.responsive.owner: invalid owner`);
512
+ validateStringList(
513
+ composition.responsive?.behaviors,
514
+ `${at}.composition.responsive.behaviors`,
515
+ diagnostics,
516
+ );
517
+ validateStringList(
518
+ composition.layout?.roles,
519
+ `${at}.composition.layout.roles`,
520
+ diagnostics,
521
+ { nonempty: true },
522
+ );
523
+ const geometryOwners = [
524
+ 'self',
525
+ 'parent',
526
+ 'child',
527
+ 'none',
528
+ 'conditional',
529
+ 'composed',
530
+ ];
531
+ for (const dimension of ['margin', 'border', 'padding'])
532
+ if (!geometryOwners.includes(composition.layout?.geometry?.[dimension]))
533
+ diagnostics.push(
534
+ `${at}.composition.layout.geometry.${dimension}: invalid geometry owner`,
535
+ );
536
+ if ('notes' in (composition.layout?.geometry ?? {}))
537
+ validateStringList(
538
+ composition.layout.geometry.notes,
539
+ `${at}.composition.layout.geometry.notes`,
540
+ diagnostics,
541
+ );
542
+ }
543
+
544
+ function validateComponent(
545
+ component,
546
+ packageRoot,
547
+ packageJson,
548
+ ids,
549
+ diagnosticIds,
550
+ diagnostics,
551
+ ) {
552
+ const at = `${packageJson.name}:${component?.id ?? '<unknown>'}`;
553
+ for (const path of [
554
+ 'id',
555
+ 'name',
556
+ 'kind',
557
+ 'purpose',
558
+ 'source',
559
+ 'publicExports',
560
+ 'sourceLinks',
561
+ 'composition.parents.mode',
562
+ 'composition.parents.entries',
563
+ 'composition.contexts',
564
+ 'composition.zones',
565
+ 'composition.children.mode',
566
+ 'composition.children.concepts',
567
+ 'composition.children.requiredConcepts',
568
+ 'composition.state',
569
+ 'composition.wiring.required',
570
+ 'composition.wiring.helpers',
571
+ 'composition.wiring.obligations',
572
+ 'composition.responsive.owner',
573
+ 'composition.responsive.behaviors',
574
+ 'composition.layout.roles',
575
+ 'composition.layout.geometry.margin',
576
+ 'composition.layout.geometry.border',
577
+ 'composition.layout.geometry.padding',
578
+ 'boundaries.rootClass',
579
+ 'boundaries.publicClasses',
580
+ 'boundaries.publicTokens',
581
+ 'accessibility.obligations',
582
+ 'diagnostics',
583
+ 'provenance.selection',
584
+ 'provenance.composition',
585
+ ])
586
+ requireDecision(component, path, at, diagnostics);
587
+
588
+ if (!component?.id) return;
589
+ if (ids.has(component.id))
590
+ diagnostics.push(`${at}.id: duplicate component id`);
591
+ ids.add(component.id);
592
+ if (!['component', 'composition', 'recipe'].includes(component.kind))
593
+ diagnostics.push(`${at}.kind: expected component, composition, or recipe`);
594
+ const sourcePath = resolve(packageRoot, component.source ?? '');
595
+ if (!component.source || !existsSync(sourcePath))
596
+ diagnostics.push(`${at}.source: file does not exist: ${component.source}`);
597
+
598
+ const exports = packageJson.exports ?? {};
599
+ // A private application (package.json#private) is bundled, never imported
600
+ // by package name, and has no per-file dist entries. Its exports may omit
601
+ // `subpath`; each name is then verified against the component's own
602
+ // `source` file, which is how the Kerf UI rules resolve its wrappers.
603
+ const privateApplication = packageJson.private === true;
604
+ if (
605
+ !Array.isArray(component.publicExports) ||
606
+ !component.publicExports.length
607
+ )
608
+ diagnostics.push(`${at}.publicExports: expected a non-empty array`);
609
+ else {
610
+ const seen = new Set();
611
+ for (const item of component.publicExports) {
612
+ const exportAt = `${at}.publicExports`;
613
+ const sourceOnly =
614
+ privateApplication &&
615
+ Boolean(item?.name) &&
616
+ !Object.hasOwn(item, 'subpath');
617
+ if (!item?.name || (!sourceOnly && typeof item?.subpath !== 'string')) {
618
+ diagnostics.push(
619
+ `${exportAt}: every export requires name and subpath (only a private application, package.json#private, may omit subpath)`,
620
+ );
621
+ continue;
622
+ }
623
+ const key = sourceOnly
624
+ ? `source:${item.name}`
625
+ : `${item.subpath}:${item.name}`;
626
+ if (seen.has(key))
627
+ diagnostics.push(
628
+ `${exportAt}: duplicate ${sourceOnly ? item.name : key}`,
629
+ );
630
+ seen.add(key);
631
+ if (sourceOnly) {
632
+ if (
633
+ existsSync(sourcePath) &&
634
+ !exportedNamesFromFile(sourcePath).has(item.name)
635
+ )
636
+ diagnostics.push(
637
+ `${exportAt}: ${item.name} is not exported by ${component.source}`,
638
+ );
639
+ continue;
640
+ }
641
+ if (!(item.subpath in exports))
642
+ diagnostics.push(
643
+ `${exportAt}: package.json does not export subpath ${item.subpath}`,
644
+ );
645
+ const sourceEntry = sourceEntryForExport(
646
+ packageRoot,
647
+ exports[item.subpath],
648
+ );
649
+ if (!sourceEntry)
650
+ diagnostics.push(
651
+ `${exportAt}: cannot map ${item.subpath} to an existing src/ entry`,
652
+ );
653
+ else if (!exportedNamesFromFile(sourceEntry).has(item.name))
654
+ diagnostics.push(
655
+ `${exportAt}: ${item.name} is not exported by ${relative(packageRoot, sourceEntry)}`,
656
+ );
657
+ }
658
+ }
659
+ validateStringList(component.sourceLinks, `${at}.sourceLinks`, diagnostics, {
660
+ nonempty: true,
661
+ });
662
+ for (const link of component.sourceLinks ?? []) {
663
+ if (/^[a-z]+:/i.test(link)) continue;
664
+ const localPath = link.split('#')[0];
665
+ if (localPath && !existsSync(resolve(packageRoot, localPath)))
666
+ diagnostics.push(
667
+ `${at}.sourceLinks: local source link does not exist: ${link}`,
668
+ );
669
+ }
670
+ validateComposition(component, at, diagnostics, packageRoot);
671
+ validateStringList(
672
+ component.boundaries?.publicClasses,
673
+ `${at}.boundaries.publicClasses`,
674
+ diagnostics,
675
+ );
676
+ if (
677
+ component.boundaries?.rootClass !== null &&
678
+ (typeof component.boundaries?.rootClass !== 'string' ||
679
+ !component.boundaries.publicClasses?.includes(
680
+ component.boundaries.rootClass,
681
+ ))
682
+ )
683
+ diagnostics.push(
684
+ `${at}.boundaries.rootClass: expected null or one publicClasses entry`,
685
+ );
686
+ // An application may place only the declared subset of public classes on
687
+ // its own elements; every other public class is the component's rendered
688
+ // anatomy (eslint-plugin-kerfjs KUI-L103). `rootElement` names the element
689
+ // the component renders around its placeable classes.
690
+ if (component.boundaries && 'placeableClasses' in component.boundaries) {
691
+ validateStringList(
692
+ component.boundaries.placeableClasses,
693
+ `${at}.boundaries.placeableClasses`,
694
+ diagnostics,
695
+ );
696
+ for (const className of Array.isArray(component.boundaries.placeableClasses)
697
+ ? component.boundaries.placeableClasses
698
+ : [])
699
+ if (!component.boundaries.publicClasses?.includes(className))
700
+ diagnostics.push(
701
+ `${at}.boundaries.placeableClasses: ${className} is not one of publicClasses`,
702
+ );
703
+ }
704
+ if (
705
+ component.boundaries?.rootElement !== undefined &&
706
+ !component.boundaries.placeableClasses?.length
707
+ )
708
+ diagnostics.push(
709
+ `${at}.boundaries.rootElement: requires a non-empty placeableClasses`,
710
+ );
711
+ validateStringList(
712
+ component.boundaries?.publicTokens,
713
+ `${at}.boundaries.publicTokens`,
714
+ diagnostics,
715
+ );
716
+ validateStringList(
717
+ component.accessibility?.obligations,
718
+ `${at}.accessibility.obligations`,
719
+ diagnostics,
720
+ );
721
+ if (!Array.isArray(component.diagnostics))
722
+ diagnostics.push(`${at}.diagnostics: expected an array`);
723
+ for (const diagnostic of component.diagnostics ?? []) {
724
+ if (
725
+ !/^KUI-C[0-9]{3}$/.test(diagnostic?.id ?? '') ||
726
+ diagnosticIds.has(diagnostic.id)
727
+ )
728
+ diagnostics.push(`${at}.diagnostics: ids must be unique KUI-C### values`);
729
+ diagnosticIds.add(diagnostic?.id);
730
+ if (!['error', 'warning'].includes(diagnostic?.severity))
731
+ diagnostics.push(
732
+ `${at}.diagnostics.${diagnostic?.id}.severity: invalid severity`,
733
+ );
734
+ if (!diagnostic?.when || !diagnostic?.message)
735
+ diagnostics.push(
736
+ `${at}.diagnostics.${diagnostic?.id}: when and message are required`,
737
+ );
738
+ }
739
+ }
740
+
741
+ function toEntry(packageName, component) {
742
+ return {
743
+ key: `${packageName}:${component.id}`,
744
+ package: packageName,
745
+ id: component.id,
746
+ name: component.name,
747
+ kind: component.kind,
748
+ purpose: component.purpose,
749
+ publicExports: component.publicExports,
750
+ sourceLinks: component.sourceLinks,
751
+ source: component.source,
752
+ ...(component.composition.rendersAs
753
+ ? { rendersAs: component.composition.rendersAs }
754
+ : {}),
755
+ ...(component.composition.insetFreeChildren
756
+ ? { insetFreeChildren: component.composition.insetFreeChildren }
757
+ : {}),
758
+ ...(component.composition.insetFreeWhen
759
+ ? { insetFreeWhen: component.composition.insetFreeWhen }
760
+ : {}),
761
+ parents: component.composition.parents,
762
+ contexts: component.composition.contexts,
763
+ zones: component.composition.zones,
764
+ children: component.composition.children,
765
+ state: component.composition.state,
766
+ wiring: component.composition.wiring,
767
+ responsive: component.composition.responsive,
768
+ layout: component.composition.layout,
769
+ accessibility: component.accessibility,
770
+ boundaries: component.boundaries,
771
+ diagnostics: component.diagnostics,
772
+ provenance: component.provenance,
773
+ };
774
+ }
775
+
776
+ // The catalog keys a package's `rendersAs` may name: entries generated in this
777
+ // run, or those of an installed dependency's shipped catalog (its
778
+ // package.json#kerfComponentCatalog.output, or @kerfjs/ui's ai/ catalog).
779
+ function dependencyCatalogKeys(packageRoot, packageName, cache) {
780
+ const cacheKey = `${packageRoot}\0${packageName}`;
781
+ if (cache.has(cacheKey)) return cache.get(cacheKey);
782
+ let keys;
783
+ for (let dir = packageRoot; ; dir = dirname(dir)) {
784
+ const manifestPath = join(dir, 'node_modules', packageName, 'package.json');
785
+ if (existsSync(manifestPath)) {
786
+ const dependencyRoot = dirname(manifestPath);
787
+ let catalogPath;
788
+ try {
789
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'));
790
+ if (manifest[CONFIG_KEY]?.output)
791
+ catalogPath = resolve(dependencyRoot, manifest[CONFIG_KEY].output);
792
+ } catch {
793
+ // An unreadable manifest leaves the package unresolved below.
794
+ }
795
+ catalogPath ??= join(dependencyRoot, 'ai', 'component-composition.json');
796
+ try {
797
+ const catalog = JSON.parse(readFileSync(catalogPath, 'utf8'));
798
+ keys = new Set(
799
+ (catalog.entries ?? []).map(
800
+ (entry) => entry.key ?? `${catalog.package}:${entry.id}`,
801
+ ),
802
+ );
803
+ } catch {
804
+ // No readable catalog: the package stays unresolved.
805
+ }
806
+ break;
807
+ }
808
+ if (dirname(dir) === dir) break;
809
+ }
810
+ cache.set(cacheKey, keys);
811
+ return keys;
812
+ }
813
+
814
+ function validateRendersAs(results, diagnostics) {
815
+ const generated = new Map(
816
+ results.map(({ catalog }) => [
817
+ catalog.package,
818
+ new Set(catalog.entries.map((entry) => entry.key)),
819
+ ]),
820
+ );
821
+ const cache = new Map();
822
+ for (const { packageRoot, metadataPath, catalog } of results)
823
+ for (const entry of catalog.entries)
824
+ for (const root of entry.rendersAs ?? []) {
825
+ const at = `${metadataPath}: components.${entry.id}.composition.rendersAs`;
826
+ const rootPackage = root.slice(0, root.lastIndexOf(':'));
827
+ if (root === entry.key) {
828
+ diagnostics.push(`${at}: ${root} names the component itself`);
829
+ continue;
830
+ }
831
+ const keys =
832
+ generated.get(rootPackage) ??
833
+ dependencyCatalogKeys(packageRoot, rootPackage, cache);
834
+ if (!keys)
835
+ diagnostics.push(
836
+ `${at}: cannot resolve a component catalog for package ${rootPackage}; install it or generate its catalog`,
837
+ );
838
+ else if (!keys.has(root))
839
+ diagnostics.push(
840
+ `${at}: ${root} is not an entry in ${rootPackage}'s catalog`,
841
+ );
842
+ }
843
+ }
844
+
845
+ // The selection catalog (the @kerfjs/ui component-catalog extension) shares
846
+ // identity, purpose, boundaries, and geometry with the composition metadata,
847
+ // so only the selection-only facts live in each component's `selection` block.
848
+ function selectionGeometry(component) {
849
+ if (component.selection?.geometry) return component.selection.geometry;
850
+ const { notes, ...owners } = component.composition.layout.geometry;
851
+ return notes?.length ? { ...owners, notes } : owners;
852
+ }
853
+
854
+ function toSelectionEntry(component) {
855
+ const { selection, boundaries } = component;
856
+ return {
857
+ id: component.id,
858
+ name: component.name,
859
+ kind: component.kind,
860
+ purpose: component.purpose,
861
+ useWhen: selection.useWhen,
862
+ avoidWhen: selection.avoidWhen,
863
+ publicClasses: boundaries.publicClasses,
864
+ publicTokens: boundaries.publicTokens,
865
+ ...(selection.uses ? { uses: selection.uses } : {}),
866
+ source: component.source,
867
+ ...(selection.styleSources ? { styleSources: selection.styleSources } : {}),
868
+ ...(selection.demoSource ? { demoSource: selection.demoSource } : {}),
869
+ geometry: selectionGeometry(component),
870
+ ...(selection.documentation
871
+ ? { documentation: selection.documentation }
872
+ : {}),
873
+ };
874
+ }
875
+
876
+ // The @kerfjs/ui selection catalog ids an installed copy ships, which a
877
+ // selection entry's `uses` may name alongside the package's own ids.
878
+ function kerfSelectionIds(packageRoot) {
879
+ for (let dir = packageRoot; ; dir = dirname(dir)) {
880
+ const catalogPath = join(
881
+ dir,
882
+ 'node_modules',
883
+ '@kerfjs',
884
+ 'ui',
885
+ 'ai',
886
+ 'component-catalog.json',
887
+ );
888
+ if (existsSync(catalogPath)) {
889
+ try {
890
+ const catalog = JSON.parse(readFileSync(catalogPath, 'utf8'));
891
+ return new Set((catalog.entries ?? []).map((entry) => entry.id));
892
+ } catch {
893
+ return null;
894
+ }
895
+ }
896
+ if (dirname(dir) === dir) return null;
897
+ }
898
+ }
899
+
900
+ function localPathExists(packageRoot, link) {
901
+ if (/^[a-z]+:/i.test(link)) return true;
902
+ const localPath = link.split('#')[0];
903
+ return !localPath || existsSync(resolve(packageRoot, localPath));
904
+ }
905
+
906
+ function posixRelative(from, to) {
907
+ const path = relative(from, to).split(sep).join('/');
908
+ return path.startsWith('.') ? path : `./${path}`;
909
+ }
910
+
911
+ function buildSelectionCatalog({
912
+ packageRoot,
913
+ packageJson,
914
+ metadata,
915
+ metadataPath,
916
+ outputPath,
917
+ selectionOutputPath,
918
+ diagnostics,
919
+ }) {
920
+ const at = metadataPath;
921
+ const selected = metadata.components.filter(
922
+ (component) => component.kind !== 'recipe',
923
+ );
924
+ if (!selectionOutputPath) {
925
+ if (metadata.description !== undefined)
926
+ diagnostics.push(
927
+ `${at}: description is emitted only to a selection catalog; configure package.json#${CONFIG_KEY}.selectionOutput or remove it`,
928
+ );
929
+ for (const component of metadata.components)
930
+ if (component.selection)
931
+ diagnostics.push(
932
+ `${at}: components.${component.id}.selection is emitted only to a selection catalog; configure package.json#${CONFIG_KEY}.selectionOutput or remove it`,
933
+ );
934
+ return null;
935
+ }
936
+
937
+ if (!metadata.description)
938
+ diagnostics.push(
939
+ `${at}.description: author decision required; the selection catalog needs a package description`,
940
+ );
941
+ const derived = posixRelative(dirname(outputPath), selectionOutputPath);
942
+ if (
943
+ metadata.componentCatalog !== undefined &&
944
+ metadata.componentCatalog !== 'not-applicable' &&
945
+ metadata.componentCatalog !== derived
946
+ )
947
+ diagnostics.push(
948
+ `${at}.componentCatalog: ${metadata.componentCatalog} disagrees with the configured selectionOutput (${derived}); remove it or set it to "not-applicable"`,
949
+ );
950
+
951
+ const ownIds = new Set(selected.map((component) => component.id));
952
+ let kerfIds;
953
+ for (const component of metadata.components) {
954
+ const componentAt = `${at}: components.${component.id}.selection`;
955
+ if (component.kind === 'recipe') {
956
+ if (component.selection)
957
+ diagnostics.push(
958
+ `${componentAt}: recipes are not selection catalog entries; remove it`,
959
+ );
960
+ continue;
961
+ }
962
+ if (!component.selection) {
963
+ diagnostics.push(
964
+ `${componentAt}: author decision required; selectionOutput is configured, so every component and composition needs useWhen and avoidWhen`,
965
+ );
966
+ continue;
967
+ }
968
+ const { selection } = component;
969
+ if (
970
+ !selection.geometry &&
971
+ Object.values(component.composition.layout.geometry).includes('composed')
972
+ )
973
+ diagnostics.push(
974
+ `${componentAt}.geometry: required because composition.layout.geometry uses "composed", which the selection catalog cannot express`,
975
+ );
976
+ for (const path of [
977
+ ...(selection.styleSources ?? []),
978
+ ...(selection.demoSource ? [selection.demoSource] : []),
979
+ ...(selection.documentation ? [selection.documentation] : []),
980
+ ])
981
+ if (!localPathExists(packageRoot, path))
982
+ diagnostics.push(`${componentAt}: local path does not exist: ${path}`);
983
+ for (const use of selection.uses ?? []) {
984
+ if (use === component.id)
985
+ diagnostics.push(
986
+ `${componentAt}.uses: ${use} names the component itself`,
987
+ );
988
+ else if (!ownIds.has(use)) {
989
+ kerfIds ??= kerfSelectionIds(packageRoot);
990
+ if (!kerfIds)
991
+ diagnostics.push(
992
+ `${componentAt}.uses: cannot resolve ${use}; install @kerfjs/ui so its selection catalog ids can be checked`,
993
+ );
994
+ else if (!kerfIds.has(use))
995
+ diagnostics.push(
996
+ `${componentAt}.uses: ${use} is neither a component in this package nor a @kerfjs/ui catalog entry`,
997
+ );
998
+ }
999
+ }
1000
+ }
1001
+ if (ownIds.size) {
1002
+ kerfIds ??= kerfSelectionIds(packageRoot);
1003
+ for (const id of ownIds)
1004
+ if (kerfIds?.has(id))
1005
+ diagnostics.push(
1006
+ `${at}: components.${id}.id duplicates a @kerfjs/ui catalog id, which the selection catalog cannot disambiguate`,
1007
+ );
1008
+ }
1009
+
1010
+ const catalog = {
1011
+ $schema:
1012
+ 'https://raw.githubusercontent.com/brianwestphal/kerf/main/ui/ai/component-catalog-extension.schema.json',
1013
+ schemaVersion: 1,
1014
+ package: packageJson.name,
1015
+ description: metadata.description,
1016
+ entries: selected
1017
+ .filter((component) => component.selection)
1018
+ .sort((a, b) => a.id.localeCompare(b.id))
1019
+ .map(toSelectionEntry),
1020
+ };
1021
+ diagnostics.push(
1022
+ ...validateDocumentAgainstSchema(
1023
+ catalog,
1024
+ selectionSchema,
1025
+ selectionOutputPath,
1026
+ ),
1027
+ );
1028
+ return catalog;
1029
+ }
1030
+
1031
+ export function generateCatalogs(root = process.cwd()) {
1032
+ const diagnostics = [];
1033
+ const packages = configuredPackages(resolve(root), diagnostics);
1034
+ if (!packages.length && !diagnostics.length)
1035
+ diagnostics.push(
1036
+ `${relative(process.cwd(), resolve(root)) || '.'}: no package declares package.json#${CONFIG_KEY}`,
1037
+ );
1038
+ const results = [];
1039
+ const packageNames = new Set();
1040
+ for (const packageRoot of packages) {
1041
+ const packagePath = join(packageRoot, 'package.json');
1042
+ const packageJson = readJson(packagePath, packagePath, diagnostics);
1043
+ if (!packageJson) continue;
1044
+ const config = packageJson[CONFIG_KEY];
1045
+ if (!packageJson.name)
1046
+ diagnostics.push(`${packagePath}: package name is required`);
1047
+ if (packageNames.has(packageJson.name))
1048
+ diagnostics.push(
1049
+ `${packagePath}: duplicate configured package name ${packageJson.name}`,
1050
+ );
1051
+ packageNames.add(packageJson.name);
1052
+ for (const key of ['source', 'output'])
1053
+ if (!config?.[key])
1054
+ diagnostics.push(`${packagePath}#${CONFIG_KEY}.${key}: is required`);
1055
+ if (
1056
+ config?.selectionOutput !== undefined &&
1057
+ (typeof config.selectionOutput !== 'string' ||
1058
+ !config.selectionOutput ||
1059
+ resolve(packageRoot, config.selectionOutput) ===
1060
+ resolve(packageRoot, config.output ?? ''))
1061
+ )
1062
+ diagnostics.push(
1063
+ `${packagePath}#${CONFIG_KEY}.selectionOutput: expected a path distinct from output`,
1064
+ );
1065
+ if (!config?.source || !config?.output) continue;
1066
+ const metadataPath = resolve(packageRoot, config.source);
1067
+ const metadata = readJson(metadataPath, metadataPath, diagnostics);
1068
+ if (!metadata) continue;
1069
+ const metadataDiagnostics = validateDocumentAgainstSchema(
1070
+ metadata,
1071
+ metadataSchema,
1072
+ metadataPath,
1073
+ );
1074
+ diagnostics.push(...metadataDiagnostics);
1075
+ if (metadataDiagnostics.length) {
1076
+ continue;
1077
+ }
1078
+ const ids = new Set();
1079
+ const diagnosticIds = new Set();
1080
+ for (const component of metadata.components)
1081
+ validateComponent(
1082
+ component,
1083
+ packageRoot,
1084
+ packageJson,
1085
+ ids,
1086
+ diagnosticIds,
1087
+ diagnostics,
1088
+ );
1089
+ const entries = [...metadata.components]
1090
+ .sort((a, b) => a.id.localeCompare(b.id))
1091
+ .map((component) => toEntry(packageJson.name, component));
1092
+ const outputPath = resolve(packageRoot, config.output);
1093
+ const selectionOutputPath =
1094
+ typeof config.selectionOutput === 'string' && config.selectionOutput
1095
+ ? resolve(packageRoot, config.selectionOutput)
1096
+ : null;
1097
+ const selection = buildSelectionCatalog({
1098
+ packageRoot,
1099
+ packageJson,
1100
+ metadata,
1101
+ metadataPath,
1102
+ outputPath,
1103
+ selectionOutputPath,
1104
+ diagnostics,
1105
+ });
1106
+ const componentCatalog = selectionOutputPath
1107
+ ? posixRelative(dirname(outputPath), selectionOutputPath)
1108
+ : (metadata.componentCatalog ?? 'not-applicable');
1109
+ const catalog = {
1110
+ $schema:
1111
+ 'https://raw.githubusercontent.com/brianwestphal/kerf/main/ui/ai/component-composition-extension.schema.json',
1112
+ schemaVersion: 1,
1113
+ package: packageJson.name,
1114
+ compatibility: {
1115
+ componentCatalog,
1116
+ identity: 'package:id',
1117
+ },
1118
+ entries,
1119
+ };
1120
+ diagnostics.push(
1121
+ ...validateDocumentAgainstSchema(catalog, catalogSchema, outputPath),
1122
+ );
1123
+ results.push({
1124
+ packageRoot,
1125
+ metadataPath,
1126
+ outputPath,
1127
+ catalog,
1128
+ ...(selection ? { selectionOutputPath, selection } : {}),
1129
+ });
1130
+ }
1131
+ validateRendersAs(results, diagnostics);
1132
+ if (diagnostics.length) throw new CatalogError(diagnostics.sort());
1133
+ return results;
1134
+ }
1135
+
1136
+ export function formatCatalog(catalog) {
1137
+ return `${JSON.stringify(catalog, null, 2)}\n`;
1138
+ }
1139
+
1140
+ function checkOutput(path, catalog, schema, label, diagnostics) {
1141
+ if (!existsSync(path)) {
1142
+ diagnostics.push(`${path}: generated ${label} is missing`);
1143
+ return;
1144
+ }
1145
+ const actualSource = readFileSync(path, 'utf8');
1146
+ const actual = readJson(path, path, diagnostics);
1147
+ if (actual)
1148
+ diagnostics.push(...validateDocumentAgainstSchema(actual, schema, path));
1149
+ if (actualSource !== formatCatalog(catalog))
1150
+ diagnostics.push(
1151
+ `${path}: generated ${label} is stale; run catalog:generate`,
1152
+ );
1153
+ }
1154
+
1155
+ export function runCatalogCommand({
1156
+ root = process.cwd(),
1157
+ check = false,
1158
+ } = {}) {
1159
+ const results = generateCatalogs(root);
1160
+ const diagnostics = [];
1161
+ for (const result of results) {
1162
+ const outputs = [
1163
+ [result.outputPath, result.catalog, catalogSchema, 'catalog'],
1164
+ ];
1165
+ if (result.selection)
1166
+ outputs.push([
1167
+ result.selectionOutputPath,
1168
+ result.selection,
1169
+ selectionSchema,
1170
+ 'selection catalog',
1171
+ ]);
1172
+ for (const [path, catalog, schema, label] of outputs) {
1173
+ if (check) checkOutput(path, catalog, schema, label, diagnostics);
1174
+ else writeFileSync(path, formatCatalog(catalog));
1175
+ }
1176
+ }
1177
+ if (diagnostics.length) throw new CatalogError(diagnostics);
1178
+ return results;
1179
+ }
1180
+
1181
+ function parseArgs(argv) {
1182
+ let root = process.cwd();
1183
+ let check = false;
1184
+ for (let index = 2; index < argv.length; index += 1) {
1185
+ const arg = argv[index];
1186
+ if (arg === '--check') check = true;
1187
+ else if (arg === '--write') check = false;
1188
+ else if (arg === '--root' && argv[index + 1]) root = resolve(argv[++index]);
1189
+ else if (arg === '--help' || arg === '-h') {
1190
+ process.stdout.write(
1191
+ 'Usage: kerf-component-catalog [--write|--check] [--root <package-or-workspace>]\n',
1192
+ );
1193
+ process.exit(0);
1194
+ } else throw new CatalogError([`unknown argument: ${arg}`]);
1195
+ }
1196
+ return { root, check };
1197
+ }
1198
+
1199
+ const isMain =
1200
+ process.argv[1] &&
1201
+ realpathSync(process.argv[1]) ===
1202
+ realpathSync(fileURLToPath(import.meta.url));
1203
+ if (isMain) {
1204
+ try {
1205
+ const options = parseArgs(process.argv);
1206
+ const results = runCatalogCommand(options);
1207
+ const verb = options.check ? 'verified' : 'wrote';
1208
+ for (const result of results)
1209
+ for (const path of [result.outputPath, result.selectionOutputPath])
1210
+ if (path)
1211
+ process.stdout.write(`${verb} ${relative(options.root, path)}\n`);
1212
+ } catch (error) {
1213
+ const diagnostics =
1214
+ error instanceof CatalogError ? error.diagnostics : [error.message];
1215
+ for (const diagnostic of diagnostics)
1216
+ process.stderr.write(`kerf-component-catalog: ${diagnostic}\n`);
1217
+ process.exitCode = 1;
1218
+ }
1219
+ }