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.
@@ -0,0 +1,253 @@
1
+ import { readFile, writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import { Node, SyntaxKind, type SourceFile } from "ts-morph";
4
+ import { dim } from "./colors";
5
+ import { detectDbStatus } from "./db-status";
6
+ import { detectProject } from "./detect";
7
+ import { editSource, appendStatements } from "./ast-edit";
8
+ import { renderBlankSchema, renderTableBlock, requiredBuilders, tableIdentifier, type TableSpec } from "./templates/schema";
9
+
10
+ const PG_CORE_MODULE = "drizzle-orm/pg-core";
11
+
12
+ export interface ParsedColumn {
13
+ key: string;
14
+ /** Referenced table's JS identifier, when this column is a `.references(() => X.id)` foreign key. */
15
+ references?: string;
16
+ }
17
+
18
+ export interface ParsedTable {
19
+ identifier: string;
20
+ sqlName: string;
21
+ columns: ParsedColumn[];
22
+ }
23
+
24
+ /**
25
+ * Reads every `export const <id> = pgTable("<name>", {...})` out of a real
26
+ * schema.ts — used for the duplicate-name check in addTable(), the
27
+ * dangling-reference check in removeTable(), and server-config's "which
28
+ * table are you removing" / "reference another table?" prompts. Walks the
29
+ * real AST (a throwaway in-memory ts-morph Project, same approach
30
+ * ast-edit.ts's helpers use) rather than regexing the file, so a
31
+ * hand-reformatted schema.ts (reordered columns, different quote style)
32
+ * doesn't throw this off.
33
+ */
34
+ export function parseSchemaTables(contents: string): ParsedTable[] {
35
+ const { sourceFile } = editSourceForReading(contents);
36
+ const tables: ParsedTable[] = [];
37
+
38
+ for (const stmt of sourceFile.getVariableStatements()) {
39
+ if (!stmt.isExported()) continue;
40
+ const decl = stmt.getDeclarations()[0];
41
+ if (!decl) continue;
42
+ const init = decl.getInitializer();
43
+ if (!init || !Node.isCallExpression(init)) continue;
44
+ const callee = init.getExpression();
45
+ if (!Node.isIdentifier(callee) || callee.getText() !== "pgTable") continue;
46
+
47
+ const [sqlNameArg, columnsArg] = init.getArguments();
48
+ const sqlName = sqlNameArg && Node.isStringLiteral(sqlNameArg) ? sqlNameArg.getLiteralValue() : "";
49
+
50
+ const columns: ParsedColumn[] = [];
51
+ if (columnsArg && Node.isObjectLiteralExpression(columnsArg)) {
52
+ for (const prop of columnsArg.getProperties()) {
53
+ if (!Node.isPropertyAssignment(prop)) continue;
54
+ columns.push({ key: prop.getName(), references: findReferencedTable(prop) });
55
+ }
56
+ }
57
+
58
+ tables.push({ identifier: decl.getName(), sqlName, columns });
59
+ }
60
+
61
+ return tables;
62
+ }
63
+
64
+ function findReferencedTable(propAssignment: Node): string | undefined {
65
+ const init = Node.isPropertyAssignment(propAssignment) ? propAssignment.getInitializer() : undefined;
66
+ if (!init) return undefined;
67
+ for (const call of init.getDescendantsOfKind(SyntaxKind.CallExpression)) {
68
+ const expr = call.getExpression();
69
+ if (!Node.isPropertyAccessExpression(expr) || expr.getName() !== "references") continue;
70
+ const arrowArg = call.getArguments()[0];
71
+ if (!arrowArg || !Node.isArrowFunction(arrowArg)) continue;
72
+ const body = arrowArg.getBody();
73
+ if (Node.isPropertyAccessExpression(body) && Node.isIdentifier(body.getExpression())) {
74
+ return body.getExpression().getText();
75
+ }
76
+ }
77
+ return undefined;
78
+ }
79
+
80
+ // A read-only pass doesn't need editSource()'s write-back plumbing, just
81
+ // the same throwaway in-memory Project + parse step it uses internally.
82
+ function editSourceForReading(contents: string): { sourceFile: SourceFile } {
83
+ let sourceFile!: SourceFile;
84
+ editSource("schema.ts", contents, (_project, sf) => {
85
+ sourceFile = sf;
86
+ });
87
+ return { sourceFile };
88
+ }
89
+
90
+ /** Adds every builder in `builders` to the shared `drizzle-orm/pg-core` import, merging into the existing declaration instead of creating a second one — unlike ast-edit.ts's ensureImports(), which is line-for-line/per-method by design (see its own doc comment), this one grows a single declaration's named-import set across repeated addTable() calls. */
91
+ function ensurePgCoreImport(sourceFile: SourceFile, builders: Set<string>): void {
92
+ const wanted = [...builders].sort();
93
+ const existing = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
94
+ if (!existing) {
95
+ sourceFile.addImportDeclaration({ moduleSpecifier: PG_CORE_MODULE, namedImports: wanted });
96
+ return;
97
+ }
98
+ const already = new Set(existing.getNamedImports().map((ni) => ni.getName()));
99
+ const missing = wanted.filter((name) => !already.has(name));
100
+ if (missing.length > 0) existing.addNamedImports(missing);
101
+ }
102
+
103
+ /** The undo side of ensurePgCoreImport() — after a table's removed, prunes any pg-core builder no longer referenced by a surviving pgTable() call anywhere in the file, and drops the whole import if nothing's left. */
104
+ function prunePgCoreImport(sourceFile: SourceFile): void {
105
+ const decl = sourceFile.getImportDeclaration((d) => d.getModuleSpecifierValue() === PG_CORE_MODULE);
106
+ if (!decl) return;
107
+
108
+ const used = new Set<string>();
109
+ for (const call of sourceFile.getDescendantsOfKind(SyntaxKind.CallExpression)) {
110
+ const expr = call.getExpression();
111
+ if (Node.isIdentifier(expr)) used.add(expr.getText());
112
+ }
113
+
114
+ for (const named of decl.getNamedImports()) {
115
+ if (!used.has(named.getName())) named.remove();
116
+ }
117
+ if (decl.getNamedImports().length === 0) decl.remove();
118
+ }
119
+
120
+ function removeTableStatement(sourceFile: SourceFile, identifier: string): boolean {
121
+ for (const stmt of sourceFile.getVariableStatements()) {
122
+ const decls = stmt.getDeclarations();
123
+ if (decls.length === 1 && decls[0]!.getName() === identifier) {
124
+ stmt.remove();
125
+ return true;
126
+ }
127
+ }
128
+ return false;
129
+ }
130
+
131
+ async function requireNeonOrPostgres(cwd: string): Promise<void> {
132
+ const status = await detectDbStatus(cwd);
133
+ if (status.driver === "neon" || status.driver === "postgres") return;
134
+ throw new Error(
135
+ `Schema management needs a "neon" or "postgres" db driver (src/config/db reports "${status.driver}") — ` +
136
+ `SQLite and "none" use a different schema dialect (or none at all) and aren't supported by add-table/remove-table yet.`
137
+ );
138
+ }
139
+
140
+ async function readSchemaFile(root: string, ext: "ts" | "js"): Promise<{ path: string; contents: string }> {
141
+ const path = join(root, "src/config", `schema.${ext}`);
142
+ try {
143
+ return { path, contents: await readFile(path, "utf-8") };
144
+ } catch (err) {
145
+ if ((err as NodeJS.ErrnoException).code === "ENOENT") {
146
+ throw new Error(
147
+ `${path} doesn't exist. This project's db.ts predates schema scaffolding — add a src/config/schema.${ext} ` +
148
+ `by hand (see the README's Database section) before using add-table.`
149
+ );
150
+ }
151
+ throw err;
152
+ }
153
+ }
154
+
155
+ export interface AddTableResult {
156
+ root: string;
157
+ identifier: string;
158
+ filePath: string;
159
+ }
160
+
161
+ /**
162
+ * Appends one real `pgTable(...)` export to schema.ts — merges into the
163
+ * shared drizzle-orm/pg-core import rather than duplicating it (see
164
+ * ensurePgCoreImport()), and only ever edits schema.ts on disk. Never runs
165
+ * drizzle-kit, never touches the actual database — generate/migrate/push
166
+ * stay separate, explicit commands, same reasoning db-status.ts's own doc
167
+ * comment gives for why it never makes a live connection either.
168
+ */
169
+ export async function addTable(spec: TableSpec, cwd: string = process.cwd()): Promise<AddTableResult> {
170
+ await requireNeonOrPostgres(cwd);
171
+ const { root, ext } = await detectProject(cwd);
172
+ const { path, contents } = await readSchemaFile(root, ext);
173
+
174
+ const identifier = tableIdentifier(spec.name);
175
+ const existingTables = parseSchemaTables(contents);
176
+ if (existingTables.some((t) => t.identifier === identifier)) {
177
+ throw new Error(`"${identifier}" is already a table in ${path}.`);
178
+ }
179
+ for (const col of spec.columns) {
180
+ if (col.references && !existingTables.some((t) => t.identifier === col.references)) {
181
+ throw new Error(`Column "${col.name}" references unknown table "${col.references}".`);
182
+ }
183
+ }
184
+
185
+ const withoutPlaceholder = contents.includes(renderBlankSchema()) ? contents.replace(renderBlankSchema(), "") : contents;
186
+
187
+ const updated = editSource(path, withoutPlaceholder, (_project, sourceFile) => {
188
+ ensurePgCoreImport(sourceFile, requiredBuilders(spec));
189
+ appendStatements(sourceFile, renderTableBlock(spec));
190
+ });
191
+
192
+ await writeFile(path, updated);
193
+ return { root, identifier, filePath: path };
194
+ }
195
+
196
+ export interface RemoveTableResult {
197
+ root: string;
198
+ identifier: string;
199
+ filePath: string;
200
+ }
201
+
202
+ /** server-config/project's "Database tables" note — same spirit as route-methods.ts's formatEndpointsDashboard(). */
203
+ export function formatTablesDashboard(tables: ParsedTable[]): string {
204
+ if (tables.length === 0) return dim("No tables yet.");
205
+ return tables
206
+ .map((t) => {
207
+ if (t.columns.length === 0) return `${t.identifier} (${t.sqlName})\n ${dim("(no columns)")}`;
208
+ const lines = t.columns.map((c) => ` ${c.key}${c.references ? dim(` → references ${c.references}.id`) : ""}`);
209
+ return `${t.identifier} (${t.sqlName})\n${lines.join("\n")}`;
210
+ })
211
+ .join("\n\n");
212
+ }
213
+
214
+ /**
215
+ * The undo for addTable(): removes one table's `pgTable(...)` export and
216
+ * prunes any pg-core builder import nothing else still uses. Refuses to
217
+ * remove a table another table's column still `.references()` — leaving
218
+ * that in place would compile to a runtime `ReferenceError` the moment
219
+ * drizzle tries to resolve it, so this is caught here instead of at
220
+ * `drizzle-kit generate` time.
221
+ */
222
+ export async function removeTable(identifier: string, cwd: string = process.cwd()): Promise<RemoveTableResult> {
223
+ await requireNeonOrPostgres(cwd);
224
+ const { root, ext } = await detectProject(cwd);
225
+ const { path, contents } = await readSchemaFile(root, ext);
226
+
227
+ const tables = parseSchemaTables(contents);
228
+ const target = tables.find((t) => t.identifier === identifier);
229
+ if (!target) {
230
+ throw new Error(`No table "${identifier}" found in ${path}.`);
231
+ }
232
+
233
+ const referencedBy = tables.filter((t) => t.identifier !== identifier && t.columns.some((c) => c.references === identifier));
234
+ if (referencedBy.length > 0) {
235
+ throw new Error(
236
+ `Can't remove "${identifier}" — still referenced by: ${referencedBy.map((t) => t.identifier).join(", ")}. ` +
237
+ `Remove those columns/tables first.`
238
+ );
239
+ }
240
+
241
+ if (tables.length === 1) {
242
+ await writeFile(path, renderBlankSchema());
243
+ return { root, identifier, filePath: path };
244
+ }
245
+
246
+ const updated = editSource(path, contents, (_project, sourceFile) => {
247
+ removeTableStatement(sourceFile, identifier);
248
+ prunePgCoreImport(sourceFile);
249
+ });
250
+
251
+ await writeFile(path, updated);
252
+ return { root, identifier, filePath: path };
253
+ }
@@ -1,6 +1,6 @@
1
1
  import type { Answers, DeployTarget, Framework, Language } from "../prompts";
2
2
  import { camelCase } from "./route";
3
- import { dbDependencies, dbEnvVars, dbReadmeNote } from "./db";
3
+ import { dbDependencies, dbDevDependencies, dbEnvVars, dbHasSchemaSupport, dbReadmeNote } from "./db";
4
4
 
5
5
  // renderIndexTs/renderAppTs/renderEndpointsIndex are intentionally NOT
6
6
  // language-aware: none of them contain TypeScript-only syntax (no type
@@ -226,6 +226,201 @@ console.log("Wrote openapi.json and docs.html");
226
226
  `;
227
227
  }
228
228
 
229
+ // Deliberately NOT built around importing src/app the way
230
+ // renderGenerateDocsScript() is — a client only needs to know verb/path/name
231
+ // per method and which of its body/query schemas exist, and all of that is
232
+ // already sitting in *.routes.<ext>/*.controller.<ext> as plain text (the
233
+ // exact same two facts route-methods.ts's parseRouteMethods()/
234
+ // detectMethodValidation() read off disk inside create-backon itself, just
235
+ // duplicated here in ~20 lines since a generated script can't import
236
+ // create-backon at runtime). No live app instance needed, so this can't fail
237
+ // because app.ts throws on a missing env var the way importing it would.
238
+ //
239
+ // The generated script re-discovers routes fresh every time it runs rather
240
+ // than being regenerated by add-route/add-method/remove-method — it reads
241
+ // src/endpoints/ at *run* time, so it never goes stale on its own; only
242
+ // client/api.<ext> (its output) needs a re-run after routes change, the
243
+ // same way `bun run docs` needs a re-run, not a re-scaffold.
244
+ //
245
+ // The generated output deliberately uses string concatenation (`+`) instead
246
+ // of template literals for building URLs — keeps this template's own
247
+ // authoring simple (no nested-backtick escaping between this file's
248
+ // template literal and the one it's generating) at the cost of slightly
249
+ // less idiomatic output code, a trade worth making for a script nobody is
250
+ // meant to hand-edit anyway (see the "auto-generated" header it writes).
251
+ export function renderGenerateClientScript(language: Language): string {
252
+ const ext = language === "javascript" ? "js" : "ts";
253
+ const typed = language === "javascript" ? "false" : "true";
254
+ // Annotates this script's OWN helper function parameters when it's being
255
+ // written as a .ts file — under the generated tsconfig's `strict: true`,
256
+ // an untyped parameter is a noImplicitAny error, unlike generate-docs.ts
257
+ // (which has no locally-defined functions to trigger it). Distinct from
258
+ // TYPED above, which is about the *output* client's type annotations —
259
+ // both happen to be driven by the same `language`, but conceptually one
260
+ // is "is this script valid strict TS" and the other is "does the file it
261
+ // writes have types".
262
+ const ann = (t: string) => (language === "javascript" ? "" : `: ${t}`);
263
+
264
+ return `// Regenerates client/api.${ext} from src/endpoints/ — reads *.routes.${ext}/*.controller.${ext}
265
+ // directly, the same source add-method/remove-method/server-config write to, so there's
266
+ // nothing to keep in sync by hand. Safe to re-run any time; nothing here needs updating
267
+ // when a route or method is added, removed, or modified — only its output does.
268
+ import { readFileSync, writeFileSync, mkdirSync } from "node:fs";
269
+ import { join } from "node:path";
270
+
271
+ const EXT = "${ext}";
272
+ const TYPED = ${typed};
273
+
274
+ const root = process.cwd();
275
+ const endpointsDir = join(root, "src/endpoints");
276
+
277
+ const MOUNT_PATTERN = /endpoints\\.(?:route|use)\\("\\/([a-z0-9-]+)"/g;
278
+ const METHOD_PATTERN = /\\.(get|post|put|patch|delete)\\(\\s*"([^"]*)"\\s*,\\s*controller\\.(\\w+)\\s*\\)/g;
279
+
280
+ function paramNames(path${ann("string")}) {
281
+ return Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g)).map((m) => m[1]);
282
+ }
283
+
284
+ function camelCase(name${ann("string")}) {
285
+ const parts = name.split("-");
286
+ return parts[0] + parts.slice(1).map((p) => p.charAt(0).toUpperCase() + p.slice(1)).join("");
287
+ }
288
+
289
+ // Builds a JS expression string for the full request path — literal
290
+ // segments as JSON string literals, :param segments as bare identifiers,
291
+ // joined with "+" — e.g. "/users/:id" becomes the text: "/users/" + id
292
+ function pathExpr(route${ann("string")}, method${ann("any")}) {
293
+ const fullPath = "/" + route + (method.path === "/" ? "" : method.path);
294
+ const pieces = [];
295
+ let lastIndex = 0;
296
+ const paramRe = /:([A-Za-z0-9_]+)/g;
297
+ let match;
298
+ while ((match = paramRe.exec(fullPath))) {
299
+ if (match.index > lastIndex) pieces.push(JSON.stringify(fullPath.slice(lastIndex, match.index)));
300
+ pieces.push(match[1]);
301
+ lastIndex = match.index + match[0].length;
302
+ }
303
+ if (lastIndex < fullPath.length) pieces.push(JSON.stringify(fullPath.slice(lastIndex)));
304
+ return pieces.join(" + ");
305
+ }
306
+
307
+ function funcArgs(method${ann("any")}) {
308
+ const args = paramNames(method.path).slice();
309
+ if (method.needsBody) args.push("body");
310
+ if (method.needsQuery) args.push("query");
311
+ return args;
312
+ }
313
+
314
+ function typedFuncArgs(method${ann("any")}) {
315
+ const parts = paramNames(method.path).map((name) => name + ": string");
316
+ if (method.needsBody) parts.push("body: z.infer<typeof " + method.name + "BodySchema>");
317
+ if (method.needsQuery) parts.push("query: z.infer<typeof " + method.name + "QuerySchema>");
318
+ return parts.join(", ");
319
+ }
320
+
321
+ const indexContents = readFileSync(join(endpointsDir, "index." + EXT), "utf-8");
322
+ const routes = Array.from(indexContents.matchAll(MOUNT_PATTERN)).map((m) => m[1]);
323
+
324
+ const groups = [];
325
+ for (const route of routes) {
326
+ let routesContents, controllerContents;
327
+ try {
328
+ routesContents = readFileSync(join(endpointsDir, route, route + ".routes." + EXT), "utf-8");
329
+ controllerContents = readFileSync(join(endpointsDir, route, route + ".controller." + EXT), "utf-8");
330
+ } catch {
331
+ continue; // mounted but missing a file — \`bun run doctor\` already flags this, skip it here
332
+ }
333
+
334
+ const methods = Array.from(routesContents.matchAll(METHOD_PATTERN)).map((m) => ({
335
+ verb: m[1],
336
+ path: m[2],
337
+ name: m[3],
338
+ needsBody: controllerContents.includes(m[3] + "BodySchema"),
339
+ needsQuery: controllerContents.includes(m[3] + "QuerySchema"),
340
+ }));
341
+ if (methods.length > 0) groups.push({ route, methods });
342
+ }
343
+
344
+ if (groups.length === 0) {
345
+ console.log("No endpoints with methods yet — nothing to generate. Run \`bun run add-method\` first.");
346
+ process.exit(0);
347
+ }
348
+
349
+ const importLines = [];
350
+ if (TYPED) {
351
+ importLines.push('import type { z } from "zod";');
352
+ const namesByModule = new Map();
353
+ for (const group of groups) {
354
+ const names = [];
355
+ for (const m of group.methods) {
356
+ if (m.needsBody) names.push(m.name + "BodySchema");
357
+ if (m.needsQuery) names.push(m.name + "QuerySchema");
358
+ }
359
+ if (names.length > 0) namesByModule.set("../src/endpoints/" + group.route + "/" + group.route + ".controller", names);
360
+ }
361
+ for (const [modulePath, names] of namesByModule) {
362
+ importLines.push('import type { ' + names.join(", ") + ' } from "' + modulePath + '";');
363
+ }
364
+ }
365
+
366
+ const helperLines = [
367
+ 'const BASE_URL = (typeof process !== "undefined" && process.env.API_BASE_URL) || "";',
368
+ "",
369
+ TYPED ? "async function request<T>(path: string, init?: RequestInit): Promise<T> {" : "async function request(path, init) {",
370
+ " const res = await fetch(BASE_URL + path, {",
371
+ " ...init,",
372
+ ' headers: { "Content-Type": "application/json", ...(init && init.headers ? init.headers : {}) },',
373
+ " });",
374
+ " if (!res.ok) {",
375
+ TYPED ? " const errBody: any = await res.json().catch(() => undefined);" : " const errBody = await res.json().catch(() => undefined);",
376
+ ' throw new Error((errBody && errBody.error && errBody.error.message) || ("Request to " + path + " failed with " + res.status));',
377
+ " }",
378
+ TYPED ? " return res.json() as Promise<T>;" : " return res.json();",
379
+ "}",
380
+ ];
381
+
382
+ const groupBlocks = groups.map((group) => {
383
+ const varName = camelCase(group.route) + "Api";
384
+ const methodLines = group.methods.map((m) => {
385
+ const signature = TYPED ? typedFuncArgs(m) : funcArgs(m).join(", ");
386
+ const genericPrefix = TYPED ? "<T = unknown>" : "";
387
+
388
+ let call = "request" + (TYPED ? "<T>" : "") + "(" + pathExpr(group.route, m);
389
+ if (m.needsQuery) call += ' + "?" + new URLSearchParams(query' + (TYPED ? " as any" : "") + ").toString()";
390
+
391
+ const initParts = [];
392
+ if (m.verb !== "get") initParts.push('method: "' + m.verb.toUpperCase() + '"');
393
+ if (m.needsBody) initParts.push("body: JSON.stringify(body)");
394
+ if (initParts.length > 0) call += ", { " + initParts.join(", ") + " }";
395
+ call += ")";
396
+
397
+ return " " + m.name + ": " + genericPrefix + "(" + signature + ") => " + call + ",";
398
+ });
399
+ return "export const " + varName + " = {\\n" + methodLines.join("\\n") + "\\n};";
400
+ });
401
+
402
+ const header =
403
+ "// Auto-generated by \`bun run generate-client\` from src/endpoints/ — re-run after adding, removing,\\n" +
404
+ "// or modifying methods (add-method/remove-method/server-config all count). Hand edits here are\\n" +
405
+ "// overwritten on the next run.\\n\\n";
406
+
407
+ const output =
408
+ header +
409
+ (importLines.length > 0 ? importLines.join("\\n") + "\\n\\n" : "") +
410
+ helperLines.join("\\n") +
411
+ "\\n\\n" +
412
+ groupBlocks.join("\\n\\n") +
413
+ "\\n";
414
+
415
+ mkdirSync(join(root, "client"), { recursive: true });
416
+ const outPath = join(root, "client", "api." + EXT);
417
+ writeFileSync(outPath, output);
418
+ console.log(
419
+ "Wrote " + outPath + " (" + groups.reduce((n, g) => n + g.methods.length, 0) + " method(s) across " + groups.length + " endpoint(s))"
420
+ );
421
+ `;
422
+ }
423
+
229
424
  export function renderEnvExample(db: Answers["db"]): string {
230
425
  return `PORT=3000
