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.
@@ -5,16 +5,27 @@ export interface DbTemplate {
5
5
  file: string;
6
6
  /** Extra runtime dependencies the generated package.json needs. */
7
7
  dependencies: Record<string, string>;
8
+ /** Extra dev-only dependencies the generated package.json needs (drizzle-kit — a CLI tool, not runtime code). */
9
+ devDependencies: Record<string, string>;
8
10
  /** Line(s) appended to .env.example. */
9
11
  envVars: string;
10
12
  /** One-line note surfaced in the generated README so the caveats aren't silently lost. */
11
13
  readmeNote: string;
14
+ /** Whether this driver gets src/config/schema.ts + drizzle.config.ts + db:generate/db:migrate/db:push scripts — true for neon/postgres (same pg-core dialect), false for sqlite/none (see schema-edit.ts's requireNeonOrPostgres()). */
15
+ hasSchemaSupport: boolean;
12
16
  }
13
17
 
18
+ // drizzle-kit is genuinely the same for "neon" and "postgres" — both speak
19
+ // dialect: "postgresql", both point at the same schema.ts, both use the
20
+ // same DATABASE_URL-shaped dbCredentials.url (see templates/schema.ts's
21
+ // renderDrizzleConfig()) — only db.ts's client construction differs.
22
+ const DRIZZLE_KIT_DEV_DEPENDENCY = { "drizzle-kit": "^0.31.0" };
23
+
14
24
  const TEMPLATES: Record<DbChoice, DbTemplate> = {
15
25
  neon: {
16
26
  file: `import { drizzle } from "drizzle-orm/neon-http";
17
27
  import { neon } from "@neondatabase/serverless";
28
+ import * as schema from "./schema";
18
29
 
19
30
  if (!process.env.DATABASE_URL) {
20
31
  throw new Error("DATABASE_URL is required (Neon connection string)");
@@ -22,19 +33,22 @@ if (!process.env.DATABASE_URL) {
22
33
 
23
34
  const sql = neon(process.env.DATABASE_URL);
24
35
 
25
- export const db = drizzle(sql);
36
+ export const db = drizzle(sql, { schema });
26
37
  `,
27
38
  dependencies: {
28
39
  "drizzle-orm": "^0.38.2",
29
40
  "@neondatabase/serverless": "^0.10.4",
30
41
  },
42
+ devDependencies: DRIZZLE_KIT_DEV_DEPENDENCY,
31
43
  envVars: "DATABASE_URL=postgres://user:password@ep-example-123456.us-east-2.aws.neon.tech/dbname?sslmode=require\n",
32
44
  readmeNote:
33
45
  "Uses Neon's HTTP driver — no connection pooling to manage, which is what makes it safe to use from serverless functions (e.g. Vercel).",
46
+ hasSchemaSupport: true,
34
47
  },
35
48
  postgres: {
36
49
  file: `import { drizzle } from "drizzle-orm/node-postgres";
37
50
  import { Pool } from "pg";
51
+ import * as schema from "./schema";
38
52
 
39
53
  // NOTE: this pooled connection is for local dev or a long-running server
40
54
  // (Docker, a VPS, Render, etc). It is NOT safe to use as-is on Vercel
@@ -48,15 +62,17 @@ if (!process.env.DATABASE_URL) {
48
62
 
49
63
  const pool = new Pool({ connectionString: process.env.DATABASE_URL });
50
64
 
51
- export const db = drizzle(pool);
65
+ export const db = drizzle(pool, { schema });
52
66
  `,
53
67
  dependencies: {
54
68
  "drizzle-orm": "^0.38.2",
55
69
  pg: "^8.13.1",
56
70
  },
71
+ devDependencies: DRIZZLE_KIT_DEV_DEPENDENCY,
57
72
  envVars: "DATABASE_URL=postgres://user:password@localhost:5432/dbname\n",
58
73
  readmeNote:
59
74
  "Pooled Postgres connection — 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.",
75
+ hasSchemaSupport: true,
60
76
  },
61
77
  sqlite: {
62
78
  file: `import { drizzle } from "drizzle-orm/bun-sqlite";
@@ -72,19 +88,26 @@ export const db = drizzle(sqlite);
72
88
  dependencies: {
73
89
  "drizzle-orm": "^0.38.2",
74
90
  },
91
+ devDependencies: {},
75
92
  envVars: "DATABASE_URL=./dev.db\n",
76
- readmeNote: "Local file-based SQLite — for local dev only, not for a serverless deploy target.",
93
+ readmeNote:
94
+ "Local file-based SQLite — for local dev only, not for a serverless deploy target. No schema.ts/add-table support yet — 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.",
95
+ hasSchemaSupport: false,
77
96
  },
78
97
  none: {
79
98
  file: `// No database configured yet. Wire up a real client here — e.g. one of
80
99
  // the neon/postgres/sqlite variants this CLI can also generate — and
81
- // export it as \`db\` so src/endpoints/*/*.services.ts can import it.
100
+ // export it as \`db\`. Any service file can then do
101
+ // \`import { db } from "#config/db";\` (see package.json's "imports" field
102
+ // and the README's Database section) regardless of how deep it's nested.
82
103
 
83
104
  export const db = undefined;
84
105
  `,
85
106
  dependencies: {},
107
+ devDependencies: {},
86
108
  envVars: "",
87
109
  readmeNote: "No database configured. src/config/db.ts is an empty stub.",
110
+ hasSchemaSupport: false,
88
111
  },
89
112
  };
90
113
 
@@ -96,6 +119,10 @@ export function dbDependencies(db: DbChoice): Record<string, string> {
96
119
  return TEMPLATES[db].dependencies;
97
120
  }
98
121
 
122
+ export function dbDevDependencies(db: DbChoice): Record<string, string> {
123
+ return TEMPLATES[db].devDependencies;
124
+ }
125
+
99
126
  export function dbEnvVars(db: DbChoice): string {
100
127
  return TEMPLATES[db].envVars;
101
128
  }
@@ -103,3 +130,7 @@ export function dbEnvVars(db: DbChoice): string {
103
130
  export function dbReadmeNote(db: DbChoice): string {
104
131
  return TEMPLATES[db].readmeNote;
105
132
  }
133
+
134
+ export function dbHasSchemaSupport(db: DbChoice): boolean {
135
+ return TEMPLATES[db].hasSchemaSupport;
136
+ }
@@ -177,9 +177,12 @@ export function serviceImports(route: string, spec: MethodSpec, language: Langua
177
177
  }
178
178
 
179
179
  export function renderServiceMethod(spec: MethodSpec, language: Language): string {
180
- const ext = language === "javascript" ? "js" : "ts";
181
180
  const argList = language === "javascript" ? serviceCallArgs(spec).join(", ") : serviceParamList(spec);
182
- return `// TODO: replace with real data access (see src/config/db.${ext})
181
+ // "#config/db" is a package.json subpath import (Node's `imports` field,
182
+ // which Bun also resolves) — points at src/config/db.<ext> regardless of
183
+ // how deep the importing file is, so this never turns into `../../config/db`
184
+ // as routes get nested. See the "Database" section of the generated README.
185
+ return `// TODO: replace with real data access — e.g. import { db } from "#config/db";
183
186
  export async function ${spec.name}(${argList}) {
184
187
  ${defaultServiceReturn(spec)}
185
188
  }`;
@@ -0,0 +1,160 @@
1
+ import { toKebabCase } from "../prompts";
2
+ import { camelCase } from "./route";
3
+
4
+ /**
5
+ * The column types offered by `add-table`/`server-config`'s table editor.
6
+ * Deliberately a curated subset of what drizzle-orm/pg-core actually
7
+ * offers, not the full set (no jsonb, arrays, enums, numeric/decimal,
8
+ * varchar-with-length, etc. — those still work fine, they just have to be
9
+ * hand-added to schema.ts, same "escape hatch, not a lock-in" approach
10
+ * obfuscateTailwind()/frontonCompression() use elsewhere in this monorepo).
11
+ * Every one of these, plus the modifier chains below, was checked against a
12
+ * real `tsc --noEmit` run against real drizzle-orm/pg-core types before
13
+ * this went in, not assumed from docs.
14
+ */
15
+ export const COLUMN_TYPES = ["text", "integer", "boolean", "timestamp", "uuid"] as const;
16
+ export type ColumnType = (typeof COLUMN_TYPES)[number];
17
+
18
+ export interface ColumnSpec {
19
+ /** Raw name as typed, e.g. "Login Count" — sqlName/jsKey are both derived from this. */
20
+ name: string;
21
+ type: ColumnType;
22
+ notNull: boolean;
23
+ unique: boolean;
24
+ /**
25
+ * Pre-rendered modifier chain fragment for a default value, e.g.
26
+ * `.default(true)`, `.defaultNow()`, `.defaultRandom()` — empty string
27
+ * means no default. Kept pre-rendered (rather than a structured value)
28
+ * because each column type's default looks nothing like the others
29
+ * (timestamp/uuid use a no-arg method, text/integer/boolean take a
30
+ * literal), so there's no shared shape worth modeling.
31
+ */
32
+ defaultExpr: string;
33
+ /**
34
+ * A referenced table's JS identifier, e.g. "users" — when set, this
35
+ * column is always rendered as `integer(...).references(() => X.id)`
36
+ * regardless of `type`, matching the idiomatic Drizzle FK pattern (an
37
+ * `integer` column referencing another table's `serial` primary key).
38
+ * Verified against a real `tsc --noEmit`.
39
+ */
40
+ references?: string;
41
+ }
42
+
43
+ export interface TableSpec {
44
+ /** Raw name as typed, e.g. "Blog Posts" — identifier/sqlName are both derived from this. */
45
+ name: string;
46
+ /** Whether to prepend `id: serial("id").primaryKey()` — on by default, matches near-universal convention. */
47
+ includeId: boolean;
48
+ columns: ColumnSpec[];
49
+ }
50
+
51
+ export function tableIdentifier(name: string): string {
52
+ return camelCase(toKebabCase(name));
53
+ }
54
+
55
+ export function tableSqlName(name: string): string {
56
+ return toKebabCase(name).replace(/-/g, "_");
57
+ }
58
+
59
+ export function columnIdentifier(name: string): string {
60
+ return camelCase(toKebabCase(name));
61
+ }
62
+
63
+ function columnSqlName(name: string): string {
64
+ return toKebabCase(name).replace(/-/g, "_");
65
+ }
66
+
67
+ /** Which drizzle-orm/pg-core builder functions a table actually needs — used to keep the shared import declaration minimal and merge-friendly across repeated add-table calls. */
68
+ export function requiredBuilders(table: TableSpec): Set<string> {
69
+ const builders = new Set<string>(["pgTable"]);
70
+ if (table.includeId) builders.add("serial");
71
+ for (const col of table.columns) {
72
+ builders.add(col.references ? "integer" : col.type);
73
+ }
74
+ return builders;
75
+ }
76
+
77
+ function renderColumnLine(col: ColumnSpec): string {
78
+ const key = columnIdentifier(col.name);
79
+ const sqlName = columnSqlName(col.name);
80
+
81
+ let expr: string;
82
+ if (col.references) {
83
+ expr = `integer("${sqlName}").references(() => ${col.references}.id)`;
84
+ } else {
85
+ expr = `${col.type}("${sqlName}")`;
86
+ }
87
+
88
+ if (col.notNull) expr += ".notNull()";
89
+ if (col.unique) expr += ".unique()";
90
+ if (col.defaultExpr) expr += col.defaultExpr;
91
+
92
+ return ` ${key}: ${expr},`;
93
+ }
94
+
95
+ /**
96
+ * Renders one `export const <identifier> = pgTable(...)` block — appended
97
+ * as-is to schema.ts by schema-edit.ts's ts-morph layer, the same
98
+ * append-real-statements approach templates/route.ts's method codegen
99
+ * uses.
100
+ */
101
+ export function renderTableBlock(table: TableSpec): string {
102
+ const identifier = tableIdentifier(table.name);
103
+ const sqlName = tableSqlName(table.name);
104
+ const lines: string[] = [];
105
+ if (table.includeId) lines.push(` id: serial("id").primaryKey(),`);
106
+ for (const col of table.columns) lines.push(renderColumnLine(col));
107
+
108
+ return `export const ${identifier} = pgTable("${sqlName}", {
109
+ ${lines.join("\n")}
110
+ });`;
111
+ }
112
+
113
+ export function renderBlankSchema(): string {
114
+ // The trailing `export {};` matters: a .ts file with zero import/export
115
+ // statements is a *script* to TypeScript, not a module, and db.ts's
116
+ // `import * as schema from "./schema"` fails to compile against a script
117
+ // file (`error TS2306: File '...' is not a module`) — caught against a
118
+ // real `tsc --noEmit` on a freshly scaffolded project, not assumed.
119
+ return `// No tables yet — add one via \`bun run add-table\` (or server-config's
120
+ // "Add a database table"). Each table becomes a real pgTable(...) export
121
+ // here, picked up automatically by both db.ts's schema import and
122
+ // drizzle-kit (see drizzle.config.ts) — nothing else needs to be told
123
+ // about a new table by hand.
124
+
125
+ export {};
126
+ `;
127
+ }
128
+
129
+ /**
130
+ * drizzle-kit's own config file, not one of backon's generated project
131
+ * files in the usual sense — drizzle-kit reads this directly, by
132
+ * convention, from the project root. `dialect: "postgresql"` is correct
133
+ * for both the "neon" and "postgres" db choices: neon-http still speaks
134
+ * the Postgres wire dialect over HTTP, so schema.ts, migrations, and this
135
+ * config are identical between the two — only db.ts's client construction
136
+ * differs (see templates/db.ts).
137
+ */
138
+ export function renderDrizzleConfig(ext: "ts" | "js"): string {
139
+ // The guard-then-use shape (rather than a TS-only `!` non-null assertion)
140
+ // matches templates/db.ts's neon/postgres templates exactly, and for the
141
+ // same reason: this file is generated for JavaScript projects too, where
142
+ // `!` isn't valid syntax at all. TypeScript's control-flow narrowing
143
+ // still applies to `process.env.DATABASE_URL` across the two statements
144
+ // below, same as it already does in db.ts.
145
+ return `import { defineConfig } from "drizzle-kit";
146
+
147
+ if (!process.env.DATABASE_URL) {
148
+ throw new Error("DATABASE_URL is required (see src/config/db.${ext})");
149
+ }
150
+
151
+ export default defineConfig({
152
+ schema: "./src/config/schema.${ext}",
153
+ out: "./drizzle",
154
+ dialect: "postgresql",
155
+ dbCredentials: {
156
+ url: process.env.DATABASE_URL,
157
+ },
158
+ });
159
+ `;
160
+ }