@canonical/summon 0.33.0 → 0.35.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 (33) hide show
  1. package/dist/src/bin.js +35 -2
  2. package/dist/src/bin.js.map +1 -1
  3. package/dist/src/components/App.d.ts +23 -2
  4. package/dist/src/components/App.js +174 -39
  5. package/dist/src/components/App.js.map +1 -1
  6. package/dist/src/components/ExecutionProgress.d.ts +1 -1
  7. package/dist/src/components/ExecutionProgress.js +1 -1
  8. package/dist/src/components/ExecutionProgress.js.map +1 -1
  9. package/dist/src/components/PromptSequence.d.ts +9 -1
  10. package/dist/src/components/PromptSequence.js +48 -23
  11. package/dist/src/components/PromptSequence.js.map +1 -1
  12. package/dist/src/components/undoPlan.d.ts +35 -0
  13. package/dist/src/components/undoPlan.js +58 -0
  14. package/dist/src/components/undoPlan.js.map +1 -0
  15. package/dist/src/discovery/loadGenerator.js +4 -1
  16. package/dist/src/discovery/loadGenerator.js.map +1 -1
  17. package/dist/src/display/printGeneratorHelp.d.ts +1 -1
  18. package/dist/src/display/printGeneratorHelp.js +1 -1
  19. package/dist/src/display/printGeneratorHelp.js.map +1 -1
  20. package/dist/src/registration/buildCommandBarrel.d.ts +16 -7
  21. package/dist/src/registration/buildCommandBarrel.js +14 -5
  22. package/dist/src/registration/buildCommandBarrel.js.map +1 -1
  23. package/dist/src/registration/index.d.ts +0 -1
  24. package/dist/src/registration/registerFromBarrel.d.ts +9 -4
  25. package/dist/src/registration/registerFromBarrel.js +295 -362
  26. package/dist/src/registration/registerFromBarrel.js.map +1 -1
  27. package/dist/src/registration/resolveMode.d.ts +29 -0
  28. package/dist/src/registration/resolveMode.js +40 -0
  29. package/dist/src/registration/resolveMode.js.map +1 -0
  30. package/package.json +9 -10
  31. package/dist/src/registration/types.d.ts +0 -26
  32. package/dist/src/registration/types.js +0 -2
  33. package/dist/src/registration/types.js.map +0 -1
@@ -1,352 +1,331 @@
1
1
  import { jsx as _jsx } from "react/jsx-runtime";
2
2
  /**
3
- * Register commands from a command barrel onto a Commander program.
3
+ * Register commands from a command barrel onto a Commander program — the
4
+ * summon HOST over the shared registration path in
5
+ * `@canonical/summon-core/projection`.
4
6
  *
5
- * Handles option wiring, grouped help, answer extraction, mode expansion
6
- * (--llm, --format json), and the action handler for each generator command.
7
+ * The projection owns everything derivable from the prompts (command specs,
8
+ * prompt options, grouped help, namespace parents); this module contributes
9
+ * only what is summon-shaped: the nine standard flags, the `--llm`/`--format
10
+ * json`/`SUMMON_LLM` mode expansions, and the action body that decides between
11
+ * the batch renderers and the Ink app.
7
12
  *
8
13
  * @note Impure — writes to stdout/stderr, renders Ink components.
9
14
  */
10
- import { createGeneratorStamp, formatEffectLine, formatEffectWithContent, formatLlmJson, formatLlmMarkdown, isVisibleEffect, } from "@canonical/cli-core";
11
- import { dryRun } from "@canonical/task";
12
- import { runUndo } from "@canonical/task/node";
15
+ import { createGeneratorStamp, formatEffectLine, formatEffectWithContent, formatLlmJson, formatLlmMarkdown, isInvalidAnswersError, missingRequiredError, validateAnswers, visiblePlanEffects, } from "@canonical/summon-core";
16
+ import { applyDefaults, extractAnswers, hasAllRequiredAnswers, missingExplicitFlags, refusalMessage, } from "@canonical/summon-core/projection";
17
+ import { emitToProcess, registerGeneratorCommands, } from "@canonical/summon-core/projection/commander";
18
+ import { collectUndos, describeEffect, dryRun, } from "@canonical/task";
19
+ import { hostExistsResolver, runCollectedUndos } from "@canonical/task/node";
13
20
  import chalk from "chalk";
14
21
  import { render } from "ink";
15
22
  import { App } from "../components/App.js";
