create-backon 0.10.0 → 0.11.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/README.md +53 -2
- package/dist/cli.js +387 -42
- package/package.json +3 -2
- package/src/add-method.ts +26 -27
- package/src/ast-edit.ts +224 -0
- package/src/cli.ts +36 -2
- package/src/crud-scaffold.ts +62 -0
- package/src/generate.ts +3 -1
- package/src/remove-method.ts +27 -29
- package/src/templates/base.ts +202 -2
package/README.md
CHANGED
|
@@ -104,7 +104,19 @@ and regenerates `src/endpoints/index.ts` so the new route is mounted next
|
|
|
104
104
|
to the ones that were already there. It refuses to run outside a backon
|
|
105
105
|
project, refuses a route name whose folder already exists, and refuses a
|
|
106
106
|
name that's already mounted. Run `add-method` next to give the new route
|
|
107
|
-
an actual GET/POST/etc
|
|
107
|
+
an actual GET/POST/etc — or add `--crud` to wire up the standard five in
|
|
108
|
+
one go instead of one at a time:
|
|
109
|
+
|
|
110
|
+
```
|
|
111
|
+
bun run add-route users --crud
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
Adds `list` (GET /), `create` (POST /), `getById` (GET /:id), `update`
|
|
115
|
+
(PUT /:id), and `remove` (DELETE /:id) right after creating the route —
|
|
116
|
+
the exact same names `add-method`'s own suggestions already default to,
|
|
117
|
+
just all five at once. Leave `--crud` off (or say no to the "Scaffold
|
|
118
|
+
standard CRUD methods now?" prompt when running `add-route` with no name)
|
|
119
|
+
to get the usual blank endpoint instead.
|
|
108
120
|
|
|
109
121
|
## Adding a method to a route
|
|
110
122
|
|
|
@@ -133,6 +145,13 @@ told to stop, so a whole endpoint's worth of methods is normally one
|
|
|
133
145
|
`bun run add-method` session. Refuses a method name or a verb+path pair
|
|
134
146
|
that's already there.
|
|
135
147
|
|
|
148
|
+
Every file edit here (and in `remove-method`, below) goes through a real
|
|
149
|
+
TypeScript/JavaScript AST ([ts-morph](https://ts-morph.com)) rather than
|
|
150
|
+
matching raw text — an import is recognized as already present by its
|
|
151
|
+
actual structure, and a method's own statements are found by the exact
|
|
152
|
+
name `add-method` already enforces is unique per endpoint. A hand-reformatted
|
|
153
|
+
mount line or import doesn't throw either operation off.
|
|
154
|
+
|
|
136
155
|
## Removing a route
|
|
137
156
|
|
|
138
157
|
The undo for `add-route`:
|
|
@@ -206,7 +225,8 @@ bun run server-config
|
|
|
206
225
|
or `bunx create-backon server-config`. The interactive alternative to
|
|
207
226
|
running `add-route`/`add-method`/`remove-route` individually — opens with
|
|
208
227
|
the same endpoint dashboard `project` shows, then a menu: add a new
|
|
209
|
-
endpoint
|
|
228
|
+
endpoint (with the same "scaffold standard CRUD methods now?" prompt
|
|
229
|
+
`add-route` offers), remove one, add a method, remove a method, or modify a method
|
|
210
230
|
(change its path, name, or body/query validation in place — the one thing
|
|
211
231
|
none of the standalone commands offer, since it's a checked
|
|
212
232
|
remove-then-re-add rather than a new codegen path). Loops back to the menu
|
|
@@ -242,6 +262,37 @@ same spec and reference page as live routes on a running server instead of
|
|
|
242
262
|
writing them to disk — useful for CI, static hosting, or feeding the spec
|
|
243
263
|
into an external tool, where `serveApiDocs`'s live routes don't apply.
|
|
244
264
|
|
|
265
|
+
## Generating a typed API client
|
|
266
|
+
|
|
267
|
+
Every generated project also includes:
|
|
268
|
+
|
|
269
|
+
```
|
|
270
|
+
bun run generate-client
|
|
271
|
+
```
|
|
272
|
+
|
|
273
|
+
Writes `client/api.<ext>` — a fetch client with one function per mounted
|
|
274
|
+
method, grouped by endpoint (`usersApi.list()`, `usersApi.create(body)`,
|
|
275
|
+
`usersApi.getById(id)`, and so on), read directly off `*.routes.<ext>`/
|
|
276
|
+
`*.controller.<ext>` — the same files `add-method`/`remove-method`/
|
|
277
|
+
`server-config` already write, so there's nothing to keep in sync by hand.
|
|
278
|
+
Backed by `scripts/generate-client.<ext>`, generated alongside everything
|
|
279
|
+
else; unlike `generate-docs.<ext>` it doesn't import `src/app` — it reads
|
|
280
|
+
the endpoint files directly, so it can't fail because `app.ts` throws on a
|
|
281
|
+
missing env var. It also never goes stale on its own: it re-discovers
|
|
282
|
+
routes fresh every time it *runs*, so only its output needs a re-run after
|
|
283
|
+
routes or methods change, not the script itself.
|
|
284
|
+
|
|
285
|
+
In TypeScript projects, each generated function's body/query parameters
|
|
286
|
+
are typed via `z.infer<typeof theSchema>` against the schema the
|
|
287
|
+
controller already exports — imported by type, not re-declared, so the
|
|
288
|
+
client's argument types can't drift from what `defineRoute()` actually
|
|
289
|
+
validates. Response shape is deliberately not claimed beyond an optional
|
|
290
|
+
`<T = unknown>` generic per call (`usersApi.list<User[]>()`) — backon
|
|
291
|
+
doesn't validate responses, so nothing here pretends to know a shape it
|
|
292
|
+
can't verify. JavaScript projects get the same functions with no type
|
|
293
|
+
annotations. `client/` is a build artifact like `openapi.json`/`docs.html`,
|
|
294
|
+
not source, so it's in the generated `.gitignore` by default.
|
|
295
|
+
|
|
245
296
|
## Deploying to Vercel
|
|
246
297
|
|
|
247
298
|
Picking Vercel at the "Where's this headed?" prompt adds two things, both
|
package/dist/cli.js
CHANGED
|
@@ -481,6 +481,169 @@ writeFileSync("docs.html", apiReferenceHtmlInline(spec, "${projectName}"));
|
|
|
481
481
|
console.log("Wrote openapi.json and docs.html");
|
|
482
482
|
`;
|
|
483
483
|
}
|
|
484
|
+
function renderGenerateClientScript(language) {
|
|
485
|
+
const ext = language === "javascript" ? "js" : "ts";
|
|
486
|
+
const typed = language === "javascript" ? "false" : "true";
|
|
487
|
+
const ann = (t) => language === "javascript" ? "" : `: ${t}`;
|
|
488
|
+
return `// Regenerates client/api.${ext} from src/endpoints/ \u2014 reads *.routes.${ext}/*.controller.${ext}
|
|
489
|
+
// directly, the same source add-method/remove-method/server-config write to, so there's
|
|
490
|
+
// nothing to keep in sync by hand. Safe to re-run any time; nothing here needs updating
|
|
491
|
+
// when a route or method is added, removed, or modified \u2014 only its output does.
|
|
492
|
+
import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
|
|
493
|
+
import { join } from "node:path";
|
|
494
|
+
|
|
495
|
+
const EXT = "${ext}";
|
|
496
|
+
const TYPED = ${typed};
|
|
497
|
+
|
|
498
|
+
const root = process.cwd();
|
|
499
|
+
const endpointsDir = join(root, "src/endpoints");
|
|
500
|
+
|
|
501
|
+
const MOUNT_PATTERN = /endpoints\\.(?:route|use)\\("\\/([a-z0-9-]+)"/g;
|
|
502
|
+
const METHOD_PATTERN = /\\.(get|post|put|patch|delete)\\(\\s*"([^"]*)"\\s*,\\s*controller\\.(\\w+)\\s*\\)/g;
|
|
503
|
+
|
|
504
|
+
function paramNames(path${ann("string")}) {
|
|
505
|
+
return Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g)).map((m) => m[1]);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
function camelCase(name${ann("string")}) {
|
|
509
|
+
const parts = name.split("-");
|
|
510
|
+
return parts[0] + parts.slice(1).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
// Builds a JS expression string for the full request path \u2014 literal
|
|
514
|
+
// segments as JSON string literals, :param segments as bare identifiers,
|
|
515
|
+
// joined with "+" \u2014 e.g. "/users/:id" becomes the text: "/users/" + id
|
|
516
|
+
function pathExpr(route${ann("string")}, method${ann("any")}) {
|
|
517
|
+
const fullPath = "/" + route + (method.path === "/" ? "" : method.path);
|
|
518
|
+
const pieces = [];
|
|
519
|
+
let lastIndex = 0;
|
|
520
|
+
const paramRe = /:([A-Za-z0-9_]+)/g;
|
|
521
|
+
let match;
|
|
522
|
+
while ((match = paramRe.exec(fullPath))) {
|
|
523
|
+
if (match.index > lastIndex) pieces.push(JSON.stringify(fullPath.slice(lastIndex, match.index)));
|
|
524
|
+
pieces.push(match[1]);
|
|
525
|
+
lastIndex = match.index + match[0].length;
|
|
526
|
+
}
|
|
527
|
+
if (lastIndex < fullPath.length) pieces.push(JSON.stringify(fullPath.slice(lastIndex)));
|
|
528
|
+
return pieces.join(" + ");
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
function funcArgs(method${ann("any")}) {
|
|
532
|
+
const args = paramNames(method.path).slice();
|
|
533
|
+
if (method.needsBody) args.push("body");
|
|
534
|
+
if (method.needsQuery) args.push("query");
|
|
535
|
+
return args;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
function typedFuncArgs(method${ann("any")}) {
|
|
539
|
+
const parts = paramNames(method.path).map((name) => name + ": string");
|
|
540
|
+
if (method.needsBody) parts.push("body: z.infer<typeof " + method.name + "BodySchema>");
|
|
541
|
+
if (method.needsQuery) parts.push("query: z.infer<typeof " + method.name + "QuerySchema>");
|
|
542
|
+
return parts.join(", ");
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
const indexContents = readFileSync(join(endpointsDir, "index." + EXT), "utf-8");
|
|
546
|
+
const routes = Array.from(indexContents.matchAll(MOUNT_PATTERN)).map((m) => m[1]);
|
|
547
|
+
|
|
548
|
+
const groups = [];
|
|
549
|
+
for (const route of routes) {
|
|
550
|
+
let routesContents, controllerContents;
|
|
551
|
+
try {
|
|
552
|
+
routesContents = readFileSync(join(endpointsDir, route, route + ".routes." + EXT), "utf-8");
|
|
553
|
+
controllerContents = readFileSync(join(endpointsDir, route, route + ".controller." + EXT), "utf-8");
|
|
554
|
+
} catch {
|
|
555
|
+
continue; // mounted but missing a file \u2014 \`bun run doctor\` already flags this, skip it here
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
const methods = Array.from(routesContents.matchAll(METHOD_PATTERN)).map((m) => ({
|
|
559
|
+
verb: m[1],
|
|
560
|
+
path: m[2],
|
|
561
|
+
name: m[3],
|
|
562
|
+
needsBody: controllerContents.includes(m[3] + "BodySchema"),
|
|
563
|
+
needsQuery: controllerContents.includes(m[3] + "QuerySchema"),
|
|
564
|
+
}));
|
|
565
|
+
if (methods.length > 0) groups.push({ route, methods });
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
if (groups.length === 0) {
|
|
569
|
+
console.log("No endpoints with methods yet \u2014 nothing to generate. Run \`bun run add-method\` first.");
|
|
570
|
+
process.exit(0);
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const importLines = [];
|
|
574
|
+
if (TYPED) {
|
|
575
|
+
importLines.push('import type { z } from "zod";');
|
|
576
|
+
const namesByModule = new Map();
|
|
577
|
+
for (const group of groups) {
|
|
578
|
+
const names = [];
|
|
579
|
+
for (const m of group.methods) {
|
|
580
|
+
if (m.needsBody) names.push(m.name + "BodySchema");
|
|
581
|
+
if (m.needsQuery) names.push(m.name + "QuerySchema");
|
|
582
|
+
}
|
|
583
|
+
if (names.length > 0) namesByModule.set("../src/endpoints/" + group.route + "/" + group.route + ".controller", names);
|
|
584
|
+
}
|
|
585
|
+
for (const [modulePath, names] of namesByModule) {
|
|
586
|
+
importLines.push('import type { ' + names.join(", ") + ' } from "' + modulePath + '";');
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
const helperLines = [
|
|
591
|
+
'const BASE_URL = (typeof process !== "undefined" && process.env.API_BASE_URL) || "";',
|
|
592
|
+
"",
|
|
593
|
+
TYPED ? "async function request<T>(path: string, init?: RequestInit): Promise<T> {" : "async function request(path, init) {",
|
|
594
|
+
" const res = await fetch(BASE_URL + path, {",
|
|
595
|
+
" ...init,",
|
|
596
|
+
' headers: { "Content-Type": "application/json", ...(init && init.headers ? init.headers : {}) },',
|
|
597
|
+
" });",
|
|
598
|
+
" if (!res.ok) {",
|
|
599
|
+
TYPED ? " const errBody: any = await res.json().catch(() => undefined);" : " const errBody = await res.json().catch(() => undefined);",
|
|
600
|
+
' throw new Error((errBody && errBody.error && errBody.error.message) || ("Request to " + path + " failed with " + res.status));',
|
|
601
|
+
" }",
|
|
602
|
+
TYPED ? " return res.json() as Promise<T>;" : " return res.json();",
|
|
603
|
+
"}",
|
|
604
|
+
];
|
|
605
|
+
|
|
606
|
+
const groupBlocks = groups.map((group) => {
|
|
607
|
+
const varName = camelCase(group.route) + "Api";
|
|
608
|
+
const methodLines = group.methods.map((m) => {
|
|
609
|
+
const signature = TYPED ? typedFuncArgs(m) : funcArgs(m).join(", ");
|
|
610
|
+
const genericPrefix = TYPED ? "<T = unknown>" : "";
|
|
611
|
+
|
|
612
|
+
let call = "request" + (TYPED ? "<T>" : "") + "(" + pathExpr(group.route, m);
|
|
613
|
+
if (m.needsQuery) call += ' + "?" + new URLSearchParams(query' + (TYPED ? " as any" : "") + ").toString()";
|
|
614
|
+
|
|
615
|
+
const initParts = [];
|
|
616
|
+
if (m.verb !== "get") initParts.push('method: "' + m.verb.toUpperCase() + '"');
|
|
617
|
+
if (m.needsBody) initParts.push("body: JSON.stringify(body)");
|
|
618
|
+
if (initParts.length > 0) call += ", { " + initParts.join(", ") + " }";
|
|
619
|
+
call += ")";
|
|
620
|
+
|
|
621
|
+
return " " + m.name + ": " + genericPrefix + "(" + signature + ") => " + call + ",";
|
|
622
|
+
});
|
|
623
|
+
return "export const " + varName + " = {\\n" + methodLines.join("\\n") + "\\n};";
|
|
624
|
+
});
|
|
625
|
+
|
|
626
|
+
const header =
|
|
627
|
+
"// Auto-generated by \`bun run generate-client\` from src/endpoints/ \u2014 re-run after adding, removing,\\n" +
|
|
628
|
+
"// or modifying methods (add-method/remove-method/server-config all count). Hand edits here are\\n" +
|
|
629
|
+
"// overwritten on the next run.\\n\\n";
|
|
630
|
+
|
|
631
|
+
const output =
|
|
632
|
+
header +
|
|
633
|
+
(importLines.length > 0 ? importLines.join("\\n") + "\\n\\n" : "") +
|
|
634
|
+
helperLines.join("\\n") +
|
|
635
|
+
"\\n\\n" +
|
|
636
|
+
groupBlocks.join("\\n\\n") +
|
|
637
|
+
"\\n";
|
|
638
|
+
|
|
639
|
+
mkdirSync(join(root, "client"), { recursive: true });
|
|
640
|
+
const outPath = join(root, "client", "api." + EXT);
|
|
641
|
+
writeFileSync(outPath, output);
|
|
642
|
+
console.log(
|
|
643
|
+
"Wrote " + outPath + " (" + groups.reduce((n, g) => n + g.methods.length, 0) + " method(s) across " + groups.length + " endpoint(s))"
|
|
644
|
+
);
|
|
645
|
+
`;
|
|
646
|
+
}
|
|
484
647
|
function renderEnvExample(db) {
|
|
485
648
|
return `PORT=3000
|
|
486
649
|
ALLOWED_ORIGINS=
|
|
@@ -503,7 +666,7 @@ function renderTsconfig() {
|
|
|
503
666
|
"noEmit": true,
|
|
504
667
|
"allowJs": false
|
|
505
668
|
},
|
|
506
|
-
"include": ["index.ts", "src", "scripts"]
|
|
669
|
+
"include": ["index.ts", "src", "scripts", "client"]
|
|
507
670
|
}
|
|
508
671
|
`;
|
|
509
672
|
}
|
|
@@ -517,7 +680,7 @@ function renderJsconfig() {
|
|
|
517
680
|
"checkJs": false,
|
|
518
681
|
"allowJs": true
|
|
519
682
|
},
|
|
520
|
-
"include": ["index.js", "src", "scripts"]
|
|
683
|
+
"include": ["index.js", "src", "scripts", "client"]
|
|
521
684
|
}
|
|
522
685
|
`;
|
|
523
686
|
}
|
|
@@ -558,7 +721,12 @@ function renderPackageJson(projectName, framework, language, db) {
|
|
|
558
721
|
// remember which of the individual subcommands above does what.
|
|
559
722
|
project: "bunx create-backon project",
|
|
560
723
|
"server-config": "bunx create-backon server-config",
|
|
561
|
-
docs: `bun run scripts/generate-docs.${ext}
|
|
724
|
+
docs: `bun run scripts/generate-docs.${ext}`,
|
|
725
|
+
// Regenerates client/api.<ext> — a typed fetch client, one function per
|
|
726
|
+
// mounted method, read straight off *.routes.<ext>/*.controller.<ext>
|
|
727
|
+
// (the same files add-method/server-config write). client/ is a build
|
|
728
|
+
// artifact like openapi.json/docs.html, not source — see .gitignore.
|
|
729
|
+
"generate-client": `bun run scripts/generate-client.${ext}`
|
|
562
730
|
};
|
|
563
731
|
if (language === "typescript") {
|
|
564
732
|
scripts.typecheck = "tsc --noEmit";
|
|
@@ -708,6 +876,7 @@ dist/
|
|
|
708
876
|
.env.local
|
|
709
877
|
openapi.json
|
|
710
878
|
docs.html
|
|
879
|
+
client/
|
|
711
880
|
${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
|
|
712
881
|
],
|
|
713
882
|
[join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
|
|
@@ -718,6 +887,7 @@ ${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
|
|
|
718
887
|
],
|
|
719
888
|
[join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
|
|
720
889
|
[join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
|
|
890
|
+
[join(root, `scripts/generate-client.${ext}`), renderGenerateClientScript(answers.language)],
|
|
721
891
|
...answers.deployTarget === "vercel" ? [[join(root, "vercel.json"), renderVercelJson()]] : []
|
|
722
892
|
];
|
|
723
893
|
for (const route of answers.routes) {
|
|
@@ -918,6 +1088,143 @@ async function runDoctor(cwd = process.cwd()) {
|
|
|
918
1088
|
import { readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
|
|
919
1089
|
import { join as join8 } from "node:path";
|
|
920
1090
|
|
|
1091
|
+
// src/ast-edit.ts
|
|
1092
|
+
import { Node, Project } from "ts-morph";
|
|
1093
|
+
function makeProject() {
|
|
1094
|
+
return new Project({
|
|
1095
|
+
useInMemoryFileSystem: true,
|
|
1096
|
+
compilerOptions: { allowJs: true, checkJs: false }
|
|
1097
|
+
});
|
|
1098
|
+
}
|
|
1099
|
+
function loadSource(path, contents) {
|
|
1100
|
+
const project = makeProject();
|
|
1101
|
+
const sourceFile = project.createSourceFile(path, contents);
|
|
1102
|
+
return { project, sourceFile };
|
|
1103
|
+
}
|
|
1104
|
+
function editSource(path, contents, mutate) {
|
|
1105
|
+
const { project, sourceFile } = loadSource(path, contents);
|
|
1106
|
+
mutate(project, sourceFile);
|
|
1107
|
+
return printSource(sourceFile);
|
|
1108
|
+
}
|
|
1109
|
+
function parseImportLine(project, line) {
|
|
1110
|
+
const scratch = project.createSourceFile("__scratch_import__.ts", line, { overwrite: true });
|
|
1111
|
+
const decl = scratch.getImportDeclarations()[0];
|
|
1112
|
+
if (!decl) throw new Error(`Not a valid import statement: ${line}`);
|
|
1113
|
+
const parsed = {
|
|
1114
|
+
moduleSpecifier: decl.getModuleSpecifierValue(),
|
|
1115
|
+
isTypeOnly: decl.isTypeOnly(),
|
|
1116
|
+
namespaceImport: decl.getNamespaceImport()?.getText(),
|
|
1117
|
+
namedImports: decl.getNamedImports().map((ni) => ni.getName())
|
|
1118
|
+
};
|
|
1119
|
+
project.removeSourceFile(scratch);
|
|
1120
|
+
return parsed;
|
|
1121
|
+
}
|
|
1122
|
+
function ensureImports(sourceFile, project, lines) {
|
|
1123
|
+
for (const line of lines) {
|
|
1124
|
+
const spec = parseImportLine(project, line);
|
|
1125
|
+
const alreadyPresent = sourceFile.getImportDeclarations().some((d) => {
|
|
1126
|
+
if (d.getModuleSpecifierValue() !== spec.moduleSpecifier) return false;
|
|
1127
|
+
if (d.isTypeOnly() !== spec.isTypeOnly) return false;
|
|
1128
|
+
if (spec.namespaceImport) return d.getNamespaceImport()?.getText() === spec.namespaceImport;
|
|
1129
|
+
const names = new Set(d.getNamedImports().map((ni) => ni.getName()));
|
|
1130
|
+
return spec.namedImports.length > 0 && spec.namedImports.every((n) => names.has(n));
|
|
1131
|
+
});
|
|
1132
|
+
if (alreadyPresent) continue;
|
|
1133
|
+
sourceFile.addImportDeclaration({
|
|
1134
|
+
moduleSpecifier: spec.moduleSpecifier,
|
|
1135
|
+
isTypeOnly: spec.isTypeOnly,
|
|
1136
|
+
...spec.namespaceImport ? { namespaceImport: spec.namespaceImport } : { namedImports: spec.namedImports }
|
|
1137
|
+
});
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
function appendStatements(sourceFile, code) {
|
|
1141
|
+
sourceFile.addStatements(`
|
|
1142
|
+
${code}`);
|
|
1143
|
+
}
|
|
1144
|
+
function removeControllerMethod(sourceFile, name) {
|
|
1145
|
+
const targets = /* @__PURE__ */ new Set([name, `${name}ParamsSchema`, `${name}BodySchema`, `${name}QuerySchema`]);
|
|
1146
|
+
let removed = false;
|
|
1147
|
+
for (const stmt of sourceFile.getVariableStatements()) {
|
|
1148
|
+
const decls = stmt.getDeclarations();
|
|
1149
|
+
if (decls.length === 1 && targets.has(decls[0].getName())) {
|
|
1150
|
+
stmt.remove();
|
|
1151
|
+
removed = true;
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
if (removed) stripOrphanedTodoComment(sourceFile, name);
|
|
1155
|
+
return removed;
|
|
1156
|
+
}
|
|
1157
|
+
function stripOrphanedTodoComment(sourceFile, name) {
|
|
1158
|
+
const marker = `replace with the real shape of "${name}"`;
|
|
1159
|
+
const ranges = [];
|
|
1160
|
+
for (const stmt of sourceFile.getStatements()) {
|
|
1161
|
+
for (const range of stmt.getLeadingCommentRanges()) {
|
|
1162
|
+
if (range.getText().includes(marker)) ranges.push({ pos: range.getPos(), end: range.getEnd() });
|
|
1163
|
+
}
|
|
1164
|
+
}
|
|
1165
|
+
ranges.sort((a, b) => b.pos - a.pos);
|
|
1166
|
+
const fullText = sourceFile.getFullText();
|
|
1167
|
+
for (const { pos, end } of ranges) {
|
|
1168
|
+
const end2 = fullText[end] === "\n" ? end + 1 : end;
|
|
1169
|
+
sourceFile.removeText(pos, end2);
|
|
1170
|
+
}
|
|
1171
|
+
}
|
|
1172
|
+
function removeRouteMount(sourceFile, name) {
|
|
1173
|
+
for (const stmt of sourceFile.getStatements()) {
|
|
1174
|
+
if (!Node.isExpressionStatement(stmt)) continue;
|
|
1175
|
+
const expr = stmt.getExpression();
|
|
1176
|
+
if (!Node.isCallExpression(expr)) continue;
|
|
1177
|
+
const args = expr.getArguments();
|
|
1178
|
+
const last = args[args.length - 1];
|
|
1179
|
+
if (last && Node.isPropertyAccessExpression(last) && last.getName() === name) {
|
|
1180
|
+
stmt.remove();
|
|
1181
|
+
return true;
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
return false;
|
|
1185
|
+
}
|
|
1186
|
+
function removeServiceMethod(sourceFile, name) {
|
|
1187
|
+
const fn = sourceFile.getFunction(name);
|
|
1188
|
+
if (!fn) return false;
|
|
1189
|
+
fn.remove();
|
|
1190
|
+
const methodTypeNames = /* @__PURE__ */ new Set([`${name}ParamsSchema`, `${name}BodySchema`, `${name}QuerySchema`]);
|
|
1191
|
+
for (const importDecl of sourceFile.getImportDeclarations()) {
|
|
1192
|
+
const names = importDecl.getNamedImports().map((ni) => ni.getName());
|
|
1193
|
+
if (names.length > 0 && names.every((n) => methodTypeNames.has(n))) {
|
|
1194
|
+
importDecl.remove();
|
|
1195
|
+
}
|
|
1196
|
+
}
|
|
1197
|
+
return true;
|
|
1198
|
+
}
|
|
1199
|
+
var SCHEMA_CONST_SUFFIXES = ["ParamsSchema", "BodySchema", "QuerySchema"];
|
|
1200
|
+
function isSchemaConstStatement(node) {
|
|
1201
|
+
if (!Node.isVariableStatement(node)) return false;
|
|
1202
|
+
const decls = node.getDeclarations();
|
|
1203
|
+
return decls.length === 1 && SCHEMA_CONST_SUFFIXES.some((suffix) => decls[0].getName().endsWith(suffix));
|
|
1204
|
+
}
|
|
1205
|
+
function printSource(sourceFile) {
|
|
1206
|
+
const importDecls = sourceFile.getImportDeclarations();
|
|
1207
|
+
const importText = importDecls.map((d) => d.getText()).join("\n");
|
|
1208
|
+
const rest = sourceFile.getStatements().filter((s) => !Node.isImportDeclaration(s));
|
|
1209
|
+
const paragraphs = [];
|
|
1210
|
+
let i = 0;
|
|
1211
|
+
while (i < rest.length) {
|
|
1212
|
+
const parts = [];
|
|
1213
|
+
while (i < rest.length && isSchemaConstStatement(rest[i])) {
|
|
1214
|
+
parts.push(rest[i].getFullText().trim());
|
|
1215
|
+
i++;
|
|
1216
|
+
}
|
|
1217
|
+
if (i < rest.length) {
|
|
1218
|
+
parts.push(rest[i].getFullText().trim());
|
|
1219
|
+
i++;
|
|
1220
|
+
}
|
|
1221
|
+
paragraphs.push(parts.join("\n"));
|
|
1222
|
+
}
|
|
1223
|
+
const blocks = [importText, ...paragraphs].filter((b) => b.length > 0);
|
|
1224
|
+
return blocks.length > 0 ? `${blocks.join("\n\n")}
|
|
1225
|
+
` : "";
|
|
1226
|
+
}
|
|
1227
|
+
|
|
921
1228
|
// src/route-methods.ts
|
|
922
1229
|
import { readFile as readFile3 } from "node:fs/promises";
|
|
923
1230
|
import { join as join7 } from "node:path";
|
|
@@ -1001,24 +1308,6 @@ var PLACEHOLDER_PATTERN = /\/\/ No (?:routes|methods) yet[^\n]*\n\n?/;
|
|
|
1001
1308
|
function stripPlaceholder(content) {
|
|
1002
1309
|
return content.replace(PLACEHOLDER_PATTERN, "");
|
|
1003
1310
|
}
|
|
1004
|
-
function ensureImports(content, importLines) {
|
|
1005
|
-
const stripped = stripPlaceholder(content);
|
|
1006
|
-
const missing = importLines.filter((line) => !stripped.includes(line));
|
|
1007
|
-
if (missing.length === 0) return stripped;
|
|
1008
|
-
const lines = stripped.split("\n");
|
|
1009
|
-
let insertAt = 0;
|
|
1010
|
-
while (insertAt < lines.length && lines[insertAt]?.startsWith("import ")) insertAt++;
|
|
1011
|
-
lines.splice(insertAt, 0, ...missing);
|
|
1012
|
-
return lines.join("\n");
|
|
1013
|
-
}
|
|
1014
|
-
function appendBlock(content, block) {
|
|
1015
|
-
const trimmed = content.replace(/\n+$/, "");
|
|
1016
|
-
return trimmed ? `${trimmed}
|
|
1017
|
-
|
|
1018
|
-
${block}
|
|
1019
|
-
` : `${block}
|
|
1020
|
-
`;
|
|
1021
|
-
}
|
|
1022
1311
|
async function addMethod(route, spec, cwd = process.cwd()) {
|
|
1023
1312
|
const { root, framework, language, ext } = await detectProject(cwd);
|
|
1024
1313
|
const { contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
@@ -1042,12 +1331,18 @@ async function addMethod(route, spec, cwd = process.cwd()) {
|
|
|
1042
1331
|
if (existing.some((m) => m.verb === spec.verb && m.path === spec.path)) {
|
|
1043
1332
|
throw new Error(`${spec.verb.toUpperCase()} ${spec.path} is already mounted in ${routesPath}.`);
|
|
1044
1333
|
}
|
|
1045
|
-
const newController =
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
)
|
|
1050
|
-
|
|
1334
|
+
const newController = editSource(controllerPath, stripPlaceholder(controllerContents), (project, sourceFile) => {
|
|
1335
|
+
ensureImports(sourceFile, project, controllerImports(route, framework));
|
|
1336
|
+
appendStatements(sourceFile, renderControllerMethod(spec));
|
|
1337
|
+
});
|
|
1338
|
+
const newRoutes = editSource(routesPath, stripPlaceholder(routesContents), (project, sourceFile) => {
|
|
1339
|
+
ensureImports(sourceFile, project, [`import * as controller from "./${route}.controller";`]);
|
|
1340
|
+
appendStatements(sourceFile, routeMountLine(route, spec));
|
|
1341
|
+
});
|
|
1342
|
+
const newServices = editSource(servicesPath, stripPlaceholder(servicesContents), (project, sourceFile) => {
|
|
1343
|
+
ensureImports(sourceFile, project, serviceImports(route, spec, language));
|
|
1344
|
+
appendStatements(sourceFile, renderServiceMethod(spec, language));
|
|
1345
|
+
});
|
|
1051
1346
|
await Promise.all([
|
|
1052
1347
|
writeFile4(controllerPath, newController),
|
|
1053
1348
|
writeFile4(routesPath, newRoutes),
|
|
@@ -1059,15 +1354,6 @@ async function addMethod(route, spec, cwd = process.cwd()) {
|
|
|
1059
1354
|
// src/remove-method.ts
|
|
1060
1355
|
import { readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
|
|
1061
1356
|
import { join as join9 } from "node:path";
|
|
1062
|
-
function removeBlock(content, matches) {
|
|
1063
|
-
const blocks = content.split(/\n\n+/);
|
|
1064
|
-
const index = blocks.findIndex(matches);
|
|
1065
|
-
if (index === -1) return content;
|
|
1066
|
-
blocks.splice(index, 1);
|
|
1067
|
-
const joined = blocks.filter((b) => b.length > 0).join("\n\n");
|
|
1068
|
-
return joined ? `${joined}
|
|
1069
|
-
` : "";
|
|
1070
|
-
}
|
|
1071
1357
|
async function removeMethod(route, verb, path, cwd = process.cwd()) {
|
|
1072
1358
|
const { root, framework, language, ext } = await detectProject(cwd);
|
|
1073
1359
|
const { contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
@@ -1098,10 +1384,15 @@ async function removeMethod(route, verb, path, cwd = process.cwd()) {
|
|
|
1098
1384
|
]);
|
|
1099
1385
|
return { route, root, removed: match };
|
|
1100
1386
|
}
|
|
1101
|
-
const
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
const
|
|
1387
|
+
const newController = editSource(controllerPath, controllerContents, (_project, sourceFile) => {
|
|
1388
|
+
removeControllerMethod(sourceFile, name);
|
|
1389
|
+
});
|
|
1390
|
+
const newRoutes = editSource(routesPath, routesContents, (_project, sourceFile) => {
|
|
1391
|
+
removeRouteMount(sourceFile, name);
|
|
1392
|
+
});
|
|
1393
|
+
const newServices = editSource(servicesPath, servicesContents, (_project, sourceFile) => {
|
|
1394
|
+
removeServiceMethod(sourceFile, name);
|
|
1395
|
+
});
|
|
1105
1396
|
await Promise.all([
|
|
1106
1397
|
writeFile5(controllerPath, newController),
|
|
1107
1398
|
writeFile5(routesPath, newRoutes),
|
|
@@ -1176,6 +1467,32 @@ async function detectDbStatus(cwd = process.cwd()) {
|
|
|
1176
1467
|
};
|
|
1177
1468
|
}
|
|
1178
1469
|
|
|
1470
|
+
// src/crud-scaffold.ts
|
|
1471
|
+
var CRUD_METHOD_SPECS = [
|
|
1472
|
+
{ verb: "get", path: "/", name: "list", needsBody: false, needsQuery: false },
|
|
1473
|
+
{ verb: "post", path: "/", name: "create", needsBody: true, needsQuery: false },
|
|
1474
|
+
{ verb: "get", path: "/:id", name: "getById", needsBody: false, needsQuery: false },
|
|
1475
|
+
{ verb: "put", path: "/:id", name: "update", needsBody: true, needsQuery: false },
|
|
1476
|
+
{ verb: "delete", path: "/:id", name: "remove", needsBody: false, needsQuery: false }
|
|
1477
|
+
];
|
|
1478
|
+
async function addCrudMethods(route, cwd = process.cwd()) {
|
|
1479
|
+
const summaries = await listEndpointsWithMethods(cwd);
|
|
1480
|
+
const existing = [...summaries.find((s) => s.route === route)?.methods ?? []];
|
|
1481
|
+
const added = [];
|
|
1482
|
+
const skipped = [];
|
|
1483
|
+
for (const spec of CRUD_METHOD_SPECS) {
|
|
1484
|
+
const collides = existing.some((m) => m.name === spec.name || m.verb === spec.verb && m.path === spec.path);
|
|
1485
|
+
if (collides) {
|
|
1486
|
+
skipped.push(spec.name);
|
|
1487
|
+
continue;
|
|
1488
|
+
}
|
|
1489
|
+
await addMethod(route, spec, cwd);
|
|
1490
|
+
added.push(spec.name);
|
|
1491
|
+
existing.push({ verb: spec.verb, path: spec.path, name: spec.name });
|
|
1492
|
+
}
|
|
1493
|
+
return { route, added, skipped };
|
|
1494
|
+
}
|
|
1495
|
+
|
|
1179
1496
|
// src/cli.ts
|
|
1180
1497
|
var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
|
|
1181
1498
|
var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
|
|
@@ -1197,15 +1514,36 @@ async function promptForRouteName(introText) {
|
|
|
1197
1514
|
}
|
|
1198
1515
|
return answer;
|
|
1199
1516
|
}
|
|
1517
|
+
function logCrudResult(result) {
|
|
1518
|
+
const skippedNote = result.skipped.length ? ` (skipped, already there: ${result.skipped.join(", ")})` : "";
|
|
1519
|
+
p2.log.success(`Added CRUD methods to ${result.route}: ${result.added.join(", ") || "none"}${skippedNote}`);
|
|
1520
|
+
}
|
|
1200
1521
|
async function runAddRoute(args) {
|
|
1201
|
-
|
|
1522
|
+
const crudFlagIndex = args.indexOf("--crud");
|
|
1523
|
+
const withCrud = crudFlagIndex !== -1;
|
|
1524
|
+
const positional = withCrud ? args.filter((_, i) => i !== crudFlagIndex) : args;
|
|
1525
|
+
let [name] = positional;
|
|
1526
|
+
let interactive = false;
|
|
1202
1527
|
if (!name) {
|
|
1528
|
+
interactive = true;
|
|
1203
1529
|
name = await promptForRouteName("create-backon add-route");
|
|
1204
1530
|
p2.outro(`Adding ${name}...`);
|
|
1205
1531
|
}
|
|
1206
1532
|
const { route, root, filesWritten } = await addRoute(name);
|
|
1207
1533
|
p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
|
|
1208
|
-
|
|
1534
|
+
let scaffoldCrud = withCrud;
|
|
1535
|
+
if (!withCrud && interactive) {
|
|
1536
|
+
const answer = await p2.confirm({
|
|
1537
|
+
message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
|
|
1538
|
+
initialValue: false
|
|
1539
|
+
});
|
|
1540
|
+
scaffoldCrud = !p2.isCancel(answer) && answer;
|
|
1541
|
+
}
|
|
1542
|
+
if (scaffoldCrud) {
|
|
1543
|
+
logCrudResult(await addCrudMethods(route, root));
|
|
1544
|
+
} else {
|
|
1545
|
+
p2.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
|
|
1546
|
+
}
|
|
1209
1547
|
}
|
|
1210
1548
|
async function runRemoveRoute(args) {
|
|
1211
1549
|
let [name] = args;
|
|
@@ -1371,6 +1709,13 @@ async function serverConfigAddEndpoint() {
|
|
|
1371
1709
|
}
|
|
1372
1710
|
const { route, filesWritten } = await addRoute(name);
|
|
1373
1711
|
p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet).`);
|
|
1712
|
+
const scaffoldCrud = await p2.confirm({
|
|
1713
|
+
message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
|
|
1714
|
+
initialValue: false
|
|
1715
|
+
});
|
|
1716
|
+
if (!p2.isCancel(scaffoldCrud) && scaffoldCrud) {
|
|
1717
|
+
logCrudResult(await addCrudMethods(route));
|
|
1718
|
+
}
|
|
1374
1719
|
}
|
|
1375
1720
|
async function serverConfigRemoveEndpoint(summaries) {
|
|
1376
1721
|
if (summaries.length === 0) {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-backon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.11.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",
|