@canonical/summon 0.37.0 → 0.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/dist/src/index.d.ts +15 -0
  2. package/dist/src/index.js +16 -0
  3. package/dist/src/index.js.map +1 -0
  4. package/package.json +17 -12
  5. package/src/bin.tsx +238 -0
  6. package/src/completion.test.ts +202 -0
  7. package/src/completion.ts +492 -0
  8. package/src/components/App.askMissing.test.tsx +164 -0
  9. package/src/components/App.confirmGate.test.tsx +111 -0
  10. package/src/components/App.escBack.test.tsx +98 -0
  11. package/src/components/App.invalidAnswer.test.tsx +71 -0
  12. package/src/components/App.tsx +1305 -0
  13. package/src/components/ExecutionProgress.tsx +222 -0
  14. package/src/components/FileTreePreview.tsx +97 -0
  15. package/src/components/PromptSequence.tsx +558 -0
  16. package/src/components/Spinner.tsx +36 -0
  17. package/src/components/index.ts +16 -0
  18. package/src/components/undoPlan.test.ts +99 -0
  19. package/src/components/undoPlan.ts +70 -0
  20. package/src/discovery/index.ts +1 -0
  21. package/src/discovery/loadGenerator.ts +40 -0
  22. package/src/display/index.ts +2 -0
  23. package/src/display/printGeneratorHelp.ts +130 -0
  24. package/src/display/printNode.ts +76 -0
  25. package/src/index.ts +16 -0
  26. package/src/registration/buildCommandBarrel.test.ts +80 -0
  27. package/src/registration/buildCommandBarrel.ts +66 -0
  28. package/src/registration/conformance.subprocess.test.ts +192 -0
  29. package/src/registration/index.ts +2 -0
  30. package/src/registration/interaction.subprocess.test.ts +458 -0
  31. package/src/registration/registerFromBarrel.tsx +501 -0
  32. package/src/registration/resolveMode.test.ts +118 -0
  33. package/src/registration/resolveMode.ts +52 -0
  34. package/src/testing/globalSetup.test.ts +165 -0
  35. package/src/testing/globalSetup.ts +501 -0
  36. package/src/ui/index.tsx +31 -0
