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/dist/cli.js CHANGED
@@ -1,6 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  // src/cli.ts
4
+ import { readFile as readFile8 } from "node:fs/promises";
5
+ import { join as join12 } from "node:path";
4
6
  import * as p2 from "@clack/prompts";
5
7
 
6
8
  // src/prompts.ts
@@ -220,19 +222,20 @@ function serviceImports(route, spec, language) {
220
222
  return imports;
221
223
  }
222
224
  function renderServiceMethod(spec, language) {
223
- const ext = language === "javascript" ? "js" : "ts";
224
225
  const argList = language === "javascript" ? serviceCallArgs(spec).join(", ") : serviceParamList(spec);
225
- return `// TODO: replace with real data access (see src/config/db.${ext})
226
+ return `// TODO: replace with real data access \u2014 e.g. import { db } from "#config/db";
226
227
  export async function ${spec.name}(${argList}) {
227
228
  ${defaultServiceReturn(spec)}
228
229
  }`;
229
230
  }
230
231
 
231
232
  // src/templates/db.ts
233
+ var DRIZZLE_KIT_DEV_DEPENDENCY = { "drizzle-kit": "^0.31.0" };
232
234
  var TEMPLATES = {
233
235
  neon: {
234
236
  file: `import { drizzle } from "drizzle-orm/neon-http";
235
237
  import { neon } from "@neondatabase/serverless";
238
+ import * as schema from "./schema";
236
239
 
237
240
  if (!process.env.DATABASE_URL) {
238
241
  throw new Error("DATABASE_URL is required (Neon connection string)");
@@ -240,18 +243,21 @@ if (!process.env.DATABASE_URL) {
240
243
 
241
244
  const sql = neon(process.env.DATABASE_URL);
242
245
 
243
- export const db = drizzle(sql);
246
+ export const db = drizzle(sql, { schema });
244
247
  `,
245
248
  dependencies: {
246
249
  "drizzle-orm": "^0.38.2",
247
250
  "@neondatabase/serverless": "^0.10.4"
248
251
  },
252
+ devDependencies: DRIZZLE_KIT_DEV_DEPENDENCY,
249
253
  envVars: "DATABASE_URL=postgres://user:password@ep-example-123456.us-east-2.aws.neon.tech/dbname?sslmode=require\n",
250
- readmeNote: "Uses Neon's HTTP driver \u2014 no connection pooling to manage, which is what makes it safe to use from serverless functions (e.g. Vercel)."
254
+ readmeNote: "Uses Neon's HTTP driver \u2014 no connection pooling to manage, which is what makes it safe to use from serverless functions (e.g. Vercel).",
255
+ hasSchemaSupport: true
251
256
  },
252
257
  postgres: {
253
258
  file: `import { drizzle } from "drizzle-orm/node-postgres";
254
259
  import { Pool } from "pg";
260
+ import * as schema from "./schema";
255
261
 
256
262
  // NOTE: this pooled connection is for local dev or a long-running server
257
263
  // (Docker, a VPS, Render, etc). It is NOT safe to use as-is on Vercel
@@ -265,14 +271,16 @@ if (!process.env.DATABASE_URL) {
265
271
 
266
272
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
267
273
 
268
- export const db = drizzle(pool);
274
+ export const db = drizzle(pool, { schema });
269
275
  `,
270
276
  dependencies: {
271
277
  "drizzle-orm": "^0.38.2",
272
278
  pg: "^8.13.1"
273
279
  },
280
+ devDependencies: DRIZZLE_KIT_DEV_DEPENDENCY,
274
281
  envVars: "DATABASE_URL=postgres://user:password@localhost:5432/dbname\n",
275
- readmeNote: "Pooled Postgres connection \u2014 fine for local dev or a long-running server, NOT safe as-is on Vercel serverless functions (connection pool exhaustion on cold starts). Use Neon for serverless deploys."
282
+ readmeNote: "Pooled Postgres connection \u2014 fine for local dev or a long-running server, NOT safe as-is on Vercel serverless functions (connection pool exhaustion on cold starts). Use Neon for serverless deploys.",
283
+ hasSchemaSupport: true
276
284
  },
277
285
  sqlite: {
278
286
  file: `import { drizzle } from "drizzle-orm/bun-sqlite";
@@ -288,19 +296,25 @@ export const db = drizzle(sqlite);
288
296
  dependencies: {
289
297
  "drizzle-orm": "^0.38.2"
290
298
  },
299
+ devDependencies: {},
291
300
  envVars: "DATABASE_URL=./dev.db\n",
292
- readmeNote: "Local file-based SQLite \u2014 for local dev only, not for a serverless deploy target."
301
+ readmeNote: "Local file-based SQLite \u2014 for local dev only, not for a serverless deploy target. No schema.ts/add-table support yet \u2014 SQLite uses a different set of drizzle-orm column builders (sqlite-core, not pg-core), hand-write a schema with drizzle-orm/sqlite-core if you need one.",
302
+ hasSchemaSupport: false
293
303
  },
294
304
  none: {
295
305
  file: `// No database configured yet. Wire up a real client here \u2014 e.g. one of
296
306
  // the neon/postgres/sqlite variants this CLI can also generate \u2014 and
297
- // export it as \`db\` so src/endpoints/*/*.services.ts can import it.
307
+ // export it as \`db\`. Any service file can then do
308
+ // \`import { db } from "#config/db";\` (see package.json's "imports" field
309
+ // and the README's Database section) regardless of how deep it's nested.
298
310
 
299
311
  export const db = undefined;
300
312
  `,
301
313
  dependencies: {},
314
+ devDependencies: {},
302
315
  envVars: "",
303
- readmeNote: "No database configured. src/config/db.ts is an empty stub."
316
+ readmeNote: "No database configured. src/config/db.ts is an empty stub.",
317
+ hasSchemaSupport: false
304
318
  }
305
319
  };
306
320
  function renderDbFile(db) {
@@ -309,12 +323,18 @@ function renderDbFile(db) {
309
323
  function dbDependencies(db) {
310
324
  return TEMPLATES[db].dependencies;
311
325
  }
326
+ function dbDevDependencies(db) {
327
+ return TEMPLATES[db].devDependencies;
328
+ }
312
329
  function dbEnvVars(db) {
313
330
  return TEMPLATES[db].envVars;
314
331
  }
315
332
  function dbReadmeNote(db) {
316
333
  return TEMPLATES[db].readmeNote;
317
334
  }
335
+ function dbHasSchemaSupport(db) {
336
+ return TEMPLATES[db].hasSchemaSupport;
337
+ }
318
338
 
319
339
  // src/templates/base.ts
320
340
  function renderIndexTs(framework) {
@@ -481,6 +501,169 @@ writeFileSync("docs.html", apiReferenceHtmlInline(spec, "${projectName}"));
481
501
  console.log("Wrote openapi.json and docs.html");
482
502
  `;
483
503
  }
504
+ function renderGenerateClientScript(language) {
505
+ const ext = language === "javascript" ? "js" : "ts";
506
+ const typed = language === "javascript" ? "false" : "true";
507
+ const ann = (t) => language === "javascript" ? "" : `: ${t}`;
508
+ return `// Regenerates client/api.${ext} from src/endpoints/ \u2014 reads *.routes.${ext}/*.controller.${ext}
509
+ // directly, the same source add-method/remove-method/server-config write to, so there's
510
+ // nothing to keep in sync by hand. Safe to re-run any time; nothing here needs updating
511
+ // when a route or method is added, removed, or modified \u2014 only its output does.
512
+ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
513
+ import { join } from "node:path";
514
+
515
+ const EXT = "${ext}";
516
+ const TYPED = ${typed};
517
+
518
+ const root = process.cwd();
519
+ const endpointsDir = join(root, "src/endpoints");
520
+
521
+ const MOUNT_PATTERN = /endpoints\\.(?:route|use)\\("\\/([a-z0-9-]+)"/g;
522
+ const METHOD_PATTERN = /\\.(get|post|put|patch|delete)\\(\\s*"([^"]*)"\\s*,\\s*controller\\.(\\w+)\\s*\\)/g;
523
+
524
+ function paramNames(path${ann("string")}) {
525
+ return Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g)).map((m) => m[1]);
526
+ }
527
+
528
+ function camelCase(name${ann("string")}) {
529
+ const parts = name.split("-");
530
+ return parts[0] + parts.slice(1).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
531
+ }
532
+
533
+ // Builds a JS expression string for the full request path \u2014 literal
534
+ // segments as JSON string literals, :param segments as bare identifiers,
535
+ // joined with "+" \u2014 e.g. "/users/:id" becomes the text: "/users/" + id
536
+ function pathExpr(route${ann("string")}, method${ann("any")}) {
537
+ const fullPath = "/" + route + (method.path === "/" ? "" : method.path);
538
+ const pieces = [];
539
+ let lastIndex = 0;
540
+ const paramRe = /:([A-Za-z0-9_]+)/g;
541
+ let match;
542
+ while ((match = paramRe.exec(fullPath))) {
543
+ if (match.index > lastIndex) pieces.push(JSON.stringify(fullPath.slice(lastIndex, match.index)));
544
+ pieces.push(match[1]);
545
+ lastIndex = match.index + match[0].length;
546
+ }
547
+ if (lastIndex < fullPath.length) pieces.push(JSON.stringify(fullPath.slice(lastIndex)));
548
+ return pieces.join(" + ");
549
+ }
550
+
551
+ function funcArgs(method${ann("any")}) {
552
+ const args = paramNames(method.path).slice();
553
+ if (method.needsBody) args.push("body");
554
+ if (method.needsQuery) args.push("query");
555
+ return args;
556
+ }
557
+
558
+ function typedFuncArgs(method${ann("any")}) {
559
+ const parts = paramNames(method.path).map((name) => name + ": string");
560
+ if (method.needsBody) parts.push("body: z.infer<typeof " + method.name + "BodySchema>");
561
+ if (method.needsQuery) parts.push("query: z.infer<typeof " + method.name + "QuerySchema>");
562
+ return parts.join(", ");
563
+ }
564
+
565
+ const indexContents = readFileSync(join(endpointsDir, "index." + EXT), "utf-8");
566
+ const routes = Array.from(indexContents.matchAll(MOUNT_PATTERN)).map((m) => m[1]);
567
+
568
+ const groups = [];
569
+ for (const route of routes) {
570
+ let routesContents, controllerContents;
571
+ try {
572
+ routesContents = readFileSync(join(endpointsDir, route, route + ".routes." + EXT), "utf-8");
573
+ controllerContents = readFileSync(join(endpointsDir, route, route + ".controller." + EXT), "utf-8");
574
+ } catch {
575
+ continue; // mounted but missing a file \u2014 \`bun run doctor\` already flags this, skip it here
576
+ }
577
+
578
+ const methods = Array.from(routesContents.matchAll(METHOD_PATTERN)).map((m) => ({
579
+ verb: m[1],
580
+ path: m[2],
581
+ name: m[3],
582
+ needsBody: controllerContents.includes(m[3] + "BodySchema"),
583
+ needsQuery: controllerContents.includes(m[3] + "QuerySchema"),
584
+ }));
585
+ if (methods.length > 0) groups.push({ route, methods });
586
+ }
587
+
588
+ if (groups.length === 0) {
589
+ console.log("No endpoints with methods yet \u2014 nothing to generate. Run \`bun run add-method\` first.");
590
+ process.exit(0);
591
+ }
592
+
593
+ const importLines = [];
594
+ if (TYPED) {
595
+ importLines.push('import type { z } from "zod";');
596
+ const namesByModule = new Map();
597
+ for (const group of groups) {
598
+ const names = [];
599
+ for (const m of group.methods) {
600
+ if (m.needsBody) names.push(m.name + "BodySchema");
601
+ if (m.needsQuery) names.push(m.name + "QuerySchema");
602
+ }
603
+ if (names.length > 0) namesByModule.set("../src/endpoints/" + group.route + "/" + group.route + ".controller", names);
604
+ }
605
+ for (const [modulePath, names] of namesByModule) {
606
+ importLines.push('import type { ' + names.join(", ") + ' } from "' + modulePath + '";');
607
+ }
608
+ }
609
+
610
+ const helperLines = [
611
+ 'const BASE_URL = (typeof process !== "undefined" && process.env.API_BASE_URL) || "";',
612
+ "",
613
+ TYPED ? "async function request<T>(path: string, init?: RequestInit): Promise<T> {" : "async function request(path, init) {",
614
+ " const res = await fetch(BASE_URL + path, {",
615
+ " ...init,",
616
+ ' headers: { "Content-Type": "application/json", ...(init && init.headers ? init.headers : {}) },',
617
+ " });",
618
+ " if (!res.ok) {",
619
+ TYPED ? " const errBody: any = await res.json().catch(() => undefined);" : " const errBody = await res.json().catch(() => undefined);",
620
+ ' throw new Error((errBody && errBody.error && errBody.error.message) || ("Request to " + path + " failed with " + res.status));',
621
+ " }",
622
+ TYPED ? " return res.json() as Promise<T>;" : " return res.json();",
623
+ "}",
624
+ ];
625
+
626
+ const groupBlocks = groups.map((group) => {
627
+ const varName = camelCase(group.route) + "Api";
628
+ const methodLines = group.methods.map((m) => {
629
+ const signature = TYPED ? typedFuncArgs(m) : funcArgs(m).join(", ");
630
+ const genericPrefix = TYPED ? "<T = unknown>" : "";
631
+
632
+ let call = "request" + (TYPED ? "<T>" : "") + "(" + pathExpr(group.route, m);
633
+ if (m.needsQuery) call += ' + "?" + new URLSearchParams(query' + (TYPED ? " as any" : "") + ").toString()";
634
+
635
+ const initParts = [];
636
+ if (m.verb !== "get") initParts.push('method: "' + m.verb.toUpperCase() + '"');
637
+ if (m.needsBody) initParts.push("body: JSON.stringify(body)");
638
+ if (initParts.length > 0) call += ", { " + initParts.join(", ") + " }";
639
+ call += ")";
640
+
641
+ return " " + m.name + ": " + genericPrefix + "(" + signature + ") => " + call + ",";
642
+ });
643
+ return "export const " + varName + " = {\\n" + methodLines.join("\\n") + "\\n};";
644
+ });
645
+
646
+ const header =
647
+ "// Auto-generated by \`bun run generate-client\` from src/endpoints/ \u2014 re-run after adding, removing,\\n" +
648
+ "// or modifying methods (add-method/remove-method/server-config all count). Hand edits here are\\n" +
649
+ "// overwritten on the next run.\\n\\n";
650
+
651
+ const output =
652
+ header +
653
+ (importLines.length > 0 ? importLines.join("\\n") + "\\n\\n" : "") +
654
+ helperLines.join("\\n") +
655
+ "\\n\\n" +
656
+ groupBlocks.join("\\n\\n") +
657
+ "\\n";
658
+
659
+ mkdirSync(join(root, "client"), { recursive: true });
660
+ const outPath = join(root, "client", "api." + EXT);
661
+ writeFileSync(outPath, output);
662
+ console.log(
663
+ "Wrote " + outPath + " (" + groups.reduce((n, g) => n + g.methods.length, 0) + " method(s) across " + groups.length + " endpoint(s))"
664
+ );
665
+ `;
666
+ }
484
667
  function renderEnvExample(db) {
485
668
  return `PORT=3000
486
669
  ALLOWED_ORIGINS=
@@ -503,7 +686,7 @@ function renderTsconfig() {
503
686
  "noEmit": true,
504
687
  "allowJs": false
505
688
  },
506
- "include": ["index.ts", "src", "scripts"]
689
+ "include": ["index.ts", "src", "scripts", "client"]
507
690
  }
508
691
  `;
509
692
  }
@@ -517,7 +700,7 @@ function renderJsconfig() {
517
700
  "checkJs": false,
518
701
  "allowJs": true
519
702
  },
520
- "include": ["index.js", "src", "scripts"]
703
+ "include": ["index.js", "src", "scripts", "client"]
521
704
  }
522
705
  `;
523
706
  }
@@ -537,7 +720,7 @@ function renderPackageJson(projectName, framework, language, db) {
537
720
  zod: "^3.24.1",
538
721
  ...dbDependencies(db)
539
722
  };
540
- const devDependencies = language === "javascript" ? {} : framework === "express" ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2" } : { "@types/bun": "latest", typescript: "^5.7.2" };
723
+ const devDependencies = language === "javascript" ? { ...dbDevDependencies(db) } : framework === "express" ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2", ...dbDevDependencies(db) } : { "@types/bun": "latest", typescript: "^5.7.2", ...dbDevDependencies(db) };
541
724
  const scripts = {
542
725
  dev: `bun run --watch index.${ext}`,
543
726
  start: `bun run index.${ext}`,
@@ -558,16 +741,38 @@ function renderPackageJson(projectName, framework, language, db) {
558
741
  // remember which of the individual subcommands above does what.
559
742
  project: "bunx create-backon project",
560
743
  "server-config": "bunx create-backon server-config",
561
- docs: `bun run scripts/generate-docs.${ext}`
744
+ docs: `bun run scripts/generate-docs.${ext}`,
745
+ // Regenerates client/api.<ext> — a typed fetch client, one function per
746
+ // mounted method, read straight off *.routes.<ext>/*.controller.<ext>
747
+ // (the same files add-method/server-config write). client/ is a build
748
+ // artifact like openapi.json/docs.html, not source — see .gitignore.
749
+ "generate-client": `bun run scripts/generate-client.${ext}`
562
750
  };
563
751
  if (language === "typescript") {
564
752
  scripts.typecheck = "tsc --noEmit";
565
753
  }
754
+ if (dbHasSchemaSupport(db)) {
755
+ scripts["add-table"] = "bunx create-backon add-table";
756
+ scripts["remove-table"] = "bunx create-backon remove-table";
757
+ scripts["db:generate"] = "drizzle-kit generate";
758
+ scripts["db:migrate"] = "drizzle-kit migrate";
759
+ scripts["db:push"] = "drizzle-kit push";
760
+ }
566
761
  const pkg = {
567
762
  name: projectName,
568
763
  version: "0.1.0",
569
764
  private: true,
570
765
  type: "module",
766
+ // Node's package.json subpath imports (Bun resolves these too, both
767
+ // locally and on Vercel's Bun runtime — no bundler-specific config
768
+ // needed, unlike a tsconfig "paths" alias). Lets any file import the db
769
+ // client as `import { db } from "#config/db"` regardless of how deep
770
+ // it's nested under src/endpoints/, instead of a depth-counted
771
+ // `../../config/db`. Verified against a real `bun run` and a real
772
+ // `tsc --noEmit` (moduleResolution: "bundler" already resolves it).
773
+ imports: {
774
+ "#config/*": `./src/config/*.${ext}`
775
+ },
571
776
  scripts,
572
777
  dependencies,
573
778
  devDependencies
@@ -616,6 +821,28 @@ both for free.
616
821
  `;
617
822
  }
618
823
  }
824
+ function renderSchemaReadmeSection(ext) {
825
+ return `
826
+ ### Table schema
827
+
828
+ \`src/config/schema.${ext}\` holds every table (empty until you add one \u2014 see below). \`bun run
829
+ add-table\`/\`bun run remove-table\` (also reachable from \`server-config\`'s menu) edit it for you \u2014
830
+ picking a column type, nullability, uniqueness, a default, and whether it references another
831
+ table's \`id\`. This only ever edits \`schema.${ext}\` on disk; it never touches the actual database.
832
+
833
+ To apply a schema change for real:
834
+
835
+ \`\`\`
836
+ bun run db:generate # writes a reviewable .sql migration under drizzle/ \u2014 no DB connection needed
837
+ bun run db:migrate # applies pending migrations to DATABASE_URL
838
+ \`\`\`
839
+
840
+ \`bun run db:push\` applies \`schema.${ext}\` straight to the database with no migration file \u2014 faster
841
+ to iterate with early on (empty/throwaway dev database), but skips the reviewable, versioned trail
842
+ \`generate\`/\`migrate\` gives you. Switch to \`generate\`/\`migrate\` once there's real data, or before
843
+ deploying anywhere with staging/prod.
844
+ `;
845
+ }
619
846
  function renderReadme(answers) {
620
847
  const routeList = answers.routes.length ? answers.routes.map((route) => `- \`src/endpoints/${route}/\``).join("\n") : "- (none yet \u2014 add one under src/endpoints/)";
621
848
  const backonImport = answers.framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
@@ -641,6 +868,11 @@ document to \`openapi.json\`/\`docs.html\` on disk, for CI or static hosting.
641
868
 
642
869
  ${dbReadmeNote(answers.db)}
643
870
 
871
+ Import the client from anywhere as \`import { db } from "#config/db";\` \u2014 a package.json subpath
872
+ import (\`imports\`), not a relative path, so it stays \`#config/db\` no matter how deeply nested the
873
+ importing file is under \`src/endpoints/\`. Bun resolves it the same way locally and on Vercel;
874
+ \`tsc --noEmit\` resolves it too, no extra tsconfig needed.
875
+ ${dbHasSchemaSupport(answers.db) ? renderSchemaReadmeSection(ext) : ""}
644
876
  ## Routes
645
877
 
646
878
  ${routeList}
@@ -653,6 +885,80 @@ request (via \`defineRoute\` from \`${backonImport}\`) and calls into
653
885
  ${renderDeploySection(answers.deployTarget, ext)}`;
654
886
  }
655
887
 
888
+ // src/templates/schema.ts
889
+ var COLUMN_TYPES = ["text", "integer", "boolean", "timestamp", "uuid"];
890
+ function tableIdentifier(name) {
891
+ return camelCase(toKebabCase(name));
892
+ }
893
+ function tableSqlName(name) {
894
+ return toKebabCase(name).replace(/-/g, "_");
895
+ }
896
+ function columnIdentifier(name) {
897
+ return camelCase(toKebabCase(name));
898
+ }
899
+ function columnSqlName(name) {
900
+ return toKebabCase(name).replace(/-/g, "_");
901
+ }
902
+ function requiredBuilders(table) {
903
+ const builders = /* @__PURE__ */ new Set(["pgTable"]);
904
+ if (table.includeId) builders.add("serial");
905
+ for (const col of table.columns) {
906
+ builders.add(col.references ? "integer" : col.type);
907
+ }
908
+ return builders;
909
+ }
910
+ function renderColumnLine(col) {
911
+ const key = columnIdentifier(col.name);
912
+ const sqlName = columnSqlName(col.name);
913
+ let expr;
914
+ if (col.references) {
915
+ expr = `integer("${sqlName}").references(() => ${col.references}.id)`;
916
+ } else {
917
+ expr = `${col.type}("${sqlName}")`;
918
+ }
919
+ if (col.notNull) expr += ".notNull()";
920
+ if (col.unique) expr += ".unique()";
921
+ if (col.defaultExpr) expr += col.defaultExpr;
922
+ return ` ${key}: ${expr},`;
923
+ }
924
+ function renderTableBlock(table) {
925
+ const identifier = tableIdentifier(table.name);
926
+ const sqlName = tableSqlName(table.name);
927
+ const lines = [];
928
+ if (table.includeId) lines.push(` id: serial("id").primaryKey(),`);
929
+ for (const col of table.columns) lines.push(renderColumnLine(col));
930
+ return `export const ${identifier} = pgTable("${sqlName}", {
931
+ ${lines.join("\n")}
932
+ });`;
933
+ }
934
+ function renderBlankSchema() {
935
+ return `// No tables yet \u2014 add one via \`bun run add-table\` (or server-config's
936
+ // "Add a database table"). Each table becomes a real pgTable(...) export
937
+ // here, picked up automatically by both db.ts's schema import and
938
+ // drizzle-kit (see drizzle.config.ts) \u2014 nothing else needs to be told
939
+ // about a new table by hand.
940
+
941
+ export {};
942
+ `;
943
+ }
944
+ function renderDrizzleConfig(ext) {
945
+ return `import { defineConfig } from "drizzle-kit";
946
+
947
+ if (!process.env.DATABASE_URL) {
948
+ throw new Error("DATABASE_URL is required (see src/config/db.${ext})");
949
+ }
950
+
951
+ export default defineConfig({
952
+ schema: "./src/config/schema.${ext}",
953
+ out: "./drizzle",
954
+ dialect: "postgresql",
955
+ dbCredentials: {
956
+ url: process.env.DATABASE_URL,
957
+ },
958
+ });
959
+ `;
960
+ }
961
+
656
962
  // src/generate.ts
657
963
  async function write(path, contents) {
658
964
  await mkdir(dirname(path), { recursive: true });
@@ -708,16 +1014,22 @@ dist/
708
1014
  .env.local
709
1015
  openapi.json
710
1016
  docs.html
1017
+ client/
711
1018
  ${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
712
1019
  ],
713
1020
  [join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
714
1021
  [join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
1022
+ ...dbHasSchemaSupport(answers.db) ? [
1023
+ [join(root, `src/config/schema.${ext}`), renderBlankSchema()],
1024
+ [join(root, "drizzle.config.ts"), renderDrizzleConfig(ext)]
1025
+ ] : [],
715
1026
  [
716
1027
  join(root, `src/middleware/example.middleware.${ext}`),
717
1028
  renderExampleMiddleware(answers.framework, answers.language)
718
1029
  ],
719
1030
  [join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
720
1031
  [join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
1032
+ [join(root, `scripts/generate-client.${ext}`), renderGenerateClientScript(answers.language)],
721
1033
  ...answers.deployTarget === "vercel" ? [[join(root, "vercel.json"), renderVercelJson()]] : []
722
1034
  ];
723
1035
  for (const route of answers.routes) {
@@ -918,6 +1230,143 @@ async function runDoctor(cwd = process.cwd()) {
918
1230
  import { readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
919
1231
  import { join as join8 } from "node:path";
920
1232
 
1233
+ // src/ast-edit.ts
1234
+ import { Node, Project } from "ts-morph";
1235
+ function makeProject() {
1236
+ return new Project({
1237
+ useInMemoryFileSystem: true,
1238
+ compilerOptions: { allowJs: true, checkJs: false }
1239
+ });
1240
+ }
1241
+ function loadSource(path, contents) {
1242
+ const project = makeProject();
1243
+ const sourceFile = project.createSourceFile(path, contents);
1244
+ return { project, sourceFile };
1245
+ }
1246
+ function editSource(path, contents, mutate) {
1247
+ const { project, sourceFile } = loadSource(path, contents);
1248
+ mutate(project, sourceFile);
1249
+ return printSource(sourceFile);
1250
+ }
1251
+ function parseImportLine(project, line) {
1252
+ const scratch = project.createSourceFile("__scratch_import__.ts", line, { overwrite: true });
1253
+ const decl = scratch.getImportDeclarations()[0];
1254
+ if (!decl) throw new Error(`Not a valid import statement: ${line}`);
1255
+ const parsed = {
1256
+ moduleSpecifier: decl.getModuleSpecifierValue(),
1257
+ isTypeOnly: decl.isTypeOnly(),
1258
+ namespaceImport: decl.getNamespaceImport()?.getText(),
1259
+ namedImports: decl.getNamedImports().map((ni) => ni.getName())
1260
+ };
1261
+ project.removeSourceFile(scratch);
1262
+ return parsed;
1263
+ }
1264
+ function ensureImports(sourceFile, project, lines) {
1265
+ for (const line of lines) {
1266
+ const spec = parseImportLine(project, line);
1267
+ const alreadyPresent = sourceFile.getImportDeclarations().some((d) => {
1268
+ if (d.getModuleSpecifierValue() !== spec.moduleSpecifier) return false;
1269
+ if (d.isTypeOnly() !== spec.isTypeOnly) return false;
1270
+ if (spec.namespaceImport) return d.getNamespaceImport()?.getText() === spec.namespaceImport;
1271
+ const names = new Set(d.getNamedImports().map((ni) => ni.getName()));
1272
+ return spec.namedImports.length > 0 && spec.namedImports.every((n) => names.has(n));
1273
+ });
1274
+ if (alreadyPresent) continue;
1275
+ sourceFile.addImportDeclaration({
1276
+ moduleSpecifier: spec.moduleSpecifier,
1277
+ isTypeOnly: spec.isTypeOnly,
1278
+ ...spec.namespaceImport ? { namespaceImport: spec.namespaceImport } : { namedImports: spec.namedImports }
1279
+ });
1280
+ }
1281
+ }
1282
+ function appendStatements(sourceFile, code) {
1283
+ sourceFile.addStatements(`
1284
+ ${code}`);
1285
+ }
1286
+ function removeControllerMethod(sourceFile, name) {
1287
+ const targets = /* @__PURE__ */ new Set([name, `${name}ParamsSchema`, `${name}BodySchema`, `${name}QuerySchema`]);
1288
+ let removed = false;
1289
+ for (const stmt of sourceFile.getVariableStatements()) {
1290
+ const decls = stmt.getDeclarations();
1291
+ if (decls.length === 1 && targets.has(decls[0].getName())) {
1292
+ stmt.remove();
1293
+ removed = true;
1294
+ }
1295
+ }
1296
+ if (removed) stripOrphanedTodoComment(sourceFile, name);
1297
+ return removed;
1298
+ }
1299
+ function stripOrphanedTodoComment(sourceFile, name) {
1300
+ const marker = `replace with the real shape of "${name}"`;
1301
+ const ranges = [];
1302
+ for (const stmt of sourceFile.getStatements()) {
1303
+ for (const range of stmt.getLeadingCommentRanges()) {
1304
+ if (range.getText().includes(marker)) ranges.push({ pos: range.getPos(), end: range.getEnd() });
1305
+ }
1306
+ }
1307
+ ranges.sort((a, b) => b.pos - a.pos);
1308
+ const fullText = sourceFile.getFullText();
1309
+ for (const { pos, end } of ranges) {
1310
+ const end2 = fullText[end] === "\n" ? end + 1 : end;
1311
+ sourceFile.removeText(pos, end2);
1312
+ }
1313
+ }
1314
+ function removeRouteMount(sourceFile, name) {
1315
+ for (const stmt of sourceFile.getStatements()) {
1316
+ if (!Node.isExpressionStatement(stmt)) continue;
1317
+ const expr = stmt.getExpression();
1318
+ if (!Node.isCallExpression(expr)) continue;
1319
+ const args = expr.getArguments();
1320
+ const last = args[args.length - 1];
1321
+ if (last && Node.isPropertyAccessExpression(last) && last.getName() === name) {
1322
+ stmt.remove();
1323
+ return true;
1324
+ }
1325
+ }
1326
+ return false;
1327
+ }
1328
+ function removeServiceMethod(sourceFile, name) {
1329
+ const fn = sourceFile.getFunction(name);
1330
+ if (!fn) return false;
1331
+ fn.remove();
1332
+ const methodTypeNames = /* @__PURE__ */ new Set([`${name}ParamsSchema`, `${name}BodySchema`, `${name}QuerySchema`]);
1333
+ for (const importDecl of sourceFile.getImportDeclarations()) {
1334
+ const names = importDecl.getNamedImports().map((ni) => ni.getName());
1335
+ if (names.length > 0 && names.every((n) => methodTypeNames.has(n))) {
1336
+ importDecl.remove();
1337
+ }
1338
+ }
1339
+ return true;
1340
+ }
1341
+ var SCHEMA_CONST_SUFFIXES = ["ParamsSchema", "BodySchema", "QuerySchema"];
1342
+ function isSchemaConstStatement(node) {
1343
+ if (!Node.isVariableStatement(node)) return false;
1344
+ const decls = node.getDeclarations();
1345
+ return decls.length === 1 && SCHEMA_CONST_SUFFIXES.some((suffix) => decls[0].getName().endsWith(suffix));
1346
+ }
1347
+ function printSource(sourceFile) {
1348
+ const importDecls = sourceFile.getImportDeclarations();
1349
+ const importText = importDecls.map((d) => d.getText()).join("\n");
1350
+ const rest = sourceFile.getStatements().filter((s) => !Node.isImportDeclaration(s));
1351
+ const paragraphs = [];
1352
+ let i = 0;
1353
+ while (i < rest.length) {
1354
+ const parts = [];
1355
+ while (i < rest.length && isSchemaConstStatement(rest[i])) {
1356
+ parts.push(rest[i].getFullText().trim());
1357
+ i++;
1358
+ }
1359
+ if (i < rest.length) {
1360
+ parts.push(rest[i].getFullText().trim());
1361
+ i++;
1362
+ }
1363
+ paragraphs.push(parts.join("\n"));
1364
+ }
1365
+ const blocks = [importText, ...paragraphs].filter((b) => b.length > 0);
1366
+ return blocks.length > 0 ? `${blocks.join("\n\n")}
1367
+ ` : "";
1368
+ }
1369
+
921
1370
  // src/route-methods.ts
922
1371
  import { readFile as readFile3 } from "node:fs/promises";
923
1372
  import { join as join7 } from "node:path";
@@ -1001,24 +1450,6 @@ var PLACEHOLDER_PATTERN = /\/\/ No (?:routes|methods) yet[^\n]*\n\n?/;
1001
1450
  function stripPlaceholder(content) {
1002
1451
  return content.replace(PLACEHOLDER_PATTERN, "");
1003
1452
  }
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
1453
  async function addMethod(route, spec, cwd = process.cwd()) {
1023
1454
  const { root, framework, language, ext } = await detectProject(cwd);
1024
1455
  const { contents: indexContents } = await readEndpointsIndex(root, ext);
@@ -1042,12 +1473,18 @@ async function addMethod(route, spec, cwd = process.cwd()) {
1042
1473
  if (existing.some((m) => m.verb === spec.verb && m.path === spec.path)) {
1043
1474
  throw new Error(`${spec.verb.toUpperCase()} ${spec.path} is already mounted in ${routesPath}.`);
1044
1475
  }
1045
- const newController = appendBlock(ensureImports(controllerContents, controllerImports(route, framework)), renderControllerMethod(spec));
1046
- const newRoutes = appendBlock(
1047
- ensureImports(routesContents, [`import * as controller from "./${route}.controller";`]),
1048
- routeMountLine(route, spec)
1049
- );
1050
- const newServices = appendBlock(ensureImports(servicesContents, serviceImports(route, spec, language)), renderServiceMethod(spec, language));
1476
+ const newController = editSource(controllerPath, stripPlaceholder(controllerContents), (project, sourceFile) => {
1477
+ ensureImports(sourceFile, project, controllerImports(route, framework));
1478
+ appendStatements(sourceFile, renderControllerMethod(spec));
1479
+ });
1480
+ const newRoutes = editSource(routesPath, stripPlaceholder(routesContents), (project, sourceFile) => {
1481
+ ensureImports(sourceFile, project, [`import * as controller from "./${route}.controller";`]);
1482
+ appendStatements(sourceFile, routeMountLine(route, spec));
1483
+ });
1484
+ const newServices = editSource(servicesPath, stripPlaceholder(servicesContents), (project, sourceFile) => {
1485
+ ensureImports(sourceFile, project, serviceImports(route, spec, language));
1486
+ appendStatements(sourceFile, renderServiceMethod(spec, language));
1487
+ });
1051
1488
  await Promise.all([
1052
1489
  writeFile4(controllerPath, newController),
1053
1490
  writeFile4(routesPath, newRoutes),
@@ -1059,15 +1496,6 @@ async function addMethod(route, spec, cwd = process.cwd()) {
1059
1496
  // src/remove-method.ts
1060
1497
  import { readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
1061
1498
  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
1499
  async function removeMethod(route, verb, path, cwd = process.cwd()) {
1072
1500
  const { root, framework, language, ext } = await detectProject(cwd);
1073
1501
  const { contents: indexContents } = await readEndpointsIndex(root, ext);
@@ -1098,10 +1526,15 @@ async function removeMethod(route, verb, path, cwd = process.cwd()) {
1098
1526
  ]);
1099
1527
  return { route, root, removed: match };
1100
1528
  }
1101
- const expectedMountLine = routeMountLine(route, { verb, path, name, needsBody: false, needsQuery: false });
1102
- const newController = removeBlock(controllerContents, (block) => block.includes(`export const ${name} = defineRoute(`));
1103
- const newRoutes = removeBlock(routesContents, (block) => block.trim() === expectedMountLine);
1104
- const newServices = removeBlock(servicesContents, (block) => block.includes(`export async function ${name}(`));
1529
+ const newController = editSource(controllerPath, controllerContents, (_project, sourceFile) => {
1530
+ removeControllerMethod(sourceFile, name);
1531
+ });
1532
+ const newRoutes = editSource(routesPath, routesContents, (_project, sourceFile) => {
1533
+ removeRouteMount(sourceFile, name);
1534
+ });
1535
+ const newServices = editSource(servicesPath, servicesContents, (_project, sourceFile) => {
1536
+ removeServiceMethod(sourceFile, name);
1537
+ });
1105
1538
  await Promise.all([
1106
1539
  writeFile5(controllerPath, newController),
1107
1540
  writeFile5(routesPath, newRoutes),
@@ -1176,6 +1609,196 @@ async function detectDbStatus(cwd = process.cwd()) {
1176
1609
  };
1177
1610
  }
1178
1611
 
1612
+ // src/crud-scaffold.ts
1613
+ var CRUD_METHOD_SPECS = [
1614
+ { verb: "get", path: "/", name: "list", needsBody: false, needsQuery: false },
1615
+ { verb: "post", path: "/", name: "create", needsBody: true, needsQuery: false },
1616
+ { verb: "get", path: "/:id", name: "getById", needsBody: false, needsQuery: false },
1617
+ { verb: "put", path: "/:id", name: "update", needsBody: true, needsQuery: false },
1618
+ { verb: "delete", path: "/:id", name: "remove", needsBody: false, needsQuery: false }
1619
+ ];
1620
+ async function addCrudMethods(route, cwd = process.cwd()) {
1621
+ const summaries = await listEndpointsWithMethods(cwd);
1622
+ const existing = [...summaries.find((s) => s.route === route)?.methods ?? []];
1623
+ const added = [];
1624
+ const skipped = [];
1625
+ for (const spec of CRUD_METHOD_SPECS) {
1626
+ const collides = existing.some((m) => m.name === spec.name || m.verb === spec.verb && m.path === spec.path);
1627
+ if (collides) {
1628
+ skipped.push(spec.name);
1629
+ continue;
1630
+ }
1631
+ await addMethod(route, spec, cwd);
1632
+ added.push(spec.name);
1633
+ existing.push({ verb: spec.verb, path: spec.path, name: spec.name });
1634
+ }
1635
+ return { route, added, skipped };
1636
+ }
1637
+
1638
+ // src/schema-edit.ts
1639
+ import { readFile as readFile7, writeFile as writeFile6 } from "node:fs/promises";
1640
+ import { join as join11 } from "node:path";
1641
+ import { Node as Node2, SyntaxKind } from "ts-morph";
1642
+ var PG_CORE_MODULE = "drizzle-orm/pg-core";
1643
+ function parseSchemaTables(contents) {
1644
+ const { sourceFile } = editSourceForReading(contents);
1645
+ const tables = [];
1646
+ for (const stmt of sourceFile.getVariableStatements()) {
1647
+ if (!stmt.isExported()) continue;
1648
+ const decl = stmt.getDeclarations()[0];
1649
+ if (!decl) continue;
1650
+ const init = decl.getInitializer();
1651
+ if (!init || !Node2.isCallExpression(init)) continue;
1652
+ const callee = init.getExpression();
1653
+ if (!Node2.isIdentifier(callee) || callee.getText() !== "pgTable") continue;
1654
+ const [sqlNameArg, columnsArg] = init.getArguments();
1655
+ const sqlName = sqlNameArg && Node2.isStringLiteral(sqlNameArg) ? sqlNameArg.getLiteralValue() : "";
1656
+ const columns = [];
1657
+ if (columnsArg && Node2.isObjectLiteralExpression(columnsArg)) {
1658
+ for (const prop of columnsArg.getProperties()) {
1659
+ if (!Node2.isPropertyAssignment(prop)) continue;
1660
+ columns.push({ key: prop.getName(), references: findReferencedTable(prop) });
1661
+ }
1662
+ }
1663
+ tables.push({ identifier: decl.getName(), sqlName, columns });
1664
+ }
1665
+ return tables;
1666
+ }
1667
+ function findReferencedTable(propAssignment) {
1668
+ const init = Node2.isPropertyAssignment(propAssignment) ? propAssignment.getInitializer() : void 0;
1669
+ if (!init) return void 0;
1670
+ for (const call of init.getDescendantsOfKind(SyntaxKind.CallExpression)) {
1671
+ const expr = call.getExpression();
1672
+ if (!Node2.isPropertyAccessExpression(expr) || expr.getName() !== "references") continue;
1673
+ const arrowArg = call.getArguments()[0];
1674
+ if (!arrowArg || !Node2.isArrowFunction(arrowArg)) continue;
1675
+ const body = arrowArg.getBody();
1676
+ if (Node2.isPropertyAccessExpression(body) && Node2.isIdentifier(body.getExpression())) {
1677
+ return body.getExpression().getText();
1678
+ }
1679
+ }
1680
+ return void 0;
1681
+ }
1682
+ function editSourceForReading(contents) {
1683
+ let sourceFile;
1684
+ editSource("schema.ts", contents, (_project, sf) => {
1685
+ sourceFile = sf;
1686
+ });
1687
+ return { sourceFile };
1688
+ }
1689
+ function ensurePgCoreImport(sourceFile, builders) {
1690
+ const wanted = [...builders].sort();
1691
+ const existing = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
1692
+ if (!existing) {
1693
+ sourceFile.addImportDeclaration({ moduleSpecifier: PG_CORE_MODULE, namedImports: wanted });
1694
+ return;
1695
+ }
1696
+ const already = new Set(existing.getNamedImports().map((ni) => ni.getName()));
1697
+ const missing = wanted.filter((name) => !already.has(name));
1698
+ if (missing.length > 0) existing.addNamedImports(missing);
1699
+ }
1700
+ function prunePgCoreImport(sourceFile) {
1701
+ const decl = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
1702
+ if (!decl) return;
1703
+ const used = /* @__PURE__ */ new Set();
1704
+ for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
1705
+ const expr = call.getExpression();
1706
+ if (Node2.isIdentifier(expr)) used.add(expr.getText());
1707
+ }
1708
+ for (const named of decl.getNamedImports()) {
1709
+ if (!used.has(named.getName())) named.remove();
1710
+ }
1711
+ if (decl.getNamedImports().length === 0) decl.remove();
1712
+ }
1713
+ function removeTableStatement(sourceFile, identifier) {
1714
+ for (const stmt of sourceFile.getVariableStatements()) {
1715
+ const decls = stmt.getDeclarations();
1716
+ if (decls.length === 1 && decls[0].getName() === identifier) {
1717
+ stmt.remove();
1718
+ return true;
1719
+ }
1720
+ }
1721
+ return false;
1722
+ }
1723
+ async function requireNeonOrPostgres(cwd) {
1724
+ const status = await detectDbStatus(cwd);
1725
+ if (status.driver === "neon" || status.driver === "postgres") return;
1726
+ throw new Error(
1727
+ `Schema management needs a "neon" or "postgres" db driver (src/config/db reports "${status.driver}") \u2014 SQLite and "none" use a different schema dialect (or none at all) and aren't supported by add-table/remove-table yet.`
1728
+ );
1729
+ }
1730
+ async function readSchemaFile(root, ext) {
1731
+ const path = join11(root, "src/config", `schema.${ext}`);
1732
+ try {
1733
+ return { path, contents: await readFile7(path, "utf-8") };
1734
+ } catch (err) {
1735
+ if (err.code === "ENOENT") {
1736
+ throw new Error(
1737
+ `${path} doesn't exist. This project's db.ts predates schema scaffolding \u2014 add a src/config/schema.${ext} by hand (see the README's Database section) before using add-table.`
1738
+ );
1739
+ }
1740
+ throw err;
1741
+ }
1742
+ }
1743
+ async function addTable(spec, cwd = process.cwd()) {
1744
+ await requireNeonOrPostgres(cwd);
1745
+ const { root, ext } = await detectProject(cwd);
1746
+ const { path, contents } = await readSchemaFile(root, ext);
1747
+ const identifier = tableIdentifier(spec.name);
1748
+ const existingTables = parseSchemaTables(contents);
1749
+ if (existingTables.some((t) => t.identifier === identifier)) {
1750
+ throw new Error(`"${identifier}" is already a table in ${path}.`);
1751
+ }
1752
+ for (const col of spec.columns) {
1753
+ if (col.references && !existingTables.some((t) => t.identifier === col.references)) {
1754
+ throw new Error(`Column "${col.name}" references unknown table "${col.references}".`);
1755
+ }
1756
+ }
1757
+ const withoutPlaceholder = contents.includes(renderBlankSchema()) ? contents.replace(renderBlankSchema(), "") : contents;
1758
+ const updated = editSource(path, withoutPlaceholder, (_project, sourceFile) => {
1759
+ ensurePgCoreImport(sourceFile, requiredBuilders(spec));
1760
+ appendStatements(sourceFile, renderTableBlock(spec));
1761
+ });
1762
+ await writeFile6(path, updated);
1763
+ return { root, identifier, filePath: path };
1764
+ }
1765
+ function formatTablesDashboard(tables) {
1766
+ if (tables.length === 0) return dim("No tables yet.");
1767
+ return tables.map((t) => {
1768
+ if (t.columns.length === 0) return `${t.identifier} (${t.sqlName})
1769
+ ${dim("(no columns)")}`;
1770
+ const lines = t.columns.map((c) => ` ${c.key}${c.references ? dim(` \u2192 references ${c.references}.id`) : ""}`);
1771
+ return `${t.identifier} (${t.sqlName})
1772
+ ${lines.join("\n")}`;
1773
+ }).join("\n\n");
1774
+ }
1775
+ async function removeTable(identifier, cwd = process.cwd()) {
1776
+ await requireNeonOrPostgres(cwd);
1777
+ const { root, ext } = await detectProject(cwd);
1778
+ const { path, contents } = await readSchemaFile(root, ext);
1779
+ const tables = parseSchemaTables(contents);
1780
+ const target = tables.find((t) => t.identifier === identifier);
1781
+ if (!target) {
1782
+ throw new Error(`No table "${identifier}" found in ${path}.`);
1783
+ }
1784
+ const referencedBy = tables.filter((t) => t.identifier !== identifier && t.columns.some((c) => c.references === identifier));
1785
+ if (referencedBy.length > 0) {
1786
+ throw new Error(
1787
+ `Can't remove "${identifier}" \u2014 still referenced by: ${referencedBy.map((t) => t.identifier).join(", ")}. Remove those columns/tables first.`
1788
+ );
1789
+ }
1790
+ if (tables.length === 1) {
1791
+ await writeFile6(path, renderBlankSchema());
1792
+ return { root, identifier, filePath: path };
1793
+ }
1794
+ const updated = editSource(path, contents, (_project, sourceFile) => {
1795
+ removeTableStatement(sourceFile, identifier);
1796
+ prunePgCoreImport(sourceFile);
1797
+ });
1798
+ await writeFile6(path, updated);
1799
+ return { root, identifier, filePath: path };
1800
+ }
1801
+
1179
1802
  // src/cli.ts
1180
1803
  var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
1181
1804
  var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
@@ -1184,6 +1807,8 @@ var DOCTOR_SUBCOMMANDS = /* @__PURE__ */ new Set(["doctor"]);
1184
1807
  var ADD_METHOD_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-method", "method"]);
1185
1808
  var PROJECT_SUBCOMMANDS = /* @__PURE__ */ new Set(["project"]);
1186
1809
  var SERVER_CONFIG_SUBCOMMANDS = /* @__PURE__ */ new Set(["server-config"]);
1810
+ var ADD_TABLE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-table", "table"]);
1811
+ var REMOVE_TABLE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-table", "rm-table"]);
1187
1812
  async function promptForRouteName(introText) {
1188
1813
  p2.intro(introText);
1189
1814
  const answer = await p2.text({
@@ -1197,15 +1822,36 @@ async function promptForRouteName(introText) {
1197
1822
  }
1198
1823
  return answer;
1199
1824
  }
1825
+ function logCrudResult(result) {
1826
+ const skippedNote = result.skipped.length ? ` (skipped, already there: ${result.skipped.join(", ")})` : "";
1827
+ p2.log.success(`Added CRUD methods to ${result.route}: ${result.added.join(", ") || "none"}${skippedNote}`);
1828
+ }
1200
1829
  async function runAddRoute(args) {
1201
- let [name] = args;
1830
+ const crudFlagIndex = args.indexOf("--crud");
1831
+ const withCrud = crudFlagIndex !== -1;
1832
+ const positional = withCrud ? args.filter((_, i) => i !== crudFlagIndex) : args;
1833
+ let [name] = positional;
1834
+ let interactive = false;
1202
1835
  if (!name) {
1836
+ interactive = true;
1203
1837
  name = await promptForRouteName("create-backon add-route");
1204
1838
  p2.outro(`Adding ${name}...`);
1205
1839
  }
1206
1840
  const { route, root, filesWritten } = await addRoute(name);
1207
1841
  p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
1208
- p2.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
1842
+ let scaffoldCrud = withCrud;
1843
+ if (!withCrud && interactive) {
1844
+ const answer = await p2.confirm({
1845
+ message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
1846
+ initialValue: false
1847
+ });
1848
+ scaffoldCrud = !p2.isCancel(answer) && answer;
1849
+ }
1850
+ if (scaffoldCrud) {
1851
+ logCrudResult(await addCrudMethods(route, root));
1852
+ } else {
1853
+ p2.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
1854
+ }
1209
1855
  }
1210
1856
  async function runRemoveRoute(args) {
1211
1857
  let [name] = args;
@@ -1257,6 +1903,245 @@ async function runProjectOverview() {
1257
1903
  }
1258
1904
  p2.outro("Manage endpoints and methods with `bun run server-config`.");
1259
1905
  }
1906
+ async function ensureSchemaSupport() {
1907
+ const status = await detectDbStatus();
1908
+ if (status.driver === "neon" || status.driver === "postgres") return true;
1909
+ p2.log.error(
1910
+ `Schema management needs a "neon" or "postgres" db driver (src/config/db reports "${status.driver}") \u2014 SQLite and "none" use a different schema dialect (or none at all) and aren't supported here yet.`
1911
+ );
1912
+ return false;
1913
+ }
1914
+ async function readSchemaTables() {
1915
+ const { root, ext } = await detectProject();
1916
+ try {
1917
+ const contents = await readFile8(join12(root, "src/config", `schema.${ext}`), "utf-8");
1918
+ return parseSchemaTables(contents);
1919
+ } catch {
1920
+ return [];
1921
+ }
1922
+ }
1923
+ async function promptDefaultExpr(type) {
1924
+ if (type === "timestamp") {
1925
+ const v2 = await p2.confirm({ message: "Default to now()?", initialValue: false });
1926
+ if (p2.isCancel(v2)) return null;
1927
+ return v2 ? ".defaultNow()" : "";
1928
+ }
1929
+ if (type === "uuid") {
1930
+ const v2 = await p2.confirm({ message: "Default to a random UUID?", initialValue: false });
1931
+ if (p2.isCancel(v2)) return null;
1932
+ return v2 ? ".defaultRandom()" : "";
1933
+ }
1934
+ if (type === "boolean") {
1935
+ const v2 = await p2.select({
1936
+ message: "Default value",
1937
+ options: [
1938
+ { value: "none", label: "None" },
1939
+ { value: "true", label: "true" },
1940
+ { value: "false", label: "false" }
1941
+ ],
1942
+ initialValue: "none"
1943
+ });
1944
+ if (p2.isCancel(v2)) return null;
1945
+ return v2 === "none" ? "" : `.default(${v2})`;
1946
+ }
1947
+ const v = await p2.text({
1948
+ message: "Default value (blank for none)",
1949
+ placeholder: type === "integer" ? "e.g. 0" : "e.g. pending"
1950
+ });
1951
+ if (p2.isCancel(v)) return null;
1952
+ if (!v) return "";
1953
+ if (type === "integer") {
1954
+ const n = Number(v);
1955
+ if (Number.isNaN(n)) {
1956
+ p2.log.warn(`"${v}" isn't a number \u2014 skipping the default.`);
1957
+ return "";
1958
+ }
1959
+ return `.default(${n})`;
1960
+ }
1961
+ return `.default(${JSON.stringify(v)})`;
1962
+ }
1963
+ async function promptForColumns(existingTables) {
1964
+ const columns = [];
1965
+ p2.log.step("Add columns one at a time. Leave the name blank to finish.");
1966
+ while (true) {
1967
+ const nameProbe = await p2.text({
1968
+ message: columns.length === 0 ? "Column name" : "Another column? (blank to finish)",
1969
+ placeholder: columns.length === 0 ? "e.g. email" : ""
1970
+ });
1971
+ if (p2.isCancel(nameProbe)) return null;
1972
+ if (!nameProbe) break;
1973
+ const key = columnIdentifier(nameProbe);
1974
+ if (columns.some((c) => columnIdentifier(c.name) === key)) {
1975
+ p2.log.error(`"${key}" is already a column on this table.`);
1976
+ continue;
1977
+ }
1978
+ let references;
1979
+ if (existingTables.length > 0) {
1980
+ const refChoice = await p2.select({
1981
+ message: `Does "${nameProbe}" reference another table's id?`,
1982
+ options: [
1983
+ { value: "__none__", label: "No" },
1984
+ ...existingTables.map((t) => ({ value: t.identifier, label: t.identifier }))
1985
+ ],
1986
+ initialValue: "__none__"
1987
+ });
1988
+ if (p2.isCancel(refChoice)) return null;
1989
+ if (refChoice !== "__none__") references = refChoice;
1990
+ }
1991
+ let type = "integer";
1992
+ let defaultExpr = "";
1993
+ if (!references) {
1994
+ const typeChoice = await p2.select({
1995
+ message: "Column type",
1996
+ options: COLUMN_TYPES.map((t) => ({ value: t, label: t }))
1997
+ });
1998
+ if (p2.isCancel(typeChoice)) return null;
1999
+ type = typeChoice;
2000
+ const expr = await promptDefaultExpr(type);
2001
+ if (expr === null) return null;
2002
+ defaultExpr = expr;
2003
+ }
2004
+ const notNull = await p2.confirm({ message: "Required (NOT NULL)?", initialValue: true });
2005
+ if (p2.isCancel(notNull)) return null;
2006
+ const unique = await p2.confirm({ message: "Unique?", initialValue: false });
2007
+ if (p2.isCancel(unique)) return null;
2008
+ columns.push({ name: nameProbe, type, notNull, unique, defaultExpr, references });
2009
+ }
2010
+ return columns;
2011
+ }
2012
+ async function collectTableSpec(existingTables, forcedName) {
2013
+ let name = forcedName;
2014
+ if (name) {
2015
+ const id = tableIdentifier(name);
2016
+ if (existingTables.some((t) => t.identifier === id)) {
2017
+ p2.log.error(`"${id}" already exists.`);
2018
+ return null;
2019
+ }
2020
+ } else {
2021
+ const answer = await p2.text({
2022
+ message: "New table name",
2023
+ placeholder: "e.g. users",
2024
+ validate: (value) => {
2025
+ if (!value) return "Required.";
2026
+ if (existingTables.some((t) => t.identifier === tableIdentifier(value))) {
2027
+ return `"${tableIdentifier(value)}" already exists.`;
2028
+ }
2029
+ return void 0;
2030
+ }
2031
+ });
2032
+ if (p2.isCancel(answer)) return null;
2033
+ name = answer;
2034
+ }
2035
+ const includeId = await p2.confirm({
2036
+ message: "Add an auto-increment id primary key column?",
2037
+ initialValue: true
2038
+ });
2039
+ if (p2.isCancel(includeId)) return null;
2040
+ const columns = await promptForColumns(existingTables);
2041
+ if (columns === null) return null;
2042
+ return { name, includeId, columns };
2043
+ }
2044
+ async function runAddTable(args) {
2045
+ p2.intro("create-backon add-table");
2046
+ if (!await ensureSchemaSupport()) return;
2047
+ const [forcedName] = args;
2048
+ let existingTables = await readSchemaTables();
2049
+ let first = true;
2050
+ while (true) {
2051
+ const spec = await collectTableSpec(existingTables, first ? forcedName : void 0);
2052
+ first = false;
2053
+ if (!spec) {
2054
+ p2.cancel("Cancelled.");
2055
+ return;
2056
+ }
2057
+ try {
2058
+ const { filePath, identifier } = await addTable(spec);
2059
+ p2.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` to create a migration for it.`);
2060
+ existingTables = await readSchemaTables();
2061
+ } catch (err) {
2062
+ p2.log.error(err instanceof Error ? err.message : String(err));
2063
+ }
2064
+ const again = await p2.confirm({ message: "Add another table?", initialValue: false });
2065
+ if (p2.isCancel(again) || !again) break;
2066
+ }
2067
+ p2.outro("Done.");
2068
+ }
2069
+ async function runRemoveTable(args) {
2070
+ p2.intro("create-backon remove-table");
2071
+ if (!await ensureSchemaSupport()) return;
2072
+ const existingTables = await readSchemaTables();
2073
+ if (existingTables.length === 0) {
2074
+ p2.log.info("No tables yet.");
2075
+ return;
2076
+ }
2077
+ const [forcedName] = args;
2078
+ let identifier;
2079
+ if (forcedName) {
2080
+ identifier = tableIdentifier(forcedName);
2081
+ if (!existingTables.some((t) => t.identifier === identifier)) {
2082
+ p2.log.error(`No table "${identifier}" found.`);
2083
+ return;
2084
+ }
2085
+ } else {
2086
+ const choice = await p2.select({
2087
+ message: "Remove which table?",
2088
+ options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
2089
+ });
2090
+ if (p2.isCancel(choice)) {
2091
+ p2.cancel("Cancelled.");
2092
+ return;
2093
+ }
2094
+ identifier = choice;
2095
+ }
2096
+ const confirmed = await p2.confirm({
2097
+ message: `Remove table "${identifier}" from schema.ts? This only edits the file \u2014 nothing is dropped from the actual database until you run a migration.`,
2098
+ initialValue: false
2099
+ });
2100
+ if (p2.isCancel(confirmed) || !confirmed) {
2101
+ p2.cancel("Cancelled.");
2102
+ return;
2103
+ }
2104
+ try {
2105
+ const { filePath } = await removeTable(identifier);
2106
+ p2.log.success(`Removed "${identifier}" from ${filePath}. Run \`bun run db:generate\` to create a migration for this change.`);
2107
+ } catch (err) {
2108
+ p2.log.error(err instanceof Error ? err.message : String(err));
2109
+ }
2110
+ p2.outro("Done.");
2111
+ }
2112
+ async function serverConfigAddTable(existingTables) {
2113
+ const spec = await collectTableSpec(existingTables);
2114
+ if (!spec) {
2115
+ p2.cancel("Cancelled.");
2116
+ return;
2117
+ }
2118
+ const { filePath, identifier } = await addTable(spec);
2119
+ p2.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
2120
+ }
2121
+ async function serverConfigRemoveTable(existingTables) {
2122
+ if (existingTables.length === 0) {
2123
+ p2.log.info("No tables yet.");
2124
+ return;
2125
+ }
2126
+ const choice = await p2.select({
2127
+ message: "Remove which table?",
2128
+ options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
2129
+ });
2130
+ if (p2.isCancel(choice)) {
2131
+ p2.cancel("Cancelled.");
2132
+ return;
2133
+ }
2134
+ const confirmed = await p2.confirm({
2135
+ message: `Remove table "${choice}" from schema.ts? Nothing is dropped from the actual database until you run a migration.`,
2136
+ initialValue: false
2137
+ });
2138
+ if (p2.isCancel(confirmed) || !confirmed) {
2139
+ p2.cancel("Cancelled.");
2140
+ return;
2141
+ }
2142
+ const { filePath } = await removeTable(choice);
2143
+ p2.log.success(`Removed "${choice}" from ${filePath}. Run \`bun run db:generate\` next.`);
2144
+ }
1260
2145
  function suggestMethodName(verb, path) {
1261
2146
  const params = paramNamesFromPath(path);
1262
2147
  if (verb === "get" && params.length === 0) return "list";
@@ -1371,6 +2256,13 @@ async function serverConfigAddEndpoint() {
1371
2256
  }
1372
2257
  const { route, filesWritten } = await addRoute(name);
1373
2258
  p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet).`);
2259
+ const scaffoldCrud = await p2.confirm({
2260
+ message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
2261
+ initialValue: false
2262
+ });
2263
+ if (!p2.isCancel(scaffoldCrud) && scaffoldCrud) {
2264
+ logCrudResult(await addCrudMethods(route));
2265
+ }
1374
2266
  }
1375
2267
  async function serverConfigRemoveEndpoint(summaries) {
1376
2268
  if (summaries.length === 0) {
@@ -1592,6 +2484,11 @@ async function runServerConfig() {
1592
2484
  const { root } = await detectProject();
1593
2485
  const summaries = await listEndpointsWithMethods();
1594
2486
  p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
2487
+ const dbStatus = await detectDbStatus();
2488
+ const schemaCapable = dbStatus.driver === "neon" || dbStatus.driver === "postgres";
2489
+ if (schemaCapable) {
2490
+ p2.note(formatTablesDashboard(await readSchemaTables()), "Database tables");
2491
+ }
1595
2492
  const action = await p2.select({
1596
2493
  message: "What do you want to do?",
1597
2494
  options: [
@@ -1600,6 +2497,8 @@ async function runServerConfig() {
1600
2497
  { value: "add-method", label: "Add a method" },
1601
2498
  { value: "remove-method", label: "Remove a method" },
1602
2499
  { value: "modify-method", label: "Modify a method" },
2500
+ { value: "add-table", label: "Add a database table" },
2501
+ { value: "remove-table", label: "Remove a database table" },
1603
2502
  { value: "exit", label: "Exit" }
1604
2503
  ]
1605
2504
  });
@@ -1621,6 +2520,12 @@ async function runServerConfig() {
1621
2520
  case "modify-method":
1622
2521
  await serverConfigModifyMethod(summaries);
1623
2522
  break;
2523
+ case "add-table":
2524
+ if (await ensureSchemaSupport()) await serverConfigAddTable(await readSchemaTables());
2525
+ break;
2526
+ case "remove-table":
2527
+ if (await ensureSchemaSupport()) await serverConfigRemoveTable(await readSchemaTables());
2528
+ break;
1624
2529
  }
1625
2530
  } catch (err) {
1626
2531
  p2.log.error(err instanceof Error ? err.message : String(err));
@@ -1667,6 +2572,14 @@ async function main() {
1667
2572
  await runServerConfig();
1668
2573
  return;
1669
2574
  }
2575
+ if (subcommand && ADD_TABLE_SUBCOMMANDS.has(subcommand)) {
2576
+ await runAddTable(rest);
2577
+ return;
2578
+ }
2579
+ if (subcommand && REMOVE_TABLE_SUBCOMMANDS.has(subcommand)) {
2580
+ await runRemoveTable(rest);
2581
+ return;
2582
+ }
1670
2583
  await runScaffold();
1671
2584
  }
1672
2585
  main().catch((err) => {