@canonical/summon-core 0.18.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,449 @@
1
+ /**
2
+ * Discover available generators from the filesystem.
3
+ *
4
+ * Scans local directories, global package manager locations, and
5
+ * project node_modules for summon-* packages, building a tree of
6
+ * {@link GeneratorNode} entries.
7
+ *
8
+ * @note Impure — performs filesystem I/O (readdir, stat, access, import).
9
+ */
10
+
11
+ import * as fs from "node:fs/promises";
12
+ import * as path from "node:path";
13
+ import chalk from "chalk";
14
+ import type { GeneratorDefinition } from "../types.js";
15
+ import { generatorCache } from "./generatorCache.js";
16
+ import type { GeneratorNode, GeneratorOrigin } from "./types.js";
17
+
18
+ // =============================================================================
19
+ // Internal helpers
20
+ // =============================================================================
21
+
22
+ /**
23
+ * Merge a child node into a parent, combining children if the topic already exists.
24
+ */
25
+ const mergeIntoTree = (parent: GeneratorNode, child: GeneratorNode): void => {
26
+ const existing = parent.children.get(child.name);
27
+ if (existing) {
28
+ // Merge children - existing (local) takes precedence for indexPath
29
+ for (const [name, grandchild] of child.children) {
30
+ if (!existing.children.has(name)) {
31
+ existing.children.set(name, grandchild);
32
+ }
33
+ }
34
+ // Only set indexPath if existing doesn't have one (local takes precedence)
35
+ if (!existing.indexPath && child.indexPath) {
36
+ existing.indexPath = child.indexPath;
37
+ }
38
+ } else {
39
+ parent.children.set(child.name, child);
40
+ }
41
+ };
42
+
43
+ /**
44
+ * Build a tree of generators from a directory.
45
+ * Supports nested structure like:
46
+ * generators/component/react/index.ts -> summon component react
47
+ * generators/component/svelte/index.ts -> summon component svelte
48
+ * generators/util/index.ts -> summon util
49
+ */
50
+ const buildGeneratorTree = async (
51
+ dir: string,
52
+ node: GeneratorNode,
53
+ origin: GeneratorOrigin = "local",
54
+ ): Promise<void> => {
55
+ try {
56
+ const entries = await fs.readdir(dir, { withFileTypes: true });
57
+
58
+ for (const entry of entries) {
59
+ if (entry.isDirectory()) {
60
+ const childDir = path.join(dir, entry.name);
61
+ const indexPath = path.join(childDir, "index.ts");
62
+
63
+ const childNode: GeneratorNode = {
64
+ name: entry.name,
65
+ path: childDir,
66
+ children: new Map(),
67
+ origin,
68
+ };
69
+
70
+ // Check if this directory has an index.ts (is a runnable generator)
71
+ try {
72
+ await fs.access(indexPath);
73
+ childNode.indexPath = indexPath;
74
+ } catch {
75
+ // No index.ts, might still have children
76
+ }
77
+
78
+ // Recursively discover children
79
+ await buildGeneratorTree(childDir, childNode, origin);
80
+
81
+ // Only add node if it has an index.ts or has children with generators
82
+ if (childNode.indexPath || childNode.children.size > 0) {
83
+ mergeIntoTree(node, childNode);
84
+ }
85
+ }
86
+ }
87
+ } catch {
88
+ // Directory doesn't exist
89
+ }
90
+ };
91
+
92
+ /**
93
+ * Check if a path is a directory (follows symlinks).
94
+ */
95
+ const isDirectory = async (filePath: string): Promise<boolean> => {
96
+ try {
97
+ const stat = await fs.stat(filePath); // stat follows symlinks
98
+ return stat.isDirectory();
99
+ } catch {
100
+ return false;
101
+ }
102
+ };
103
+
104
+ /**
105
+ * Insert a generator into the tree at the given path.
106
+ * Creates intermediate namespace nodes as needed.
107
+ */
108
+ const insertGeneratorAtPath = (
109
+ root: GeneratorNode,
110
+ pathStr: string,
111
+ generator: GeneratorDefinition,
112
+ origin: GeneratorOrigin = "package",
113
+ ): void => {
114
+ const segments = pathStr.split("/").filter(Boolean);
115
+ let current = root;
116
+
117
+ // Cache the generator for later lookup
118
+ generatorCache.set(pathStr, generator);
119
+
120
+ for (let i = 0; i < segments.length; i++) {
121
+ const segment = segments[i] ?? "";
122
+ const isLast = i === segments.length - 1;
123
+
124
+ if (!current.children.has(segment)) {
125
+ current.children.set(segment, {
126
+ name: segment,
127
+ path: "",
128
+ children: new Map(),
129
+ origin,
130
+ });
131
+ }
132
+
133
+ const child = current.children.get(segment);
134
+ if (!child) continue; // Should never happen since we just set it
135
+
136
+ if (isLast) {
137
+ // Mark as having a generator (use path as synthetic indexPath)
138
+ child.indexPath = `cache:${pathStr}`;
139
+ child.origin = origin;
140
+ }
141
+
142
+ current = child;
143
+ }
144
+ };
145
+
146
+ /**
147
+ * Process a summon-* package.
148
+ *
149
+ * Imports the package's main entry and looks for a `generators` export
150
+ * mapping command paths to generator definitions.
151
+ */
152
+ const processPackage = async (
153
+ pkgName: string,
154
+ pkgDir: string,
155
+ root: GeneratorNode,
156
+ origin: GeneratorOrigin = "package",
157
+ ): Promise<void> => {
158
+ // Read package.json to get the main entry
159
+ const pkgJsonPath = path.join(pkgDir, "package.json");
160
+ let mainEntry: string | undefined;
161
+
162
+ try {
163
+ const pkgJson = JSON.parse(await fs.readFile(pkgJsonPath, "utf-8"));
164
+ mainEntry = pkgJson.main;
165
+ } catch {
166
+ return; // Can't read package.json
167
+ }
168
+
169
+ if (!mainEntry) return;
170
+
171
+ // Import the package's main entry
172
+ const entryPath = path.join(pkgDir, mainEntry);
173
+ try {
174
+ const module = await import(entryPath);
175
+ const generators =
176
+ module.generators ?? module.default ?? ({} as Record<string, unknown>);
177
+
178
+ // Insert each generator into the tree
179
+ for (const [cmdPath, generator] of Object.entries(generators)) {
180
+ if (generator && typeof generator === "object" && "meta" in generator) {
181
+ insertGeneratorAtPath(
182
+ root,
183
+ cmdPath,
184
+ generator as GeneratorDefinition,
185
+ origin,
186
+ );
187
+ }
188
+ }
189
+ } catch (err) {
190
+ console.error(
191
+ chalk.yellow(`Warning: Could not load generators from '${pkgName}':`),
192
+ (err as Error).message,
193
+ );
194
+ }
195
+ };
196
+
197
+ /**
198
+ * Discover summon-* packages in node_modules.
199
+ */
200
+ const discoverNodeModulesPackages = async (
201
+ nodeModulesDir: string,
202
+ root: GeneratorNode,
203
+ ): Promise<void> => {
204
+ try {
205
+ const entries = await fs.readdir(nodeModulesDir);
206
+
207
+ for (const entry of entries) {
208
+ const entryPath = path.join(nodeModulesDir, entry);
209
+
210
+ if (entry.startsWith("@")) {
211
+ // Scoped packages - look inside @scope/
212
+ if (!(await isDirectory(entryPath))) continue;
213
+ try {
214
+ const scopedEntries = await fs.readdir(entryPath);
215
+ for (const scopedEntry of scopedEntries) {
216
+ if (scopedEntry.startsWith("summon-")) {
217
+ const pkgDir = path.join(entryPath, scopedEntry);
218
+ if (await isDirectory(pkgDir)) {
219
+ await processPackage(`${entry}/${scopedEntry}`, pkgDir, root);
220
+ }
221
+ }
222
+ }
223
+ } catch {
224
+ // Scope directory doesn't exist or can't be read
225
+ }
226
+ } else if (entry.startsWith("summon-")) {
227
+ // Unscoped summon-* package
228
+ if (await isDirectory(entryPath)) {
229
+ await processPackage(entry, entryPath, root);
230
+ }
231
+ }
232
+ }
233
+ } catch {
234
+ // node_modules doesn't exist
235
+ }
236
+ };
237
+
238
+ /**
239
+ * Get bun's global node_modules directory.
240
+ * Default is ~/.bun/install/global/node_modules
241
+ */
242
+ const getBunGlobalNodeModules = (): string => {
243
+ const bunInstallDir =
244
+ process.env.BUN_INSTALL ?? path.join(process.env.HOME ?? "~", ".bun");
245
+ return path.join(bunInstallDir, "install", "global", "node_modules");
246
+ };
247
+
248
+ /**
249
+ * Get npm's global node_modules directory.
250
+ * Uses `npm root -g` equivalent logic.
251
+ */
252
+ const getNpmGlobalNodeModules = async (): Promise<string | null> => {
253
+ // Check common npm global locations
254
+ const npmPrefix = process.env.NPM_CONFIG_PREFIX;
255
+ if (npmPrefix) {
256
+ return path.join(npmPrefix, "lib", "node_modules");
257
+ }
258
+
259
+ // Try NVM location
260
+ const nvmDir = process.env.NVM_DIR;
261
+ if (nvmDir) {
262
+ // NVM stores globals in the current node version's lib/node_modules
263
+ const nodeVersion = process.version;
264
+ const nvmNodeModules = path.join(
265
+ nvmDir,
266
+ "versions",
267
+ "node",
268
+ nodeVersion,
269
+ "lib",
270
+ "node_modules",
271
+ );
272
+ try {
273
+ await fs.access(nvmNodeModules);
274
+ return nvmNodeModules;
275
+ } catch {
276
+ // NVM path doesn't exist
277
+ }
278
+ }
279
+
280
+ // Fallback: check common system locations
281
+ const commonPaths = [
282
+ "/usr/local/lib/node_modules",
283
+ "/usr/lib/node_modules",
284
+ path.join(process.env.HOME ?? "~", ".npm-global", "lib", "node_modules"),
285
+ ];
286
+
287
+ for (const p of commonPaths) {
288
+ try {
289
+ await fs.access(p);
290
+ return p;
291
+ } catch {
292
+ // Path doesn't exist
293
+ }
294
+ }
295
+
296
+ return null;
297
+ };
298
+
299
+ /**
300
+ * Scan a node_modules directory for summon-* packages.
301
+ */
302
+ const scanNodeModulesForSummonPackages = async (
303
+ nodeModulesDir: string,
304
+ root: GeneratorNode,
305
+ origin: GeneratorOrigin = "global",
306
+ ): Promise<void> => {
307
+ try {
308
+ await fs.access(nodeModulesDir);
309
+ const entries = await fs.readdir(nodeModulesDir);
310
+
311
+ for (const entry of entries) {
312
+ const entryPath = path.join(nodeModulesDir, entry);
313
+
314
+ if (entry.startsWith("@")) {
315
+ // Scoped packages
316
+ if (!(await isDirectory(entryPath))) continue;
317
+ try {
318
+ const scopedEntries = await fs.readdir(entryPath);
319
+ for (const scopedEntry of scopedEntries) {
320
+ if (scopedEntry.startsWith("summon-")) {
321
+ const pkgDir = path.join(entryPath, scopedEntry);
322
+ if (await isDirectory(pkgDir)) {
323
+ await processPackage(
324
+ `${entry}/${scopedEntry}`,
325
+ pkgDir,
326
+ root,
327
+ origin,
328
+ );
329
+ }
330
+ }
331
+ }
332
+ } catch {
333
+ // Scope directory doesn't exist
334
+ }
335
+ } else if (entry.startsWith("summon-")) {
336
+ if (await isDirectory(entryPath)) {
337
+ await processPackage(entry, entryPath, root, origin);
338
+ }
339
+ }
340
+ }
341
+ } catch {
342
+ // Directory doesn't exist - that's fine
343
+ }
344
+ };
345
+
346
+ /**
347
+ * Discover globally installed summon-* packages.
348
+ * Looks in global package manager locations:
349
+ * 1. Bun global packages (~/.bun/install/global/node_modules)
350
+ * 2. NPM global packages (npm root -g)
351
+ *
352
+ * Users can link packages globally using:
353
+ * bun link # from the package directory
354
+ * npm link # from the package directory
355
+ */
356
+ const discoverGlobalPackages = async (root: GeneratorNode): Promise<void> => {
357
+ // 1. Bun global packages
358
+ const bunGlobalNodeModules = getBunGlobalNodeModules();
359
+ await scanNodeModulesForSummonPackages(bunGlobalNodeModules, root, "global");
360
+
361
+ // 2. NPM global packages
362
+ const npmGlobalNodeModules = await getNpmGlobalNodeModules();
363
+ if (npmGlobalNodeModules) {
364
+ await scanNodeModulesForSummonPackages(
365
+ npmGlobalNodeModules,
366
+ root,
367
+ "global",
368
+ );
369
+ }
370
+ };
371
+
372
+ // =============================================================================
373
+ // Public API
374
+ // =============================================================================
375
+
376
+ interface DiscoverOptions {
377
+ /** When set, ONLY load from this path (for testing). */
378
+ explicitPath?: string;
379
+ /** Directory containing built-in generators. Defaults to ../generators relative to this file. */
380
+ builtinDir?: string;
381
+ }
382
+
383
+ /**
384
+ * Create the root generator tree from all sources.
385
+ *
386
+ * When `explicitPath` is provided, ONLY load from that path (for testing).
387
+ *
388
+ * Otherwise, priority (highest to lowest, later overrides earlier):
389
+ * 1. Built-in generators from \@canonical/summon
390
+ * 2. Global packages (bun link / npm link locations)
391
+ * 3. Project ./node_modules/summon-* packages (highest priority)
392
+ *
393
+ * @note Impure — scans the filesystem and imports generator modules.
394
+ */
395
+ export default async function discoverGeneratorTree(
396
+ explicitPathOrOptions?: string | DiscoverOptions,
397
+ ): Promise<GeneratorNode> {
398
+ const options: DiscoverOptions =
399
+ typeof explicitPathOrOptions === "string"
400
+ ? { explicitPath: explicitPathOrOptions }
401
+ : (explicitPathOrOptions ?? {});
402
+ const { explicitPath, builtinDir } = options;
403
+ const root: GeneratorNode = {
404
+ name: "root",
405
+ path: "",
406
+ children: new Map(),
407
+ };
408
+
409
+ if (explicitPath) {
410
+ // Explicit path mode: ONLY load from the specified path
411
+ const absolutePath = path.isAbsolute(explicitPath)
412
+ ? explicitPath
413
+ : path.join(process.cwd(), explicitPath);
414
+
415
+ // Check if it's a package with package.json (barrel export)
416
+ const pkgJsonPath = path.join(absolutePath, "package.json");
417
+ try {
418
+ await fs.access(pkgJsonPath);
419
+ // It's a package - use processPackage to load from barrel
420
+ await processPackage(
421
+ path.basename(absolutePath),
422
+ absolutePath,
423
+ root,
424
+ "local",
425
+ );
426
+ } catch {
427
+ // Not a package - scan directory for generators
428
+ await buildGeneratorTree(absolutePath, root, "local");
429
+ }
430
+ return root;
431
+ }
432
+
433
+ // Normal discovery mode (order matters: later sources override earlier)
434
+
435
+ // 1. Built-in generators (lowest priority)
436
+ const defaultBuiltinDir = path.join(__dirname, "..", "generators");
437
+ await buildGeneratorTree(builtinDir ?? defaultBuiltinDir, root, "builtin");
438
+
439
+ // 2-3. Global packages and generators
440
+ await discoverGlobalPackages(root);
441
+
442
+ // 3. node_modules packages (project-level, highest priority)
443
+ await discoverNodeModulesPackages(
444
+ path.join(process.cwd(), "node_modules"),
445
+ root,
446
+ );
447
+
448
+ return root;
449
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Shared generator cache — stores generators loaded from package barrels.
3
+ *
4
+ * Extracted into its own module so both {@link discoverGeneratorTree}
5
+ * (library) and `loadGenerator` (binary) can access the same Map instance
6
+ * without coupling library code to binary-only modules.
7
+ */
8
+
9
+ import type { GeneratorDefinition } from "../types.js";
10
+
11
+ /**
12
+ * Key is the command path (e.g., "component/react").
13
+ * Populated by {@link discoverGeneratorTree} when processing package barrels.
14
+ * Read by `loadGenerator` when resolving `cache:` prefixed paths.
15
+ */
16
+ export const generatorCache = new Map<string, GeneratorDefinition>();
@@ -0,0 +1,3 @@
1
+ export { default as discoverGeneratorTree } from "./discoverGeneratorTree.js";
2
+ export { generatorCache } from "./generatorCache.js";
3
+ export type { GeneratorNode, GeneratorOrigin } from "./types.js";
@@ -0,0 +1,18 @@
1
+ /** Origin of a generator (for display purposes). */
2
+ export type GeneratorOrigin = "local" | "global" | "package" | "builtin";
3
+
4
+ /** A node in the generator discovery tree. */
5
+ export interface GeneratorNode {
6
+ name: string;
7
+ /** Directory path */
8
+ path: string;
9
+ /** Path to index.ts if this is a runnable generator */
10
+ indexPath?: string;
11
+ children: Map<string, GeneratorNode>;
12
+ origin?: GeneratorOrigin;
13
+ meta?: {
14
+ name: string;
15
+ description: string;
16
+ version: string;
17
+ };
18
+ }
package/src/index.ts ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Summon - A Monadic Task-Centric Code Generator Framework
3
+ *
4
+ * The effect framework (Task, Effect, combinators, primitives, interpreter,
5
+ * dry-run) lives in @canonical/task. This package provides the generation
6
+ * layer on top: generator definitions, templates, stamps, and CLI types.
7
+ *
8
+ * @packageDocumentation
9
+ */
10
+
11
+ // =============================================================================
12
+ // Generator Types
13
+ // =============================================================================
14
+
15
+ export type {
16
+ AnyGenerator,
17
+ GeneratorDefinition,
18
+ GeneratorMeta,
19
+ PromptDefinition,
20
+ } from "./types.js";
21
+
22
+ // =============================================================================
23
+ // Stamps (generated file stamp comments)
24
+ // =============================================================================
25
+
26
+ export type { RunTaskWithStampOptions, StampConfig } from "./stamp.js";
27
+ export { applyStamp, runTaskWithStamp } from "./stamp.js";
28
+
29
+ // =============================================================================
30
+ // Templates
31
+ // =============================================================================
32
+
33
+ export type {
34
+ StampOptions,
35
+ TemplateDirOptions,
36
+ TemplateOptions,
37
+ TemplatingEngine,
38
+ } from "./template.js";
39
+ export {
40
+ ejsEngine,
41
+ generateStamp,
42
+ generatorComment,
43
+ generatorHtmlComment,
44
+ prependStamp,
45
+ renderFile,
46
+ renderString,
47
+ renderStringAsync,
48
+ template,
49
+ templateDir,
50
+ templateHelpers,
51
+ withHelpers,
52
+ } from "./template.js";
53
+
54
+ // =============================================================================
55
+ // CLI Types (for generator authors)
56
+ // =============================================================================
57
+
58
+ export type { ForbidReserved, ReservedOption } from "./cli-types.js";
59
+
60
+ // =============================================================================
61
+ // Discovery (generator tree algorithm + types)
62
+ // =============================================================================
63
+
64
+ export { default as discoverGeneratorTree } from "./discovery/discoverGeneratorTree.js";
65
+ export { generatorCache } from "./discovery/generatorCache.js";
66
+ export type { GeneratorNode, GeneratorOrigin } from "./discovery/types.js";