231
426
  ALLOWED_ORIGINS=
@@ -249,7 +444,7 @@ export function renderTsconfig(): string {
249
444
  "noEmit": true,
250
445
  "allowJs": false
251
446
  },
252
- "include": ["index.ts", "src", "scripts"]
447
+ "include": ["index.ts", "src", "scripts", "client"]
253
448
  }
254
449
  `;
255
450
  }
@@ -272,7 +467,7 @@ export function renderJsconfig(): string {
272
467
  "checkJs": false,
273
468
  "allowJs": true
274
469
  },
275
- "include": ["index.js", "src", "scripts"]
470
+ "include": ["index.js", "src", "scripts", "client"]
276
471
  }
277
472
  `;
278
473
  }
@@ -305,13 +500,15 @@ export function renderPackageJson(
305
500
 
306
501
  // JavaScript mode intentionally has zero TypeScript-related devDependencies
307
502
  // (no `typescript`, no `@types/*`) — there's nothing being compiled or
308
- // typechecked, so pulling those in would just be dead weight.
503
+ // typechecked, so pulling those in would just be dead weight. drizzle-kit
504
+ // is a CLI tool driven by schema.ts's shape, not by language, so it's
505
+ // merged in either way via dbDevDependencies(db).
309
506
  const devDependencies: Record<string, string> =
310
507
  language === "javascript"
311
- ? {}
508
+ ? { ...dbDevDependencies(db) }
312
509
  : framework === "express"
313
- ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2" }
314
- : { "@types/bun": "latest", typescript: "^5.7.2" };
510
+ ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2", ...dbDevDependencies(db) }
511
+ : { "@types/bun": "latest", typescript: "^5.7.2", ...dbDevDependencies(db) };
315
512
 
316
513
  const scripts: Record<string, string> = {
317
514
  dev: `bun run --watch index.${ext}`,
@@ -334,16 +531,42 @@ export function renderPackageJson(
334
531
  project: "bunx create-backon project",
335
532
  "server-config": "bunx create-backon server-config",
336
533
  docs: `bun run scripts/generate-docs.${ext}`,
534
+ // Regenerates client/api.<ext> — a typed fetch client, one function per
535
+ // mounted method, read straight off *.routes.<ext>/*.controller.<ext>
536
+ // (the same files add-method/server-config write). client/ is a build
537
+ // artifact like openapi.json/docs.html, not source — see .gitignore.
538
+ "generate-client": `bun run scripts/generate-client.${ext}`,
337
539
  };
338
540
  if (language === "typescript") {
339
541
  scripts.typecheck = "tsc --noEmit";
340
542
  }
543
+ if (dbHasSchemaSupport(db)) {
544
+ // add-table/remove-table: thin aliases matching the add-route/add-method
545
+ // pattern above. db:generate/db:migrate/db:push call drizzle-kit
546
+ // directly (not create-backon) — schema.ts is a real drizzle-kit
547
+ // config target, no wrapper needed.
548
+ scripts["add-table"] = "bunx create-backon add-table";
549
+ scripts["remove-table"] = "bunx create-backon remove-table";
550
+ scripts["db:generate"] = "drizzle-kit generate";
551
+ scripts["db:migrate"] = "drizzle-kit migrate";
552
+ scripts["db:push"] = "drizzle-kit push";
553
+ }
341
554
 
342
555
  const pkg = {
343
556
  name: projectName,
344
557
  version: "0.1.0",
345
558
  private: true,
346
559
  type: "module",
560
+ // Node's package.json subpath imports (Bun resolves these too, both
561
+ // locally and on Vercel's Bun runtime — no bundler-specific config
562
+ // needed, unlike a tsconfig "paths" alias). Lets any file import the db
563
+ // client as `import { db } from "#config/db"` regardless of how deep
564
+ // it's nested under src/endpoints/, instead of a depth-counted
565
+ // `../../config/db`. Verified against a real `bun run` and a real
566
+ // `tsc --noEmit` (moduleResolution: "bundler" already resolves it).
567
+ imports: {
568
+ "#config/*": `./src/config/*.${ext}`,
569
+ },
347
570
  scripts,
348
571
  dependencies,
349
572
  devDependencies,
@@ -394,6 +617,29 @@ both for free.
394
617
  }
395
618
  }
396
619
 
620
+ function renderSchemaReadmeSection(ext: string): string {
621
+ return `
622
+ ### Table schema
623
+
624
+ \`src/config/schema.${ext}\` holds every table (empty until you add one — see below). \`bun run
625
+ add-table\`/\`bun run remove-table\` (also reachable from \`server-config\`'s menu) edit it for you —
626
+ picking a column type, nullability, uniqueness, a default, and whether it references another
627
+ table's \`id\`. This only ever edits \`schema.${ext}\` on disk; it never touches the actual database.
628
+
629
+ To apply a schema change for real:
630
+
631
+ \`\`\`
632
+ bun run db:generate # writes a reviewable .sql migration under drizzle/ — no DB connection needed
633
+ bun run db:migrate # applies pending migrations to DATABASE_URL
634
+ \`\`\`
635
+
636
+ \`bun run db:push\` applies \`schema.${ext}\` straight to the database with no migration file — faster
637
+ to iterate with early on (empty/throwaway dev database), but skips the reviewable, versioned trail
638
+ \`generate\`/\`migrate\` gives you. Switch to \`generate\`/\`migrate\` once there's real data, or before
639
+ deploying anywhere with staging/prod.
640
+ `;
641
+ }
642
+
397
643
  export function renderReadme(answers: Answers): string {
398
644
  const routeList = answers.routes.length
399
645
  ? answers.routes.map((route) => `- \`src/endpoints/${route}/\``).join("\n")
@@ -423,6 +669,11 @@ document to \`openapi.json\`/\`docs.html\` on disk, for CI or static hosting.
423
669
 
424
670
  ${dbReadmeNote(answers.db)}
425
671
 
672
+ Import the client from anywhere as \`import { db } from "#config/db";\` — a package.json subpath
673
+ import (\`imports\`), not a relative path, so it stays \`#config/db\` no matter how deeply nested the
674
+ importing file is under \`src/endpoints/\`. Bun resolves it the same way locally and on Vercel;
675
+ \`tsc --noEmit\` resolves it too, no extra tsconfig needed.
676
+ ${dbHasSchemaSupport(answers.db) ? renderSchemaReadmeSection(ext) : ""}
426
677
  ## Routes
427
678
 
428
679
  ${routeList}