23
+ import { describeUndoSteps, isUnreversibleExec, } from "../components/undoPlan.js";
24
+ import { resolveSummonMode, summonIsTTY } from "./resolveMode.js";
16
25
  // =============================================================================
17
- // Internal helpers
26
+ // The summon host: standard flags + help rows
27
+ // =============================================================================
28
+ /** Register summon's nine standard per-generator flags. */
29
+ function registerStandardFlags(cmd) {
30
+ cmd
31
+ .option("-d, --dry-run", "Preview without writing files")
32
+ .option("--undo", "Reverse a previously executed generator")
33
+ .option("-y, --yes", "Skip confirmation prompts and preview")
34
+ .option("-v, --verbose", "Show debug output")
35
+ .option("--show-files", "Show file contents in dry-run")
36
+ .option("--no-preview", "Skip the file preview")
37
+ .option("--no-generated-stamp", "Disable generated file stamp comments")
38
+ .option("-l, --llm", "LLM mode: dry-run with markdown output, no prompts, no stamps")
39
+ .option("--format <type>", "Output format: json (implies dry-run, no prompts, no stamps)");
40
+ }
41
+ /** Summon's standard-flag rows for the grouped-help Global Options block. */
42
+ const STANDARD_FLAG_HELP = [
43
+ { flags: "-d, --dry-run", description: "Preview without writing files" },
44
+ // `--undo` was registered but MISSING from the grouped help's hard-coded
45
+ // block for as long as the block existed; the parity set (prompt-derived ∪
46
+ // --dry-run/--undo/--yes) makes the omission a test failure, so it is fixed.
47
+ { flags: "--undo", description: "Reverse a previously executed generator" },
48
+ { flags: "-y, --yes", description: "Skip confirmation prompts and preview" },
49
+ { flags: "-v, --verbose", description: "Show debug output" },
50
+ { flags: "--show-files", description: "Show file contents in dry-run" },
51
+ { flags: "--no-preview", description: "Skip the file preview" },
52
+ {
53
+ flags: "--no-generated-stamp",
54
+ description: "Disable generated file stamp comments",
55
+ },
56
+ {
57
+ flags: "-l, --llm",
58
+ description: "Dry-run with markdown output, no prompts, no stamps",
59
+ },
60
+ {
61
+ flags: "--format <type>",
62
+ description: "Output format: json (dry-run, no prompts, no stamps)",
63
+ },
64
+ { flags: "-h, --help", description: "display help for command" },
65
+ ];
66
+ // =============================================================================
67
+ // The summon action
18
68
  // =============================================================================
19
69
  /**
20
- * Convert camelCase to kebab-case.
21
- * withTests -> with-tests
70
+ * Generate the batch task, validating the SUCCESS path: `--generators` loads
71
+ * unchecked JS, so a `generate()` that forgot its `return` hands back
72
+ * undefined — named here as the same generator-bug class a throwing
73
+ * `generate` is (the action's catch renders the bare line, exit 1), instead
74
+ * of the interpreter's incidental TypeError
75
+ * (`undefined is not an object (evaluating 'cur._tag')`). The App's
76
+ * `generateTask` holds the run/wizard arms to the same message.
22
77
  */
