create-backon 0.10.0 → 0.13.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-backon",
3
- "version": "0.10.0",
3
+ "version": "0.13.0",
4
4
  "type": "module",
5
5
  "description": "Scaffolds a new backend project on backon — like `bun create vite@latest`, but for a consistent controller/routes/services backend layout. Runs via bunx/bun create or npx/npm create.",
6
6
  "license": "MIT",
@@ -27,7 +27,8 @@
27
27
  "prepublishOnly": "bun run typecheck && bun run test && bun run build"
28
28
  },
29
29
  "dependencies": {
30
- "@clack/prompts": "^0.9.1"
30
+ "@clack/prompts": "^0.9.1",
31
+ "ts-morph": "^28.0.0"
31
32
  },
32
33
  "devDependencies": {
33
34
  "@types/bun": "latest",
package/src/add-method.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { readFile, writeFile } from "node:fs/promises";
2
2
  import { join } from "node:path";
3
+ import { editSource, ensureImports, appendStatements } from "./ast-edit";
3
4
  import { detectProject } from "./detect";
4
5
  import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
5
6
  import { parseRouteMethods } from "./route-methods";
@@ -19,33 +20,16 @@ export interface AddMethodResult {
19
20
  }
20
21
 
21
22
  // The exact placeholder comment each blank file starts with — see
22
- // templates/route.ts. Stripped the first time a real method lands, wherever
23
- // it happens to sit in the file (start of controller.ts/services.ts, but
24
- // mid-file in routes.ts, after the Router()/Hono() line).
23
+ // templates/route.ts. Stripped as plain text before the AST layer below
24
+ // ever sees the file: a file that's only a comment (no statements yet) has
25
+ // nothing for ensureImports()/appendStatements() to attach it to, and this
26
+ // comment isn't code that needs AST-accurate handling anyway.
25
27
  const PLACEHOLDER_PATTERN = /\/\/ No (?:routes|methods) yet[^\n]*\n\n?/;
26
28
 
27
29
  function stripPlaceholder(content: string): string {
28
30
  return content.replace(PLACEHOLDER_PATTERN, "");
29
31
  }
30
32
 
31
- /** Inserts any of importLines not already present, right after the file's existing leading import block. */
32
- function ensureImports(content: string, importLines: string[]): string {
33
- const stripped = stripPlaceholder(content);
34
- const missing = importLines.filter((line) => !stripped.includes(line));
35
- if (missing.length === 0) return stripped;
36
-
37
- const lines = stripped.split("\n");
38
- let insertAt = 0;
39
- while (insertAt < lines.length && lines[insertAt]?.startsWith("import ")) insertAt++;
40
- lines.splice(insertAt, 0, ...missing);
41
- return lines.join("\n");
42
- }
43
-
44
- function appendBlock(content: string, block: string): string {
45
- const trimmed = content.replace(/\n+$/, "");
46
- return trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`;
47
- }
48
-
49
33
  /**
50
34
  * Adds one HTTP method to an already-mounted, already-blank-or-partial
51
35
  * endpoint: appends a defineRoute() export (with whatever params/body/query
@@ -55,6 +39,13 @@ function appendBlock(content: string, block: string): string {
55
39
  * the route mount line. All three files are read fresh off disk first, so
56
40
  * this is safe to call repeatedly, or after the previous method's stub was
57
41
  * hand-edited.
42
+ *
43
+ * Every file edit goes through ast-edit.ts's ts-morph helpers: an import is
44
+ * only added if the real AST doesn't already have one covering it (not
45
+ * whether an identical line of text happens to appear anywhere), and the
46
+ * new method's code is appended as real parsed statements rather than
47
+ * spliced-in text — so this stays correct even if the file was previously
48
+ * hand-reformatted in a way that would have thrown off a text-based check.
58
49
  */
59
50
  export async function addMethod(route: string, spec: MethodSpec, cwd: string = process.cwd()): Promise<AddMethodResult> {
60
51
  const { root, framework, language, ext } = await detectProject(cwd);
@@ -84,12 +75,20 @@ export async function addMethod(route: string, spec: MethodSpec, cwd: string = p
84
75
  throw new Error(`${spec.verb.toUpperCase()} ${spec.path} is already mounted in ${routesPath}.`);
85
76
  }
86
77
 
87
- const newController = appendBlock(ensureImports(controllerContents, controllerImports(route, framework)), renderControllerMethod(spec));
88
- const newRoutes = appendBlock(
89
- ensureImports(routesContents, [`import * as controller from "./${route}.controller";`]),
90
- routeMountLine(route, spec)
91
- );
92
- const newServices = appendBlock(ensureImports(servicesContents, serviceImports(route, spec, language)), renderServiceMethod(spec, language));
78
+ const newController = editSource(controllerPath, stripPlaceholder(controllerContents), (project, sourceFile) => {
79
+ ensureImports(sourceFile, project, controllerImports(route, framework));
80
+ appendStatements(sourceFile, renderControllerMethod(spec));
81
+ });
82
+
83
+ const newRoutes = editSource(routesPath, stripPlaceholder(routesContents), (project, sourceFile) => {
84
+ ensureImports(sourceFile, project, [`import * as controller from "./${route}.controller";`]);
85
+ appendStatements(sourceFile, routeMountLine(route, spec));
86
+ });
87
+
88
+ const newServices = editSource(servicesPath, stripPlaceholder(servicesContents), (project, sourceFile) => {
89
+ ensureImports(sourceFile, project, serviceImports(route, spec, language));
90
+ appendStatements(sourceFile, renderServiceMethod(spec, language));
91
+ });
93
92
 
94
93
  await Promise.all([
95
94
  writeFile(controllerPath, newController),
@@ -0,0 +1,224 @@
1
+ import { Node, Project, type SourceFile } from "ts-morph";
2
+
3
+ /**
4
+ * The AST-based replacement for the old ensureImports()/appendBlock()
5
+ * (add-method.ts) and removeBlock() (remove-method.ts) pair — both used to
6
+ * find "this method's code" by splitting file content on blank lines and
7
+ * matching text, which only works if nothing nearby ever gets reformatted.
8
+ * ts-morph gives real statement/import identity instead: an import is
9
+ * recognized as already present by its actual module+specifier structure
10
+ * (not by whether an identical line of text happens to appear anywhere in
11
+ * the file), and a method's statements are found and removed by the exact
12
+ * name addMethod()/removeMethod() already enforce is unique per endpoint —
13
+ * so a hand-reformatted quote style, semicolon, or import order doesn't
14
+ * make either operation silently miss its target.
15
+ *
16
+ * One throwaway in-memory Project per file edit — these are cheap and
17
+ * short-lived (one per addMethod()/removeMethod() call), not shared across
18
+ * the CLI's lifetime.
19
+ */
20
+ function makeProject(): Project {
21
+ return new Project({
22
+ useInMemoryFileSystem: true,
23
+ compilerOptions: { allowJs: true, checkJs: false },
24
+ });
25
+ }
26
+
27
+ export function loadSource(path: string, contents: string): { project: Project; sourceFile: SourceFile } {
28
+ const project = makeProject();
29
+ const sourceFile = project.createSourceFile(path, contents);
30
+ return { project, sourceFile };
31
+ }
32
+
33
+ /** Load → mutate → print, in one call — the shape every add-method.ts/remove-method.ts edit follows. */
34
+ export function editSource(path: string, contents: string, mutate: (project: Project, sourceFile: SourceFile) => void): string {
35
+ const { project, sourceFile } = loadSource(path, contents);
36
+ mutate(project, sourceFile);
37
+ return printSource(sourceFile);
38
+ }
39
+
40
+ interface ParsedImportLine {
41
+ moduleSpecifier: string;
42
+ isTypeOnly: boolean;
43
+ namespaceImport?: string;
44
+ namedImports: string[];
45
+ }
46
+
47
+ /** Parses one raw `import ... from "...";` line (as templates/route.ts already produces) into its real structure, via a disposable scratch file in the same project. */
48
+ function parseImportLine(project: Project, line: string): ParsedImportLine {
49
+ const scratch = project.createSourceFile("__scratch_import__.ts", line, { overwrite: true });
50
+ const decl = scratch.getImportDeclarations()[0];
51
+ if (!decl) throw new Error(`Not a valid import statement: ${line}`);
52
+ const parsed: ParsedImportLine = {
53
+ moduleSpecifier: decl.getModuleSpecifierValue(),
54
+ isTypeOnly: decl.isTypeOnly(),
55
+ namespaceImport: decl.getNamespaceImport()?.getText(),
56
+ namedImports: decl.getNamedImports().map((ni) => ni.getName()),
57
+ };
58
+ project.removeSourceFile(scratch);
59
+ return parsed;
60
+ }
61
+
62
+ /**
63
+ * Adds each of `lines` to `sourceFile` unless a declaration already covers
64
+ * it — checked by real import structure, not raw text. Each line becomes
65
+ * its own new import declaration when nothing already covers it (mirrors
66
+ * the old one-declaration-per-addMethod-call granularity, just checked more
67
+ * accurately — this doesn't merge into an existing *different* named-import
68
+ * declaration from the same module, since remove-method.ts's cleanup relies
69
+ * on each method's schema-type import staying in its own declaration).
70
+ */
71
+ export function ensureImports(sourceFile: SourceFile, project: Project, lines: string[]): void {
72
+ for (const line of lines) {
73
+ const spec = parseImportLine(project, line);
74
+ const alreadyPresent = sourceFile.getImportDeclarations().some((d) => {
75
+ if (d.getModuleSpecifierValue() !== spec.moduleSpecifier) return false;
76
+ if (d.isTypeOnly() !== spec.isTypeOnly) return false;
77
+ if (spec.namespaceImport) return d.getNamespaceImport()?.getText() === spec.namespaceImport;
78
+ const names = new Set(d.getNamedImports().map((ni) => ni.getName()));
79
+ return spec.namedImports.length > 0 && spec.namedImports.every((n) => names.has(n));
80
+ });
81
+ if (alreadyPresent) continue;
82
+
83
+ sourceFile.addImportDeclaration({
84
+ moduleSpecifier: spec.moduleSpecifier,
85
+ isTypeOnly: spec.isTypeOnly,
86
+ ...(spec.namespaceImport ? { namespaceImport: spec.namespaceImport } : { namedImports: spec.namedImports }),
87
+ });
88
+ }
89
+ }
90
+
91
+ /** Appends a method's generated code (from templates/route.ts) as real statements at the end of the file. */
92
+ export function appendStatements(sourceFile: SourceFile, code: string): void {
93
+ sourceFile.addStatements(`\n${code}`);
94
+ }
95
+
96
+ /**
97
+ * Removes a method's schema consts (nameParamsSchema/BodySchema/QuerySchema)
98
+ * and its defineRoute() export from a controller file — found by exact
99
+ * declared name, the same uniqueness addMethod() already enforces per
100
+ * endpoint, rather than by which \n\n-delimited block of text they happen
101
+ * to sit in. Returns whether anything was actually removed, so the caller
102
+ * can tell "nothing there" apart from "removed everything there was".
103
+ */
104
+ export function removeControllerMethod(sourceFile: SourceFile, name: string): boolean {
105
+ const targets = new Set([name, `${name}ParamsSchema`, `${name}BodySchema`, `${name}QuerySchema`]);
106
+ let removed = false;
107
+ for (const stmt of sourceFile.getVariableStatements()) {
108
+ const decls = stmt.getDeclarations();
109
+ if (decls.length === 1 && targets.has(decls[0]!.getName())) {
110
+ stmt.remove();
111
+ removed = true;
112
+ }
113
+ }
114
+ // renderControllerMethod() puts a "// TODO: replace with the real shape
115
+ // of ..." comment directly above a body/query schema const, with no
116
+ // blank line between them. When a method's schema const sits right next
117
+ // to ANOTHER statement in the same group (e.g. paramsSchema directly
118
+ // above bodySchema, no blank line), ts-morph's leading-trivia detection
119
+ // can attribute that comment to more than one statement, and .remove()
120
+ // above doesn't reliably take it with it — it survives, reattached as
121
+ // leading trivia on whatever statement now comes next. Sweep for it
122
+ // explicitly, matched by this method's own name (never another method's,
123
+ // since the name is unique per endpoint) rather than by position, and
124
+ // only AFTER the statement removals above, once each surviving
125
+ // statement's leading trivia is no longer ambiguous.
126
+ if (removed) stripOrphanedTodoComment(sourceFile, name);
127
+ return removed;
128
+ }
129
+
130
+ function stripOrphanedTodoComment(sourceFile: SourceFile, name: string): void {
131
+ const marker = `replace with the real shape of "${name}"`;
132
+ const ranges: Array<{ pos: number; end: number }> = [];
133
+ for (const stmt of sourceFile.getStatements()) {
134
+ for (const range of stmt.getLeadingCommentRanges()) {
135
+ if (range.getText().includes(marker)) ranges.push({ pos: range.getPos(), end: range.getEnd() });
136
+ }
137
+ }
138
+ // Remove furthest-in-the-file first, so an earlier removal never shifts
139
+ // the position of a range still waiting to be processed.
140
+ ranges.sort((a, b) => b.pos - a.pos);
141
+ const fullText = sourceFile.getFullText();
142
+ for (const { pos, end } of ranges) {
143
+ const end2 = fullText[end] === "\n" ? end + 1 : end; // eat the comment's own newline too, not just its text
144
+ sourceFile.removeText(pos, end2);
145
+ }
146
+ }
147
+
148
+ /** Removes the mount-line ExpressionStatement calling controller.<name> — matched by that reference, not by verb/path text, so a hand-reformatted line (quotes, spacing, a trailing comment) doesn't hide it. */
149
+ export function removeRouteMount(sourceFile: SourceFile, name: string): boolean {
150
+ for (const stmt of sourceFile.getStatements()) {
151
+ if (!Node.isExpressionStatement(stmt)) continue;
152
+ const expr = stmt.getExpression();
153
+ if (!Node.isCallExpression(expr)) continue;
154
+ const args = expr.getArguments();
155
+ const last = args[args.length - 1];
156
+ if (last && Node.isPropertyAccessExpression(last) && last.getName() === name) {
157
+ stmt.remove();
158
+ return true;
159
+ }
160
+ }
161
+ return false;
162
+ }
163
+
164
+ /** Removes a service function by name, plus any import declaration whose entire named-import set belongs to that same method's schema types (each method's type import stays in its own declaration — see ensureImports()'s doc comment — so "entire set" never catches another method's names too). */
165
+ export function removeServiceMethod(sourceFile: SourceFile, name: string): boolean {
166
+ const fn = sourceFile.getFunction(name);
167
+ if (!fn) return false;
168
+ fn.remove();
169
+
170
+ const methodTypeNames = new Set([`${name}ParamsSchema`, `${name}BodySchema`, `${name}QuerySchema`]);
171
+ for (const importDecl of sourceFile.getImportDeclarations()) {
172
+ const names = importDecl.getNamedImports().map((ni) => ni.getName());
173
+ if (names.length > 0 && names.every((n) => methodTypeNames.has(n))) {
174
+ importDecl.remove();
175
+ }
176
+ }
177
+ return true;
178
+ }
179
+
180
+ const SCHEMA_CONST_SUFFIXES = ["ParamsSchema", "BodySchema", "QuerySchema"];
181
+
182
+ function isSchemaConstStatement(node: Node): boolean {
183
+ if (!Node.isVariableStatement(node)) return false;
184
+ const decls = node.getDeclarations();
185
+ return decls.length === 1 && SCHEMA_CONST_SUFFIXES.some((suffix) => decls[0]!.getName().endsWith(suffix));
186
+ }
187
+
188
+ /**
189
+ * Reconstructs the file's text from its current AST instead of returning
190
+ * whatever ts-morph's in-place text edits left behind — in-place edits are
191
+ * precise about *removing* a node's own text, but don't reliably leave the
192
+ * same blank-line spacing around the survivors that the old block-based
193
+ * convention had. Import declarations stay packed together with no blank
194
+ * line between them (as generated); every other top-level statement gets
195
+ * its own blank-line-separated paragraph, EXCEPT a schema const
196
+ * (*ParamsSchema/*BodySchema/*QuerySchema) which stays glued to the
197
+ * statement right after it — renderControllerMethod() always emits a
198
+ * method's schema consts immediately followed by its defineRoute() export,
199
+ * with no blank line between them, and this keeps that grouping intact
200
+ * through arbitrary add/remove cycles instead of only on first write.
201
+ */
202
+ export function printSource(sourceFile: SourceFile): string {
203
+ const importDecls = sourceFile.getImportDeclarations();
204
+ const importText = importDecls.map((d) => d.getText()).join("\n");
205
+
206
+ const rest = sourceFile.getStatements().filter((s) => !Node.isImportDeclaration(s));
207
+ const paragraphs: string[] = [];
208
+ let i = 0;
209
+ while (i < rest.length) {
210
+ const parts: string[] = [];
211
+ while (i < rest.length && isSchemaConstStatement(rest[i]!)) {
212
+ parts.push(rest[i]!.getFullText().trim());
213
+ i++;
214
+ }
215
+ if (i < rest.length) {
216
+ parts.push(rest[i]!.getFullText().trim());
217
+ i++;
218
+ }
219
+ paragraphs.push(parts.join("\n"));
220
+ }
221
+
222
+ const blocks = [importText, ...paragraphs].filter((b) => b.length > 0);
223
+ return blocks.length > 0 ? `${blocks.join("\n\n")}\n` : "";
224
+ }