@canonical/summon 0.37.0 → 0.38.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,15 @@
1
+ /**
2
+ * Public, types-only API surface for `@canonical/summon`.
3
+ *
4
+ * Per the tool-ts convention this barrel exports types only — no runtime
5
+ * values cross the package boundary, so importing it can never start the CLI.
6
+ * The runtime surface stays exactly where the `exports` map already puts it:
7
+ * the `summon` binary and the `@canonical/summon/ui` subpath.
8
+ *
9
+ * `src/bin.tsx` is deliberately NOT re-exported: it parses `argv` and runs a
10
+ * generator at module scope, so re-exporting it would turn an `import` into a
11
+ * CLI invocation.
12
+ *
13
+ * @module
14
+ */
15
+ export type { AppProps, AppState } from "./components/App.js";
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Public, types-only API surface for `@canonical/summon`.
3
+ *
4
+ * Per the tool-ts convention this barrel exports types only — no runtime
5
+ * values cross the package boundary, so importing it can never start the CLI.
6
+ * The runtime surface stays exactly where the `exports` map already puts it:
7
+ * the `summon` binary and the `@canonical/summon/ui` subpath.
8
+ *
9
+ * `src/bin.tsx` is deliberately NOT re-exported: it parses `argv` and runs a
10
+ * generator at module scope, so re-exporting it would turn an `import` into a
11
+ * CLI invocation.
12
+ *
13
+ * @module
14
+ */
15
+ export {};
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG"}
package/package.json CHANGED
@@ -1,9 +1,10 @@
1
1
  {
2
2
  "name": "@canonical/summon",
3
3
  "description": "Summon CLI binary: interactive code generator with Ink UI, shell completion, and Commander registration.",
4
- "version": "0.37.0",
4
+ "version": "0.38.0",
5
5
  "type": "module",
6
- "module": "dist/src/bin.js",
6
+ "module": "src/index.ts",
7
+ "types": "src/index.ts",
7
8
  "bin": {
8
9
  "summon": "dist/src/bin.js"
9
10
  },
@@ -18,6 +19,7 @@
18
19
  }
19
20
  },
20
21
  "files": [
22
+ "src",
21
23
  "dist"
22
24
  ],
