create-backon 0.9.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/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
  }
@@ -552,7 +715,18 @@ function renderPackageJson(projectName, framework, language, db) {
552
715
  "remove-route": "bunx create-backon remove-route",
553
716
  "list-routes": "bunx create-backon list-routes",
554
717
  doctor: "bunx create-backon doctor",
555
- docs: `bun run scripts/generate-docs.${ext}`
718
+ // project: read-only overview (db status, endpoints, methods, doctor
719
+ // summary). server-config: the interactive manager for actually
720
+ // changing endpoints/methods — add/remove/modify, without needing to
721
+ // remember which of the individual subcommands above does what.
722
+ project: "bunx create-backon project",
723
+ "server-config": "bunx create-backon server-config",
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}`
556
730
  };
557
731
  if (language === "typescript") {
558
732
  scripts.typecheck = "tsc --noEmit";
@@ -702,6 +876,7 @@ dist/
702
876
  .env.local
703
877
  openapi.json
704
878
  docs.html
879
+ client/
705
880
  ${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
706
881
  ],
707
882
  [join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
@@ -712,6 +887,7 @@ ${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
712
887
  ],
713
888
  [join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
714
889
  [join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
890
+ [join(root, `scripts/generate-client.${ext}`), renderGenerateClientScript(answers.language)],
715
891
  ...answers.deployTarget === "vercel" ? [[join(root, "vercel.json"), renderVercelJson()]] : []
716
892
  ];
717
893
  for (const route of answers.routes) {
@@ -912,6 +1088,143 @@ async function runDoctor(cwd = process.cwd()) {
912
1088
  import { readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
913
1089
  import { join as join8 } from "node:path";
914
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
+
915
1228
  // src/route-methods.ts
916
1229
  import { readFile as readFile3 } from "node:fs/promises";
917
1230
  import { join as join7 } from "node:path";
@@ -933,6 +1246,12 @@ function colorVerb(verb) {
933
1246
  function dim(text3) {
934
1247
  return `\x1B[2m${text3}${RESET}`;
935
1248
  }
1249
+ function ok(text3) {
1250
+ return `\x1B[32m${text3}${RESET}`;
1251
+ }
1252
+ function warn(text3) {
1253
+ return `\x1B[33m${text3}${RESET}`;
1254
+ }
936
1255
 
937
1256
  // src/route-methods.ts
938
1257
  var METHOD_MOUNT_PATTERN = /\.(get|post|put|patch|delete)\(\s*"([^"]*)"\s*,\s*controller\.(\w+)\s*\)/g;
@@ -946,6 +1265,15 @@ function parseRouteMethods(routesFileContents) {
946
1265
  }
947
1266
  return methods;
948
1267
  }
1268
+ async function detectMethodValidation(route, name, cwd = process.cwd()) {
1269
+ const { root, ext } = await detectProject(cwd);
1270
+ const controllerPath = join7(root, "src/endpoints", route, `${route}.controller.${ext}`);
1271
+ const contents = await readFile3(controllerPath, "utf-8");
1272
+ return {
1273
+ needsBody: contents.includes(`export const ${name}BodySchema`),
1274
+ needsQuery: contents.includes(`export const ${name}QuerySchema`)
1275
+ };
1276
+ }
949
1277
  async function listEndpointsWithMethods(cwd = process.cwd()) {
950
1278
  const { root, ext } = await detectProject(cwd);
951
1279
  const { contents } = await readEndpointsIndex(root, ext);
@@ -980,24 +1308,6 @@ var PLACEHOLDER_PATTERN = /\/\/ No (?:routes|methods) yet[^\n]*\n\n?/;
980
1308
  function stripPlaceholder(content) {
981
1309
  return content.replace(PLACEHOLDER_PATTERN, "");
982
1310
  }
983
- function ensureImports(content, importLines) {
984
- const stripped = stripPlaceholder(content);
985
- const missing = importLines.filter((line) => !stripped.includes(line));
986
- if (missing.length === 0) return stripped;
987
- const lines = stripped.split("\n");
988
- let insertAt = 0;
989
- while (insertAt < lines.length && lines[insertAt]?.startsWith("import ")) insertAt++;
990
- lines.splice(insertAt, 0, ...missing);
991
- return lines.join("\n");
992
- }
993
- function appendBlock(content, block) {
994
- const trimmed = content.replace(/\n+$/, "");
995
- return trimmed ? `${trimmed}
996
-
997
- ${block}
998
- ` : `${block}
999
- `;
1000
- }
1001
1311
  async function addMethod(route, spec, cwd = process.cwd()) {
1002
1312
  const { root, framework, language, ext } = await detectProject(cwd);
1003
1313
  const { contents: indexContents } = await readEndpointsIndex(root, ext);
@@ -1021,12 +1331,18 @@ async function addMethod(route, spec, cwd = process.cwd()) {
1021
1331
  if (existing.some((m) => m.verb === spec.verb && m.path === spec.path)) {
1022
1332
  throw new Error(`${spec.verb.toUpperCase()} ${spec.path} is already mounted in ${routesPath}.`);
1023
1333
  }
1024
- const newController = appendBlock(ensureImports(controllerContents, controllerImports(route, framework)), renderControllerMethod(spec));
1025
- const newRoutes = appendBlock(
1026
- ensureImports(routesContents, [`import * as controller from "./${route}.controller";`]),
1027
- routeMountLine(route, spec)
1028
- );
1029
- const newServices = appendBlock(ensureImports(servicesContents, serviceImports(route, spec, language)), renderServiceMethod(spec, language));
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
+ });
1030
1346
  await Promise.all([
1031
1347
  writeFile4(controllerPath, newController),
1032
1348
  writeFile4(routesPath, newRoutes),
@@ -1035,12 +1351,156 @@ async function addMethod(route, spec, cwd = process.cwd()) {
1035
1351
  return { route, root, filesWritten: [controllerPath, routesPath, servicesPath] };
1036
1352
  }
1037
1353
 
1354
+ // src/remove-method.ts
1355
+ import { readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
1356
+ import { join as join9 } from "node:path";
1357
+ async function removeMethod(route, verb, path, cwd = process.cwd()) {
1358
+ const { root, framework, language, ext } = await detectProject(cwd);
1359
+ const { contents: indexContents } = await readEndpointsIndex(root, ext);
1360
+ const mounted = parseMountedRoutes(indexContents);
1361
+ if (!mounted.includes(route)) {
1362
+ throw new Error(`"${route}" isn't mounted in src/endpoints/index.${ext}.`);
1363
+ }
1364
+ const routeDir = join9(root, "src/endpoints", route);
1365
+ const controllerPath = join9(routeDir, `${route}.controller.${ext}`);
1366
+ const routesPath = join9(routeDir, `${route}.routes.${ext}`);
1367
+ const servicesPath = join9(routeDir, `${route}.services.${ext}`);
1368
+ const [controllerContents, routesContents, servicesContents] = await Promise.all([
1369
+ readFile5(controllerPath, "utf-8"),
1370
+ readFile5(routesPath, "utf-8"),
1371
+ readFile5(servicesPath, "utf-8")
1372
+ ]);
1373
+ const existing = parseRouteMethods(routesContents);
1374
+ const match = existing.find((m) => m.verb === verb && m.path === path);
1375
+ if (!match) {
1376
+ throw new Error(`${verb.toUpperCase()} ${path} isn't mounted in ${routesPath}.`);
1377
+ }
1378
+ const { name } = match;
1379
+ if (existing.length === 1) {
1380
+ await Promise.all([
1381
+ writeFile5(controllerPath, renderBlankController()),
1382
+ writeFile5(routesPath, renderBlankRoutes(route, framework, language)),
1383
+ writeFile5(servicesPath, renderBlankServices())
1384
+ ]);
1385
+ return { route, root, removed: match };
1386
+ }
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
+ });
1396
+ await Promise.all([
1397
+ writeFile5(controllerPath, newController),
1398
+ writeFile5(routesPath, newRoutes),
1399
+ writeFile5(servicesPath, newServices)
1400
+ ]);
1401
+ return { route, root, removed: match };
1402
+ }
1403
+
1404
+ // src/db-status.ts
1405
+ import { readFile as readFile6 } from "node:fs/promises";
1406
+ import { join as join10 } from "node:path";
1407
+ var DRIVER_SIGNATURES = [
1408
+ ["drizzle-orm/neon-http", "neon"],
1409
+ ["drizzle-orm/node-postgres", "postgres"],
1410
+ ["drizzle-orm/bun-sqlite", "sqlite"]
1411
+ ];
1412
+ function detectDriver(dbFileContents) {
1413
+ for (const [signature, driver] of DRIVER_SIGNATURES) {
1414
+ if (dbFileContents.includes(signature)) return driver;
1415
+ }
1416
+ if (dbFileContents.includes("No database configured yet")) return "none";
1417
+ return "custom";
1418
+ }
1419
+ function parseEnvValue(envContents, key) {
1420
+ const match = envContents.match(new RegExp(`^${key}=(.*)$`, "m"));
1421
+ const value = match?.[1]?.trim();
1422
+ return value ? value : void 0;
1423
+ }
1424
+ async function detectDbStatus(cwd = process.cwd()) {
1425
+ const { root, ext } = await detectProject(cwd);
1426
+ let dbFileContents;
1427
+ try {
1428
+ dbFileContents = await readFile6(join10(root, "src/config", `db.${ext}`), "utf-8");
1429
+ } catch {
1430
+ dbFileContents = void 0;
1431
+ }
1432
+ const driver = dbFileContents === void 0 ? "missing" : detectDriver(dbFileContents);
1433
+ let envContents = "";
1434
+ let envFileExists = true;
1435
+ try {
1436
+ envContents = await readFile6(join10(root, ".env"), "utf-8");
1437
+ } catch {
1438
+ envFileExists = false;
1439
+ }
1440
+ const databaseUrl = parseEnvValue(envContents, "DATABASE_URL");
1441
+ if (driver === "missing") {
1442
+ return { driver, envFileExists, ready: "unknown", summary: warn("src/config/db file not found.") };
1443
+ }
1444
+ if (driver === "custom") {
1445
+ return {
1446
+ driver,
1447
+ envFileExists,
1448
+ ready: "unknown",
1449
+ summary: `${dim("custom")} \u2014 src/config/db has been hand-edited, can't tell you its status here.`
1450
+ };
1451
+ }
1452
+ if (driver === "none") {
1453
+ return { driver, envFileExists, ready: true, summary: dim("none \u2014 no database configured.") };
1454
+ }
1455
+ if (driver === "sqlite") {
1456
+ const path = databaseUrl ?? "./dev.db";
1457
+ return { driver, envFileExists, ready: true, summary: `${ok("sqlite")} \u2014 using ${path}.` };
1458
+ }
1459
+ if (databaseUrl) {
1460
+ return { driver, envFileExists, ready: true, summary: `${ok(driver)} \u2014 DATABASE_URL is set in .env.` };
1461
+ }
1462
+ return {
1463
+ driver,
1464
+ envFileExists,
1465
+ ready: false,
1466
+ summary: `${warn(driver)} \u2014 DATABASE_URL missing from .env${envFileExists ? "" : " (no .env file)"}; src/config/db.ts will throw at startup until it's set.`
1467
+ };
1468
+ }
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
+
1038
1496
  // src/cli.ts
