create-backon 0.11.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) {
@@ -700,7 +720,7 @@ function renderPackageJson(projectName, framework, language, db) {
700
720
  zod: "^3.24.1",
701
721
  ...dbDependencies(db)
702
722
  };
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" };
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) };
704
724
  const scripts = {
705
725
  dev: `bun run --watch index.${ext}`,
706
726
  start: `bun run index.${ext}`,
@@ -731,11 +751,28 @@ function renderPackageJson(projectName, framework, language, db) {
731
751
  if (language === "typescript") {
732
752
  scripts.typecheck = "tsc --noEmit";
733
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
+ }
734
761
  const pkg = {
735
762
  name: projectName,
736
763
  version: "0.1.0",
737
764
  private: true,
738
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
+ },
739
776
  scripts,
740
777
  dependencies,
741
778
  devDependencies
@@ -784,6 +821,28 @@ both for free.
784
821
  `;
785
822
  }
786
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
+ }
787
846
  function renderReadme(answers) {
788
847
  const routeList = answers.routes.length ? answers.routes.map((route) => `- \`src/endpoints/${route}/\``).join("\n") : "- (none yet \u2014 add one under src/endpoints/)";
789
848
  const backonImport = answers.framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
@@ -809,6 +868,11 @@ document to \`openapi.json\`/\`docs.html\` on disk, for CI or static hosting.
809
868
 
810
869
  ${dbReadmeNote(answers.db)}
811
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) : ""}
812
876
  ## Routes
813
877
 
814
878
  ${routeList}
@@ -821,6 +885,80 @@ request (via \`defineRoute\` from \`${backonImport}\`) and calls into
821
885
  ${renderDeploySection(answers.deployTarget, ext)}`;
822
886
  }
823
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
+
824
962
  // src/generate.ts
825
963
  async function write(path, contents) {
826
964
  await mkdir(dirname(path), { recursive: true });
@@ -881,6 +1019,10 @@ ${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
881
1019
  ],
882
1020
  [join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
883
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
+ ] : [],
884
1026
  [
885
1027
  join(root, `src/middleware/example.middleware.${ext}`),
886
1028
  renderExampleMiddleware(answers.framework, answers.language)
@@ -1493,6 +1635,170 @@ async function addCrudMethods(route, cwd = process.cwd()) {
1493
1635
  return { route, added, skipped };
1494
1636
  }
1495
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
+
1496
1802
  // src/cli.ts
1497
1803
  var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
1498
1804
  var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
@@ -1501,6 +1807,8 @@ var DOCTOR_SUBCOMMANDS = /* @__PURE__ */ new Set(["doctor"]);
1501
1807
  var ADD_METHOD_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-method", "method"]);
1502
1808
  var PROJECT_SUBCOMMANDS = /* @__PURE__ */ new Set(["project"]);
1503
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"]);
1504
1812
  async function promptForRouteName(introText) {
1505
1813
  p2.intro(introText);
1506
1814
  const answer = await p2.text({
@@ -1595,6 +1903,245 @@ async function runProjectOverview() {
1595
1903
  }
1596
1904
  p2.outro("Manage endpoints and methods with `bun run server-config`.");
1597
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
+ }
1598
2145
  function suggestMethodName(verb, path) {
1599
2146
  const params = paramNamesFromPath(path);
1600
2147
  if (verb === "get" && params.length === 0) return "list";
@@ -1937,6 +2484,11 @@ async function runServerConfig() {
1937
2484
  const { root } = await detectProject();
1938
2485
  const summaries = await listEndpointsWithMethods();
1939
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
+ }
1940
2492
  const action = await p2.select({
1941
2493
  message: "What do you want to do?",
1942
2494
  options: [
@@ -1945,6 +2497,8 @@ async function runServerConfig() {
1945
2497
  { value: "add-method", label: "Add a method" },
1946
2498
  { value: "remove-method", label: "Remove a method" },
1947
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" },
1948
2502
  { value: "exit", label: "Exit" }
1949
2503
  ]
1950
2504
  });
@@ -1966,6 +2520,12 @@ async function runServerConfig() {
1966
2520
  case "modify-method":
1967
2521
  await serverConfigModifyMethod(summaries);
1968
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;
1969
2529
  }
1970
2530
  } catch (err) {
1971
2531
  p2.log.error(err instanceof Error ? err.message : String(err));
@@ -2012,6 +2572,14 @@ async function main() {
2012
2572
  await runServerConfig();
2013
2573
  return;
2014
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
+ }
2015
2583
  await runScaffold();
2016
2584
  }
2017
2585
  main().catch((err) => {