@magmonium/cli 0.8.30 → 0.10.1

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/bin/cli.js CHANGED
@@ -26,6 +26,8 @@ const genCodeCommand = require('./commands/gen-code');
26
26
  const genTestCommand = require('./commands/gen-test');
27
27
  const validateCommand = require('./commands/validate');
28
28
  const apiOpsCommand = require('./commands/api-ops');
29
+ const gestureCommand = require('./commands/gesture');
30
+ const inspectCommand = require('./commands/inspect');
29
31
 
30
32
  const program = new Command();
31
33
 
@@ -61,5 +63,7 @@ genCodeCommand(program);
61
63
  genTestCommand(program);
62
64
  validateCommand(program);
63
65
  apiOpsCommand(program);
66
+ gestureCommand(program);
67
+ inspectCommand(program);
64
68
 
65
69
  program.parse();
@@ -0,0 +1,198 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { readDesignFiles } = require('./gen-code');
4
+ const {
5
+ DESIGN_ROOT,
6
+ appTypeScript,
7
+ findViolations,
8
+ loadBundles,
9
+ themeCatalogOf,
10
+ writeCanonical,
11
+ } = require('./validate');
12
+
13
+ /**
14
+ * Runs one of the editor's gestures — or an ordered batch of them — against
15
+ * `.magmonium/` exactly as the editor runs it (gesture-catalog, 0128_13): the
16
+ * same writes, seeds, cleanups and refusals, so an AI edit is one the editor
17
+ * could have made.
18
+ *
19
+ * Dry by default: the report says what each gesture did (its notes), which
20
+ * files it would change, and every Violation the result holds that the design
21
+ * did not. `--write` lands it only when nothing new blocks — the Invariants
22
+ * and the codec-drop diff judged against the design before the gesture — in
23
+ * the form the editor saves (canonical order, a fresh `write-id`).
24
+ *
25
+ * `status`: `ok`, `refused` (a gesture refused, or its result holds a new
26
+ * blocking Violation — nothing written), `invalid` (bad arguments, an unknown
27
+ * gesture, or a design the codec cannot read).
28
+ */
29
+ async function gesture({ root = process.cwd(), name, args, batch, write = false }) {
30
+ const bundles = loadBundles();
31
+ const { codegen, gestures } = bundles;
32
+ const report = { status: 'ok', notes: [], changed: [], removed: [], canonicalised: [], violations: [] };
33
+ const invalid = (reason, detail) => ({ ...report, status: 'invalid', refusal: { reason, ...(detail ? { detail } : {}) } });
34
+
35
+ const steps = batch ?? [{ gesture: name, args: args ?? {} }];
36
+ if (!Array.isArray(steps) || !steps.length) return invalid('batch-empty');
37
+ const resolved = [];
38
+ for (const [index, step] of steps.entries()) {
39
+ const found = step && gestures.gestureByName(step.gesture);
40
+ if (!found) return invalid('gesture-unknown', { step: index, gesture: step && step.gesture });
41
+ resolved.push({ gesture: found, args: step.args ?? {} });
42
+ }
43
+
44
+ if (!fs.existsSync(path.join(root, DESIGN_ROOT, 'index.json')))
45
+ return invalid('design-absent', { path: `${DESIGN_ROOT}/index.json` });
46
+ const files = readDesignFiles(root);
47
+ const read = codegen.readDesignSource(files);
48
+ if (!read.ok || !read.source) return invalid('design-unreadable', read.refusal);
49
+ const source = read.source;
50
+
51
+ // `function-save` compiles the body the way the function editor does.
52
+ const ts = appTypeScript(root);
53
+ gestures.setFunctionBodyCheck(ts ? gestures.functionBodyCheckFor(ts) : undefined);
54
+
55
+ const run = gestures.runBatch(source, resolved);
56
+ report.notes = run.notes;
57
+ if (!run.ok || !run.source) {
58
+ return {
59
+ ...report,
60
+ status: 'refused',
61
+ refusal: {
62
+ gesture: steps[run.failedAt ?? 0].gesture,
63
+ step: run.failedAt ?? 0,
64
+ ...(run.refusal || { reason: 'refused' }),
65
+ },
66
+ };
67
+ }
68
+
69
+ // Judged as the editor would read the result back: written canonically,
70
+ // then through the codec again, so a row the gesture left unreadable shows
71
+ // as a drop rather than vanishing.
72
+ const operationOf = codegen.operationResolverOf(source.operations);
73
+ const catalog = themeCatalogOf(root);
74
+ const canonicalBefore = codegen.buildDesignSource({ ...source, operationOf }, source.operations);
75
+ const afterFiles = codegen.buildDesignSource({ ...run.source, operationOf }, source.operations);
76
+ const reread = codegen.readDesignSource(afterFiles);
77
+ if (!reread.ok || !reread.source)
78
+ return { ...report, status: 'refused', refusal: { reason: 'result-unreadable', detail: reread.refusal } };
79
+
80
+ const held = new Set(
81
+ findViolations(bundles, source, catalog, operationOf, files, ts).map((one) => one.id)
82
+ );
83
+ report.violations = findViolations(bundles, reread.source, catalog, operationOf, afterFiles, ts).filter(
84
+ (one) => !held.has(one.id)
85
+ );
86
+ report.changed = Object.keys(afterFiles).filter((rel) => canonicalBefore[rel] !== afterFiles[rel]);
87
+ report.removed = Object.keys(canonicalBefore).filter((rel) => !(rel in afterFiles));
88
+ // Files the gesture did not change but a write still rewrites: the design
89
+ // on disk is not in the form the editor saves — the migration its next Save
90
+ // would make too.
91
+ report.canonicalised = Object.keys(afterFiles).filter(
92
+ (rel) => !report.changed.includes(rel) && files[rel] !== afterFiles[rel]
93
+ );
94
+
95
+ if (report.violations.some((one) => one.severity === 'blocking')) {
96
+ return { ...report, status: 'refused', refusal: { reason: 'violations' } };
97
+ }
98
+ if (write) {
99
+ report.written = writeCanonical(root, codegen, { ...run.source, operationOf }, source.operations, files);
100
+ }
101
+ return report;
102
+ }
103
+
104
+ const EXIT = { ok: 0, refused: 1, invalid: 2 };
105
+
106
+ const parseJson = (text, what) => {
107
+ try {
108
+ return JSON.parse(text);
109
+ } catch (error) {
110
+ throw new Error(`${what} is not JSON: ${error.message}`);
111
+ }
112
+ };
113
+
114
+ function printReport(report) {
115
+ if (report.status === 'invalid') {
116
+ console.error(`❌ gesture: ${report.refusal.reason}${report.refusal.detail ? ` ${JSON.stringify(report.refusal.detail)}` : ''}`);
117
+ return;
118
+ }
119
+ report.notes.forEach((note) => console.log(`• ${note}`));
120
+ if (report.status === 'refused') {
121
+ const r = report.refusal;
122
+ console.error(
123
+ `❌ refused${r.gesture ? ` — ${r.gesture} (step ${r.step})` : ''}: ${r.reason}${r.detail ? ` ${JSON.stringify(r.detail)}` : ''}`
124
+ );
125
+ }
126
+ report.violations.forEach((one) =>
127
+ console.log(`${one.severity === 'blocking' ? '❌' : '⚠️'} ${one.invariant}: ${one.subject}`)
128
+ );
129
+ if (report.status === 'ok') {
130
+ console.log(
131
+ report.written
132
+ ? `✅ written: ${report.changed.length} file(s) changed${report.removed.length ? `, ${report.removed.length} removed` : ''}`
133
+ : `✅ dry run: would change ${report.changed.length} file(s) — pass --write to land it`
134
+ );
135
+ report.changed.forEach((rel) => console.log(` ${rel}`));
136
+ if (report.canonicalised.length)
137
+ console.log(
138
+ ` + ${report.canonicalised.length} file(s) ${report.written ? 'rewritten' : 'to rewrite'} in the editor's saved form only (no content change): ${report.canonicalised.join(', ')}`
139
+ );
140
+ }
141
+ }
142
+
143
+ function gestureCommand(program) {
144
+ program
145
+ .command('gesture [name]')
146
+ .description(
147
+ "Run one of the m-one-ui editor's gestures on .magmonium/ — the editor's own writes, seeds and refusals. Dry run unless --write."
148
+ )
149
+ .option('--root <path>', 'App root (default: cwd)')
150
+ .option('--args <json>', 'The gesture\'s arguments as JSON, e.g. \'{"screenId":"…"}\'')
151
+ .option('--args-file <path>', 'Read the arguments from a JSON file')
152
+ .option('--batch <path>', 'A JSON file of [{ "gesture", "args" }] run in order, all or nothing')
153
+ .option('--list', 'List every gesture with its arguments')
154
+ .option('--write', 'Land the result when nothing new blocks (canonical form, fresh write-id)')
155
+ .option('--json', 'Print the report as JSON')
156
+ .action(async (name, options) => {
157
+ let report;
158
+ try {
159
+ if (options.list) {
160
+ const { gestures } = loadBundles();
161
+ const list = gestures.GESTURES.map(({ name: gestureName, summary, args }) => ({
162
+ name: gestureName,
163
+ summary,
164
+ args,
165
+ }));
166
+ if (options.json) console.log(JSON.stringify(list, null, 2));
167
+ else
168
+ list.forEach((one) => {
169
+ console.log(`${one.name} — ${one.summary}`);
170
+ Object.entries(one.args).forEach(([key, arg]) =>
171
+ console.log(` ${key}${arg.required ? '' : '?'} (${arg.type}): ${arg.doc}`)
172
+ );
173
+ });
174
+ return;
175
+ }
176
+ const root = options.root || process.cwd();
177
+ const args = options.argsFile
178
+ ? parseJson(fs.readFileSync(path.resolve(options.argsFile), 'utf8'), '--args-file')
179
+ : options.args
180
+ ? parseJson(options.args, '--args')
181
+ : undefined;
182
+ const batch = options.batch
183
+ ? parseJson(fs.readFileSync(path.resolve(options.batch), 'utf8'), '--batch')
184
+ : undefined;
185
+ if (!name && !batch) throw new Error('name a gesture, pass --batch, or --list');
186
+ report = await gesture({ root, name, args, batch, write: Boolean(options.write) });
187
+ } catch (error) {
188
+ console.error(`❌ gesture: ${error.message}`);
189
+ process.exit(EXIT.invalid);
190
+ }
191
+ if (options.json) console.log(JSON.stringify(report, null, 2));
192
+ else printReport(report);
193
+ process.exit(EXIT[report.status] ?? EXIT.invalid);
194
+ });
195
+ }
196
+
197
+ module.exports = gestureCommand;
198
+ module.exports.gesture = gesture;
@@ -0,0 +1,141 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { readDesignFiles } = require('./gen-code');
4
+ const {
5
+ DESIGN_ROOT,
6
+ loadBundles,
7
+ messageText,
8
+ readApiSpec,
9
+ readDesignFilesAt,
10
+ } = require('./validate');
11
+
12
+ /**
13
+ * Asks one of the m-one-ui editor's read-only questions of `.magmonium/`
14
+ * (inspect-catalog, 0129_02): who uses a store member, what names a Screen or
15
+ * a PureFunction, what is drawn from an ApiOperation, what the backend
16
+ * changed under the design, which OneFunctions exist, what changed between
17
+ * two refs — the answers the editor's Usage, Used by and Recheck panels give.
18
+ *
19
+ * Never writes. `status`: `ok`, or `invalid` (an unknown inspection, a
20
+ * missing argument, an id the design does not hold, a design the codec cannot
21
+ * read, a ref git cannot show).
22
+ */
23
+ async function inspect({ root = process.cwd(), name, args = {}, spec, bundles = loadBundles() }) {
24
+ const { codegen, inspections } = bundles;
25
+ const invalid = (reason, detail) => ({
26
+ status: 'invalid',
27
+ inspection: name,
28
+ refusal: { reason, ...(detail ? { detail } : {}) },
29
+ });
30
+
31
+ const inspection = inspections.inspectionByName(name);
32
+ if (!inspection) return invalid('inspection-unknown', { inspection: name });
33
+
34
+ const atRef = name === 'change' && args.to;
35
+ if (!atRef && !fs.existsSync(path.join(root, DESIGN_ROOT, 'index.json')))
36
+ return invalid('design-absent', { path: `${DESIGN_ROOT}/index.json` });
37
+
38
+ const input = {};
39
+ if (name === 'change') {
40
+ if (!args.from) return invalid('args-invalid', { missing: ['from'] });
41
+ input.baseFiles = readDesignFilesAt(root, args.from);
42
+ input.files = args.to ? readDesignFilesAt(root, args.to) : readDesignFiles(root);
43
+ }
44
+ const read = codegen.readDesignSource(input.files ?? readDesignFiles(root));
45
+ if (!read.ok || !read.source) return invalid('design-unreadable', read.refusal);
46
+ input.source = read.source;
47
+
48
+ let specRead;
49
+ if (name === 'drift') {
50
+ const { where, spec: apiSpec } = await readApiSpec(bundles, spec, read.source.appTarget);
51
+ input.spec = apiSpec;
52
+ specRead = where;
53
+ }
54
+
55
+ const run = inspections.runInspection(inspection, input, args);
56
+ if (!run.ok) return invalid(run.refusal.reason, run.refusal.detail);
57
+ // A SpecDrift row carries its message as a key, like a Violation.
58
+ const result =
59
+ name === 'drift'
60
+ ? run.result.map((row) => ({ ...row, text: messageText(row.message) }))
61
+ : run.result;
62
+ return { status: 'ok', inspection: name, ...(specRead ? { spec: specRead } : {}), result };
63
+ }
64
+
65
+ const EXIT = { ok: 0, invalid: 2 };
66
+
67
+ const ARG_OPTIONS = ['member', 'screen', 'function', 'op', 'reach', 'from', 'to'];
68
+
69
+ function printReport(report) {
70
+ if (report.status !== 'ok') {
71
+ const r = report.refusal;
72
+ console.error(`❌ inspect ${report.inspection ?? ''}: ${r.reason}${r.detail ? ` ${JSON.stringify(r.detail)}` : ''}`);
73
+ return;
74
+ }
75
+ const rows = Array.isArray(report.result) ? report.result : undefined;
76
+ if (rows && !rows.length) {
77
+ console.log('✅ nothing');
78
+ return;
79
+ }
80
+ console.log(JSON.stringify(report.result, null, 2));
81
+ }
82
+
83
+ function inspectCommand(program) {
84
+ program
85
+ .command('inspect [name]')
86
+ .description(
87
+ "Ask one of the m-one-ui editor's read-only questions of .magmonium/ — usage, used-by, api-holders, drift, one-functions, change. Never writes."
88
+ )
89
+ .option('--root <path>', 'App root (default: cwd)')
90
+ .option('--member <id>', 'usage: the store member id')
91
+ .option('--screen <id>', 'used-by: the Screen id')
92
+ .option('--function <id>', 'used-by: the PureFunction id')
93
+ .option('--op <"VERB /path">', 'api-holders: the ApiOperation, e.g. "GET /orders/{id}"')
94
+ .option('--reach <reach>', 'one-functions: only those offered at this reach')
95
+ .option('--from <ref>', 'change: the base git ref')
96
+ .option('--to <ref>', 'change: the compared git ref (default: the working tree)')
97
+ .option('--spec [urlOrFile]', "drift: swagger.json to read (default: the Environment backend's)")
98
+ .option('--list', 'List every inspection with its arguments')
99
+ .option('--json', 'Print the report as JSON')
100
+ .action(async (name, options) => {
101
+ let report;
102
+ try {
103
+ if (options.list) {
104
+ const { inspections } = loadBundles();
105
+ const list = inspections.INSPECTIONS.map(({ name: inspectionName, summary, args }) => ({
106
+ name: inspectionName,
107
+ summary,
108
+ args,
109
+ }));
110
+ if (options.json) console.log(JSON.stringify(list, null, 2));
111
+ else
112
+ list.forEach((one) => {
113
+ console.log(`${one.name} — ${one.summary}`);
114
+ Object.entries(one.args).forEach(([key, arg]) =>
115
+ console.log(` --${key}${arg.required ? '' : '?'}: ${arg.doc}`)
116
+ );
117
+ });
118
+ return;
119
+ }
120
+ if (!name) throw new Error('name an inspection, or --list');
121
+ const args = Object.fromEntries(
122
+ ARG_OPTIONS.filter((key) => options[key] !== undefined).map((key) => [key, String(options[key])])
123
+ );
124
+ report = await inspect({
125
+ root: options.root || process.cwd(),
126
+ name,
127
+ args,
128
+ spec: options.spec === true ? '' : options.spec,
129
+ });
130
+ } catch (error) {
131
+ console.error(`❌ inspect: ${error.message}`);
132
+ process.exit(EXIT.invalid);
133
+ }
134
+ if (options.json) console.log(JSON.stringify(report, null, 2));
135
+ else printReport(report);
136
+ process.exit(EXIT[report.status] ?? EXIT.invalid);
137
+ });
138
+ }
139
+
140
+ module.exports = inspectCommand;
141
+ module.exports.inspect = inspect;
@@ -19,6 +19,8 @@ function loadBundles() {
19
19
  const names = {
20
20
  codegen: 'index.js',
21
21
  invariants: 'invariant-catalog.js',
22
+ gestures: 'gesture-catalog.js',
23
+ inspections: 'inspect-catalog.js',
22
24
  swagger: 'swagger-helper.js',
23
25
  };
24
26
  const missing = Object.values(names).filter(
@@ -346,19 +348,202 @@ function readDesignFilesAt(root, ref) {
346
348
  return files;
347
349
  }
348
350
 
351
+ /**
352
+ * The AppRepo's own `typescript`, which the PureFunction body check runs on
353
+ * (0128_12) — not a dependency of the cli, so a repo without one skips the
354
+ * check and says so rather than failing.
355
+ */
356
+ function appTypeScript(root) {
357
+ try {
358
+ return require(require.resolve('typescript', { paths: [root] }));
359
+ } catch {
360
+ return undefined;
361
+ }
362
+ }
363
+
364
+ /**
365
+ * Every PureFunction body checked the way the editor checks it: against its
366
+ * signature and the curated pure lib, so a body that does not compile or
367
+ * reaches past its parameters is blocking here as it is in the function
368
+ * editor (ADR 0046).
369
+ */
370
+ function bodyBreaches(bundles, source, ts) {
371
+ if (!ts) return [];
372
+ const check = bundles.gestures.functionBodyCheckFor(ts);
373
+ const owned = [
374
+ ...Object.values(source.functions || {}).map((fn) => [fn, undefined]),
375
+ ...Object.values(source.features || {}).flatMap((feature) =>
376
+ Object.values(feature.functions || {}).map((fn) => [fn, feature])
377
+ ),
378
+ ];
379
+ return owned.flatMap(([fn, feature]) => {
380
+ const problems = check(source, fn, feature && feature.id);
381
+ if (!problems.length) return [];
382
+ const first = problems[0];
383
+ return [
384
+ {
385
+ id: `function-body-invalid::${fn.id}`,
386
+ invariant: 'function-body-invalid',
387
+ message: 'invariant-function-body-invalid',
388
+ subject: `${feature ? feature.name : 'shared'} · ${fn.name} (${first.line}: ${first.message})`,
389
+ severity: 'blocking',
390
+ target: {
391
+ kind: 'function',
392
+ ...(feature ? { featureId: feature.id } : {}),
393
+ functionId: fn.id,
394
+ },
395
+ problems,
396
+ },
397
+ ];
398
+ });
399
+ }
400
+
401
+ /**
402
+ * What the emit would leave out (GLOSSARY.md EmitGap), the Repair Register's
403
+ * list: advisory, as the editor holds it — a design skill refuses any one new
404
+ * against its baseline (0128_05).
405
+ */
406
+ function emitGapAdvisories(bundles, source, operationOf) {
407
+ return bundles.invariants
408
+ .collectEmitGaps({
409
+ screens: source.screens,
410
+ features: source.features,
411
+ navMap: source.navMap,
412
+ functions: source.functions,
413
+ enums: source.enums,
414
+ operationOf,
415
+ })
416
+ .map((gap) => ({
417
+ id: `emit-gap-${gap.kind}::${gap.screenId}::${gap.subject}`,
418
+ invariant: `emit-gap-${gap.kind}`,
419
+ message: gap.message,
420
+ subject: `${gap.screenName} → ${gap.subject}${gap.detail ? ` (${gap.detail})` : ''}`,
421
+ severity: 'advisory',
422
+ target: gap.screenId
423
+ ? { kind: 'screen', screenId: gap.screenId }
424
+ : { kind: 'panel', panel: 'config' },
425
+ }));
426
+ }
427
+
428
+ // Config keys a Control carries that its inspector form does not list,
429
+ // because a side panel or the gesture itself writes them: the born name, the
430
+ // TextSource's label and `noTranslate`, a link's URLs, a table's columns, a
431
+ // menu's options, a button's key, a SubmitTarget, a pick, and a remote's or a
432
+ // doc's mount wiring (0128_12, measured on the store and invest designs).
433
+ const SIDE_PANEL_KEYS = new Set([
434
+ 'name', 'label', 'noTranslate', 'url', 'murl', 'img_sizes', 'columns',
435
+ 'options', 'buttonKey', 'submitTarget', 'selection', 'mountName', 'outFn',
436
+ 'urlMode', 'remote', 'remoteName', 'designSrc',
437
+ ]);
438
+
439
+ /**
440
+ * The English text of each message key (`message-text.json`, compiled from
441
+ * the m-one-ui i18n assets, 0129_03), so a report says what the editor says
442
+ * rather than only its key. A key with no text reads as itself.
443
+ */
444
+ let messageTexts;
445
+ // The checks only the cli makes — the editor's gestures refuse what they catch,
446
+ // so no editor panel ever says them and no i18n asset holds their text.
447
+ const CLI_MESSAGE_TEXT = {
448
+ 'invariant-codec-dropped':
449
+ 'The editor would drop this row on read — a reserved or duplicate name, a clashing Screen name, an unknown Control type',
450
+ 'invariant-control-configs':
451
+ "This Control's configs hold a key or value its inspector does not offer",
452
+ 'invariant-control-placement':
453
+ 'This Control sits where the editor would not let it land — the ControlRelationship whitelist, an unknown type, or a child or parent link that disagrees',
454
+ 'invariant-function-body-invalid': 'This PureFunction body does not compile',
455
+ 'invariant-method-operation-unresolved':
456
+ 'This StoreMethod resolves to no ApiOperation — neither the stored operations nor the spec has its verb and path',
457
+ 'invariant-nav-structure':
458
+ 'The Nav tree is malformed — a missing or doubly-listed child, a navId off its parent, two Default Navs, or a pageId or componentKey naming the wrong Screen',
459
+ };
460
+ function messageText(key) {
461
+ if (!messageTexts) {
462
+ const file = path.join(__dirname, '..', '..', 'codegen', 'message-text.json');
463
+ messageTexts = {
464
+ ...CLI_MESSAGE_TEXT,
465
+ ...(fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : {}),
466
+ };
467
+ }
468
+ return messageTexts[key] ?? key;
469
+ }
470
+
471
+ function controlConfigsCatalog() {
472
+ const file = path.join(__dirname, '..', '..', 'codegen', 'control-configs.json');
473
+ return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : undefined;
474
+ }
475
+
476
+ /**
477
+ * A Control's `configs` read against what its inspector offers
478
+ * (`control-configs.json`, compiled from the m-form `<type>_controls.yml`):
479
+ * a key no form lists and no side panel writes, or a dropdown value the
480
+ * field does not offer. Advisory — the editor accepts both on read, and a
481
+ * form-less ControlType is not judged at all; a design skill refuses any new
482
+ * one against its baseline (0128_05).
483
+ */
484
+ function configsAdvisories(catalog, source) {
485
+ if (!catalog) return [];
486
+ // A layout key some form offers for some type (margin, padding, …) is one a
487
+ // shared mixin writes, not a typo.
488
+ const anyForm = new Set(Object.values(catalog).flatMap((keys) => Object.keys(keys)));
489
+ return source.screens.flatMap(({ meta, state }) =>
490
+ Object.values(state.controlMap || {}).flatMap((control) => {
491
+ const known = catalog[control.type];
492
+ if (!known) return [];
493
+ return Object.entries(control.configs || {}).flatMap(([key, value]) => {
494
+ const at = `${meta.name} → ${control.configs && control.configs.name ? control.configs.name : control.id}`;
495
+ const finding = (problem) => ({
496
+ id: `control-configs::${meta.id}:${control.id}:${key}`,
497
+ invariant: 'control-configs',
498
+ message: 'invariant-control-configs',
499
+ subject: `${at}: ${problem}`,
500
+ severity: 'advisory',
501
+ target: { kind: 'control', screenId: meta.id, controlId: control.id },
502
+ });
503
+ if (!(key in known)) {
504
+ return SIDE_PANEL_KEYS.has(key) || anyForm.has(key)
505
+ ? []
506
+ : [finding(`\`${key}\` is not a ${control.type} config`)];
507
+ }
508
+ const allowed = known[key];
509
+ // `''` is a dropdown's unset row; objects are bound or authored values.
510
+ if (!allowed || value === undefined || value === null || value === '' || typeof value === 'object')
511
+ return [];
512
+ return allowed.includes(String(value))
513
+ ? []
514
+ : [finding(`\`${key}: ${value}\` is not one of ${allowed.filter(Boolean).join(', ')}`)];
515
+ });
516
+ })
517
+ );
518
+ }
519
+
349
520
  // Every Violation a read design holds: the editor's Invariants, plus what its
350
- // gestures would have refused and what resolves to no ApiOperation.
351
- function findViolations(bundles, source, catalog, operationOf, files = {}) {
521
+ // gestures would have refused, what resolves to no ApiOperation, the rows the
522
+ // codec dropped on read, every body that does not compile, and the EmitGaps.
523
+ function findViolations(
524
+ bundles,
525
+ source,
526
+ catalog,
527
+ operationOf,
528
+ files = {},
529
+ ts = undefined
530
+ ) {
352
531
  const { codegen, invariants } = bundles;
353
532
  return [
533
+ ...invariants.codecDrops(files, source, DESIGN_ROOT),
354
534
  ...placementBreaches(codegen, source.screens),
355
535
  ...navBreaches(source),
356
536
  ...rawNavBreaches(source, files),
357
537
  ...unresolvedMethods(codegen, source.features, operationOf),
538
+ ...bodyBreaches(bundles, source, ts),
539
+ ...emitGapAdvisories(bundles, source, operationOf),
540
+ ...configsAdvisories(controlConfigsCatalog(), source),
358
541
  ...invariants
359
542
  .runInvariants(invariants.invariantScopeOf(source, catalog || []))
360
543
  .filter((one) => catalog || one.invariant !== THEME_INVARIANT),
361
- ].sort((a, b) =>
544
+ ]
545
+ .map((one) => ({ ...one, text: messageText(one.message) }))
546
+ .sort((a, b) =>
362
547
  a.severity === b.severity ? 0 : a.severity === 'blocking' ? -1 : 1
363
548
  );
364
549
  }
@@ -419,6 +604,8 @@ async function validate({
419
604
 
420
605
  const catalog = themeCatalogOf(root);
421
606
  if (!catalog) report.skipped.push(THEME_INVARIANT);
607
+ const ts = appTypeScript(root);
608
+ if (!ts) report.skipped.push('function-body-invalid');
422
609
 
423
610
  // With a spec, StoreMethods resolve against it and `--write` refreshes the
424
611
  // snapshot from what they draw; without one, against the snapshot as stored.
@@ -437,7 +624,8 @@ async function validate({
437
624
  source,
438
625
  catalog,
439
626
  ws.operationOf,
440
- files
627
+ files,
628
+ ts
441
629
  );
442
630
 
443
631
  // What the design already held at the baseline is not this change's to fix:
@@ -454,7 +642,8 @@ async function validate({
454
642
  codegen.operationResolverOf(
455
643
  spec === undefined ? before.source.operations : operations
456
644
  ),
457
- beforeFiles
645
+ beforeFiles,
646
+ ts
458
647
  ).map((one) => one.id)
459
648
  : []
460
649
  );
@@ -515,6 +704,7 @@ function printReport(report) {
515
704
  console.log(
516
705
  `${mark} ${one.invariant} — ${one.subject} (${JSON.stringify(one.target)})`
517
706
  );
707
+ if (one.text !== one.message) console.log(` ${one.text}`);
518
708
  });
519
709
  report.skipped.forEach((name) =>
520
710
  console.log(`⏭️ ${name} skipped — no theme folder on disk`)
@@ -581,3 +771,10 @@ module.exports = validateCommand;
581
771
  module.exports.validate = validate;
582
772
  module.exports.loadBundles = loadBundles;
583
773
  module.exports.readApiSpec = readApiSpec;
774
+ module.exports.findViolations = findViolations;
775
+ module.exports.writeCanonical = writeCanonical;
776
+ module.exports.themeCatalogOf = themeCatalogOf;
777
+ module.exports.appTypeScript = appTypeScript;
778
+ module.exports.readDesignFilesAt = readDesignFilesAt;
779
+ module.exports.messageText = messageText;
780
+ module.exports.DESIGN_ROOT = DESIGN_ROOT;