1039
1497
  var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
1040
1498
  var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
1041
1499
  var LIST_ROUTES_SUBCOMMANDS = /* @__PURE__ */ new Set(["list-routes", "routes"]);
1042
1500
  var DOCTOR_SUBCOMMANDS = /* @__PURE__ */ new Set(["doctor"]);
1043
1501
  var ADD_METHOD_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-method", "method"]);
1502
+ var PROJECT_SUBCOMMANDS = /* @__PURE__ */ new Set(["project"]);
1503
+ var SERVER_CONFIG_SUBCOMMANDS = /* @__PURE__ */ new Set(["server-config"]);
1044
1504
  async function promptForRouteName(introText) {
1045
1505
  p2.intro(introText);
1046
1506
  const answer = await p2.text({
@@ -1054,15 +1514,36 @@ async function promptForRouteName(introText) {
1054
1514
  }
1055
1515
  return answer;
1056
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
+ }
1057
1521
  async function runAddRoute(args) {
1058
- let [name] = args;
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;
1059
1527
  if (!name) {
1528
+ interactive = true;
1060
1529
  name = await promptForRouteName("create-backon add-route");
1061
1530
  p2.outro(`Adding ${name}...`);
1062
1531
  }
1063
1532
  const { route, root, filesWritten } = await addRoute(name);
1064
1533
  p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
1065
- p2.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
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
+ }
1066
1547
  }
1067
1548
  async function runRemoveRoute(args) {
1068
1549
  let [name] = args;
@@ -1099,6 +1580,21 @@ async function runDoctorCommand() {
1099
1580
  ${issues.map((issue) => ` - ${issue.detail}`).join("\n")}`);
1100
1581
  process.exitCode = 1;
1101
1582
  }
1583
+ async function runProjectOverview() {
1584
+ p2.intro("create-backon project");
1585
+ const { root } = await detectProject();
1586
+ const dbStatus = await detectDbStatus();
1587
+ const summaries = await listEndpointsWithMethods();
1588
+ const { issues } = await runDoctor();
1589
+ p2.note(dbStatus.summary, "Database");
1590
+ p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
1591
+ if (issues.length > 0) {
1592
+ p2.log.warn(`${issues.length} issue(s) between src/endpoints/ and index \u2014 run \`bun run doctor\` for details.`);
1593
+ } else {
1594
+ p2.log.success("No drift between src/endpoints/ and index.");
1595
+ }
1596
+ p2.outro("Manage endpoints and methods with `bun run server-config`.");
1597
+ }
1102
1598
  function suggestMethodName(verb, path) {
1103
1599
  const params = paramNamesFromPath(path);
1104
1600
  if (verb === "get" && params.length === 0) return "list";
@@ -1201,6 +1697,282 @@ async function runAddMethod() {
1201
1697
  }
1202
1698
  p2.outro("Done.");
1203
1699
  }
