@canonical/summon-component 0.1.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.
@@ -0,0 +1,310 @@
1
+ /**
2
+ * Tests for @canonical/summon-component generators
3
+ *
4
+ * Uses dry-run to verify generator output without writing files.
5
+ * Uses dryRunWith with ReadFile mock to test template rendering.
6
+ */
7
+
8
+ import * as fs from "node:fs";
9
+ import { dryRun, dryRunWith, type Effect } from "@canonical/summon";
10
+ import { describe, expect, it } from "vitest";
11
+ import { generators } from "../index.js";
12
+
13
+ /**
14
+ * Helper: dry-run with actual file reading for templates.
15
+ * This allows testing template output without writing files.
16
+ */
17
+ const dryRunWithTemplates = <A>(task: import("@canonical/summon").Task<A>) => {
18
+ const mocks = new Map<string, (effect: Effect) => unknown>([
19
+ [
20
+ "ReadFile",
21
+ (effect) => {
22
+ const e = effect as { path: string };
23
+ // Actually read template files
24
+ if (e.path.endsWith(".ejs")) {
25
+ return fs.readFileSync(e.path, "utf-8");
26
+ }
27
+ return `[mock content of ${e.path}]`;
28
+ },
29
+ ],
30
+ ]);
31
+ return dryRunWith(task, mocks);
32
+ };
33
+
34
+ describe("generators barrel", () => {
35
+ it("exports component/react generator", () => {
36
+ expect(generators["component/react"]).toBeDefined();
37
+ expect(generators["component/react"].meta.name).toBe("component/react");
38
+ });
39
+
40
+ it("exports component/svelte generator", () => {
41
+ expect(generators["component/svelte"]).toBeDefined();
42
+ expect(generators["component/svelte"].meta.name).toBe("component/svelte");
43
+ });
44
+ });
45
+
46
+ describe("component/react generator", () => {
47
+ const generator = generators["component/react"];
48
+
49
+ describe("meta", () => {
50
+ it("has correct name", () => {
51
+ expect(generator.meta.name).toBe("component/react");
52
+ });
53
+
54
+ it("has description", () => {
55
+ expect(generator.meta.description).toContain("React component");
56
+ });
57
+
58
+ it("has version", () => {
59
+ expect(generator.meta.version).toBe("0.1.0");
60
+ });
61
+
62
+ it("has help text", () => {
63
+ expect(generator.meta.help).toBeDefined();
64
+ expect(generator.meta.help).toContain("TypeScript");
65
+ });
66
+
67
+ it("has examples", () => {
68
+ expect(generator.meta.examples).toBeDefined();
69
+ expect(generator.meta.examples!.length).toBeGreaterThan(0);
70
+ });
71
+ });
72
+
73
+ describe("prompts", () => {
74
+ it("has componentPath prompt", () => {
75
+ const prompt = generator.prompts.find((p) => p.name === "componentPath");
76
+ expect(prompt).toBeDefined();
77
+ expect(prompt!.type).toBe("text");
78
+ expect(prompt!.default).toBe("src/components/MyComponent");
79
+ });
80
+
81
+ it("has withStyles prompt", () => {
82
+ const prompt = generator.prompts.find((p) => p.name === "withStyles");
83
+ expect(prompt).toBeDefined();
84
+ expect(prompt!.type).toBe("confirm");
85
+ expect(prompt!.default).toBe(true);
86
+ });
87
+
88
+ it("has withStories prompt", () => {
89
+ const prompt = generator.prompts.find((p) => p.name === "withStories");
90
+ expect(prompt).toBeDefined();
91
+ expect(prompt!.type).toBe("confirm");
92
+ expect(prompt!.default).toBe(true);
93
+ });
94
+
95
+ it("has withSsrTests prompt", () => {
96
+ const prompt = generator.prompts.find((p) => p.name === "withSsrTests");
97
+ expect(prompt).toBeDefined();
98
+ expect(prompt!.type).toBe("confirm");
99
+ expect(prompt!.default).toBe(true);
100
+ });
101
+ });
102
+
103
+ describe("generate", () => {
104
+ it("creates component files with all options enabled", () => {
105
+ const task = generator.generate({
106
+ componentPath: "src/components/Button",
107
+ withStyles: true,
108
+ withStories: true,
109
+ withSsrTests: true,
110
+ });
111
+
112
+ const result = dryRun(task);
113
+ const paths = result.effects
114
+ .filter((e) => e._tag === "WriteFile")
115
+ .map((e) => (e as { path: string }).path);
116
+
117
+ expect(paths).toContain("src/components/Button/Button.tsx");
118
+ expect(paths).toContain("src/components/Button/types.ts");
119
+ expect(paths).toContain("src/components/Button/index.ts");
120
+ expect(paths).toContain("src/components/Button/Button.test.tsx");
121
+ expect(paths).toContain("src/components/Button/Button.ssr.test.tsx");
122
+ expect(paths).toContain("src/components/Button/Button.stories.tsx");
123
+ expect(paths).toContain("src/components/Button/styles.css");
124
+ });
125
+
126
+ it("creates minimal component without optional files", () => {
127
+ const task = generator.generate({
128
+ componentPath: "src/components/Icon",
129
+ withStyles: false,
130
+ withStories: false,
131
+ withSsrTests: false,
132
+ });
133
+
134
+ const result = dryRun(task);
135
+ const paths = result.effects
136
+ .filter((e) => e._tag === "WriteFile")
137
+ .map((e) => (e as { path: string }).path);
138
+
139
+ expect(paths).toContain("src/components/Icon/Icon.tsx");
140
+ expect(paths).toContain("src/components/Icon/types.ts");
141
+ expect(paths).toContain("src/components/Icon/index.ts");
142
+ expect(paths).toContain("src/components/Icon/Icon.test.tsx");
143
+ expect(paths).not.toContain("src/components/Icon/Icon.ssr.test.tsx");
144
+ expect(paths).not.toContain("src/components/Icon/Icon.stories.tsx");
145
+ expect(paths).not.toContain("src/components/Icon/styles.css");
146
+ });
147
+
148
+ it("extracts component name from path", () => {
149
+ const task = generator.generate({
150
+ componentPath: "src/components/MyButton",
151
+ withStyles: false,
152
+ withStories: false,
153
+ withSsrTests: false,
154
+ });
155
+
156
+ const result = dryRunWithTemplates(task);
157
+ const mainFile = result.effects.find(
158
+ (e) =>
159
+ e._tag === "WriteFile" &&
160
+ (e as { path: string }).path.endsWith("MyButton.tsx"),
161
+ );
162
+
163
+ expect(mainFile).toBeDefined();
164
+ const content = (mainFile as { content: string }).content;
165
+ expect(content).toContain("MyButton");
166
+ expect(content).toContain("MyButtonProps");
167
+ });
168
+
169
+ it("generates kebab-case class name", () => {
170
+ const task = generator.generate({
171
+ componentPath: "src/components/MyButton",
172
+ withStyles: false,
173
+ withStories: false,
174
+ withSsrTests: false,
175
+ });
176
+
177
+ const result = dryRunWithTemplates(task);
178
+ const mainFile = result.effects.find(
179
+ (e) =>
180
+ e._tag === "WriteFile" &&
181
+ (e as { path: string }).path.endsWith("MyButton.tsx"),
182
+ );
183
+
184
+ const content = (mainFile as { content: string }).content;
185
+ expect(content).toContain("my-button");
186
+ });
187
+
188
+ it("appends export to parent index", () => {
189
+ const task = generator.generate({
190
+ componentPath: "src/components/Card",
191
+ withStyles: false,
192
+ withStories: false,
193
+ withSsrTests: false,
194
+ });
195
+
196
+ const result = dryRun(task);
197
+ const parentIndex = result.effects.find(
198
+ (e) =>
199
+ e._tag === "WriteFile" &&
200
+ (e as { path: string }).path === "src/components/index.ts",
201
+ );
202
+
203
+ expect(parentIndex).toBeDefined();
204
+ const content = (parentIndex as { content: string }).content;
205
+ expect(content).toContain('export * from "./Card"');
206
+ });
207
+ });
208
+ });
209
+
210
+ describe("component/svelte generator", () => {
211
+ const generator = generators["component/svelte"];
212
+
213
+ describe("meta", () => {
214
+ it("has correct name", () => {
215
+ expect(generator.meta.name).toBe("component/svelte");
216
+ });
217
+
218
+ it("has description", () => {
219
+ expect(generator.meta.description).toContain("Svelte");
220
+ });
221
+
222
+ it("has version", () => {
223
+ expect(generator.meta.version).toBe("0.1.0");
224
+ });
225
+ });
226
+
227
+ describe("prompts", () => {
228
+ it("has componentPath prompt with svelte default", () => {
229
+ const prompt = generator.prompts.find((p) => p.name === "componentPath");
230
+ expect(prompt).toBeDefined();
231
+ expect(prompt!.default).toBe("src/lib/components/MyComponent");
232
+ });
233
+
234
+ it("has useTsStories prompt", () => {
235
+ const prompt = generator.prompts.find((p) => p.name === "useTsStories");
236
+ expect(prompt).toBeDefined();
237
+ expect(prompt!.type).toBe("confirm");
238
+ expect(prompt!.default).toBe(false);
239
+ });
240
+ });
241
+
242
+ describe("generate", () => {
243
+ it("creates svelte component files with all options", () => {
244
+ const task = generator.generate({
245
+ componentPath: "src/lib/components/Button",
246
+ withStyles: true,
247
+ withStories: true,
248
+ useTsStories: false,
249
+ withSsrTests: true,
250
+ });
251
+
252
+ const result = dryRun(task);
253
+ const paths = result.effects
254
+ .filter((e) => e._tag === "WriteFile")
255
+ .map((e) => (e as { path: string }).path);
256
+
257
+ expect(paths).toContain("src/lib/components/Button/Button.svelte");
258
+ expect(paths).toContain("src/lib/components/Button/types.ts");
259
+ expect(paths).toContain("src/lib/components/Button/index.ts");
260
+ expect(paths).toContain(
261
+ "src/lib/components/Button/Button.svelte.test.ts",
262
+ );
263
+ expect(paths).toContain("src/lib/components/Button/Button.ssr.test.ts");
264
+ expect(paths).toContain(
265
+ "src/lib/components/Button/Button.stories.svelte",
266
+ );
267
+ });
268
+
269
+ it("creates typescript stories when useTsStories is true", () => {
270
+ const task = generator.generate({
271
+ componentPath: "src/lib/components/Card",
272
+ withStyles: false,
273
+ withStories: true,
274
+ useTsStories: true,
275
+ withSsrTests: false,
276
+ });
277
+
278
+ const result = dryRun(task);
279
+ const paths = result.effects
280
+ .filter((e) => e._tag === "WriteFile")
281
+ .map((e) => (e as { path: string }).path);
282
+
283
+ expect(paths).toContain("src/lib/components/Card/Card.stories.ts");
284
+ expect(paths).not.toContain(
285
+ "src/lib/components/Card/Card.stories.svelte",
286
+ );
287
+ });
288
+
289
+ it("generates svelte 5 runes syntax", () => {
290
+ const task = generator.generate({
291
+ componentPath: "src/lib/components/Toggle",
292
+ withStyles: false,
293
+ withStories: false,
294
+ useTsStories: false,
295
+ withSsrTests: false,
296
+ });
297
+
298
+ const result = dryRunWithTemplates(task);
299
+ const mainFile = result.effects.find(
300
+ (e) =>
301
+ e._tag === "WriteFile" &&
302
+ (e as { path: string }).path.endsWith("Toggle.svelte"),
303
+ );
304
+
305
+ const content = (mainFile as { content: string }).content;
306
+ expect(content).toContain("$props()");
307
+ expect(content).toContain("@render children");
308
+ });
309
+ });
310
+ });
package/src/index.ts ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @canonical/summon-component
3
+ *
4
+ * Component generators for Summon CLI.
5
+ *
6
+ * This package provides generators for creating React and Svelte components
7
+ * with TypeScript, tests, stories, and styles.
8
+ *
9
+ * @example
10
+ * ```bash
11
+ * # Generate a React component
12
+ * summon component react --component-path=src/components/Button
13
+ *
14
+ * # Generate a Svelte component
15
+ * summon component svelte --component-path=src/lib/components/Button
16
+ * ```
17
+ *
18
+ * @packageDocumentation
19
+ */
20
+
21
+ import type { AnyGenerator } from "@canonical/summon";
22
+ import { generator as reactGenerator } from "./react/index.js";
23
+ import { generator as svelteGenerator } from "./svelte/index.js";
24
+
25
+ /**
26
+ * Registry of all component generators.
27
+ *
28
+ * Keys are command paths (e.g., "component/react") that map to the CLI command structure.
29
+ * Values are generator definitions that can be executed by Summon.
30
+ */
31
+ export const generators = {
32
+ "component/react": reactGenerator,
33
+ "component/svelte": svelteGenerator,
34
+ } as const satisfies Record<string, AnyGenerator>;
35
+
36
+ export default generators;
@@ -0,0 +1,177 @@
1
+ /**
2
+ * React Component Generator
3
+ *
4
+ * Generates a React component with a consistent file structure:
5
+ * - `ComponentName.tsx` - Main component file
6
+ * - `types.ts` - TypeScript types and props interface
7
+ * - `index.ts` - Barrel export
8
+ * - `ComponentName.test.tsx` - Unit tests with @testing-library/react
9
+ * - `ComponentName.ssr.test.tsx` - SSR tests (optional)
10
+ * - `ComponentName.stories.tsx` - Storybook stories (optional)
11
+ * - `styles.css` - CSS styles (optional)
12
+ *
13
+ * @example
14
+ * ```bash
15
+ * summon component react --component-path=src/components/Button
16
+ * summon component react --component-path=src/components/Card --with-styles --with-stories
17
+ * ```
18
+ *
19
+ * @module
20
+ */
21
+
22
+ import * as path from "node:path";
23
+ import { fileURLToPath } from "node:url";
24
+ import {
25
+ debug,
26
+ type GeneratorDefinition,
27
+ info,
28
+ mkdir,
29
+ sequence_,
30
+ template,
31
+ when,
32
+ } from "@canonical/summon";
33
+
34
+ import {
35
+ appendExportToParentIndex,
36
+ createComponentPathPrompt,
37
+ createTemplateContext,
38
+ getComponentName,
39
+ getParentDir,
40
+ sharedPrompts,
41
+ } from "../shared/index.js";
42
+ import type { ReactComponentAnswers } from "./types.js";
43
+
44
+ // =============================================================================
45
+ // Template Paths
46
+ // =============================================================================
47
+
48
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
49
+ const templatesDir = path.join(__dirname, "..", "templates");
50
+
51
+ const reactTemplates = {
52
+ component: path.join(templatesDir, "react", "component.tsx.ejs"),
53
+ types: path.join(templatesDir, "react", "types.ts.ejs"),
54
+ index: path.join(templatesDir, "react", "index.ts.ejs"),
55
+ test: path.join(templatesDir, "react", "test.tsx.ejs"),
56
+ ssrTest: path.join(templatesDir, "react", "ssr.test.tsx.ejs"),
57
+ stories: path.join(templatesDir, "react", "stories.tsx.ejs"),
58
+ styles: path.join(templatesDir, "shared", "styles.css.ejs"),
59
+ };
60
+
61
+ // =============================================================================
62
+ // Generator Definition
63
+ // =============================================================================
64
+
65
+ /**
66
+ * React component generator definition.
67
+ *
68
+ * This generator creates a complete React component with TypeScript support,
69
+ * testing infrastructure, and optional Storybook stories and CSS styles.
70
+ *
71
+ * @see {@link https://summon.dev/generators/component/react} for documentation
72
+ */
73
+ export const generator = {
74
+ meta: {
75
+ name: "component/react",
76
+ description:
77
+ "Generate a React component with TypeScript, tests, stories, and styles",
78
+ version: "0.1.0",
79
+ help: `Generate a React component with TypeScript, tests, stories, and styles.
80
+
81
+ FEATURES:
82
+ - TypeScript types and props interface
83
+ - Unit tests with @testing-library/react
84
+ - Storybook integration (optional)
85
+ - CSS styles (optional)
86
+ - SSR tests (optional)
87
+ - Auto-export from parent index.ts
88
+
89
+ The component name is extracted from the path and must be PascalCase.
90
+ For example, 'src/components/Button' creates a 'Button' component.`,
91
+ examples: [
92
+ "summon component react --component-path=src/components/Button",
93
+ "summon component react --component-path=src/components/Card --with-styles --with-stories",
94
+ "summon component react --component-path=src/components/Modal --no-with-ssr-tests",
95
+ "summon component react --component-path=src/components/Button --dry-run",
96
+ ],
97
+ },
98
+
99
+ prompts: [createComponentPathPrompt("react"), ...sharedPrompts],
100
+
101
+ generate: (answers) => {
102
+ const componentName = getComponentName(answers.componentPath);
103
+ const componentDir = answers.componentPath;
104
+ const parentDir = getParentDir(answers.componentPath);
105
+ const ctx = createTemplateContext(answers, "react");
106
+
107
+ return sequence_([
108
+ info(`Generating React component: ${componentName}`),
109
+
110
+ debug("Creating component directory"),
111
+ mkdir(componentDir),
112
+
113
+ debug("Creating main component file"),
114
+ template({
115
+ source: reactTemplates.component,
116
+ dest: path.join(componentDir, `${componentName}.tsx`),
117
+ vars: ctx,
118
+ }),
119
+
120
+ debug("Creating types file"),
121
+ template({
122
+ source: reactTemplates.types,
123
+ dest: path.join(componentDir, "types.ts"),
124
+ vars: ctx,
125
+ }),
126
+
127
+ debug("Creating index barrel file"),
128
+ template({
129
+ source: reactTemplates.index,
130
+ dest: path.join(componentDir, "index.ts"),
131
+ vars: ctx,
132
+ }),
133
+
134
+ debug("Creating test file"),
135
+ template({
136
+ source: reactTemplates.test,
137
+ dest: path.join(componentDir, `${componentName}.test.tsx`),
138
+ vars: ctx,
139
+ }),
140
+
141
+ when(answers.withSsrTests, debug("Creating SSR test file")),
142
+ when(
143
+ answers.withSsrTests,
144
+ template({
145
+ source: reactTemplates.ssrTest,
146
+ dest: path.join(componentDir, `${componentName}.ssr.test.tsx`),
147
+ vars: ctx,
148
+ }),
149
+ ),
150
+
151
+ when(answers.withStories, debug("Creating stories file")),
152
+ when(
153
+ answers.withStories,
154
+ template({
155
+ source: reactTemplates.stories,
156
+ dest: path.join(componentDir, `${componentName}.stories.tsx`),
157
+ vars: ctx,
158
+ }),
159
+ ),
160
+
161
+ when(answers.withStyles, debug("Creating styles file")),
162
+ when(
163
+ answers.withStyles,
164
+ template({
165
+ source: reactTemplates.styles,
166
+ dest: path.join(componentDir, "styles.css"),
167
+ vars: ctx,
168
+ }),
169
+ ),
170
+
171
+ debug("Updating parent index.ts with export"),
172
+ appendExportToParentIndex(parentDir, componentName),
173
+
174
+ info(`Created ${componentName} component at ${componentDir}`),
175
+ ]);
176
+ },
177
+ } as const satisfies GeneratorDefinition<ReactComponentAnswers>;
@@ -0,0 +1,6 @@
1
+ /**
2
+ * React Component Generator - Barrel export
3
+ */
4
+
5
+ export { generator } from "./generator.js";
6
+ export type { ReactComponentAnswers } from "./types.js";
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Types for React component generator
3
+ */
4
+
5
+ import type { BaseComponentAnswers } from "../shared/index.js";
6
+
7
+ /** React component generator answers - uses base answers only */
8
+ export type ReactComponentAnswers = BaseComponentAnswers;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * File operation utilities for component generators
3
+ */
4
+
5
+ import * as path from "node:path";
6
+ import {
7
+ appendFile,
8
+ exists,
9
+ flatMap,
10
+ ifElseM,
11
+ pure,
12
+ readFile,
13
+ type Task,
14
+ writeFile,
15
+ } from "@canonical/summon";
16
+
17
+ /**
18
+ * Append export to parent index.ts file (or create if not exists)
19
+ */
20
+ export const appendExportToParentIndex = (
21
+ parentDir: string,
22
+ componentName: string,
23
+ ): Task<void> => {
24
+ const indexPath = path.join(parentDir, "index.ts");
25
+ const exportLine = `export * from "./${componentName}";\n`;
26
+
27
+ return ifElseM(
28
+ exists(indexPath),
29
+ // If exists, append (if not already exported)
30
+ flatMap(readFile(indexPath), (content) => {
31
+ if (content.includes(`"./${componentName}"`)) {
32
+ return pure(undefined); // Already exported
33
+ }
34
+ return appendFile(indexPath, exportLine);
35
+ }),
36
+ // If not exists, create new file
37
+ writeFile(indexPath, exportLine),
38
+ );
39
+ };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Shared utilities and types for component generators
3
+ */
4
+
5
+ export * from "./file-operations.js";
6
+ export * from "./prompts.js";
7
+ export * from "./string-helpers.js";
8
+ export * from "./template-context.js";
9
+ export type * from "./types.js";
10
+ export * from "./validation.js";
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Shared prompt definitions for component generators
3
+ */
4
+
5
+ import type { PromptDefinition } from "@canonical/summon";
6
+ import type { Framework } from "./types.js";
7
+ import { validateComponentPath } from "./validation.js";
8
+
9
+ /**
10
+ * Create component path prompt with framework-specific defaults.
11
+ *
12
+ * This prompt is marked as positional, allowing users to run:
13
+ * summon component react src/components/Button
14
+ * instead of:
15
+ * summon component react --component-path=src/components/Button
16
+ */
17
+ export const createComponentPathPrompt = (
18
+ framework: Framework,
19
+ ): PromptDefinition => ({
20
+ name: "componentPath",
21
+ type: "text",
22
+ message: "Component path:",
23
+ default:
24
+ framework === "react"
25
+ ? "src/components/MyComponent"
26
+ : "src/lib/components/MyComponent",
27
+ validate: validateComponentPath,
28
+ group: "Component",
29
+ positional: true,
30
+ });
31
+
32
+ /**
33
+ * Shared prompts for both frameworks
34
+ */
35
+ export const sharedPrompts: PromptDefinition[] = [
36
+ {
37
+ name: "withStyles",
38
+ type: "confirm",
39
+ message: "Include styles?",
40
+ default: true,
41
+ group: "Options",
42
+ },
43
+ {
44
+ name: "withStories",
45
+ type: "confirm",
46
+ message: "Include Storybook stories?",
47
+ default: true,
48
+ group: "Options",
49
+ },
50
+ {
51
+ name: "withSsrTests",
52
+ type: "confirm",
53
+ message: "Include SSR tests?",
54
+ default: true,
55
+ group: "Options",
56
+ },
57
+ ];
@@ -0,0 +1,29 @@
1
+ /**
2
+ * String manipulation utilities for component generators
3
+ */
4
+
5
+ import * as path from "node:path";
6
+
7
+ /**
8
+ * Convert PascalCase to kebab-case
9
+ */
10
+ export const kebabCase = (str: string): string => {
11
+ return str
12
+ .replace(/([a-z])([A-Z])/g, "$1-$2")
13
+ .replace(/([A-Z])([A-Z][a-z])/g, "$1-$2")
14
+ .toLowerCase();
15
+ };
16
+
17
+ /**
18
+ * Extract component name from path
19
+ */
20
+ export const getComponentName = (componentPath: string): string => {
21
+ return path.basename(componentPath);
22
+ };
23
+
24
+ /**
25
+ * Get parent directory of component
26
+ */
27
+ export const getParentDir = (componentPath: string): string => {
28
+ return path.dirname(componentPath);
29
+ };