23
25
  "author": {
@@ -39,18 +41,20 @@
39
41
  "scripts": {
40
42
  "build": "tsc -p tsconfig.build.json && bun ../../../scripts/copy-templates.ts generators dist/generators",
41
43
  "build:all": "bun run build",
42
- "check": "bun run check:biome && bun run check:ts",
43
- "check:fix": "bun run check:biome:fix && bun run check:ts",
44
+ "check": "bun run check:biome && bun run check:ts && bun run check:ts:build && bun run check:webarchitect",
45
+ "check:fix": "bun run check:biome:fix && bun run check:ts && bun run check:ts:build",
44
46
  "check:biome": "biome check",
45
47
  "check:biome:fix": "biome check --write",
46
- "check:ts": "tsc -p tsconfig.build.json --noEmit && tsc -p tsconfig.json --noEmit",
48
+ "check:ts": "tsc --noEmit",
49
+ "check:ts:build": "tsc -p tsconfig.build.json --noEmit",
50
+ "check:webarchitect": "webarchitect tool-ts",
47
51
  "test": "vitest run --passWithNoTests",
48
52
  "test:watch": "vitest"
49
53
  },
50
54
  "dependencies": {
51
- "@canonical/summon-core": "^0.37.0",
52
- "@canonical/task": "^0.37.0",
53
- "@canonical/utils": "^0.37.0",
55
+ "@canonical/summon-core": "^0.38.0",
56
+ "@canonical/task": "^0.38.0",
57
+ "@canonical/utils": "^0.38.0",
54
58
  "chalk": "^6.0.0",
55
59
  "commander": "^15.0.0",
56
60
  "ink": "^6.8.0",
@@ -61,9 +65,10 @@
61
65
  "react": "^19.2.4"
62
66
  },
63
67
  "devDependencies": {
64
- "@biomejs/biome": "2.4.9",
65
- "@canonical/biome-config": "^0.37.0",
66
- "@canonical/typescript-config": "^0.37.0",
68
+ "@biomejs/biome": "2.5.13",
69
+ "@canonical/biome-config": "^0.38.0",
70
+ "@canonical/typescript-config": "^0.38.0",
71
+ "@canonical/webarchitect": "^0.38.0",
67
72
  "@types/bun": "^1.3.10",
68
73
  "@types/node": "^26.0.0",
69
74
  "@types/omelette": "^0.4.5",
@@ -75,5 +80,5 @@
75
80
  "engines": {
76
81
  "node": ">=22.18 <23 || >=23.6"
77
82
  },
78
- "gitHead": "ac8383bdb4be1bcd6fa6c4960a1e3d78c0279688"
83
+ "gitHead": "4d10a68a9b299af6fe3d1d7d053e54ca128944ad"
79
84
  }
package/src/bin.tsx ADDED
@@ -0,0 +1,238 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Summon CLI — thin orchestrator.
5
+ *
6
+ * Wires together generator discovery, display, registration, and completion.
7
+ * All domain logic lives in the corresponding modules.
8
+ *
9
+ * @note Impure — CLI entry point.
10
+ */
11
+
12
+ import * as path from "node:path";
13
+ import { fileURLToPath } from "node:url";
14
+ import {
15
+ discoverGeneratorTree,
16
+ type GeneratorNode,
17
+ } from "@canonical/summon-core";
18
+ import chalk from "chalk";
19
+ import { Command, CommanderError } from "commander";
20
+ import {
21
+ type CompletionNode,
22
+ handleSetupRequest,
23
+ initCompletion,
24
+ isCompletionRequest,
25
+ isSetupRequest,
26
+ } from "./completion.js";
27
+ import { loadGenerator } from "./discovery/index.js";
28
+ import { printGeneratorHelp, printNode } from "./display/index.js";
29
+ import {
30
+ buildCommandBarrel,
31
+ registerFromBarrel,
32
+ } from "./registration/index.js";
33
+
34
+ // =============================================================================
35
+ // Helpers
36
+ // =============================================================================
37
+
38
+ /**
39
+ * Navigate the generator tree by path segments.
40
+ * Returns [node, remainingSegments] where node is as deep as we could go.
41
+ */
42
+ const navigateTree = (
43
+ root: GeneratorNode,
44
+ segments: string[],
45
+ ): [GeneratorNode, string[]] => {
46
+ let current = root;
47
+ let i = 0;
48
+
49
+ for (; i < segments.length; i++) {
50
+ const child = current.children.get(segments[i]);
51
+ if (!child) break;
52
+ current = child;
53
+ }
54
+
55
+ return [current, segments.slice(i)];
56
+ };
57
+
58
+ /**
59
+ * Convert GeneratorNode to CompletionNode for the completion module.
60
+ */
61
+ const toCompletionNode = (node: GeneratorNode): CompletionNode => ({
62
+ name: node.name,
63
+ indexPath: node.indexPath,
64
+ children: new Map(
65
+ [...node.children.entries()].map(([name, child]) => [
66
+ name,
67
+ toCompletionNode(child),
68
+ ]),
69
+ ),
70
+ });
71
+
72
+ /**
73
+ * Register all generator commands from the tree.
74
+ * Uses the barrel pattern: build flat list → sort by depth → register in order.
75
+ */
76
+ const registerGeneratorCommands = async (
77
+ parentCmd: Command,
78
+ node: GeneratorNode,
79
+ ): Promise<void> => {
80
+ const barrel = await buildCommandBarrel(node);
81
+ registerFromBarrel(parentCmd, barrel);
82
+ };
83
+
84
+ // =============================================================================
85
+ // Main
86
+ // =============================================================================
87
+
88
+ const program = new Command();
89
+
90
+ const main = async () => {
91
+ // Get generators path from args early (before full parse)
92
+ const generatorsIdx = process.argv.indexOf("--generators");
93
+ const gIdx = process.argv.indexOf("-g");
94
+ const generatorsPath =
95
+ generatorsIdx !== -1
96
+ ? process.argv[generatorsIdx + 1]
97
+ : gIdx !== -1
98
+ ? process.argv[gIdx + 1]
99
+ : undefined;
100
+
101
+ // Discover generators (needed for both completion and normal CLI).
102
+ // Derive the module dir from import.meta.url — `__dirname` is a CommonJS
103
+ // global that is absent in ESM under Node (bun polyfills it, Node does not),
104
+ // which is exactly the portability gap this CLI needs to run under plain Node.
105
+ const moduleDir = path.dirname(fileURLToPath(import.meta.url));
106
+ const builtinDir = path.join(moduleDir, "..", "generators");
107
+ const root = await discoverGeneratorTree(
108
+ generatorsPath ? { explicitPath: generatorsPath } : { builtinDir },
109
+ );
110
+
111
+ // Initialize shell completion (must happen before commander parsing)
112
+ if (isCompletionRequest() || isSetupRequest()) {
113
+ const completionTree = toCompletionNode(root);
114
+ const complete = await initCompletion(completionTree, loadGenerator);
115
+
116
+ // Handle setup/cleanup requests
117
+ if (isSetupRequest()) {
118
+ handleSetupRequest(complete);
119
+ return;
120
+ }
121
+
122
+ // For completion requests, omelette handles everything via init()
123
+ return;
124
+ }
125
+
126
+ program
127
+ .name("summon")
128
+ .description("A monadic task-centric code generator framework")
129
+ .version("0.1.0")
130
+ .option(
131
+ "-g, --generators <path>",
132
+ "Load generators ONLY from this path (for testing)",
133
+ )
134
+ .option("--setup-completion", "Install shell autocompletion")
135
+ .option("--cleanup-completion", "Remove shell autocompletion");
136
+
137
+ // If no arguments, show available topics
138
+ if (process.argv.length === 2) {
139
+ printNode(root, []);
140
+ console.log(
141
+ chalk.dim(
142
+ "Tip: Run 'summon --setup-completion' to enable TAB completion\n",
143
+ ),
144
+ );
145
+ return;
146
+ }
147
+
148
+ // Intercept --help --llm (or --help -l) for structured markdown help
149
+ const hasHelp =
150
+ process.argv.includes("--help") || process.argv.includes("-h");
151
+ const hasLlm =
152
+ process.argv.includes("--llm") ||
153
+ process.argv.includes("-l") ||
154
+ process.env.SUMMON_LLM === "1";
155
+ if (hasHelp && hasLlm) {
156
+ // Extract command path segments (skip flags and flag arguments)
157
+ const skipFlags = new Set([
158
+ "--help",
159
+ "-h",
160
+ "--llm",
161
+ "-l",
162
+ "--generators",
163
+ "-g",
164
+ "--format",
165
+ ]);
166
+ const args = process.argv.slice(2);
167
+ const segments: string[] = [];
168
+ let skipNext = false;
169
+ for (const arg of args) {
170
+ if (skipNext) {
171
+ skipNext = false;
172
+ continue;
173
+ }
174
+ if (skipFlags.has(arg)) {
175
+ if (arg === "--generators" || arg === "-g" || arg === "--format")
176
+ skipNext = true;
177
+ continue;
178
+ }
179
+ if (arg.startsWith("-")) continue;
180
+ segments.push(arg);
181
+ }
182
+
183
+ if (segments.length > 0) {
184
+ const [node] = navigateTree(root, segments);
185
+ if (node.indexPath) {
186
+ await printGeneratorHelp(node, segments, true);
187
+ return;
188
+ }
189
+ }
190
+ // Fall through to normal help if we can't find the generator
191
+ }
192
+
193
+ // Throw CommanderError instead of exiting, so the classification below owns
194
+ // every exit code. Set BEFORE registration: subcommands copy the override
195
+ // at creation, and it is the LEAF that raises an unknown-option error.
196
+ program.exitOverride();
197
+
198
+ // Register generator commands dynamically
199
+ await registerGeneratorCommands(program, root);
200
+
201
+ // Parse and execute
202
+ try {
203
+ program.parse();
204
+ } catch (error) {
205
+ // Mirror pragma's classification of Commander parse failures
206
+ // (`packages/cli/pragma/src/bin.ts` handleProgramError): informational
207
+ // exits keep their own codes; every usage error is exit 2. Commander has
208
+ // already written its output (help pages, `error: …` lines) through its
209
+ // own writers before throwing, so only the exit code is owned here —
210
+ // stderr stays byte-identical to Commander's.
211
+ if (!(error instanceof CommanderError)) throw error;
212
+ if (
213
+ error.code === "commander.helpDisplayed" ||
214
+ error.code === "commander.version"
215
+ ) {
216
+ process.exitCode = 0;
217
+ return;
218
+ }
219
+ if (error.code === "commander.help") {
220
+ // Respect the help error's OWN exit code. Live cases: the ROOT invoked
221
+ // with options but no command (help on stderr, carries 1) and the
222
+ // implicit `help` command (stdout help, carries 0). A bare NAMESPACE
223
+ // never raises this — the projection's namespace action writes that
224
+ // help and sets exit 1 itself.
225
+ process.exitCode = error.exitCode;
226
+ return;
227
+ }
228
+ // Usage errors (unknown option/command, missing or excess argument):
229
+ // exit 2, matching pragma — Commander's own code was 1 for these.
230
+ process.exitCode = 2;
231
+ }
232
+ };
233
+
234
+ // Run main
235
+ main().catch((err) => {
236
+ console.error(chalk.red("Error:"), err.message);
237
+ process.exit(1);
238
+ });
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Tests for shell autocompletion utilities
3
+ */
4
+
5
+ import type { PromptDefinition } from "@canonical/summon-core";
6
+ import { describe, expect, it } from "vitest";
7
+ import { getArgumentCompletions, isPathPrompt } from "./completion.js";
8
+
9
+ // =============================================================================
10
+ // isPathPrompt
11
+ // =============================================================================
12
+
13
+ describe("isPathPrompt", () => {
14
+ it("detects path in prompt name", () => {
15
+ expect(
16
+ isPathPrompt({ name: "componentPath", type: "text", message: "Enter:" }),
17
+ ).toBe(true);
18
+ });
19
+
20
+ it("detects dir in prompt name", () => {
21
+ expect(
22
+ isPathPrompt({ name: "outputDir", type: "text", message: "Enter:" }),
23
+ ).toBe(true);
24
+ });
25
+
26
+ it("detects directory in prompt name", () => {
27
+ expect(
28
+ isPathPrompt({
29
+ name: "outputDirectory",
30
+ type: "text",
31
+ message: "Enter:",
32
+ }),
33
+ ).toBe(true);
34
+ });
35
+
36
+ it("detects file in prompt name", () => {
37
+ expect(
38
+ isPathPrompt({ name: "configFile", type: "text", message: "Enter:" }),
39
+ ).toBe(true);
40
+ });
41
+
42
+ it("detects folder in prompt message", () => {
43
+ expect(
44
+ isPathPrompt({
45
+ name: "output",
46
+ type: "text",
47
+ message: "Choose output folder:",
48
+ }),
49
+ ).toBe(true);
50
+ });
51
+
52
+ it("detects location in prompt message", () => {
53
+ expect(
54
+ isPathPrompt({
55
+ name: "output",
56
+ type: "text",
57
+ message: "File location:",
58
+ }),
59
+ ).toBe(true);
60
+ });
61
+
62
+ it("returns false for non-path prompts", () => {
63
+ expect(
64
+ isPathPrompt({ name: "name", type: "text", message: "Package name:" }),
65
+ ).toBe(false);
66
+ });
67
+
68
+ it("returns false for confirm prompts", () => {
69
+ expect(
70
+ isPathPrompt({
71
+ name: "withStyles",
72
+ type: "confirm",
73
+ message: "Include styles?",
74
+ }),
75
+ ).toBe(false);
76
+ });
77
+
78
+ it("is case-insensitive", () => {
79
+ expect(
80
+ isPathPrompt({ name: "MyPath", type: "text", message: "Enter:" }),
81
+ ).toBe(true);
82
+ });
83
+ });
84
+
85
+ // =============================================================================
86
+ // getArgumentCompletions
87
+ // =============================================================================
88
+
89
+ describe("getArgumentCompletions", () => {
90
+ const prompts: PromptDefinition[] = [
91
+ { name: "componentPath", type: "text", message: "Component path:" },
92
+ {
93
+ name: "withStyles",
94
+ type: "confirm",
95
+ message: "Include styles?",
96
+ default: true,
97
+ },
98
+ {
99
+ name: "withStories",
100
+ type: "confirm",
101
+ message: "Include stories?",
102
+ default: true,
103
+ },
104
+ {
105
+ name: "type",
106
+ type: "select",
107
+ message: "Package type:",
108
+ choices: [
109
+ { value: "library", label: "Library" },
110
+ { value: "tool-ts", label: "Tool" },
111
+ { value: "css", label: "CSS" },
112
+ ],
113
+ },
114
+ ];
115
+
116
+ it("returns flag completions when completing a flag name", () => {
117
+ const completions = getArgumentCompletions(
118
+ prompts,
119
+ "summon test --comp",
120
+ "--comp",
121
+ );
122
+
123
+ expect(completions).toContain("--component-path");
124
+ });
125
+
126
+ it("shows --no-X for confirm prompts with default true", () => {
127
+ const completions = getArgumentCompletions(
128
+ prompts,
129
+ "summon test --no-",
130
+ "--no-",
131
+ );
132
+
133
+ expect(completions).toContain("--no-with-styles");
134
+ expect(completions).toContain("--no-with-stories");
135
+ });
136
+
137
+ it("returns select choices when completing a flag value", () => {
138
+ const completions = getArgumentCompletions(
139
+ prompts,
140
+ "summon test --type=",
141
+ "",
142
+ );
143
+
144
+ expect(completions).toContain("library");
145
+ expect(completions).toContain("tool-ts");
146
+ expect(completions).toContain("css");
147
+ });
148
+
149
+ it("filters select choices by partial value", () => {
150
+ const completions = getArgumentCompletions(
151
+ prompts,
152
+ "summon test --type=lib",
153
+ "",
154
+ );
155
+
156
+ expect(completions).toContain("library");
157
+ expect(completions).not.toContain("tool-ts");
158
+ expect(completions).not.toContain("css");
159
+ });
160
+
161
+ it("includes built-in flags", () => {
162
+ const completions = getArgumentCompletions(
163
+ prompts,
164
+ "summon test --dry",
165
+ "--dry",
166
+ );
167
+
168
+ expect(completions).toContain("--dry-run");
169
+ });
170
+
171
+ it("shows all flags when showAll is true", () => {
172
+ const completions = getArgumentCompletions(
173
+ prompts,
174
+ "summon test",
175
+ "",
176
+ true,
177
+ );
178
+
179
+ expect(completions).toContain("--component-path");
180
+ expect(completions).toContain("--dry-run");
181
+ expect(completions).toContain("--help");
182
+ });
183
+
184
+ it("returns empty array when no matches", () => {
185
+ const completions = getArgumentCompletions(
186
+ prompts,
187
+ "summon test --zzz",
188
+ "--zzz",
189
+ );
190
+
191
+ expect(completions).toHaveLength(0);
192
+ });
193
+
194
+ it("includes --yes and --verbose in built-in flags", () => {
195
+ const completions = getArgumentCompletions([], "summon test --", "--");
196
+
197
+ expect(completions).toContain("--yes");
198
+ expect(completions).toContain("--verbose");
199
+ expect(completions).toContain("--llm");
200
+ expect(completions).toContain("--help");
201
+ });
202
+ });