@@ -0,0 +1,458 @@
1
+ /**
2
+ * The interaction-decision corners on the REAL summon bin, one subprocess per
3
+ * cell — the summon-side pins of the shared truth table (§B of the parity
4
+ * contract; the 32-cell exhaustive test lives in summon-core).
5
+ *
6
+ * Non-TTY throughout (a piped child is the CI shape). Covered here:
7
+ * - row 6: a bare non-TTY mutation REFUSES (message + exit 2, no Ink mount);
8
+ * - row 5: a fully-explicit non-TTY invocation runs without `--yes`;
9
+ * - row 1/2: `--dry-run`/`--undo` are batch renders, dry-run taking
10
+ * precedence, and a missing/invalid batch answer errors loudly (exit 2);
11
+ * - the run arm's exit codes: an execution failure renders in the App and
12
+ * exits 1 (the cross-CLI matrix — never exit 0 on a rendered failure);
13
+ * - the exit classification's INFORMATIONAL branches: `--help`/`--version`
14
+ * exit 0, the root invoked with options but no command carries the help
15
+ * error's own exit 1, the implicit `help` command exits 0 — the branches
16
+ * a blanket exit-2 refactor would silently break — and the projection's
17
+ * bare-namespace arm (help on stderr, exit 1, the `help [command]` row);
18
+ * - the designed excess-positional error (exit 2).
19
+ */
20
+
21
+ import { execFileSync, spawnSync } from "node:child_process";
22
+ import { mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs";
23
+ import { tmpdir } from "node:os";
24
+ import { dirname, join, resolve } from "node:path";
25
+ import { fileURLToPath } from "node:url";
26
+ import { describe, expect, it } from "vitest";
27
+
28
+ const here = dirname(fileURLToPath(import.meta.url));
29
+ const packageRoot = resolve(here, "../..");
30
+ const repoRoot = resolve(packageRoot, "../..");
31
+ const summonBin = join(packageRoot, "src/bin.tsx");
32
+ const taskDist = join(repoRoot, "runtime/task/dist/esm/index.js");
33
+ const coreDist = join(repoRoot, "summon/core/dist/esm/index.js");
34
+
35
+ const freshCwd = (): string => mkdtempSync(join(tmpdir(), "summon-inter-"));
36
+
37
+ /**
38
+ * A fixture generator tree served via `--generators`: one `gadget` generator
39
+ * with a REQUIRED (default-less) prompt, a select, and a validated text — the
40
+ * shapes the builtin generators (all-defaulted) cannot exercise.
41
+ */
42
+ function writeFixtureGenerators(): string {
43
+ const dir = mkdtempSync(join(tmpdir(), "summon-fixture-gen-"));
44
+ mkdirSync(join(dir, "gadget"));
45
+ writeFileSync(
46
+ join(dir, "gadget", "index.js"),
47
+ `import { writeFile } from ${JSON.stringify(`file://${taskDist}`)};
48
+ export default {
49
+ meta: { name: "gadget", displayName: "gadget", description: "A fixture gadget", version: "0.0.1" },
50
+ prompts: [
51
+ { name: "title", type: "text", message: "Title:" },
52
+ { name: "kind", type: "select", message: "Kind:", choices: [
53
+ { label: "a", value: "a" }, { label: "b", value: "b" },
54
+ ], default: "a" },
55
+ { name: "outPath", type: "text", message: "Output path:", default: "out.txt",
56
+ validate: (v) => v !== "bad" || "path must not be bad" },
57
+ ],
58
+ generate: (answers) =>
59
+ writeFile(answers.outPath, "# " + answers.title + " (" + answers.kind + ")\\n"),
60
+ };
61
+ `,
62
+ );
63
+ // A generator whose `generate` throws a PLAIN Error — the non-typed class
64
+ // (application/react's name-derivation throw is the shipped shape). §3:
65
+ // any execution failure past the validation gate exits 1 in every arm.
66
+ mkdirSync(join(dir, "explosive"));
67
+ writeFileSync(
68
+ join(dir, "explosive", "index.js"),
69
+ `export default {
70
+ meta: { name: "explosive", displayName: "explosive", description: "A throwing fixture", version: "0.0.1" },
71
+ prompts: [],
72
+ generate: () => { throw new Error("fixture generate exploded"); },
73
+ };
74
+ `,
75
+ );
76
+ // A generator whose `generate` RETURNS nothing (the author forgot the
77
+ // `return` — plain-JS generators are unchecked) — the success-path twin of
78
+ // `explosive`: pre-validation the run arm HUNG forever (the App's
79
+ // `undefined` sentinel means "handled", so no state was set and
80
+ // `waitUntilExit` never resolved) and the batch arms threw the
81
+ // interpreter's incidental TypeError instead of a named line.
82
+ mkdirSync(join(dir, "silent"));
83
+ writeFileSync(
84
+ join(dir, "silent", "index.js"),
85
+ `export default {
86
+ meta: { name: "silent", displayName: "silent", description: "A fixture that forgets its return", version: "0.0.1" },
87
+ prompts: [],
88
+ generate: () => { /* author forgot the return */ },
89
+ };
90
+ `,
91
+ );
92
+ // A generator with a CROSS-answer guard raised as summon-core's typed
93
+ // invalid answer — two answers only valid together; no shipped generator
94
+ // raises one today (application/react's former guard is gone with its
95
+ // prompts), so this fixture keeps the pathway covered.
96
+ mkdirSync(join(dir, "guarded"));
97
+ writeFileSync(
98
+ join(dir, "guarded", "index.js"),
99
+ `import { writeFile } from ${JSON.stringify(`file://${taskDist}`)};
100
+ import { invalidAnswersError } from ${JSON.stringify(`file://${coreDist}`)};
101
+ export default {
102
+ meta: { name: "guarded", displayName: "guarded", description: "A guarded fixture", version: "0.0.1" },
103
+ prompts: [
104
+ { name: "ok", type: "confirm", message: "OK?", default: true },
105
+ ],
106
+ generate: (answers) => {
107
+ if (answers.ok !== true) {
108
+ throw invalidAnswersError("OK is required — drop --no-ok.");
109
+ }
110
+ return writeFile("ok.txt", "ok\\n");
111
+ },
112
+ };
113
+ `,
114
+ );
115
+ return dir;
116
+ }
117
+
118
+ const fixtureDir = writeFixtureGenerators();
119
+
120
+ /**
121
+ * Spawn the real bin non-interactively; never throws on nonzero exit. An
122
+ * optional spawn-level timeout (status `null` when it fires) exists for the
123
+ * cells whose PRE-FIX failure mode was a hang — a sync spawn cannot be
124
+ * interrupted by vitest's own test timeout.
125
+ */
126
+ function run(
127
+ args: readonly string[],
128
+ cwd: string,
129
+ timeoutMs?: number,
130
+ ): { status: number | null; stdout: string; stderr: string } {
131
+ const result = spawnSync("bun", [summonBin, ...args], {
132
+ cwd,
133
+ encoding: "utf-8",
134
+ input: "",
135
+ ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }),
136
+ });
137
+ return {
138
+ status: result.status,
139
+ stdout: result.stdout ?? "",
140
+ stderr: result.stderr ?? "",
141
+ };
142
+ }
143
+
144
+ describe("row 6 — non-TTY refusal (PROTECTED)", () => {
145
+ it("a bare mutation refuses with the shared message, exit 2, nothing written", () => {
146
+ const cwd = freshCwd();
147
+ const { status, stderr } = run(["example", "hello"], cwd);
148
+ expect(status).toBe(2);
149
+ expect(stderr).toContain(
150
+ "Refusing to scaffold in a non-interactive run without complete input. " +
151
+ "Pass --yes to accept defaults, --dry-run to preview, or provide every answer as a flag. " +
152
+ "Missing: --name, --description, --greeting, --no-with-readme.",
153
+ );
154
+ expect(readdirSync(cwd)).toEqual([]);
155
+ }, 60_000);
156
+
157
+ it("partial flags still refuse, naming only what is missing", () => {
158
+ const cwd = freshCwd();
159
+ const { status, stderr } = run(
160
+ ["example", "hello", "--name=demo", "--greeting=Hi"],
161
+ cwd,
162
+ );
163
+ expect(status).toBe(2);
164
+ expect(stderr).toContain("Missing: --description, --no-with-readme.");
165
+ expect(readdirSync(cwd)).toEqual([]);
166
+ }, 60_000);
167
+ });
168
+
169
+ describe("row 5 — fully-explicit non-TTY runs without --yes", () => {
170
+ it("generates when every answer is explicit", () => {
171
+ const cwd = freshCwd();
172
+ const { status } = run(
173
+ [
174
+ "example",
175
+ "hello",
176
+ "--name=demo",
177
+ "--description=A demo.",
178
+ "--greeting=Hi",
179
+ "--no-with-readme",
180
+ ],
181
+ cwd,
182
+ );
183
+ expect(status).toBe(0);
184
+ expect(readdirSync(cwd)).toContain("demo");
185
+ expect(readdirSync(join(cwd, "demo"))).not.toContain("README.md");
186
+ }, 60_000);
187
+
188
+ it("fixture: explicit title+kind+path runs (select equal to its default is still explicit)", () => {
189
+ const cwd = freshCwd();
190
+ const { status } = run(
191
+ [
192
+ "--generators",
193
+ fixtureDir,
194
+ "gadget",
195
+ "--title=T",
196
+ "--kind=a",
197
+ "--out-path=made.txt",
198
+ ],
199
+ cwd,
200
+ );
201
+ expect(status).toBe(0);
202
+ expect(readdirSync(cwd)).toEqual(["made.txt"]);
203
+ }, 60_000);
204
+ });
205
+
206
+ describe("rows 1–2 — batch dry-run/undo, dry-run precedence, loud failures", () => {
207
+ it("a bare --dry-run renders the batch plan from defaults, writes nothing", () => {
208
+ const cwd = freshCwd();
209
+ const { status, stdout } = run(["example", "hello", "--dry-run"], cwd);
210
+ expect(status).toBe(0);
211
+ expect(stdout).toContain("Plan:");
212
+ expect(stdout).toContain("Dry-run complete. No files were modified.");
213
+ expect(readdirSync(cwd)).toEqual([]);
214
+ }, 60_000);
215
+
216
+ it("--dry-run takes precedence over --undo", () => {
217
+ const cwd = freshCwd();
218
+ const { status, stdout } = run(
219
+ ["example", "hello", "--dry-run", "--undo"],
220
+ cwd,
221
+ );
222
+ expect(status).toBe(0);
223
+ expect(stdout).toContain("Plan:");
224
+ expect(stdout).not.toContain("Undo");
225
+ }, 60_000);
226
+
227
+ it("--undo without --yes runs the batch undo (no wizard, no prompt)", () => {
228
+ const cwd = freshCwd();
229
+ execFileSync(
230
+ "bun",
231
+ [
232
+ summonBin,
233
+ "example",
234
+ "hello",
235
+ "--name=demo",
236
+ "--description=D.",
237
+ "--greeting=Hi",
238
+ "--yes",
239
+ ],
240
+ { cwd, stdio: "pipe", input: "" },
241
+ );
242
+ expect(readdirSync(cwd)).toContain("demo");
243
+ const { status, stdout } = run(
244
+ [
245
+ "example",
246
+ "hello",
247
+ "--name=demo",
248
+ "--description=D.",
249
+ "--greeting=Hi",
250
+ "--undo",
251
+ ],
252
+ cwd,
253
+ );
254
+ expect(status).toBe(0);
255
+ expect(stdout).toContain("Undo complete");
256
+ }, 60_000);
257
+
258
+ it("a batch dry-run missing a required answer errors loudly, exit 2", () => {
259
+ const cwd = freshCwd();
260
+ const { status, stderr } = run(
261
+ ["--generators", fixtureDir, "gadget", "--dry-run"],
262
+ cwd,
263
+ );
264
+ expect(status).toBe(2);
265
+ expect(stderr).toContain(
266
+ "Missing required flag --title (Title:). Provide it non-interactively, or run interactively to be prompted.",
267
+ );
268
+ expect(readdirSync(cwd)).toEqual([]);
269
+ }, 60_000);
270
+
271
+ it("a batch dry-run with an invalid answer echoes the value, exit 2", () => {
272
+ const cwd = freshCwd();
273
+ const { status, stderr } = run(
274
+ [
275
+ "--generators",
276
+ fixtureDir,
277
+ "gadget",
278
+ "--dry-run",
279
+ "--title=T",
280
+ "--out-path=bad",
281
+ ],
282
+ cwd,
283
+ );
284
+ expect(status).toBe(2);
285
+ expect(stderr).toContain('Invalid --out-path "bad": path must not be bad');
286
+ expect(readdirSync(cwd)).toEqual([]);
287
+ }, 60_000);
288
+
289
+ it("a generator-raised typed invalid answer fails the batch the same way — bare message, exit 2, no stack", () => {
290
+ const cwd = freshCwd();
291
+ const { status, stderr } = run(
292
+ ["--generators", fixtureDir, "guarded", "--no-ok", "--dry-run"],
293
+ cwd,
294
+ );
295
+ expect(status).toBe(2);
296
+ // The WHOLE stream is the message — validateAnswers' own convention.
297
+ expect(stderr).toBe("OK is required — drop --no-ok.\n");
298
+ expect(readdirSync(cwd)).toEqual([]);
299
+ }, 60_000);
300
+
301
+ it("a plain Error from generate() fails the batch as a bare line, exit 1, no stack", () => {
302
+ const cwd = freshCwd();
303
+ const { status, stderr } = run(
304
+ ["--generators", fixtureDir, "explosive", "--dry-run"],
305
+ cwd,
306
+ );
307
+ expect(status).toBe(1);
308
+ // The WHOLE stream is the bare message line — never the un-awaited
309
+ // action's unhandled-rejection stack (a 1.2 KB source frame pre-fix).
310
+ expect(stderr).toBe("fixture generate exploded\n");
311
+ expect(readdirSync(cwd)).toEqual([]);
312
+ }, 60_000);
313
+
314
+ it("a generate() returning no task fails the batch with the NAMED line, exit 1", () => {
315
+ const cwd = freshCwd();
316
+ const { status, stderr } = run(
317
+ ["--generators", fixtureDir, "silent", "--dry-run"],
318
+ cwd,
319
+ );
320
+ expect(status).toBe(1);
321
+ // The named generator-bug line, whole stream — pre-fix this was the
322
+ // interpreter's incidental TypeError
323
+ // (`undefined is not an object (evaluating 'cur._tag')`).
324
+ expect(stderr).toBe("silent's generate returned no task\n");
325
+ expect(readdirSync(cwd)).toEqual([]);
326
+ }, 60_000);
327
+ });
328
+
329
+ describe("the run arm's exit codes — a rendered failure never exits 0", () => {
330
+ it("a generator execution failure in the run arm exits 1, error rendered in the App", () => {
331
+ const cwd = freshCwd();
332
+ // `made.txt` pre-created as a DIRECTORY: gadget's writeFile fails
333
+ // mid-execution (EISDIR), the App renders the failure on stdout, and
334
+ // the exit code must carry pragma's runtime class (mapExitCode → 1) —
335
+ // before round 7 every App-rendered failure exited 0.
336
+ mkdirSync(join(cwd, "made.txt"));
337
+ const { status, stdout } = run(
338
+ [
339
+ "--generators",
340
+ fixtureDir,
341
+ "gadget",
342
+ "--title=T",
343
+ "--kind=a",
344
+ "--out-path=made.txt",
345
+ "--yes",
346
+ ],
347
+ cwd,
348
+ );
349
+ expect(status).toBe(1);
350
+ expect(stdout).toContain("✗ Error:");
351
+ expect(stdout).toContain("Code: EXECUTION_ERROR");
352
+ }, 60_000);
353
+
354
+ it("a plain Error from generate() in the run arm enters the error phase — exit 1, nothing written", () => {
355
+ const cwd = freshCwd();
356
+ // Pre-fix, the App's catch re-threw the non-typed generate() throw into
357
+ // Ink's error boundary: a source-frame crash box on stdout and EXIT 0 —
358
+ // the silent-success class §3 forbids ("a rendered failure never exits
359
+ // 0"). Now it is the App's own error phase with the runtime class.
360
+ const { status, stdout } = run(
361
+ ["--generators", fixtureDir, "explosive", "--yes"],
362
+ cwd,
363
+ );
364
+ expect(status).toBe(1);
365
+ expect(stdout).toContain("✗ Error: fixture generate exploded");
366
+ expect(stdout).toContain("Code: GENERATE_ERROR");
367
+ expect(readdirSync(cwd)).toEqual([]);
368
+ }, 60_000);
369
+
370
+ it("a generate() returning no task enters the error phase in the run arm — exit 1, never a hang", () => {
371
+ const cwd = freshCwd();
372
+ // Pre-fix this HUNG forever: `generateTask` returned generate()'s own
373
+ // undefined, its call sites read that as "error already reported", no
374
+ // state was set and `waitUntilExit` never resolved — a spinner until
375
+ // the CI timeout, stderr empty, no exit code (measured: timeout-kill,
376
+ // exit 124). The success path is now validated: the named
377
+ // generator-bug line with the runtime class, like every other
378
+ // generate() failure.
379
+ const { status, stdout } = run(
380
+ ["--generators", fixtureDir, "silent", "--yes"],
381
+ cwd,
382
+ 30_000, // a regression hangs; the spawn timeout turns that into status null
383
+ );
384
+ expect(status).toBe(1);
385
+ expect(stdout).toContain("✗ Error: silent's generate returned no task");
386
+ expect(stdout).toContain("Code: GENERATE_ERROR");
387
+ expect(readdirSync(cwd)).toEqual([]);
388
+ }, 60_000);
389
+ });
390
+
391
+ describe("the exit classification's informational branches", () => {
392
+ // Only the usage branch (exit 2) had a pin. `--help`/`--version` pin the
393
+ // 0-branches of bin.tsx's exitOverride catch; the `commander.help` branch
394
+ // (the one that preserves the error's OWN exit code) is reached by the
395
+ // ROOT invoked with options but no command (help on stderr, exit 1) and
396
+ // by the implicit `help` command (stdout help, exit 0) — pinned here so a
397
+ // refactor that collapses the classification to a blanket exit 2 turns
398
+ // red. The bare NAMESPACE never reaches the catch: the projection's
399
+ // namespace action writes the help and sets exit 1 itself, so its cell
400
+ // pins the projection — plus the `help [command]` row that ONLY summon's
401
+ // helpCommand(true) host hook keeps alive.
402
+ it("`--help` exits 0 with the usage on stdout", () => {
403
+ const { status, stdout, stderr } = run(["--help"], freshCwd());
404
+ expect(status).toBe(0);
405
+ expect(stdout).toContain("Usage:");
406
+ expect(stderr).toBe("");
407
+ }, 60_000);
408
+
409
+ it("`--version` exits 0", () => {
410
+ const { status, stdout } = run(["--version"], freshCwd());
411
+ expect(status).toBe(0);
412
+ expect(stdout.trim()).toMatch(/^\d+\.\d+\.\d+$/);
413
+ }, 60_000);
414
+
415
+ it("the root with options but no command prints the root help on STDERR, exit 1", () => {
416
+ // The one argv shape that still raises `commander.help` at exit 1: the
417
+ // root has subcommands and no action handler, so Commander helps loudly.
418
+ const { status, stdout, stderr } = run(
419
+ ["--generators", fixtureDir],
420
+ freshCwd(),
421
+ );
422
+ expect(status).toBe(1);
423
+ expect(stderr).toContain("Usage: summon");
424
+ expect(stdout).toBe("");
425
+ }, 60_000);
426
+
427
+ it("the implicit `help` command exits 0 with the root usage on stdout", () => {
428
+ const { status, stdout } = run(["help"], freshCwd());
429
+ expect(status).toBe(0);
430
+ expect(stdout).toContain("Usage: summon");
431
+ }, 60_000);
432
+
433
+ it("`<namespace> help` exits 0 with the namespace usage on stdout — the helpCommand(true) hook", () => {
434
+ const { status, stdout } = run(["example", "help"], freshCwd());
435
+ expect(status).toBe(0);
436
+ expect(stdout).toContain("Usage: summon example");
437
+ }, 60_000);
438
+
439
+ it("a bare namespace prints its help on STDERR and exits 1 — the projection's arm, with the help row", () => {
440
+ const { status, stdout, stderr } = run(["example"], freshCwd());
441
+ expect(status).toBe(1);
442
+ expect(stderr).toContain("Usage:");
443
+ // The row exists ONLY because summon's host declares helpCommand(true) —
444
+ // the projection's namespace action suppresses Commander's implicit one.
445
+ expect(stderr).toContain("help [command]");
446
+ expect(stdout).toBe("");
447
+ }, 60_000);
448
+ });
449
+
450
+ describe("the designed excess-positional error", () => {
451
+ it("a stray operand errors with the designed message, exit 2, nothing written", () => {
452
+ const cwd = freshCwd();
453
+ const { status, stderr } = run(["example", "hello", "stray", "--yes"], cwd);
454
+ expect(status).toBe(2);
455
+ expect(stderr).toContain('error: unexpected argument "stray"');
456
+ expect(readdirSync(cwd)).toEqual([]);
457
+ }, 60_000);
458
+ });