create-backon 0.11.0 → 0.13.1

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,23 @@ 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,
253
+ // @neondatabase/serverless ships its own types — no @types/* needed.
254
+ typeOnlyDevDependencies: {},
249
255
  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)."
256
+ 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).",
257
+ hasSchemaSupport: true
251
258
  },
252
259
  postgres: {
253
260
  file: `import { drizzle } from "drizzle-orm/node-postgres";
254
261
  import { Pool } from "pg";
262
+ import * as schema from "./schema";
255
263
 
256
264
  // NOTE: this pooled connection is for local dev or a long-running server
257
265
  // (Docker, a VPS, Render, etc). It is NOT safe to use as-is on Vercel
@@ -265,14 +273,21 @@ if (!process.env.DATABASE_URL) {
265
273
 
266
274
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
267
275
 
268
- export const db = drizzle(pool);
276
+ export const db = drizzle(pool, { schema });
269
277
  `,
270
278
  dependencies: {
271
279
  "drizzle-orm": "^0.38.2",
272
280
  pg: "^8.13.1"
273
281
  },
282
+ devDependencies: DRIZZLE_KIT_DEV_DEPENDENCY,
283
+ // pg doesn't ship its own types (unlike @neondatabase/serverless) — without
284
+ // this, a freshly scaffolded TypeScript "postgres" project fails
285
+ // `tsc --noEmit` out of the box with TS7016 on `import { Pool } from "pg"`.
286
+ // Caught via a real `bun run typecheck` on a real scaffold, not assumed.
287
+ typeOnlyDevDependencies: { "@types/pg": "^8.23.1" },
274
288
  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."
289
+ 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.",
290
+ hasSchemaSupport: true
276
291
  },
