@magmonium/cli 0.8.29 → 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
@@ -24,6 +24,10 @@ const generateCommand = require('./commands/generate');
24
24
  const patchWcEnvCommand = require('./commands/patch-wc-env');
25
25
  const genCodeCommand = require('./commands/gen-code');
26
26
  const genTestCommand = require('./commands/gen-test');
27
+ const validateCommand = require('./commands/validate');
28
+ const apiOpsCommand = require('./commands/api-ops');
29
+ const gestureCommand = require('./commands/gesture');
30
+ const inspectCommand = require('./commands/inspect');
27
31
 
28
32
  const program = new Command();
29
33
 
@@ -57,5 +61,9 @@ generateCommand(program);
57
61
  patchWcEnvCommand(program);
58
62
  genCodeCommand(program);
59
63
  genTestCommand(program);
64
+ validateCommand(program);
65
+ apiOpsCommand(program);
66
+ gestureCommand(program);
67
+ inspectCommand(program);
60
68
 
61
69
  program.parse();
@@ -0,0 +1,130 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { readDesignFiles } = require('./gen-code');
4
+ const { loadBundles, readApiSpec } = require('./validate');
5
+
6
+ const DESIGN_ROOT = '.magmonium';
7
+
8
+ // The design as read, when there is one: its AppTarget names the default spec
9
+ // URL, and its StoreMethods mark which ApiOperations are already drawn.
10
+ function designOf(root, codegen) {
11
+ if (!fs.existsSync(path.join(root, DESIGN_ROOT, 'index.json')))
12
+ return undefined;
13
+ const read = codegen.readDesignSource(readDesignFiles(root));
14
+ return read.ok ? read.source : undefined;
15
+ }
16
+
17
+ function drawnIds(source) {
18
+ const ids = new Set();
19
+ Object.values(source ? source.features : {}).forEach((feature) =>
20
+ [
21
+ feature.methods,
22
+ ...Object.values(feature.subStores || {}).map((sub) => sub.methods),
23
+ ].forEach((methods) =>
24
+ Object.values(methods || {}).forEach((method) =>
25
+ ids.add(`${method.verb} ${method.path}`)
26
+ )
27
+ )
28
+ );
29
+ return ids;
30
+ }
31
+
32
+ /**
33
+ * The AppTarget's ApiOperations as the editor's API picker walks them: by
34
+ * domain, then path and verb (GLOSSARY.md ApiOperation). No filter lists the
35
+ * domains; `domain` lists its operations; `op` prints one whole — params,
36
+ * responses and the StateShapes they mint — for a StoreMethod to be drawn
37
+ * from.
38
+ */
39
+ async function apiOps({ root = process.cwd(), spec, domain, op } = {}) {
40
+ const bundles = loadBundles();
41
+ const source = designOf(root, bundles.codegen);
42
+ const read = await readApiSpec(bundles, spec, source && source.appTarget);
43
+ const drawn = drawnIds(source);
44
+ // A listing row carries the summary's first sentence; `op` prints it whole.
45
+ const row = (one) => ({
46
+ id: one.id,
47
+ summary: (one.summary || '').split(/(?<=\.)\s/)[0].slice(0, 120),
48
+ drawn: drawn.has(one.id),
49
+ });
50
+
51
+ if (op) {
52
+ const found = read.spec.operations.find((one) => one.id === op);
53
+ if (!found) throw new Error(`no ApiOperation "${op}" in ${read.where}`);
54
+ return {
55
+ spec: read.where,
56
+ operation: { ...found, drawn: drawn.has(found.id) },
57
+ };
58
+ }
59
+ if (domain) {
60
+ const ops = read.spec.byDomain[domain];
61
+ if (!ops) throw new Error(`no domain "${domain}" in ${read.where}`);
62
+ return { spec: read.where, domain, operations: ops.map(row) };
63
+ }
64
+ return {
65
+ spec: read.where,
66
+ domains: Object.keys(read.spec.byDomain)
67
+ .sort()
68
+ .map((name) => ({
69
+ domain: name,
70
+ operations: read.spec.byDomain[name].length,
71
+ drawn: read.spec.byDomain[name].filter((one) => drawn.has(one.id))
72
+ .length,
73
+ })),
74
+ };
75
+ }
76
+
77
+ function printResult(result) {
78
+ if (result.operation) {
79
+ console.log(JSON.stringify(result.operation, null, 2));
80
+ } else if (result.operations) {
81
+ result.operations.forEach((one) =>
82
+ console.log(
83
+ `${one.drawn ? '✔' : ' '} ${one.id}${one.summary ? ` — ${one.summary}` : ''}`
84
+ )
85
+ );
86
+ } else {
87
+ result.domains.forEach((one) =>
88
+ console.log(
89
+ `${one.domain}: ${one.operations} operation(s), ${one.drawn} drawn`
90
+ )
91
+ );
92
+ }
93
+ }
94
+
95
+ function apiOpsCommand(program) {
96
+ program
97
+ .command('api-ops')
98
+ .description(
99
+ "Browse the AppTarget's swagger.json the way the editor's API picker does: domains, a domain's operations, one operation whole"
100
+ )
101
+ .option('--root <path>', 'App root (default: cwd)')
102
+ .option(
103
+ '--spec <urlOrFile>',
104
+ "swagger.json (default: the Environment backend's)"
105
+ )
106
+ .option('--domain <name>', "List one domain's operations")
107
+ .option(
108
+ '--op <id>',
109
+ 'Print one operation, e.g. "get /wallet/v1/coins/{id}/"'
110
+ )
111
+ .option('--json', 'Print as JSON')
112
+ .action(async (options) => {
113
+ try {
114
+ const result = await apiOps({
115
+ root: options.root || process.cwd(),
116
+ spec: options.spec,
117
+ domain: options.domain,
118
+ op: options.op,
119
+ });
120
+ if (options.json) console.log(JSON.stringify(result, null, 2));
121
+ else printResult(result);
122
+ } catch (error) {
123
+ console.error(`❌ api-ops: ${error.message}`);
124
+ process.exit(1);
125
+ }
126
+ });
127
+ }
128
+
129
+ module.exports = apiOpsCommand;
130
+ module.exports.apiOps = apiOps;
@@ -153,3 +153,4 @@ module.exports = genCodeCommand;
153
153
  module.exports.generate = generate;
154
154
  module.exports.isNewer = isNewer;
155
155
  module.exports.clearGeneratedSet = clearGeneratedSet;
156
+ module.exports.readDesignFiles = readDesignFiles;
@@ -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;