1700
+ async function serverConfigAddEndpoint() {
1701
+ const name = await p2.text({
1702
+ message: "New endpoint name",
1703
+ placeholder: "e.g. users",
1704
+ validate: (value) => !value ? "Required." : void 0
1705
+ });
1706
+ if (p2.isCancel(name)) {
1707
+ p2.cancel("Cancelled.");
1708
+ return;
1709
+ }
1710
+ const { route, filesWritten } = await addRoute(name);
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
+ }
1719
+ }
1720
+ async function serverConfigRemoveEndpoint(summaries) {
1721
+ if (summaries.length === 0) {
1722
+ p2.log.info("No endpoints yet.");
1723
+ return;
1724
+ }
1725
+ const route = await p2.select({
1726
+ message: "Remove which endpoint?",
1727
+ options: summaries.map((s) => ({ value: s.route, label: s.route }))
1728
+ });
1729
+ if (p2.isCancel(route)) {
1730
+ p2.cancel("Cancelled.");
1731
+ return;
1732
+ }
1733
+ const confirmed = await p2.confirm({
1734
+ message: `Remove src/endpoints/${route} and unmount it? This deletes the folder.`,
1735
+ initialValue: false
1736
+ });
1737
+ if (p2.isCancel(confirmed) || !confirmed) {
1738
+ p2.cancel("Cancelled.");
1739
+ return;
1740
+ }
1741
+ const { removedDir } = await removeRoute(route);
1742
+ p2.log.success(`Removed ${removedDir}.`);
1743
+ }
1744
+ async function serverConfigAddMethod(summaries) {
1745
+ const routeChoice = await p2.select({
1746
+ message: "Add a method to which endpoint?",
1747
+ options: [
1748
+ ...summaries.map((s) => ({ value: s.route, label: s.route })),
1749
+ { value: "__new__", label: "+ New blank endpoint" }
1750
+ ]
1751
+ });
1752
+ if (p2.isCancel(routeChoice)) {
1753
+ p2.cancel("Cancelled.");
1754
+ return;
1755
+ }
1756
+ let route = routeChoice;
1757
+ let existingMethods = summaries.find((s) => s.route === route)?.methods ?? [];
1758
+ if (route === "__new__") {
1759
+ const name2 = await p2.text({
1760
+ message: "New endpoint name",
1761
+ placeholder: "e.g. users",
1762
+ validate: (value) => !value ? "Required." : void 0
1763
+ });
1764
+ if (p2.isCancel(name2)) {
1765
+ p2.cancel("Cancelled.");
1766
+ return;
1767
+ }
1768
+ const added = await addRoute(name2);
1769
+ route = added.route;
1770
+ existingMethods = [];
1771
+ p2.log.success(`Added blank endpoint src/endpoints/${route}`);
1772
+ }
1773
+ const verb = await p2.select({
1774
+ message: "HTTP method",
1775
+ options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() }))
1776
+ });
1777
+ if (p2.isCancel(verb)) {
1778
+ p2.cancel("Cancelled.");
1779
+ return;
1780
+ }
1781
+ const defaultPath = verb === "get" || verb === "post" ? "/" : "/:id";
1782
+ const path = await p2.text({
1783
+ message: "Path (relative to this endpoint's mount)",
1784
+ placeholder: defaultPath,
1785
+ initialValue: defaultPath,
1786
+ validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
1787
+ });
1788
+ if (p2.isCancel(path)) {
1789
+ p2.cancel("Cancelled.");
1790
+ return;
1791
+ }
1792
+ const defaultName = suggestMethodName(verb, path);
1793
+ const name = await p2.text({
1794
+ message: "Name (controller export + service function)",
1795
+ placeholder: defaultName,
1796
+ initialValue: defaultName,
1797
+ validate: (value) => {
1798
+ if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
1799
+ if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
1800
+ return void 0;
1801
+ }
1802
+ });
1803
+ if (p2.isCancel(name)) {
1804
+ p2.cancel("Cancelled.");
1805
+ return;
1806
+ }
1807
+ let needsBody = false;
1808
+ if (verb === "post" || verb === "put" || verb === "patch") {
1809
+ const answer = await p2.confirm({ message: "Validate a request body?", initialValue: true });
1810
+ if (p2.isCancel(answer)) {
1811
+ p2.cancel("Cancelled.");
1812
+ return;
1813
+ }
1814
+ needsBody = answer;
1815
+ }
1816
+ const needsQuery = await p2.confirm({ message: "Validate query params?", initialValue: false });
1817
+ if (p2.isCancel(needsQuery)) {
1818
+ p2.cancel("Cancelled.");
1819
+ return;
1820
+ }
1821
+ const spec = { verb, path, name, needsBody, needsQuery };
1822
+ const { filesWritten } = await addMethod(route, spec);
1823
+ p2.log.success(`Added ${verb.toUpperCase()} ${path} \u2192 ${name} in src/endpoints/${route} (${filesWritten.length} files)`);
1824
+ }
1825
+ async function selectEndpointWithMethods(summaries, message) {
1826
+ const withMethods = summaries.filter((s) => s.methods.length > 0);
1827
+ if (withMethods.length === 0) {
1828
+ p2.log.info("No methods yet \u2014 add one first.");
1829
+ return null;
1830
+ }
1831
+ const route = await p2.select({
1832
+ message,
1833
+ options: withMethods.map((s) => ({ value: s.route, label: s.route }))
1834
+ });
1835
+ if (p2.isCancel(route)) {
1836
+ p2.cancel("Cancelled.");
1837
+ return null;
1838
+ }
1839
+ return withMethods.find((s) => s.route === route) ?? null;
1840
+ }
1841
+ async function selectMethod(endpoint, message) {
1842
+ const choice = await p2.select({
1843
+ message,
1844
+ options: endpoint.methods.map((m) => ({
1845
+ value: `${m.verb}:${m.path}`,
1846
+ label: `${m.verb.toUpperCase()} ${m.path} \u2192 ${m.name}`
1847
+ }))
1848
+ });
1849
+ if (p2.isCancel(choice)) {
1850
+ p2.cancel("Cancelled.");
1851
+ return null;
1852
+ }
1853
+ const [verb, path] = choice.split(/:(.*)/s);
1854
+ return endpoint.methods.find((m) => m.verb === verb && m.path === path) ?? null;
1855
+ }
1856
+ async function serverConfigRemoveMethod(summaries) {
1857
+ const endpoint = await selectEndpointWithMethods(summaries, "Remove a method from which endpoint?");
1858
+ if (!endpoint) return;
1859
+ const method = await selectMethod(endpoint, "Remove which method?");
1860
+ if (!method) return;
1861
+ const confirmed = await p2.confirm({
1862
+ message: `Remove ${method.verb.toUpperCase()} ${method.path} (${method.name}) from ${endpoint.route}?`,
1863
+ initialValue: false
1864
+ });
1865
+ if (p2.isCancel(confirmed) || !confirmed) {
1866
+ p2.cancel("Cancelled.");
1867
+ return;
1868
+ }
1869
+ const { removed } = await removeMethod(endpoint.route, method.verb, method.path);
1870
+ p2.log.success(`Removed ${removed.verb.toUpperCase()} ${removed.path} (${removed.name}) from src/endpoints/${endpoint.route}.`);
1871
+ }
1872
+ async function serverConfigModifyMethod(summaries) {
1873
+ const endpoint = await selectEndpointWithMethods(summaries, "Modify a method on which endpoint?");
1874
+ if (!endpoint) return;
1875
+ const old = await selectMethod(endpoint, "Modify which method?");
1876
+ if (!old) return;
1877
+ const { needsBody: oldNeedsBody, needsQuery: oldNeedsQuery } = await detectMethodValidation(endpoint.route, old.name);
1878
+ const others = endpoint.methods.filter((m) => m !== old);
1879
+ const verb = await p2.select({
1880
+ message: "HTTP method",
1881
+ initialValue: old.verb,
1882
+ options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() }))
1883
+ });
1884
+ if (p2.isCancel(verb)) {
1885
+ p2.cancel("Cancelled.");
1886
+ return;
1887
+ }
1888
+ const path = await p2.text({
1889
+ message: "Path (relative to this endpoint's mount)",
1890
+ initialValue: old.path,
1891
+ validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
1892
+ });
1893
+ if (p2.isCancel(path)) {
1894
+ p2.cancel("Cancelled.");
1895
+ return;
1896
+ }
1897
+ const name = await p2.text({
1898
+ message: "Name (controller export + service function)",
1899
+ initialValue: old.name,
1900
+ validate: (value) => {
1901
+ if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
1902
+ if (others.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
1903
+ return void 0;
1904
+ }
1905
+ });
1906
+ if (p2.isCancel(name)) {
1907
+ p2.cancel("Cancelled.");
1908
+ return;
1909
+ }
1910
+ if (others.some((m) => m.verb === verb && m.path === path)) {
1911
+ p2.log.error(`${verb.toUpperCase()} ${path} is already used by another method on this endpoint.`);
1912
+ return;
1913
+ }
1914
+ let needsBody = false;
1915
+ if (verb === "post" || verb === "put" || verb === "patch") {
1916
+ const answer = await p2.confirm({ message: "Validate a request body?", initialValue: oldNeedsBody });
1917
+ if (p2.isCancel(answer)) {
1918
+ p2.cancel("Cancelled.");
1919
+ return;
1920
+ }
1921
+ needsBody = answer;
1922
+ }
1923
+ const needsQuery = await p2.confirm({ message: "Validate query params?", initialValue: oldNeedsQuery });
1924
+ if (p2.isCancel(needsQuery)) {
1925
+ p2.cancel("Cancelled.");
1926
+ return;
1927
+ }
1928
+ await removeMethod(endpoint.route, old.verb, old.path);
1929
+ const { filesWritten } = await addMethod(endpoint.route, { verb, path, name, needsBody, needsQuery });
1930
+ p2.log.success(
1931
+ `Updated src/endpoints/${endpoint.route}: ${old.verb.toUpperCase()} ${old.path} \u2192 ${verb.toUpperCase()} ${path} (${name}), ${filesWritten.length} files touched.`
1932
+ );
1933
+ }
1934
+ async function runServerConfig() {
1935
+ p2.intro("create-backon server-config");
1936
+ while (true) {
1937
+ const { root } = await detectProject();
1938
+ const summaries = await listEndpointsWithMethods();
1939
+ p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
1940
+ const action = await p2.select({
1941
+ message: "What do you want to do?",
1942
+ options: [
1943
+ { value: "add-endpoint", label: "Add a new endpoint" },
1944
+ { value: "remove-endpoint", label: "Remove an endpoint" },
1945
+ { value: "add-method", label: "Add a method" },
1946
+ { value: "remove-method", label: "Remove a method" },
1947
+ { value: "modify-method", label: "Modify a method" },
1948
+ { value: "exit", label: "Exit" }
1949
+ ]
1950
+ });
1951
+ if (p2.isCancel(action) || action === "exit") break;
1952
+ try {
1953
+ switch (action) {
1954
+ case "add-endpoint":
1955
+ await serverConfigAddEndpoint();
1956
+ break;
1957
+ case "remove-endpoint":
1958
+ await serverConfigRemoveEndpoint(summaries);
1959
+ break;
1960
+ case "add-method":
1961
+ await serverConfigAddMethod(summaries);
1962
+ break;
1963
+ case "remove-method":
1964
+ await serverConfigRemoveMethod(summaries);
1965
+ break;
1966
+ case "modify-method":
1967
+ await serverConfigModifyMethod(summaries);
1968
+ break;
1969
+ }
1970
+ } catch (err) {
1971
+ p2.log.error(err instanceof Error ? err.message : String(err));
1972
+ }
1973
+ }
1974
+ p2.outro("Done.");
1975
+ }
1204
1976
  async function runScaffold() {
1205
1977
  const answers = await runPrompts();
1206
1978
  const { root, filesWritten } = await generateProject(answers);
@@ -1232,6 +2004,14 @@ async function main() {
1232
2004
  await runAddMethod();
1233
2005
  return;
1234
2006
  }
2007
+ if (subcommand && PROJECT_SUBCOMMANDS.has(subcommand)) {
2008
+ await runProjectOverview();
2009
+ return;
2010
+ }
2011
+ if (subcommand && SERVER_CONFIG_SUBCOMMANDS.has(subcommand)) {
2012
+ await runServerConfig();
2013
+ return;
2014
+ }
1235
2015
  await runScaffold();
1236
2016
  }
1237
2017
  main().catch((err) => {