277
292
  sqlite: {
278
293
  file: `import { drizzle } from "drizzle-orm/bun-sqlite";
@@ -288,19 +303,27 @@ export const db = drizzle(sqlite);
288
303
  dependencies: {
289
304
  "drizzle-orm": "^0.38.2"
290
305
  },
306
+ devDependencies: {},
307
+ typeOnlyDevDependencies: {},
291
308
  envVars: "DATABASE_URL=./dev.db\n",
292
- readmeNote: "Local file-based SQLite \u2014 for local dev only, not for a serverless deploy target."
309
+ 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.",
310
+ hasSchemaSupport: false
293
311
  },
294
312
  none: {
295
313
  file: `// No database configured yet. Wire up a real client here \u2014 e.g. one of
296
314
  // 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.
315
+ // export it as \`db\`. Any service file can then do
316
+ // \`import { db } from "#config/db";\` (see package.json's "imports" field
317
+ // and the README's Database section) regardless of how deep it's nested.
298
318
 
299
319
  export const db = undefined;
300
320
  `,
301
321
  dependencies: {},
322
+ devDependencies: {},
323
+ typeOnlyDevDependencies: {},
302
324
  envVars: "",
303
- readmeNote: "No database configured. src/config/db.ts is an empty stub."
325
+ readmeNote: "No database configured. src/config/db.ts is an empty stub.",
326
+ hasSchemaSupport: false
304
327
  }
305
328
  };
306
329
  function renderDbFile(db) {
@@ -309,12 +332,21 @@ function renderDbFile(db) {
309
332
  function dbDependencies(db) {
310
333
  return TEMPLATES[db].dependencies;
311
334
  }
335
+ function dbDevDependencies(db) {
336
+ return TEMPLATES[db].devDependencies;
337
+ }
338
+ function dbTypeOnlyDevDependencies(db) {
339
+ return TEMPLATES[db].typeOnlyDevDependencies;
340
+ }
312
341
  function dbEnvVars(db) {
313
342
  return TEMPLATES[db].envVars;
314
343
  }
315
344
  function dbReadmeNote(db) {
316
345
  return TEMPLATES[db].readmeNote;
317
346
  }
347
+ function dbHasSchemaSupport(db) {
348
+ return TEMPLATES[db].hasSchemaSupport;
349
+ }
318
350
 
319
351
  // src/templates/base.ts
320
352
  function renderIndexTs(framework) {
@@ -700,7 +732,18 @@ function renderPackageJson(projectName, framework, language, db) {
700
732
  zod: "^3.24.1",
701
733
  ...dbDependencies(db)
702
734
  };
703
- 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" };
735
+ const devDependencies = language === "javascript" ? { ...dbDevDependencies(db) } : framework === "express" ? {
736
+ "@types/bun": "latest",
737
+ "@types/express": "^4.17.21",
738
+ typescript: "^5.7.2",
739
+ ...dbDevDependencies(db),
740
+ ...dbTypeOnlyDevDependencies(db)
741
+ } : {
742
+ "@types/bun": "latest",
743
+ typescript: "^5.7.2",
744
+ ...dbDevDependencies(db),
745
+ ...dbTypeOnlyDevDependencies(db)
746
+ };
704
747
  const scripts = {
705
748
  dev: `bun run --watch index.${ext}`,
706
749
  start: `bun run index.${ext}`,
@@ -731,11 +774,28 @@ function renderPackageJson(projectName, framework, language, db) {
731
774
  if (language === "typescript") {
732
775
  scripts.typecheck = "tsc --noEmit";
733
776
  }
777
+ if (dbHasSchemaSupport(db)) {
778
+ scripts["add-table"] = "bunx create-backon add-table";
779
+ scripts["remove-table"] = "bunx create-backon remove-table";
780
+ scripts["db:generate"] = "drizzle-kit generate";
781
+ scripts["db:migrate"] = "drizzle-kit migrate";
782
+ scripts["db:push"] = "drizzle-kit push";
783
+ }
734
784
  const pkg = {
735
785
  name: projectName,
736
786
  version: "0.1.0",
737
787
  private: true,
738
788
  type: "module",
789
+ // Node's package.json subpath imports (Bun resolves these too, both
790
+ // locally and on Vercel's Bun runtime — no bundler-specific config
791
+ // needed, unlike a tsconfig "paths" alias). Lets any file import the db
792
+ // client as `import { db } from "#config/db"` regardless of how deep
793
+ // it's nested under src/endpoints/, instead of a depth-counted
794
+ // `../../config/db`. Verified against a real `bun run` and a real
795
+ // `tsc --noEmit` (moduleResolution: "bundler" already resolves it).
796
+ imports: {
797
+ "#config/*": `./src/config/*.${ext}`
798
+ },
739
799
  scripts,
740
800
  dependencies,
741
801
  devDependencies
@@ -784,6 +844,28 @@ both for free.
784
844
  `;
785
845
  }
786
846
  }
847
+ function renderSchemaReadmeSection(ext) {
848
+ return `
849
+ ### Table schema
850
+
851
+ \`src/config/schema.${ext}\` holds every table (empty until you add one \u2014 see below). \`bun run
852
+ add-table\`/\`bun run remove-table\` (also reachable from \`server-config\`'s menu) edit it for you \u2014
853
+ picking a column type, nullability, uniqueness, a default, and whether it references another
854
+ table's \`id\`. This only ever edits \`schema.${ext}\` on disk; it never touches the actual database.
855
+
856
+ To apply a schema change for real:
857
+
858
+ \`\`\`
859
+ bun run db:generate # writes a reviewable .sql migration under drizzle/ \u2014 no DB connection needed
860
+ bun run db:migrate # applies pending migrations to DATABASE_URL
861
+ \`\`\`
862
+
863
+ \`bun run db:push\` applies \`schema.${ext}\` straight to the database with no migration file \u2014 faster
864
+ to iterate with early on (empty/throwaway dev database), but skips the reviewable, versioned trail
865
+ \`generate\`/\`migrate\` gives you. Switch to \`generate\`/\`migrate\` once there's real data, or before
866
+ deploying anywhere with staging/prod.
867
+ `;
868
+ }
787
869
  function renderReadme(answers) {
788
870
  const routeList = answers.routes.length ? answers.routes.map((route) => `- \`src/endpoints/${route}/\``).join("\n") : "- (none yet \u2014 add one under src/endpoints/)";
789
871
  const backonImport = answers.framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
@@ -809,6 +891,11 @@ document to \`openapi.json\`/\`docs.html\` on disk, for CI or static hosting.
809
891
 
810
892
  ${dbReadmeNote(answers.db)}
811
893
 
894
+ Import the client from anywhere as \`import { db } from "#config/db";\` \u2014 a package.json subpath
895
+ import (\`imports\`), not a relative path, so it stays \`#config/db\` no matter how deeply nested the
896
+ importing file is under \`src/endpoints/\`. Bun resolves it the same way locally and on Vercel;
897
+ \`tsc --noEmit\` resolves it too, no extra tsconfig needed.
898
+ ${dbHasSchemaSupport(answers.db) ? renderSchemaReadmeSection(ext) : ""}
812
899
  ## Routes
813
900
 
814
901
  ${routeList}
@@ -821,6 +908,80 @@ request (via \`defineRoute\` from \`${backonImport}\`) and calls into
821
908
  ${renderDeploySection(answers.deployTarget, ext)}`;
822
909
  }
823
910
 
911
+ // src/templates/schema.ts
912
+ var COLUMN_TYPES = ["text", "integer", "boolean", "timestamp", "uuid"];
913
+ function tableIdentifier(name) {
914
+ return camelCase(toKebabCase(name));
915
+ }
916
+ function tableSqlName(name) {
917
+ return toKebabCase(name).replace(/-/g, "_");
918
+ }
919
+ function columnIdentifier(name) {
920
+ return camelCase(toKebabCase(name));
921
+ }
922
+ function columnSqlName(name) {
923
+ return toKebabCase(name).replace(/-/g, "_");
924
+ }
925
+ function requiredBuilders(table) {
926
+ const builders = /* @__PURE__ */ new Set(["pgTable"]);
927
+ if (table.includeId) builders.add("serial");
928
+ for (const col of table.columns) {
929
+ builders.add(col.references ? "integer" : col.type);
930
+ }
931
+ return builders;
932
+ }
933
+ function renderColumnLine(col) {
934
+ const key = columnIdentifier(col.name);
935
+ const sqlName = columnSqlName(col.name);
936
+ let expr;
937
+ if (col.references) {
938
+ expr = `integer("${sqlName}").references(() => ${col.references}.id)`;
939
+ } else {
940
+ expr = `${col.type}("${sqlName}")`;
941
+ }
942
+ if (col.notNull) expr += ".notNull()";
943
+ if (col.unique) expr += ".unique()";
944
+ if (col.defaultExpr) expr += col.defaultExpr;
945
+ return ` ${key}: ${expr},`;
946
+ }
947
+ function renderTableBlock(table) {
948
+ const identifier = tableIdentifier(table.name);
949
+ const sqlName = tableSqlName(table.name);
950
+ const lines = [];
951
+ if (table.includeId) lines.push(` id: serial("id").primaryKey(),`);
952
+ for (const col of table.columns) lines.push(renderColumnLine(col));
953
+ return `export const ${identifier} = pgTable("${sqlName}", {
954
+ ${lines.join("\n")}
955
+ });`;
956
+ }
957
+ function renderBlankSchema() {
958
+ return `// No tables yet \u2014 add one via \`bun run add-table\` (or server-config's
959
+ // "Add a database table"). Each table becomes a real pgTable(...) export
960
+ // here, picked up automatically by both db.ts's schema import and
961
+ // drizzle-kit (see drizzle.config.ts) \u2014 nothing else needs to be told
962
+ // about a new table by hand.
963
+
964
+ export {};
965
+ `;
966
+ }
967
+ function renderDrizzleConfig(ext) {
968
+ return `import { defineConfig } from "drizzle-kit";
969
+
970
+ if (!process.env.DATABASE_URL) {
971
+ throw new Error("DATABASE_URL is required (see src/config/db.${ext})");
972
+ }
973
+
974
+ export default defineConfig({
975
+ schema: "./src/config/schema.${ext}",
976
+ out: "./drizzle",
977
+ dialect: "postgresql",
978
+ dbCredentials: {
979
+ url: process.env.DATABASE_URL,
980
+ },
981
+ });
982
+ `;
983
+ }
984
+
824
985
  // src/generate.ts
