@magmonium/cli 0.10.1 → 0.10.4

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.
@@ -85,13 +85,9 @@ function clearGeneratedSet(root, generatedSet) {
85
85
  return removed;
86
86
  }
87
87
 
88
- /**
89
- * Regenerates the GeneratedSet from `.magmonium/` alone (ADR 0181): the
90
- * DesignSource through the same codec and codegen the editor runs, its
91
- * operations snapshot standing in for the live spec. With `tests`, the Emitted
92
- * tests beside the code as well.
93
- */
94
- function generate({ root = process.cwd(), tests = false } = {}) {
88
+ // The DesignSource read off disk and emitted, without touching the folder. What
89
+ // `generate` writes whole and `syncGenerated` diffs.
90
+ function emitFrom(root, tests) {
95
91
  if (!fs.existsSync(path.join(root, DESIGN_ROOT, 'index.json'))) {
96
92
  throw new Error(
97
93
  `${DESIGN_ROOT}/index.json not found in ${root} — not an app emitted by the editor`
@@ -119,7 +115,17 @@ function generate({ root = process.cwd(), tests = false } = {}) {
119
115
  ...source,
120
116
  operationOf: codegen.operationResolverOf(source.operations),
121
117
  };
122
- const files = codegen.emitGeneratedFiles(ws, stringify, tests);
118
+ return { codegen, files: codegen.emitGeneratedFiles(ws, stringify, tests) };
119
+ }
120
+
121
+ /**
122
+ * Regenerates the GeneratedSet from `.magmonium/` alone (ADR 0181): the
123
+ * DesignSource through the same codec and codegen the editor runs, its
124
+ * operations snapshot standing in for the live spec. With `tests`, the Emitted
125
+ * tests beside the code as well.
126
+ */
127
+ function generate({ root = process.cwd(), tests = false } = {}) {
128
+ const { codegen, files } = emitFrom(root, tests);
123
129
  const removed = clearGeneratedSet(root, codegen.GENERATED_SET);
124
130
  for (const file of files) {
125
131
  const target = path.join(root, file.path);
@@ -129,6 +135,180 @@ function generate({ root = process.cwd(), tests = false } = {}) {
129
135
  return { written: files.length, removed };
130
136
  }
131
137
 
138
+ // Every file under the GeneratedSet's folders and top-level globs, as POSIX
139
+ // paths from the app root, kept to what `inGeneratedSet` admits.
140
+ function listGeneratedSet(root, codegen) {
141
+ const found = [];
142
+ const walk = (dir) => {
143
+ if (!fs.existsSync(dir)) return;
144
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
145
+ const full = path.join(dir, entry.name);
146
+ if (entry.isDirectory()) walk(full);
147
+ else if (entry.isFile())
148
+ found.push(path.relative(root, full).split(path.sep).join('/'));
149
+ }
150
+ };
151
+ const appDir = path.join(root, 'src', 'app');
152
+ for (const line of codegen.GENERATED_SET) {
153
+ const rel = line.replace(/^\//, '');
154
+ if (rel.endsWith('/')) walk(path.join(root, rel));
155
+ }
156
+ if (fs.existsSync(appDir)) {
157
+ for (const name of fs.readdirSync(appDir)) {
158
+ const rel = `src/app/${name}`;
159
+ if (codegen.inGeneratedSet(rel) && fs.statSync(path.join(appDir, name)).isFile())
160
+ found.push(rel);
161
+ }
162
+ }
163
+ return [...new Set(found)].filter((rel) => codegen.inGeneratedSet(rel));
164
+ }
165
+
166
+ /**
167
+ * The GeneratedSet brought to what `.magmonium/` emits, touching only what
168
+ * differs: a file whose contents already match is left alone, so a running
169
+ * `ng serve` rebuilds for the edit and not for the app. A generated file edited
170
+ * by hand is rewritten; one added by hand is removed. Without `tests`, Emitted
171
+ * tests are kept — the editor writes them and `gen-code` does not.
172
+ */
173
+ function syncGenerated({ root = process.cwd(), tests = false } = {}) {
174
+ const { codegen, files } = emitFrom(root, tests);
175
+ const next = new Map(files.map((file) => [file.path, file.contents]));
176
+ const written = [];
177
+ const removed = [];
178
+ for (const [rel, contents] of next) {
179
+ const target = path.join(root, rel);
180
+ const current = fs.existsSync(target)
181
+ ? fs.readFileSync(target, 'utf8')
182
+ : undefined;
183
+ if (current === contents) continue;
184
+ fs.mkdirSync(path.dirname(target), { recursive: true });
185
+ fs.writeFileSync(target, contents);
186
+ written.push(rel);
187
+ }
188
+ for (const rel of listGeneratedSet(root, codegen)) {
189
+ if (next.has(rel)) continue;
190
+ if (!tests && rel.endsWith('.spec.ts')) continue;
191
+ fs.rmSync(path.join(root, rel), { force: true });
192
+ removed.push(rel);
193
+ }
194
+ return { written, removed, files: next, codegen };
195
+ }
196
+
197
+ /** Quiet time after the last change before regenerating. */
198
+ const WATCH_DELAY_MS = 100;
199
+ /** The same path rewritten this often inside the window means two writers disagree. */
200
+ const FIGHT_LIMIT = 3;
201
+ const FIGHT_WINDOW_MS = 10000;
202
+
203
+ /**
204
+ * Keeps the GeneratedSet in step with `.magmonium/` while the app is worked on
205
+ * from an IDE (ADR 0222): a design file saved regenerates the code at once, and
206
+ * a generated file edited or deleted by hand is put back. Hand-written code
207
+ * belongs in `src/app/custom/`, which this never reads or writes.
208
+ *
209
+ * With `run`, starts that command beside the watch (`ng serve`) and exits with
210
+ * it. Resolves a `close()` for tests.
211
+ */
212
+ async function watchGenerated({
213
+ root = process.cwd(),
214
+ tests = false,
215
+ run,
216
+ log = console.log,
217
+ delay = WATCH_DELAY_MS,
218
+ } = {}) {
219
+ const { watch } = await import('chokidar');
220
+ let last = new Map();
221
+ let codegen;
222
+ const fights = new Map();
223
+
224
+ const regenerate = (reason) => {
225
+ try {
226
+ const result = syncGenerated({ root, tests });
227
+ last = result.files;
228
+ codegen = result.codegen;
229
+ const now = Date.now();
230
+ const changed = [...result.written, ...result.removed];
231
+ for (const rel of changed) {
232
+ const hits = (fights.get(rel) || []).filter(
233
+ (at) => now - at < FIGHT_WINDOW_MS
234
+ );
235
+ hits.push(now);
236
+ fights.set(rel, hits);
237
+ }
238
+ if (changed.length)
239
+ log(
240
+ `🔁 gen-code: ${reason} → ${result.written.length} written, ${result.removed.length} removed`
241
+ );
242
+ } catch (error) {
243
+ // A design file mid-save or hand-broken: the code on disk stays as the
244
+ // last good emit until the next save reads cleanly.
245
+ log(`⚠️ gen-code: ${error.message}`);
246
+ }
247
+ };
248
+
249
+ regenerate('start');
250
+
251
+ let timer;
252
+ let reason = '';
253
+ const schedule = (why) => {
254
+ reason = why;
255
+ clearTimeout(timer);
256
+ timer = setTimeout(() => regenerate(reason), delay);
257
+ };
258
+
259
+ const onEvent = (file) => {
260
+ const rel = file.split(path.sep).join('/');
261
+ if (rel === DESIGN_ROOT || rel.startsWith(`${DESIGN_ROOT}/`)) {
262
+ schedule(`${rel} changed`);
263
+ return;
264
+ }
265
+ if (!codegen || !codegen.inGeneratedSet(rel)) return;
266
+ if (!tests && rel.endsWith('.spec.ts') && !last.has(rel)) return;
267
+ const target = path.join(root, rel);
268
+ const current = fs.existsSync(target)
269
+ ? fs.readFileSync(target, 'utf8')
270
+ : undefined;
271
+ // Its own write, or the editor's identical one.
272
+ if (current === last.get(rel)) return;
273
+ const hits = (fights.get(rel) || []).filter(
274
+ (at) => Date.now() - at < FIGHT_WINDOW_MS
275
+ );
276
+ if (hits.length >= FIGHT_LIMIT) {
277
+ log(
278
+ `⚠️ gen-code: ${rel} keeps changing under the watch — another writer emits it differently; left as is`
279
+ );
280
+ return;
281
+ }
282
+ schedule(`${rel} is generated — restored`);
283
+ };
284
+
285
+ const watcher = watch([DESIGN_ROOT, 'src/app'], {
286
+ cwd: root,
287
+ ignoreInitial: true,
288
+ ignored: (file) =>
289
+ file.split(path.sep).join('/').includes('src/app/custom'),
290
+ });
291
+ watcher.on('add', onEvent).on('change', onEvent).on('unlink', onEvent);
292
+ log(
293
+ `👀 gen-code: watching ${DESIGN_ROOT}/ — generated code is rebuilt on every design change; hand-written code goes in src/app/custom/`
294
+ );
295
+
296
+ const close = async () => {
297
+ clearTimeout(timer);
298
+ await watcher.close();
299
+ };
300
+
301
+ if (run) {
302
+ const { spawn } = require('child_process');
303
+ const child = spawn(run, { cwd: root, shell: true, stdio: 'inherit' });
304
+ child.on('exit', async (code) => {
305
+ await close();
306
+ process.exit(code ?? 0);
307
+ });
308
+ }
309
+ return { close };
310
+ }
311
+
132
312
  function genCodeCommand(program) {
133
313
  program
134
314
  .command('gen-code')
@@ -136,9 +316,24 @@ function genCodeCommand(program) {
136
316
  'Regenerate the generated code (features, pages, widgets, shared/lib, shared/type, router and provide overlays) from .magmonium/'
137
317
  )
138
318
  .option('--root <path>', 'App root (default: cwd)')
139
- .action((options) => {
319
+ .option(
320
+ '--watch',
321
+ 'Keep regenerating on every .magmonium/ change, and put back hand edits to generated files'
322
+ )
323
+ .option('--run <command>', 'With --watch: run this command beside the watch (e.g. "ng serve")')
324
+ .action(async (options) => {
325
+ const root = options.root || process.cwd();
326
+ if (options.watch) {
327
+ try {
328
+ await watchGenerated({ root, run: options.run });
329
+ } catch (error) {
330
+ console.error(`❌ gen-code: ${error.message}`);
331
+ process.exit(1);
332
+ }
333
+ return;
334
+ }
140
335
  try {
141
- const { written } = generate({ root: options.root || process.cwd() });
336
+ const { written } = generate({ root });
142
337
  console.log(
143
338
  `✅ gen-code: ${written} file(s) generated from ${DESIGN_ROOT}/`
144
339
  );
@@ -154,3 +349,6 @@ module.exports.generate = generate;
154
349
  module.exports.isNewer = isNewer;
155
350
  module.exports.clearGeneratedSet = clearGeneratedSet;
156
351
  module.exports.readDesignFiles = readDesignFiles;
352
+ module.exports.syncGenerated = syncGenerated;
353
+ module.exports.watchGenerated = watchGenerated;
354
+ module.exports.listGeneratedSet = listGeneratedSet;
@@ -48,9 +48,11 @@ async function gesture({ root = process.cwd(), name, args, batch, write = false
48
48
  if (!read.ok || !read.source) return invalid('design-unreadable', read.refusal);
49
49
  const source = read.source;
50
50
 
51
- // `function-save` compiles the body the way the function editor does.
51
+ // `function-save` compiles the body the way the function editor does, then
52
+ // runs its cases the way Run cases does (0132_01).
52
53
  const ts = appTypeScript(root);
53
54
  gestures.setFunctionBodyCheck(ts ? gestures.functionBodyCheckFor(ts) : undefined);
55
+ gestures.setFunctionCaseRun(ts ? gestures.functionCaseRunFor(ts) : undefined);
54
56
 
55
57
  const run = gestures.runBatch(source, resolved);
56
58
  report.notes = run.notes;
@@ -468,6 +468,51 @@ function messageText(key) {
468
468
  return messageTexts[key] ?? key;
469
469
  }
470
470
 
471
+ // The packages whose version a design is stamped with on `--write`, by the
472
+ // `index.json` field that records it.
473
+ const PIN_STAMPS = { codegen: '@magmonium/cli', one: '@magmonium/one' };
474
+
475
+ /**
476
+ * A package the AppRepo's `package.json` pins below the version the design is
477
+ * stamped with (0132_03): the AppRepo's `gen-code` then refuses the design, or
478
+ * the emitted code compiles against an older `@magmonium/one` than it was
479
+ * written for — `ScreenOverlayTrigger` has no `screen` in 0.4.55. Advisory: the
480
+ * design is sound, the shell around it is behind. Ranges read as their floor.
481
+ */
482
+ function pinsBehindStamp(packageJson, indexText) {
483
+ let index;
484
+ try {
485
+ index = JSON.parse(indexText || '{}');
486
+ } catch {
487
+ return [];
488
+ }
489
+ const pins = { ...(packageJson?.dependencies || {}), ...(packageJson?.devDependencies || {}) };
490
+ return Object.entries(PIN_STAMPS).flatMap(([field, name]) => {
491
+ const stamp = index[field];
492
+ const pin = typeof pins[name] === 'string' ? pins[name].replace(/^[^\d]*/, '') : '';
493
+ if (!stamp || !pin || !isNewer(stamp, pin)) return [];
494
+ return [
495
+ {
496
+ id: `pins-behind-stamp::${name}`,
497
+ invariant: 'pins-behind-stamp',
498
+ message: 'pins-behind-stamp',
499
+ text: `package.json pins ${name} ${pin}, below the ${stamp} this design is stamped with — run npm install --save-exact ${name}@${stamp}`,
500
+ subject: `${name} ${pin} < ${stamp}`,
501
+ severity: 'advisory',
502
+ target: { kind: 'panel', panel: 'config' },
503
+ },
504
+ ];
505
+ });
506
+ }
507
+
508
+ function readPackageJson(root) {
509
+ try {
510
+ return JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'));
511
+ } catch {
512
+ return undefined;
513
+ }
514
+ }
515
+
471
516
  function controlConfigsCatalog() {
472
517
  const file = path.join(__dirname, '..', '..', 'codegen', 'control-configs.json');
473
518
  return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, 'utf8')) : undefined;
@@ -619,14 +664,10 @@ async function validate({
619
664
  ...source,
620
665
  operationOf: codegen.operationResolverOf(operations),
621
666
  };
622
- report.violations = findViolations(
623
- bundles,
624
- source,
625
- catalog,
626
- ws.operationOf,
627
- files,
628
- ts
629
- );
667
+ report.violations = [
668
+ ...findViolations(bundles, source, catalog, ws.operationOf, files, ts),
669
+ ...pinsBehindStamp(readPackageJson(root), files[`${DESIGN_ROOT}/index.json`]),
670
+ ];
630
671
 
631
672
  // What the design already held at the baseline is not this change's to fix:
632
673
  // marked, listed, and left out of the status.
@@ -777,4 +818,5 @@ module.exports.themeCatalogOf = themeCatalogOf;
777
818
  module.exports.appTypeScript = appTypeScript;
778
819
  module.exports.readDesignFilesAt = readDesignFilesAt;
779
820
  module.exports.messageText = messageText;
821
+ module.exports.pinsBehindStamp = pinsBehindStamp;
780
822
  module.exports.DESIGN_ROOT = DESIGN_ROOT;
@@ -23,10 +23,12 @@ __export(gesture_catalog_exports, {
23
23
  GESTURES: () => GESTURES,
24
24
  applyGesture: () => applyGesture,
25
25
  functionBodyCheckFor: () => functionBodyCheckFor,
26
+ functionCaseRunFor: () => functionCaseRunFor,
26
27
  gestureByName: () => gestureByName,
27
28
  runBatch: () => runBatch,
28
29
  runGesture: () => runGesture,
29
- setFunctionBodyCheck: () => setFunctionBodyCheck
30
+ setFunctionBodyCheck: () => setFunctionBodyCheck,
31
+ setFunctionCaseRun: () => setFunctionCaseRun
30
32
  });
31
33
  module.exports = __toCommonJS(gesture_catalog_exports);
32
34
 
@@ -1481,6 +1483,12 @@ function planFunctionReplace(homes, fromId, toId, holders) {
1481
1483
  return { rebind, homes: { functions, features } };
1482
1484
  }
1483
1485
  var bodyCheck;
1486
+ var caseRun;
1487
+ var setFunctionCaseRun = (run) => {
1488
+ const previous = caseRun;
1489
+ caseRun = run;
1490
+ return previous;
1491
+ };
1484
1492
  var setFunctionBodyCheck = (check) => {
1485
1493
  const previous = bodyCheck;
1486
1494
  bodyCheck = check;
@@ -1520,6 +1528,18 @@ var functionSave = {
1520
1528
  if (clash) return refuse4(clash);
1521
1529
  const problems = bodyCheck?.(ctx.source, fn, home);
1522
1530
  if (problems?.length) return refuse4("function-body-invalid", { problems });
1531
+ const results = caseRun?.(ctx.source, fn, home) ?? [];
1532
+ const failedAt = results.findIndex((result) => !result.passed);
1533
+ if (failedAt >= 0) {
1534
+ const failed = results[failedAt];
1535
+ const entry = (fn.cases ?? [])[failedAt];
1536
+ return refuse4("case-failed", {
1537
+ case: entry.name,
1538
+ args: entry.args,
1539
+ expected: entry.expected,
1540
+ ...failed.ok ? { actual: failed.actual } : { error: failed.error }
1541
+ });
1542
+ }
1523
1543
  const moved = landing.nowFeature ? landing.wasApp : landing.wasFeature;
1524
1544
  const next = savedFunctionHomes(homes, fn, landing);
1525
1545
  return {
@@ -2253,6 +2273,10 @@ function purity(ts, file, prependLines, bodyStart, bodyLineOffset) {
2253
2273
  return found;
2254
2274
  }
2255
2275
  var functionBodyCheckFor = (ts) => (source, fn, featureId) => {
2276
+ const scope = functionScopeOf(source, featureId);
2277
+ return checkFunctionBody(ts, scope.shapes, fn, scope.allowlist, scope.enums);
2278
+ };
2279
+ var functionScopeOf = (source, featureId) => {
2256
2280
  const shapes = { ...source.sharedShapes };
2257
2281
  Object.values(source.features).forEach((feature) => Object.assign(shapes, feature.shapes));
2258
2282
  source.screens.forEach(({ state }) => Object.assign(shapes, (0, import_codegen15.formShapeMap)(state.controlMap)));
@@ -2265,7 +2289,86 @@ var functionBodyCheckFor = (ts) => (source, fn, featureId) => {
2265
2289
  );
2266
2290
  return found.some((entry) => entry.library) ? found : [...found, import_codegen15.SORT_DIRECTION_ENUM];
2267
2291
  })() : [import_codegen15.SORT_DIRECTION_ENUM];
2268
- return checkFunctionBody(ts, shapes, fn, source.npmAllowlist ?? {}, enums);
2292
+ return { shapes, allowlist: source.npmAllowlist ?? {}, enums };
2293
+ };
2294
+
2295
+ // apps/m-one-ui/src/app/pages/design/lib/function-case-runner.ts
2296
+ var import_codegen16 = require("./index.js");
2297
+ function transpileFunction(ts, shapes, fn, cases, enums) {
2298
+ const named = fn.name.trim() ? fn : { ...fn, name: "name" };
2299
+ const shapeSource = ambientTypes(shapes, named, enums);
2300
+ const caseSource = cases.map((entry) => `[[${entry.args.join(", ")}], ${entry.expected}]`).join(",\n");
2301
+ const source = `${shapeSource}${(0, import_codegen16.signatureText)(shapes, named, enums)}
2302
+ ${fn.body}
2303
+ };
2304
+ `.replace(
2305
+ /^export\s+/gm,
2306
+ ""
2307
+ );
2308
+ const { outputText, diagnostics } = ts.transpileModule(
2309
+ `${source}const __cases: unknown = [
2310
+ ${caseSource}
2311
+ ];
2312
+ `,
2313
+ {
2314
+ compilerOptions: {
2315
+ target: ts.ScriptTarget.ES2020,
2316
+ // TS 6.0 reports `module: None` as a deprecation diagnostic; this
2317
+ // runner treats Error-category diagnostics as fatal, so the
2318
+ // deprecation has to be acknowledged explicitly.
2319
+ ignoreDeprecations: "6.0",
2320
+ module: ts.ModuleKind.None,
2321
+ strict: true
2322
+ },
2323
+ reportDiagnostics: true
2324
+ }
2325
+ );
2326
+ const fatal = (diagnostics ?? []).filter(
2327
+ (d) => d.category === ts.DiagnosticCategory.Error
2328
+ );
2329
+ if (fatal.length) {
2330
+ return {
2331
+ values: [],
2332
+ error: fatal.map((d) => ts.flattenDiagnosticMessageText(d.messageText, " ")).join("\n")
2333
+ };
2334
+ }
2335
+ try {
2336
+ const [impl, values] = new Function(
2337
+ `${outputText}
2338
+ return [${named.name}, __cases];`
2339
+ )();
2340
+ return { impl, values };
2341
+ } catch (error) {
2342
+ return {
2343
+ values: [],
2344
+ error: error instanceof Error ? error.message : String(error)
2345
+ };
2346
+ }
2347
+ }
2348
+ var errorText = (error) => error instanceof Error ? error.message : String(error);
2349
+ var functionCaseRunFor = (ts) => (source, fn, featureId) => {
2350
+ const cases = fn.cases ?? [];
2351
+ if (!cases.length) return [];
2352
+ const scope = functionScopeOf(source, featureId);
2353
+ const runnable = cases.filter((entry) => (0, import_codegen16.caseFits)(fn, entry, scope.shapes));
2354
+ const compiled = transpileFunction(ts, scope.shapes, fn, runnable, scope.enums);
2355
+ const impl = compiled.impl;
2356
+ if (!impl)
2357
+ return cases.map(() => ({ ok: false, passed: false, error: compiled.error ?? "" }));
2358
+ let next = 0;
2359
+ return cases.map((entry) => {
2360
+ if (!(0, import_codegen16.caseFits)(fn, entry, scope.shapes))
2361
+ return { ok: false, passed: false, error: "The case no longer fits the signature." };
2362
+ const [args, expected] = compiled.values[next++];
2363
+ try {
2364
+ const actual = impl(...args);
2365
+ if (actual instanceof Promise)
2366
+ return { ok: false, passed: false, error: "The body answered a Promise." };
2367
+ return { ok: true, passed: (0, import_codegen16.caseEquals)(actual, expected), actual };
2368
+ } catch (error) {
2369
+ return { ok: false, passed: false, error: errorText(error) };
2370
+ }
2371
+ });
2269
2372
  };
2270
2373
 
2271
2374
  // apps/m-one-ui/src/app/pages/design/lib/gesture-catalog.ts
@@ -2324,8 +2427,10 @@ var runBatch = (source, steps) => {
2324
2427
  GESTURES,
2325
2428
  applyGesture,
2326
2429
  functionBodyCheckFor,
2430
+ functionCaseRunFor,
2327
2431
  gestureByName,
2328
2432
  runBatch,
2329
2433
  runGesture,
2330
- setFunctionBodyCheck
2434
+ setFunctionBodyCheck,
2435
+ setFunctionCaseRun
2331
2436
  });