23
- const toKebabCase = (str) => str.replace(/([a-z])([A-Z])/g, "$1-$2").toLowerCase();
24
- const buildOptionInfo = (prompt) => {
25
- const kebabName = toKebabCase(prompt.name);
26
- const flagName = `--${kebabName}`;
27
- // NOTE: We intentionally do NOT pass defaultValue to Commander.
28
- // Defaults are handled by applyDefaults() after prompting, so we can
29
- // distinguish between "user didn't provide" vs "user provided default value".
30
- switch (prompt.type) {
31
- case "confirm": {
32
- const defaultVal = prompt.default === true;
33
- if (defaultVal) {
34
- return {
35
- flags: `--no-${kebabName}`,
36
- description: `${prompt.message}`,
37
- group: prompt.group,
38
- promptName: prompt.name,
39
- kebabName,
40
- };
41
- }
42
- return {
43
- flags: flagName,
44
- description: `${prompt.message}`,
45
- group: prompt.group,
46
- promptName: prompt.name,
47
- kebabName,
48
- };
49
- }
50
- case "select": {
51
- const choices = prompt.choices?.map((c) => c.value).join("|") ?? "";
52
- return {
53
- flags: `${flagName} <value>`,
54
- description: `${prompt.message} [${choices}]`,
55
- group: prompt.group,
56
- promptName: prompt.name,
57
- kebabName,
58
- };
78
+ function generateBatchTask(generator, answersWithDefaults) {
79
+ const task = generator.generate(answersWithDefaults);
80
+ if (task === undefined || task === null) {
81
+ throw new Error(`${generator.meta.name}'s generate returned no task`);
82
+ }
83
+ return task;
84
+ }
85
+ /** Run the batch (non-interactive) undo path. */
86
+ async function runBatchUndo(generator, answersWithDefaults, dryRunOnly) {
87
+ const task = generateBatchTask(generator, answersWithDefaults);
88
+ try {
89
+ const unreversible = [];
90
+ const undos = collectUndos(task, {
91
+ resolveExists: hostExistsResolver(),
92
+ onForwardEffect: (effect) => {
93
+ if (isUnreversibleExec(effect))
94
+ unreversible.push(effect);
95
+ },
96
+ });
97
+ if (undos.length === 0) {
98
+ console.log("Nothing to undo.");
99
+ return;
59
100
  }
60
- case "multiselect": {
61
- return {
62
- flags: `${flagName} <values>`,
63
- description: `${prompt.message} (comma-separated)`,
64
- group: prompt.group,
65
- promptName: prompt.name,
66
- kebabName,
67
- };
101
+ const planLines = describeUndoSteps(undos).map((effect) => effect._tag === "Log" ? effect.message : describeEffect(effect));
102
+ // Diagnostics go to stderr so stdout stays a clean data stream.
103
+ process.stderr.write(`Undo will reverse ${undos.length} step${undos.length === 1 ? "" : "s"}:\n${planLines.map((line) => ` - ${line}`).join("\n")}\n`);
104
+ if (dryRunOnly) {
105
+ console.log("Dry-run complete. Nothing was reversed.");
106
+ return;
68
107
  }
69
- default: {
70
- return {
71
- flags: `${flagName} <value>`,
72
- description: `${prompt.message}`,
73
- group: prompt.group,
74
- promptName: prompt.name,
75
- kebabName,
76
- };
108
+ const result = await runCollectedUndos(undos);
109
+ console.log(`Undo complete (${result.undoCount} step${result.undoCount === 1 ? "" : "s"} reversed).`);
110
+ if (unreversible.length > 0) {
111
+ process.stderr.write(`Note: ${unreversible.length} exec step${unreversible.length === 1 ? "" : "s"} were not reversed (e.g. installs); their artifacts may remain.\n`);
77
112
  }
78
113
  }
79
- };
80
- /**
81
- * Add prompt-based options to a Commander command.
82
- */
83
- const addPromptOptions = (cmd, prompts) => {
84
- for (const prompt of prompts) {
85
- const info = buildOptionInfo(prompt);
86
- cmd.option(info.flags, info.description, info.defaultValue);
114
+ catch (err) {
115
+ const message = err instanceof Error ? err.message : String(err);
116
+ console.error(`Undo failed: ${message}`);
117
+ process.exitCode = 1;
87
118
  }
88
- };
89
- /**
90
- * Configure custom help with grouped options for a command.
91
- */
92
- const configureGroupedHelp = (cmd, prompts) => {
93
- // Collect option info by group
94
- const groups = new Map();
95
- const defaultGroupName = "Generator Options";
96
- for (const prompt of prompts) {
97
- const info = buildOptionInfo(prompt);
98
- const groupName = info.group ?? defaultGroupName;
99
- if (!groups.has(groupName)) {
100
- groups.set(groupName, []);
101
- }
102
- groups.get(groupName)?.push(info);
119
+ }
120
+ /** Render the batch (non-interactive) dry-run in plain, llm, or json form. */
121
+ function runBatchDryRun(generator, answersWithDefaults, actualOptions) {
122
+ const verbose = actualOptions.verbose === true;
123
+ const showFiles = actualOptions.showFiles === true;
124
+ const task = generateBatchTask(generator, answersWithDefaults);
125
+ const result = dryRun(task);
126
+ if (actualOptions.llm === true) {
127
+ const output = formatLlmMarkdown(generator, answersWithDefaults, result.effects, verbose);
128
+ process.stdout.write(output);
103
129
  }
104
- // Only configure custom help if there are grouped options
105
- if (groups.size <= 1 && !prompts.some((p) => p.group)) {
106
- return;
130
+ else if (actualOptions.format === "json") {
131
+ const output = formatLlmJson(generator, answersWithDefaults, result.effects, verbose);
132
+ process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
107
133
  }
108
- // Override help output using configureHelp
109
- cmd.configureHelp({
110
- formatHelp: (cmd, helper) => {
111
- const termWidth = 28; // Fixed width for option flags column
112
- const formatItem = (term, description, defaultVal) => {
113
- const fullDesc = defaultVal
114
- ? `${description} (default: ${JSON.stringify(defaultVal)})`
115
- : description;
116
- if (description) {
117
- const padding = " ".repeat(Math.max(termWidth - term.length, 2));
118
- return ` ${term}${padding}${fullDesc}`;
119
- }
120
- return ` ${term}`;
121
- };
122
- let output = "";
123
- // Usage
124
- output += `Usage: ${helper.commandUsage(cmd)}\n`;
125
- // Description
126
- const desc = helper.commandDescription(cmd);
127
- if (desc) {
128
- output += `\n${desc}\n`;
134
+ else {
135
+ console.log();
136
+ console.log(chalk.bold.magenta(generator.meta.name));
137
+ console.log(chalk.dim(generator.meta.description));
138
+ console.log();
139
+ // The visibility filter AND the MakeDir de-duplication are ONE rule with
140
+ // several readers — this bin's dry-run, summon-core's own `--llm` / JSON
141
+ // projections, and the pragma kernel's CLI and MCP previews. This is the
142
+ // REFERENCE renderer the others are required to agree with, so it consumes
143
+ // the shared rule rather than carrying the copy it used to.
144
+ const visibleEffects = visiblePlanEffects(result.effects, verbose);
145
+ console.log(chalk.dim.bold("Plan:"));
146
+ visibleEffects.forEach((effect, index) => {
147
+ const isLast = index === visibleEffects.length - 1;
148
+ if (showFiles) {
149
+ console.log(formatEffectWithContent(effect, isLast));
129
150
  }
130
- // Built-in options (Global Options group)
131
- output += "\nGlobal Options:\n";
132
- output += formatItem("-d, --dry-run", "Preview without writing files");
133
- output += "\n";
134
- output += formatItem("-y, --yes", "Skip confirmation prompts and preview");
135
- output += "\n";
136
- output += formatItem("-v, --verbose", "Show debug output");
137
- output += "\n";
138
- output += formatItem("--show-files", "Show file contents in dry-run");
139
- output += "\n";
140
- output += formatItem("--no-preview", "Skip the file preview");
141
- output += "\n";
142
- output += formatItem("--no-generated-stamp", "Disable generated file stamp comments");
143
- output += "\n";
144
- output += formatItem("-l, --llm", "Dry-run with markdown output, no prompts, no stamps");
145
- output += "\n";
146
- output += formatItem("--format <type>", "Output format: json (dry-run, no prompts, no stamps)");
147
- output += "\n";
148
- output += formatItem("-h, --help", "display help for command");
149
- output += "\n";
150
- // Grouped prompt options
151
- for (const [groupName, options] of groups) {
152
- output += `\n${groupName}:\n`;
153
- for (const opt of options) {
154
- output += formatItem(opt.flags, opt.description, opt.defaultValue);
155
- output += "\n";
156
- }
157
- }
158
- return output;
159
- },
160
- });
161
- };
162
- /**
163
- * Extract answers from Commander options based on prompts.
164
- */
165
- const extractAnswers = (options, prompts) => {
166
- const answers = {};
167
- for (const prompt of prompts) {
168
- const value = options[prompt.name];
169
- if (value !== undefined) {
170
- switch (prompt.type) {
171
- case "confirm": {
172
- const boolValue = Boolean(value);
173
- if (boolValue !== prompt.default) {
174
- answers[prompt.name] = boolValue;
175
- }
176
- break;
177
- }
178
- case "multiselect":
179
- answers[prompt.name] =
180
- typeof value === "string"
181
- ? value.split(",").map((v) => v.trim())
182
- : value;
183
- break;
184
- default:
185
- answers[prompt.name] = value;
151
+ else {
152
+ console.log(formatEffectLine(effect, isLast));
186
153
  }
154
+ });
155
+ console.log();
156
+ console.log(chalk.dim("Dry-run complete. No files were modified."));
157
+ if (!showFiles) {
158
+ console.log(chalk.dim("Tip: Use --show-files to see generated file contents"));
187
159
  }
188
160
  }
189
- return answers;
190
- };
191
- /**
192
- * Check if all required prompts have answers.
193
- */
194
- const hasAllRequiredAnswers = (prompts, answers) => {
195
- for (const prompt of prompts) {
196
- if (prompt.when)
197
- continue;
198
- if (!(prompt.name in answers) && prompt.default === undefined) {
199
- return false;
200
- }
161
+ }
162
+ /** The summon action body for one generator invocation. */
163
+ async function runGeneratorAction(entry, positionalValue, actualOptions) {
164
+ const generator = entry.generator;
165
+ /* v8 ignore next -- the projection calls the action only for generator entries. */
166
+ if (!generator)
167
+ return;
168
+ // Support SUMMON_LLM=1 environment variable
169
+ if (process.env.SUMMON_LLM === "1" && actualOptions.llm !== true) {
170
+ actualOptions.llm = true;
201
171
  }
202
- return true;
203
- };
204
- /**
205
- * Apply defaults for prompts that don't have answers.
206
- */
207
- const applyDefaults = (prompts, answers) => {
208
- const result = { ...answers };
209
- for (const prompt of prompts) {
210
- if (!(prompt.name in result) && prompt.default !== undefined) {
211
- result[prompt.name] = prompt.default;
212
- }
172
+ // Expand --llm flag into its component flags
173
+ if (actualOptions.llm === true) {
174
+ actualOptions.dryRun = true;
175
+ actualOptions.showFiles = true;
176
+ actualOptions.yes = true;
177
+ actualOptions.generatedStamp = false;
213
178
  }
214
- return result;
215
- };
216
- /**
217
- * Configure a command with generator options and action.
218
- */
219
- const configureGeneratorCommand = (cmd, generator, positionalPrompt) => {
220
- // Add prompt-based options
221
- addPromptOptions(cmd, generator.prompts);
222
- // Configure grouped help display
223
- configureGroupedHelp(cmd, generator.prompts);
224
- // Add action
225
- cmd.action(async (positionalArg, cmdOptions) => {
226
- let actualOptions;
227
- if (positionalPrompt) {
228
- actualOptions = cmdOptions ?? {};
229
- }
230
- else {
231
- actualOptions = positionalArg ?? {};
232
- }
233
- // Support SUMMON_LLM=1 environment variable
234
- if (process.env.SUMMON_LLM === "1" && actualOptions.llm !== true) {
235
- actualOptions.llm = true;
236
- }
237
- // Expand --llm flag into its component flags
238
- if (actualOptions.llm === true) {
239
- actualOptions.dryRun = true;
240
- actualOptions.showFiles = true;
241
- actualOptions.yes = true;
242
- actualOptions.generatedStamp = false;
243
- }
244
- // Expand --format json into its component flags
245
- if (actualOptions.format === "json") {
246
- actualOptions.dryRun = true;
247
- actualOptions.showFiles = true;
248
- actualOptions.yes = true;
249
- actualOptions.generatedStamp = false;
250
- }
251
- // Extract only explicitly provided CLI answers (not defaults)
252
- const cliAnswers = extractAnswers(actualOptions, generator.prompts);
253
- // If positional argument was provided, add it to the answers
254
- if (positionalPrompt &&
255
- typeof positionalArg === "string" &&
256
- positionalArg) {
257
- cliAnswers[positionalPrompt.name] = positionalArg;
258
- }
259
- // Apply defaults for checking if we have all required answers
260
- const answersWithDefaults = applyDefaults(generator.prompts, cliAnswers);
261
- // Determine execution mode
262
- const hasAllAnswers = hasAllRequiredAnswers(generator.prompts, answersWithDefaults);
263
- const isTTY = process.stdin.isTTY === true;
264
- const skipPrompts = actualOptions.yes === true;
265
- // Build stamp config if stamps are enabled (default: enabled)
266
- const stampEnabled = actualOptions.generatedStamp !== false;
267
- const stamp = stampEnabled
268
- ? createGeneratorStamp(generator)
269
- : undefined;
270
- // Undo mode (non-interactive batch)
271
- if (hasAllAnswers && actualOptions.undo && !isTTY) {
272
- const task = generator.generate(answersWithDefaults);
273
- try {
274
- const result = await runUndo(task);
275
- if (result.undoCount === 0) {
276
- console.log("Nothing to undo.");
277
- }
278
- else {
279
- console.log(`Undo complete (${result.undoCount} step${result.undoCount === 1 ? "" : "s"} reversed).`);
280
- }
179
+ // Expand --format json into its component flags
180
+ if (actualOptions.format === "json") {
181
+ actualOptions.dryRun = true;
182
+ actualOptions.showFiles = true;
183
+ actualOptions.yes = true;
184
+ actualOptions.generatedStamp = false;
185
+ }
186
+ // Extract only explicitly provided CLI answers (not defaults)
187
+ const cliAnswers = extractAnswers(actualOptions, generator.prompts);
188
+ // If the positional argument was provided, add it to the answers
189
+ const positionalPrompt = generator.prompts.find((p) => p.positional);
190
+ if (positionalPrompt && positionalValue !== undefined) {
191
+ cliAnswers[positionalPrompt.name] = positionalValue;
192
+ }
193
+ // Apply defaults once — the batch and run modes consume these.
194
+ const answersWithDefaults = applyDefaults(generator.prompts, cliAnswers);
195
+ // The ONE interaction decision (R2), shared verbatim with pragma, resolved
196
+ // through the testable seam (`resolveMode.ts`) with summon's TTY fact:
197
+ // stdin AND stdout are TTYs (the wizard renders to stdout).
198
+ const mode = resolveSummonMode(generator.prompts, actualOptions, cliAnswers, summonIsTTY());
199
+ if (mode === "refuse") {
200
+ process.stderr.write(`${refusalMessage(missingExplicitFlags(generator.prompts, cliAnswers))}\n`);
201
+ process.exitCode = 2;
202
+ return;
203
+ }
204
+ // An invalid EXPLICIT answer fails loudly before any UI or write — run and
205
+ // wizard arms included (previously only the batch arms checked, so `--yes`
206
+ // scaffolded a tree carrying the invalid value) — but AFTER the refuse
207
+ // arm: pragma's mount decides (and refuses) before its create runtime
208
+ // loads, so refuse must win over invalid input in BOTH hosts
209
+ // (the cross-CLI matrix). The batch arms re-check the defaults-applied set
210
+ // below (an invalid generator DEFAULT stays loud).
211
+ if (!failLoudInvalidAnswers(generator, cliAnswers))
212
+ return;
213
+ // Build stamp config if stamps are enabled (default: enabled)
214
+ const stampEnabled = actualOptions.generatedStamp !== false;
215
+ const stamp = stampEnabled
216
+ ? createGeneratorStamp(generator)
217
+ : undefined;
218
+ // The batch modes run regardless of TTY, on defaults — but never on a
219
+ // missing or invalid answer: they error loudly (exit 2) where the previous
220
+ // decision block silently fell through to Ink.
221
+ if (mode === "batch-undo" || mode === "batch-dry-run") {
222
+ if (!failLoudBatchInput(generator, answersWithDefaults))
223
+ return;
224
+ try {
225
+ if (mode === "batch-undo") {
226
+ await runBatchUndo(generator, answersWithDefaults, actualOptions.dryRun === true);
281
227
  }
282
- catch (err) {
283
- const message = err instanceof Error ? err.message : String(err);
284
- console.error(`Undo failed: ${message}`);
285
- process.exitCode = 1;
228
+ else {
229
+ runBatchDryRun(generator, answersWithDefaults, actualOptions);
286
230
  }
287
- return;
288
231
  }
289
- if (hasAllAnswers && actualOptions.dryRun && !isTTY) {
290
- // Batch dry-run mode (non-interactive)
291
- const verbose = actualOptions.verbose === true;
292
- const showFiles = actualOptions.showFiles === true;
293
- const task = generator.generate(answersWithDefaults);
294
- const result = dryRun(task);
295
- if (actualOptions.llm === true) {
296
- const output = formatLlmMarkdown(generator, answersWithDefaults, result.effects, verbose);
297
- process.stdout.write(output);
298
- }
299
- else if (actualOptions.format === "json") {
300
- const output = formatLlmJson(generator, answersWithDefaults, result.effects, verbose);
301
- process.stdout.write(`${JSON.stringify(output, null, 2)}\n`);
232
+ catch (error) {
233
+ // A generator-raised typed invalid answer (a cross-answer constraint
234
+ // its `generate` enforces — two answers only valid together; no
235
+ // shipped generator raises one today)
236
+ // fails exactly like `validateAnswers` above: the bare message on
237
+ // stderr, exit 2. Any OTHER throw is a generator bug — still the bare
238
+ // message line, with the runtime class (exit 1), per §3's batch
239
+ // clause. Re-throwing (the old behavior) escaped the un-awaited async
240
+ // action as an unhandled rejection: a 1.2 KB source-frame stack
241
+ // instead of a line, and an exit code owned by the runtime, not the
242
+ // classification.
243
+ if (isInvalidAnswersError(error)) {
244
+ process.stderr.write(`${error.message}\n`);
245
+ process.exitCode = 2;
302
246
  }
303
247
  else {
304
- console.log();
305
- console.log(chalk.bold.magenta(generator.meta.name));
306
- console.log(chalk.dim(generator.meta.description));
307
- console.log();
308
- // Filter and deduplicate effects
309
- const seenDirPaths = new Set();
310
- const visibleEffects = result.effects.filter((e) => {
311
- if (!isVisibleEffect(e, verbose))
312
- return false;
313
- if (e._tag === "MakeDir") {
314
- if (seenDirPaths.has(e.path))
315
- return false;
316
- seenDirPaths.add(e.path);
317
- }
318
- return true;
319
- });
320
- console.log(chalk.dim.bold("Plan:"));
321
- visibleEffects.forEach((effect, index) => {
322
- const isLast = index === visibleEffects.length - 1;
323
- if (showFiles) {
324
- console.log(formatEffectWithContent(effect, isLast));
325
- }
326
- else {
327
- console.log(formatEffectLine(effect, isLast));
328
- }
329
- });
330
- console.log();
331
- console.log(chalk.dim("Dry-run complete. No files were modified."));
332
- if (!showFiles) {
333
- console.log(chalk.dim("Tip: Use --show-files to see generated file contents"));
334
- }
248
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
249
+ process.exitCode = 1;
335
250
  }
336
251
  }
337
- else {
338
- // Interactive mode
339
- const shouldSkipPrompts = skipPrompts || Object.keys(cliAnswers).length > 0;
340
- const passedAnswers = shouldSkipPrompts
341
- ? answersWithDefaults
342
- : undefined;
343
- const shouldShowPreview = skipPrompts
344
- ? false
345
- : actualOptions.preview;
346
- const { waitUntilExit } = render(_jsx(App, { generator: generator, preview: shouldShowPreview, dryRunOnly: actualOptions.dryRun, undo: actualOptions.undo, verbose: actualOptions.verbose, answers: passedAnswers, stamp: stamp }));
347
- await waitUntilExit();
252
+ return;
253
+ }
254
+ if (mode === "run") {
255
+ // A fully-determined run: defaults applied, no wizard, no preview gate
256
+ // (the confirm auto-resolves).
257
+ const { waitUntilExit } = render(_jsx(App, { generator: generator, preview: false, dryRunOnly: false, undo: false, verbose: actualOptions.verbose, answers: answersWithDefaults, stamp: stamp }));
258
+ await waitUntilExit();
259
+ return;
260
+ }
261
+ // mode === "wizard": ask exactly pendingPrompts(prompts, explicit) — the
262
+ // contract's shared fact. Summon's PRESENTATION (host prose, not parity
263
+ // surface): the provided answers are pre-seeded and shown in the completed
264
+ // table, the step total counts only the pending prompts, and esc at the
265
+ // confirm gate goes BACK instead of cancelling.
266
+ const { waitUntilExit } = render(_jsx(App, { generator: generator, preview: actualOptions.preview, dryRunOnly: false, undo: false, verbose: actualOptions.verbose, answers: cliAnswers, askMissing: true, stamp: stamp }));
267
+ await waitUntilExit();
268
+ }
269
+ /**
270
+ * Fail loudly (stderr + exit 2) when an answer in `answers` fails its
271
+ * prompt's own constraint. The ONE invalid-answer rendering: the action runs
272
+ * it over the EXPLICIT answers downstream of the refuse arm (refuse wins,
273
+ * exactly as pragma's mount refuses before its runtime validates) and
274
+ * before any other arm runs, and {@link failLoudBatchInput} runs it again
275
+ * over the defaults-applied set. Returns true when the answers pass.
276
+ */
277
+ function failLoudInvalidAnswers(generator, answers) {
278
+ const invalid = validateAnswers(generator.prompts, answers);
279
+ if (invalid === null)
280
+ return true;
281
+ process.stderr.write(`${invalid}\n`);
282
+ process.exitCode = 2;
283
+ return false;
284
+ }
285
+ /**
286
+ * Fail loudly (stderr + exit 2) when a batch mode's answer set is unusable: a
287
+ * required answer has no value even after defaults, or a provided answer fails
288
+ * its prompt's own constraint. Returns true when the batch may proceed.
289
+ */
290
+ function failLoudBatchInput(generator, answersWithDefaults) {
291
+ if (!hasAllRequiredAnswers(generator.prompts, answersWithDefaults)) {
292
+ const missing = generator.prompts.find((prompt) => !prompt.when &&
293
+ prompt.default === undefined &&
294
+ !(prompt.name in answersWithDefaults));
295
+ /* v8 ignore next -- hasAllRequiredAnswers false implies a missing prompt. */
296
+ if (missing) {
297
+ const effect = {
298
+ _tag: "Prompt",
299
+ question: {
300
+ type: "text",
301
+ name: missing.name,
302
+ message: missing.message,
303
+ },
304
+ };
305
+ process.stderr.write(`${missingRequiredError(effect, "flag").message}\n`);
348
306
  }
349
- });
307
+ process.exitCode = 2;
308
+ return false;
309
+ }
310
+ return failLoudInvalidAnswers(generator, answersWithDefaults);
311
+ }
312
+ /** The summon host handed to the shared registration path. */
313
+ const summonHost = {
314
+ registerFlags: registerStandardFlags,
315
+ helpFlags: STANDARD_FLAG_HELP,
316
+ action: (entry, positionalValue, options) => runGeneratorAction(entry, positionalValue, options),
317
+ // Summon's host spelling (the cross-CLI matrix): Commander's implicit
318
+ // `help` subcommand stays available on namespaces (`summon component
319
+ // help`, the `help [command]` row in the namespace help page). The
320
+ // projection's namespace action would otherwise suppress Commander's
321
+ // implicit default — and pragma deliberately does not declare it.
322
+ onNamespace: (cmd) => {
323
+ cmd.helpCommand(true);
324
+ },
325
+ // The projection's designed outcomes (usage errors, bare-namespace help)
326
+ // take the default presentation: the parity bytes on stderr, the
327
+ // outcome's exit code — the one shared process effect.
328
+ emit: emitToProcess,
350
329
  };
351
330
  // =============================================================================
352
331
  // Public API
@@ -357,52 +336,6 @@ const configureGeneratorCommand = (cmd, generator, positionalPrompt) => {
357
336
  * @note Impure — mutates the Commander program.
358
337
  */
359
338
  export default function registerFromBarrel(rootCmd, barrel) {
360
- const commandMap = new Map();
361
- commandMap.set("", rootCmd);
362
- for (const entry of barrel) {
363
- const name = entry.path[entry.path.length - 1];
364
- const parentPath = entry.path.slice(0, -1).join("/");
365
- const currentPath = entry.path.join("/");
366
- // Skip if already registered (can happen with namespace + runnable at same path)
367
- const existingCmd = commandMap.get(currentPath);
368
- if (existingCmd) {
369
- if (entry.generator) {
370
- configureGeneratorCommand(existingCmd, entry.generator);
371
- }
372
- continue;
373
- }
374
- // Get or create parent command
375
- const parentCmd = commandMap.get(parentPath) ?? rootCmd;
376
- if (entry.generator) {
377
- const positionalPrompt = entry.generator.prompts.find((p) => p.positional);
378
- const commandSpec = positionalPrompt
379
- ? `${name} [${toKebabCase(positionalPrompt.name)}]`
380
- : name;
381
- const cmd = parentCmd
382
- .command(commandSpec)
383
- .description(entry.generator.meta.description)
384
- .option("-d, --dry-run", "Preview without writing files")
385
- .option("--undo", "Reverse a previously executed generator")
386
- .option("-y, --yes", "Skip confirmation prompts and preview")
387
- .option("-v, --verbose", "Show debug output")
388
- .option("--show-files", "Show file contents in dry-run")
389
- .option("--no-preview", "Skip the file preview")
390
- .option("--no-generated-stamp", "Disable generated file stamp comments")
391
- .option("-l, --llm", "LLM mode: dry-run with markdown output, no prompts, no stamps")
392
- .option("--format <type>", "Output format: json (implies dry-run, no prompts, no stamps)");
393
- if (positionalPrompt) {
394
- const positionalName = toKebabCase(positionalPrompt.name);
395
- cmd.usage(`[${positionalName}] [options]`);
396
- }
397
- configureGeneratorCommand(cmd, entry.generator, positionalPrompt);
398
- commandMap.set(currentPath, cmd);
399
- }
400
- else {
401
- const cmd = parentCmd
402
- .command(name)
403
- .description(entry.description ?? `${name} commands`);
404
- commandMap.set(currentPath, cmd);
405
- }
406
- }
339
+ registerGeneratorCommands(rootCmd, barrel, summonHost);
407
340
  }
408
341
  //# sourceMappingURL=registerFromBarrel.js.map