825
986
  async function write(path, contents) {
826
987
  await mkdir(dirname(path), { recursive: true });
@@ -881,6 +1042,10 @@ ${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
881
1042
  ],
882
1043
  [join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
883
1044
  [join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
1045
+ ...dbHasSchemaSupport(answers.db) ? [
1046
+ [join(root, `src/config/schema.${ext}`), renderBlankSchema()],
1047
+ [join(root, "drizzle.config.ts"), renderDrizzleConfig(ext)]
1048
+ ] : [],
884
1049
  [
885
1050
  join(root, `src/middleware/example.middleware.${ext}`),
886
1051
  renderExampleMiddleware(answers.framework, answers.language)
@@ -1493,6 +1658,170 @@ async function addCrudMethods(route, cwd = process.cwd()) {
1493
1658
  return { route, added, skipped };
1494
1659
  }
1495
1660
 
1661
+ // src/schema-edit.ts
1662
+ import { readFile as readFile7, writeFile as writeFile6 } from "node:fs/promises";
1663
+ import { join as join11 } from "node:path";
1664
+ import { Node as Node2, SyntaxKind } from "ts-morph";
1665
+ var PG_CORE_MODULE = "drizzle-orm/pg-core";
1666
+ function parseSchemaTables(contents) {
1667
+ const { sourceFile } = editSourceForReading(contents);
1668
+ const tables = [];
1669
+ for (const stmt of sourceFile.getVariableStatements()) {
1670
+ if (!stmt.isExported()) continue;
1671
+ const decl = stmt.getDeclarations()[0];
1672
+ if (!decl) continue;
1673
+ const init = decl.getInitializer();
1674
+ if (!init || !Node2.isCallExpression(init)) continue;
1675
+ const callee = init.getExpression();
1676
+ if (!Node2.isIdentifier(callee) || callee.getText() !== "pgTable") continue;
1677
+ const [sqlNameArg, columnsArg] = init.getArguments();
1678
+ const sqlName = sqlNameArg && Node2.isStringLiteral(sqlNameArg) ? sqlNameArg.getLiteralValue() : "";
1679
+ const columns = [];
1680
+ if (columnsArg && Node2.isObjectLiteralExpression(columnsArg)) {
1681
+ for (const prop of columnsArg.getProperties()) {
1682
+ if (!Node2.isPropertyAssignment(prop)) continue;
1683
+ columns.push({ key: prop.getName(), references: findReferencedTable(prop) });
1684
+ }
1685
+ }
1686
+ tables.push({ identifier: decl.getName(), sqlName, columns });
1687
+ }
1688
+ return tables;
1689
+ }
1690
+ function findReferencedTable(propAssignment) {
1691
+ const init = Node2.isPropertyAssignment(propAssignment) ? propAssignment.getInitializer() : void 0;
1692
+ if (!init) return void 0;
1693
+ for (const call of init.getDescendantsOfKind(SyntaxKind.CallExpression)) {
1694
+ const expr = call.getExpression();
1695
+ if (!Node2.isPropertyAccessExpression(expr) || expr.getName() !== "references") continue;
1696
+ const arrowArg = call.getArguments()[0];
1697
+ if (!arrowArg || !Node2.isArrowFunction(arrowArg)) continue;
1698
+ const body = arrowArg.getBody();
1699
+ if (Node2.isPropertyAccessExpression(body) && Node2.isIdentifier(body.getExpression())) {
1700
+ return body.getExpression().getText();
1701
+ }
1702
+ }
1703
+ return void 0;
1704
+ }
1705
+ function editSourceForReading(contents) {
1706
+ let sourceFile;
1707
+ editSource("schema.ts", contents, (_project, sf) => {
1708
+ sourceFile = sf;
1709
+ });
1710
+ return { sourceFile };
1711
+ }
1712
+ function ensurePgCoreImport(sourceFile, builders) {
1713
+ const wanted = [...builders].sort();
1714
+ const existing = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
1715
+ if (!existing) {
1716
+ sourceFile.addImportDeclaration({ moduleSpecifier: PG_CORE_MODULE, namedImports: wanted });
1717
+ return;
1718
+ }
1719
+ const already = new Set(existing.getNamedImports().map((ni) => ni.getName()));
1720
+ const missing = wanted.filter((name) => !already.has(name));
1721
+ if (missing.length > 0) existing.addNamedImports(missing);
1722
+ }
1723
+ function prunePgCoreImport(sourceFile) {
1724
+ const decl = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
1725
+ if (!decl) return;
1726
+ const used = /* @__PURE__ */ new Set();
1727
+ for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
1728
+ const expr = call.getExpression();
1729
+ if (Node2.isIdentifier(expr)) used.add(expr.getText());
1730
+ }
1731
+ for (const named of decl.getNamedImports()) {
1732
+ if (!used.has(named.getName())) named.remove();
1733
+ }
1734
+ if (decl.getNamedImports().length === 0) decl.remove();
1735
+ }
1736
+ function removeTableStatement(sourceFile, identifier) {
1737
+ for (const stmt of sourceFile.getVariableStatements()) {
1738
+ const decls = stmt.getDeclarations();
1739
+ if (decls.length === 1 && decls[0].getName() === identifier) {
1740
+ stmt.remove();
1741
+ return true;
1742
+ }
1743
+ }
1744
+ return false;
1745
+ }
1746
+ async function requireNeonOrPostgres(cwd) {
1747
+ const status = await detectDbStatus(cwd);
1748
+ if (status.driver === "neon" || status.driver === "postgres") return;
1749
+ throw new Error(
1750
+ `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.`
1751
+ );
1752
+ }
1753
+ async function readSchemaFile(root, ext) {
1754
+ const path = join11(root, "src/config", `schema.${ext}`);
1755
+ try {
1756
+ return { path, contents: await readFile7(path, "utf-8") };
1757
+ } catch (err) {
1758
+ if (err.code === "ENOENT") {
1759
+ throw new Error(
1760
+ `${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.`
1761
+ );
1762
+ }
1763
+ throw err;
1764
+ }
1765
+ }
1766
+ async function addTable(spec, cwd = process.cwd()) {
1767
+ await requireNeonOrPostgres(cwd);
1768
+ const { root, ext } = await detectProject(cwd);
1769
+ const { path, contents } = await readSchemaFile(root, ext);
1770
+ const identifier = tableIdentifier(spec.name);
1771
+ const existingTables = parseSchemaTables(contents);
1772
+ if (existingTables.some((t) => t.identifier === identifier)) {
1773
+ throw new Error(`"${identifier}" is already a table in ${path}.`);
1774
+ }
1775
+ for (const col of spec.columns) {
1776
+ if (col.references && !existingTables.some((t) => t.identifier === col.references)) {
1777
+ throw new Error(`Column "${col.name}" references unknown table "${col.references}".`);
1778
+ }
1779
+ }
1780
+ const withoutPlaceholder = contents.includes(renderBlankSchema()) ? contents.replace(renderBlankSchema(), "") : contents;
1781
+ const updated = editSource(path, withoutPlaceholder, (_project, sourceFile) => {
1782
+ ensurePgCoreImport(sourceFile, requiredBuilders(spec));
1783
+ appendStatements(sourceFile, renderTableBlock(spec));
1784
+ });
1785
+ await writeFile6(path, updated);
1786
+ return { root, identifier, filePath: path };
1787
+ }
1788
+ function formatTablesDashboard(tables) {
1789
+ if (tables.length === 0) return dim("No tables yet.");
1790
+ return tables.map((t) => {
1791
+ if (t.columns.length === 0) return `${t.identifier} (${t.sqlName})
1792
+ ${dim("(no columns)")}`;
1793
+ const lines = t.columns.map((c) => ` ${c.key}${c.references ? dim(` \u2192 references ${c.references}.id`) : ""}`);
1794
+ return `${t.identifier} (${t.sqlName})
1795
+ ${lines.join("\n")}`;
1796
+ }).join("\n\n");
1797
+ }
1798
+ async function removeTable(identifier, cwd = process.cwd()) {
1799
+ await requireNeonOrPostgres(cwd);
1800
+ const { root, ext } = await detectProject(cwd);
1801
+ const { path, contents } = await readSchemaFile(root, ext);
1802
+ const tables = parseSchemaTables(contents);
1803
+ const target = tables.find((t) => t.identifier === identifier);
1804
+ if (!target) {
1805
+ throw new Error(`No table "${identifier}" found in ${path}.`);
1806
+ }
1807
+ const referencedBy = tables.filter((t) => t.identifier !== identifier && t.columns.some((c) => c.references === identifier));
1808
+ if (referencedBy.length > 0) {
1809
+ throw new Error(
1810
+ `Can't remove "${identifier}" \u2014 still referenced by: ${referencedBy.map((t) => t.identifier).join(", ")}. Remove those columns/tables first.`
1811
+ );
1812
+ }
1813
+ if (tables.length === 1) {
1814
+ await writeFile6(path, renderBlankSchema());
1815
+ return { root, identifier, filePath: path };
1816
+ }
1817
+ const updated = editSource(path, contents, (_project, sourceFile) => {
1818
+ removeTableStatement(sourceFile, identifier);
1819
+ prunePgCoreImport(sourceFile);
1820
+ });
1821
+ await writeFile6(path, updated);
1822
+ return { root, identifier, filePath: path };
1823
+ }
1824
+
1496
1825
  // src/cli.ts
1497
1826
  var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
1498
1827
  var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
@@ -1501,6 +1830,8 @@ var DOCTOR_SUBCOMMANDS = /* @__PURE__ */ new Set(["doctor"]);
1501
1830
  var ADD_METHOD_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-method", "method"]);
1502
1831
  var PROJECT_SUBCOMMANDS = /* @__PURE__ */ new Set(["project"]);
1503
1832
  var SERVER_CONFIG_SUBCOMMANDS = /* @__PURE__ */ new Set(["server-config"]);
1833
+ var ADD_TABLE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-table", "table"]);
1834
+ var REMOVE_TABLE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-table", "rm-table"]);
1504
1835
  async function promptForRouteName(introText) {
1505
1836
  p2.intro(introText);
1506
1837
  const answer = await p2.text({
@@ -1595,6 +1926,245 @@ async function runProjectOverview() {
1595
1926
  }
1596
1927
  p2.outro("Manage endpoints and methods with `bun run server-config`.");
1597
1928
  }
1929
+ async function ensureSchemaSupport() {
1930
+ const status = await detectDbStatus();
1931
+ if (status.driver === "neon" || status.driver === "postgres") return true;
1932
+ p2.log.error(
1933
+ `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.`
1934
+ );
1935
+ return false;
1936
+ }
1937
+ async function readSchemaTables() {
1938
+ const { root, ext } = await detectProject();
1939
+ try {
1940
+ const contents = await readFile8(join12(root, "src/config", `schema.${ext}`), "utf-8");
1941
+ return parseSchemaTables(contents);
1942
+ } catch {
1943
+ return [];
1944
+ }
1945
+ }
1946
+ async function promptDefaultExpr(type) {
1947
+ if (type === "timestamp") {
1948
+ const v2 = await p2.confirm({ message: "Default to now()?", initialValue: false });
1949
+ if (p2.isCancel(v2)) return null;
1950
+ return v2 ? ".defaultNow()" : "";
1951
+ }
1952
+ if (type === "uuid") {
1953
+ const v2 = await p2.confirm({ message: "Default to a random UUID?", initialValue: false });
1954
+ if (p2.isCancel(v2)) return null;
1955
+ return v2 ? ".defaultRandom()" : "";
1956
+ }
1957
+ if (type === "boolean") {
1958
+ const v2 = await p2.select({
1959
+ message: "Default value",
1960
+ options: [
1961
+ { value: "none", label: "None" },
1962
+ { value: "true", label: "true" },
1963
+ { value: "false", label: "false" }
1964
+ ],
1965
+ initialValue: "none"
1966
+ });
1967
+ if (p2.isCancel(v2)) return null;
1968
+ return v2 === "none" ? "" : `.default(${v2})`;
1969
+ }
1970
+ const v = await p2.text({
1971
+ message: "Default value (blank for none)",
1972
+ placeholder: type === "integer" ? "e.g. 0" : "e.g. pending"
1973
+ });
1974
+ if (p2.isCancel(v)) return null;
1975
+ if (!v) return "";
1976
+ if (type === "integer") {
1977
+ const n = Number(v);
1978
+ if (Number.isNaN(n)) {
1979
+ p2.log.warn(`"${v}" isn't a number \u2014 skipping the default.`);
1980
+ return "";
1981
+ }
1982
+ return `.default(${n})`;
1983
+ }
1984
+ return `.default(${JSON.stringify(v)})`;
1985
+ }
1986
+ async function promptForColumns(existingTables) {
1987
+ const columns = [];
1988
+ p2.log.step("Add columns one at a time. Leave the name blank to finish.");
1989
+ while (true) {
1990
+ const nameProbe = await p2.text({
1991
+ message: columns.length === 0 ? "Column name" : "Another column? (blank to finish)",
1992
+ placeholder: columns.length === 0 ? "e.g. email" : ""
1993
+ });
1994
+ if (p2.isCancel(nameProbe)) return null;
1995
+ if (!nameProbe) break;
1996
+ const key = columnIdentifier(nameProbe);
1997
+ if (columns.some((c) => columnIdentifier(c.name) === key)) {
1998
+ p2.log.error(`"${key}" is already a column on this table.`);
1999
+ continue;
2000
+ }
2001
+ let references;
2002
+ if (existingTables.length > 0) {
2003
+ const refChoice = await p2.select({
2004
+ message: `Does "${nameProbe}" reference another table's id?`,
2005
+ options: [
2006
+ { value: "__none__", label: "No" },
2007
+ ...existingTables.map((t) => ({ value: t.identifier, label: t.identifier }))
2008
+ ],
2009
+ initialValue: "__none__"
2010
+ });
2011
+ if (p2.isCancel(refChoice)) return null;
2012
+ if (refChoice !== "__none__") references = refChoice;
2013
+ }
2014
+ let type = "integer";
2015
+ let defaultExpr = "";
2016
+ if (!references) {
2017
+ const typeChoice = await p2.select({
2018
+ message: "Column type",
2019
+ options: COLUMN_TYPES.map((t) => ({ value: t, label: t }))
2020
+ });
2021
+ if (p2.isCancel(typeChoice)) return null;
2022
+ type = typeChoice;
2023
+ const expr = await promptDefaultExpr(type);
2024
+ if (expr === null) return null;
2025
+ defaultExpr = expr;
2026
+ }
2027
+ const notNull = await p2.confirm({ message: "Required (NOT NULL)?", initialValue: true });
2028
+ if (p2.isCancel(notNull)) return null;
2029
+ const unique = await p2.confirm({ message: "Unique?", initialValue: false });
2030
+ if (p2.isCancel(unique)) return null;
2031
+ columns.push({ name: nameProbe, type, notNull, unique, defaultExpr, references });
2032
+ }
2033
+ return columns;
2034
+ }
2035
+ async function collectTableSpec(existingTables, forcedName) {
2036
+ let name = forcedName;
2037
+ if (name) {
2038
+ const id = tableIdentifier(name);
2039
+ if (existingTables.some((t) => t.identifier === id)) {
2040
+ p2.log.error(`"${id}" already exists.`);
2041
+ return null;
2042
+ }
2043
+ } else {
2044
+ const answer = await p2.text({
2045
+ message: "New table name",
2046
+ placeholder: "e.g. users",
2047
+ validate: (value) => {
2048
+ if (!value) return "Required.";
2049
+ if (existingTables.some((t) => t.identifier === tableIdentifier(value))) {
2050
+ return `"${tableIdentifier(value)}" already exists.`;
2051
+ }
2052
+ return void 0;
2053
+ }
2054
+ });
2055
+ if (p2.isCancel(answer)) return null;
2056
+ name = answer;
2057
+ }
2058
+ const includeId = await p2.confirm({
2059
+ message: "Add an auto-increment id primary key column?",
2060
+ initialValue: true
2061
+ });
2062
+ if (p2.isCancel(includeId)) return null;
2063
+ const columns = await promptForColumns(existingTables);
2064
+ if (columns === null) return null;
2065
+ return { name, includeId, columns };
2066
+ }
2067
+ async function runAddTable(args) {
2068
+ p2.intro("create-backon add-table");
2069
+ if (!await ensureSchemaSupport()) return;
2070
+ const [forcedName] = args;
2071
+ let existingTables = await readSchemaTables();
2072
+ let first = true;
2073
+ while (true) {
2074
+ const spec = await collectTableSpec(existingTables, first ? forcedName : void 0);
2075
+ first = false;
2076
+ if (!spec) {
2077
+ p2.cancel("Cancelled.");
2078
+ return;
2079
+ }
2080
+ try {
2081
+ const { filePath, identifier } = await addTable(spec);
2082
+ p2.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` to create a migration for it.`);
2083
+ existingTables = await readSchemaTables();
2084
+ } catch (err) {
2085
+ p2.log.error(err instanceof Error ? err.message : String(err));
2086
+ }
2087
+ const again = await p2.confirm({ message: "Add another table?", initialValue: false });
2088
+ if (p2.isCancel(again) || !again) break;
2089
+ }
2090
+ p2.outro("Done.");
2091
+ }
2092
+ async function runRemoveTable(args) {
2093
+ p2.intro("create-backon remove-table");
2094
+ if (!await ensureSchemaSupport()) return;
2095
+ const existingTables = await readSchemaTables();
2096
+ if (existingTables.length === 0) {
2097
+ p2.log.info("No tables yet.");
2098
+ return;
2099
+ }
2100
+ const [forcedName] = args;
2101
+ let identifier;
2102
+ if (forcedName) {
2103
+ identifier = tableIdentifier(forcedName);
2104
+ if (!existingTables.some((t) => t.identifier === identifier)) {
2105
+ p2.log.error(`No table "${identifier}" found.`);
2106
+ return;
2107
+ }
2108
+ } else {
2109
+ const choice = await p2.select({
2110
+ message: "Remove which table?",
2111
+ options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
2112
+ });
2113
+ if (p2.isCancel(choice)) {
2114
+ p2.cancel("Cancelled.");
2115
+ return;
2116
+ }
2117
+ identifier = choice;
2118
+ }
2119
+ const confirmed = await p2.confirm({
2120
+ 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.`,
2121
+ initialValue: false
2122
+ });
2123
+ if (p2.isCancel(confirmed) || !confirmed) {
2124
+ p2.cancel("Cancelled.");
2125
+ return;
2126
+ }
2127
+ try {
2128
+ const { filePath } = await removeTable(identifier);
2129
+ p2.log.success(`Removed "${identifier}" from ${filePath}. Run \`bun run db:generate\` to create a migration for this change.`);
2130
+ } catch (err) {
2131
+ p2.log.error(err instanceof Error ? err.message : String(err));
2132
+ }
2133
+ p2.outro("Done.");
2134
+ }
2135
+ async function serverConfigAddTable(existingTables) {
2136
+ const spec = await collectTableSpec(existingTables);
2137
+ if (!spec) {
2138
+ p2.cancel("Cancelled.");
2139
+ return;
2140
+ }
2141
+ const { filePath, identifier } = await addTable(spec);
2142
+ p2.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
2143
+ }
2144
+ async function serverConfigRemoveTable(existingTables) {
2145
+ if (existingTables.length === 0) {
2146
+ p2.log.info("No tables yet.");
2147
+ return;
2148
+ }
2149
+ const choice = await p2.select({
2150
+ message: "Remove which table?",
2151
+ options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` }))
2152
+ });
2153
+ if (p2.isCancel(choice)) {
2154
+ p2.cancel("Cancelled.");
2155
+ return;
2156
+ }
2157
+ const confirmed = await p2.confirm({
2158
+ message: `Remove table "${choice}" from schema.ts? Nothing is dropped from the actual database until you run a migration.`,
2159
+ initialValue: false
2160
+ });
2161
+ if (p2.isCancel(confirmed) || !confirmed) {
2162
+ p2.cancel("Cancelled.");
2163
+ return;
2164
+ }
2165
+ const { filePath } = await removeTable(choice);
2166
+ p2.log.success(`Removed "${choice}" from ${filePath}. Run \`bun run db:generate\` next.`);
2167
+ }
1598
2168
  function suggestMethodName(verb, path) {
1599
2169
  const params = paramNamesFromPath(path);
1600
2170
  if (verb === "get" && params.length === 0) return "list";
@@ -1937,6 +2507,11 @@ async function runServerConfig() {
1937
2507
  const { root } = await detectProject();
1938
2508
  const summaries = await listEndpointsWithMethods();
1939
2509
  p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
2510
+ const dbStatus = await detectDbStatus();
2511
+ const schemaCapable = dbStatus.driver === "neon" || dbStatus.driver === "postgres";
2512
+ if (schemaCapable) {
2513
+ p2.note(formatTablesDashboard(await readSchemaTables()), "Database tables");
2514
+ }
1940
2515
  const action = await p2.select({
1941
2516
  message: "What do you want to do?",
1942
2517
  options: [
@@ -1945,6 +2520,8 @@ async function runServerConfig() {
1945
2520
  { value: "add-method", label: "Add a method" },
1946
2521
  { value: "remove-method", label: "Remove a method" },
1947
2522
  { value: "modify-method", label: "Modify a method" },
2523
+ { value: "add-table", label: "Add a database table" },
2524
+ { value: "remove-table", label: "Remove a database table" },
1948
2525
  { value: "exit", label: "Exit" }
1949
2526
  ]
1950
2527
  });
@@ -1966,6 +2543,12 @@ async function runServerConfig() {
1966
2543
  case "modify-method":
1967
2544
  await serverConfigModifyMethod(summaries);
1968
2545
  break;
2546
+ case "add-table":
2547
+ if (await ensureSchemaSupport()) await serverConfigAddTable(await readSchemaTables());
2548
+ break;
2549
+ case "remove-table":
2550
+ if (await ensureSchemaSupport()) await serverConfigRemoveTable(await readSchemaTables());
2551
+ break;
1969
2552
  }
1970
2553
  } catch (err) {
1971
2554
  p2.log.error(err instanceof Error ? err.message : String(err));
@@ -2012,6 +2595,14 @@ async function main() {
2012
2595
  await runServerConfig();
2013
2596
  return;
2014
2597
  }
2598
+ if (subcommand && ADD_TABLE_SUBCOMMANDS.has(subcommand)) {
2599
+ await runAddTable(rest);
2600
+ return;
2601
+ }
2602
+ if (subcommand && REMOVE_TABLE_SUBCOMMANDS.has(subcommand)) {
2603
+ await runRemoveTable(rest);
2604
+ return;
2605
+ }
2015
2606
  await runScaffold();
2016
2607
  }
2017
2608
  main().catch((err) => {