create-backon 0.13.3 → 0.14.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 +780 -70
- package/package.json +5 -5
- package/src/cli.ts +430 -70
- package/src/schema-edit.ts +118 -36
- package/src/templates/base.ts +8 -7
- package/src/templates/schema.ts +102 -27
- package/src/tui.ts +336 -0
package/src/cli.ts
CHANGED
|
@@ -7,6 +7,7 @@
|
|
|
7
7
|
// first line. Local dev (`bun run src/cli.ts`, the "start" script) doesn't
|
|
8
8
|
// need a shebang either; `bun run` executes the given file directly, it
|
|
9
9
|
// doesn't rely on the OS reading a shebang the way `./cli.ts` would.
|
|
10
|
+
import { spawnSync } from "node:child_process";
|
|
10
11
|
import { readFile } from "node:fs/promises";
|
|
11
12
|
import { join } from "node:path";
|
|
12
13
|
import * as p from "@clack/prompts";
|
|
@@ -29,26 +30,36 @@ import {
|
|
|
29
30
|
type EndpointSummary,
|
|
30
31
|
} from "./route-methods";
|
|
31
32
|
import { HTTP_VERBS, paramNamesFromPath, pascalCase, type HttpVerb, type MethodSpec } from "./templates/route";
|
|
32
|
-
import {
|
|
33
|
-
|
|
33
|
+
import {
|
|
34
|
+
addColumn,
|
|
35
|
+
addTable,
|
|
36
|
+
removeTable,
|
|
37
|
+
parseSchemaTables,
|
|
38
|
+
formatTablesDashboard,
|
|
39
|
+
type ParsedTable,
|
|
40
|
+
} from "./schema-edit";
|
|
41
|
+
import {
|
|
42
|
+
buildJunctionTableSpec,
|
|
43
|
+
COLUMN_TYPES,
|
|
44
|
+
columnIdentifier,
|
|
45
|
+
ON_DELETE_ACTIONS,
|
|
46
|
+
tableIdentifier,
|
|
47
|
+
type ColumnSpec,
|
|
48
|
+
type ColumnType,
|
|
49
|
+
type OnDeleteAction,
|
|
50
|
+
type TableSpec,
|
|
51
|
+
} from "./templates/schema";
|
|
52
|
+
import { runServerConfigTui } from "./tui";
|
|
34
53
|
|
|
35
54
|
const ADD_ROUTE_SUBCOMMANDS = new Set(["add-route", "route"]);
|
|
36
55
|
const REMOVE_ROUTE_SUBCOMMANDS = new Set(["remove-route", "rm-route"]);
|
|
37
56
|
const LIST_ROUTES_SUBCOMMANDS = new Set(["list-routes", "routes"]);
|
|
38
57
|
const DOCTOR_SUBCOMMANDS = new Set(["doctor"]);
|
|
39
58
|
const ADD_METHOD_SUBCOMMANDS = new Set(["add-method", "method"]);
|
|
40
|
-
// project: a read-only overview (db status, endpoints, methods, doctor
|
|
41
|
-
// summary) — nothing here writes to disk. server-config: the interactive
|
|
42
|
-
// wrapper around add-route/remove-route/add-method/remove-method (plus
|
|
43
|
-
// modify, which neither standalone command offers) for managing endpoints
|
|
44
|
-
// without remembering individual subcommand names. Deliberately two
|
|
45
|
-
// separate commands rather than one combined dashboard — "just show me
|
|
46
|
-
// what's here" and "let me start changing things" are different intents,
|
|
47
|
-
// and collapsing them risks an accidental edit from someone who only
|
|
48
|
-
// wanted to look.
|
|
49
59
|
const PROJECT_SUBCOMMANDS = new Set(["project"]);
|
|
50
60
|
const SERVER_CONFIG_SUBCOMMANDS = new Set(["server-config"]);
|
|
51
61
|
const ADD_TABLE_SUBCOMMANDS = new Set(["add-table", "table"]);
|
|
62
|
+
const ADD_COLUMN_SUBCOMMANDS = new Set(["add-column", "column"]);
|
|
52
63
|
const REMOVE_TABLE_SUBCOMMANDS = new Set(["remove-table", "rm-table"]);
|
|
53
64
|
|
|
54
65
|
async function promptForRouteName(introText: string): Promise<string> {
|
|
@@ -196,9 +207,10 @@ async function readSchemaTables(): Promise<ParsedTable[]> {
|
|
|
196
207
|
}
|
|
197
208
|
}
|
|
198
209
|
|
|
199
|
-
/** Type-specific
|
|
210
|
+
/** Type-specific default prompt — returns pre-rendered modifier fragment, "" for none, or null on cancel. */
|
|
200
211
|
async function promptDefaultExpr(type: ColumnType): Promise<string | null> {
|
|
201
|
-
if (type === "
|
|
212
|
+
if (type === "serial") return "";
|
|
213
|
+
if (type === "timestamp" || type === "date") {
|
|
202
214
|
const v = await p.confirm({ message: "Default to now()?", initialValue: false });
|
|
203
215
|
if (p.isCancel(v)) return null;
|
|
204
216
|
return v ? ".defaultNow()" : "";
|
|
@@ -221,14 +233,28 @@ async function promptDefaultExpr(type: ColumnType): Promise<string | null> {
|
|
|
221
233
|
if (p.isCancel(v)) return null;
|
|
222
234
|
return v === "none" ? "" : `.default(${v})`;
|
|
223
235
|
}
|
|
224
|
-
|
|
236
|
+
if (type === "jsonb") {
|
|
237
|
+
const v = await p.select({
|
|
238
|
+
message: "Default JSON value",
|
|
239
|
+
options: [
|
|
240
|
+
{ value: "none", label: "None" },
|
|
241
|
+
{ value: "{}", label: "{} (empty object)" },
|
|
242
|
+
{ value: "[]", label: "[] (empty array)" },
|
|
243
|
+
],
|
|
244
|
+
initialValue: "none",
|
|
245
|
+
});
|
|
246
|
+
if (p.isCancel(v)) return null;
|
|
247
|
+
return v === "none" ? "" : `.default(${v})`;
|
|
248
|
+
}
|
|
249
|
+
// text / varchar / integer / numeric / real
|
|
250
|
+
const isNumber = type === "integer" || type === "real";
|
|
225
251
|
const v = await p.text({
|
|
226
252
|
message: "Default value (blank for none)",
|
|
227
|
-
placeholder: type === "
|
|
253
|
+
placeholder: isNumber ? "e.g. 0" : type === "numeric" ? "e.g. 0.00" : "e.g. pending",
|
|
228
254
|
});
|
|
229
255
|
if (p.isCancel(v)) return null;
|
|
230
256
|
if (!v) return "";
|
|
231
|
-
if (
|
|
257
|
+
if (isNumber) {
|
|
232
258
|
const n = Number(v);
|
|
233
259
|
if (Number.isNaN(n)) {
|
|
234
260
|
p.log.warn(`"${v}" isn't a number — skipping the default.`);
|
|
@@ -239,8 +265,78 @@ async function promptDefaultExpr(type: ColumnType): Promise<string | null> {
|
|
|
239
265
|
return `.default(${JSON.stringify(v)})`;
|
|
240
266
|
}
|
|
241
267
|
|
|
268
|
+
/** Collects a single column definition (used by both table creation and `add-column`). */
|
|
269
|
+
async function promptSingleColumn(
|
|
270
|
+
name: string,
|
|
271
|
+
existingTables: ParsedTable[],
|
|
272
|
+
defaultRequired = true
|
|
273
|
+
): Promise<ColumnSpec | null> {
|
|
274
|
+
let references: string | undefined;
|
|
275
|
+
let onDelete: OnDeleteAction | undefined;
|
|
276
|
+
if (existingTables.length > 0) {
|
|
277
|
+
const refChoice = await p.select({
|
|
278
|
+
message: `Does "${name}" reference another table's id?`,
|
|
279
|
+
options: [
|
|
280
|
+
{ value: "__none__", label: "No" },
|
|
281
|
+
...existingTables.map((t) => ({ value: t.identifier, label: t.identifier })),
|
|
282
|
+
],
|
|
283
|
+
initialValue: "__none__",
|
|
284
|
+
});
|
|
285
|
+
if (p.isCancel(refChoice)) return null;
|
|
286
|
+
if (refChoice !== "__none__") {
|
|
287
|
+
references = refChoice;
|
|
288
|
+
const deleteChoice = await p.select({
|
|
289
|
+
message: "On referenced row delete",
|
|
290
|
+
options: [
|
|
291
|
+
{ value: "__none__", label: "Default (no action)" },
|
|
292
|
+
...ON_DELETE_ACTIONS.map((a) => ({ value: a, label: a })),
|
|
293
|
+
],
|
|
294
|
+
initialValue: "cascade",
|
|
295
|
+
});
|
|
296
|
+
if (p.isCancel(deleteChoice)) return null;
|
|
297
|
+
if (deleteChoice !== "__none__") onDelete = deleteChoice as OnDeleteAction;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
let type: ColumnType = "integer";
|
|
302
|
+
let varcharLength: number | undefined;
|
|
303
|
+
let defaultExpr = "";
|
|
304
|
+
if (!references) {
|
|
305
|
+
const typeChoice = await p.select({
|
|
306
|
+
message: "Column type",
|
|
307
|
+
options: COLUMN_TYPES.map((t) => ({ value: t, label: t })),
|
|
308
|
+
});
|
|
309
|
+
if (p.isCancel(typeChoice)) return null;
|
|
310
|
+
type = typeChoice;
|
|
311
|
+
|
|
312
|
+
if (type === "varchar") {
|
|
313
|
+
const lenInput = await p.text({
|
|
314
|
+
message: "Max varchar length",
|
|
315
|
+
initialValue: "255",
|
|
316
|
+
validate: (value) => {
|
|
317
|
+
const n = Number(value);
|
|
318
|
+
return !value || !Number.isInteger(n) || n <= 0 ? "Enter a positive integer." : undefined;
|
|
319
|
+
},
|
|
320
|
+
});
|
|
321
|
+
if (p.isCancel(lenInput)) return null;
|
|
322
|
+
varcharLength = Number(lenInput);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const expr = await promptDefaultExpr(type);
|
|
326
|
+
if (expr === null) return null;
|
|
327
|
+
defaultExpr = expr;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const notNull = await p.confirm({ message: "Required (NOT NULL)?", initialValue: defaultRequired });
|
|
331
|
+
if (p.isCancel(notNull)) return null;
|
|
332
|
+
const unique = await p.confirm({ message: "Unique?", initialValue: false });
|
|
333
|
+
if (p.isCancel(unique)) return null;
|
|
334
|
+
|
|
335
|
+
return { name, type, notNull, unique, defaultExpr, varcharLength, references, onDelete };
|
|
336
|
+
}
|
|
337
|
+
|
|
242
338
|
/** Full column-collection loop for one table — stops on a blank column name, propagates a cancel as `null`. */
|
|
243
|
-
async function promptForColumns(existingTables: ParsedTable[]): Promise<ColumnSpec[] | null> {
|
|
339
|
+
async function promptForColumns(existingTables: ParsedTable[], existingKeys: string[] = []): Promise<ColumnSpec[] | null> {
|
|
244
340
|
const columns: ColumnSpec[] = [];
|
|
245
341
|
p.log.step("Add columns one at a time. Leave the name blank to finish.");
|
|
246
342
|
// eslint-disable-next-line no-constant-condition
|
|
@@ -253,51 +349,20 @@ async function promptForColumns(existingTables: ParsedTable[]): Promise<ColumnSp
|
|
|
253
349
|
if (!nameProbe) break;
|
|
254
350
|
|
|
255
351
|
const key = columnIdentifier(nameProbe);
|
|
256
|
-
if (columns.some((c) => columnIdentifier(c.name) === key)) {
|
|
352
|
+
if (existingKeys.includes(key) || columns.some((c) => columnIdentifier(c.name) === key)) {
|
|
257
353
|
p.log.error(`"${key}" is already a column on this table.`);
|
|
258
354
|
continue;
|
|
259
355
|
}
|
|
260
356
|
|
|
261
|
-
|
|
262
|
-
if (
|
|
263
|
-
|
|
264
|
-
message: `Does "${nameProbe}" reference another table's id?`,
|
|
265
|
-
options: [
|
|
266
|
-
{ value: "__none__", label: "No" },
|
|
267
|
-
...existingTables.map((t) => ({ value: t.identifier, label: t.identifier })),
|
|
268
|
-
],
|
|
269
|
-
initialValue: "__none__",
|
|
270
|
-
});
|
|
271
|
-
if (p.isCancel(refChoice)) return null;
|
|
272
|
-
if (refChoice !== "__none__") references = refChoice;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
let type: ColumnType = "integer";
|
|
276
|
-
let defaultExpr = "";
|
|
277
|
-
if (!references) {
|
|
278
|
-
const typeChoice = await p.select({
|
|
279
|
-
message: "Column type",
|
|
280
|
-
options: COLUMN_TYPES.map((t) => ({ value: t, label: t })),
|
|
281
|
-
});
|
|
282
|
-
if (p.isCancel(typeChoice)) return null;
|
|
283
|
-
type = typeChoice;
|
|
284
|
-
const expr = await promptDefaultExpr(type);
|
|
285
|
-
if (expr === null) return null;
|
|
286
|
-
defaultExpr = expr;
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
const notNull = await p.confirm({ message: "Required (NOT NULL)?", initialValue: true });
|
|
290
|
-
if (p.isCancel(notNull)) return null;
|
|
291
|
-
const unique = await p.confirm({ message: "Unique?", initialValue: false });
|
|
292
|
-
if (p.isCancel(unique)) return null;
|
|
293
|
-
|
|
294
|
-
columns.push({ name: nameProbe, type, notNull, unique, defaultExpr, references });
|
|
357
|
+
const spec = await promptSingleColumn(nameProbe, existingTables);
|
|
358
|
+
if (spec === null) return null;
|
|
359
|
+
columns.push(spec);
|
|
295
360
|
}
|
|
296
361
|
|
|
297
362
|
return columns;
|
|
298
363
|
}
|
|
299
364
|
|
|
300
|
-
/** Full table-collection flow: name
|
|
365
|
+
/** Full table-collection flow: name, id primary key, timestamps preset, and columns. */
|
|
301
366
|
async function collectTableSpec(existingTables: ParsedTable[], forcedName?: string): Promise<TableSpec | null> {
|
|
302
367
|
let name = forcedName;
|
|
303
368
|
if (name) {
|
|
@@ -328,23 +393,100 @@ async function collectTableSpec(existingTables: ParsedTable[], forcedName?: stri
|
|
|
328
393
|
});
|
|
329
394
|
if (p.isCancel(includeId)) return null;
|
|
330
395
|
|
|
331
|
-
const
|
|
396
|
+
const includeTimestamps = await p.confirm({
|
|
397
|
+
message: "Add createdAt / updatedAt timestamp columns?",
|
|
398
|
+
initialValue: true,
|
|
399
|
+
});
|
|
400
|
+
if (p.isCancel(includeTimestamps)) return null;
|
|
401
|
+
|
|
402
|
+
const columns = await promptForColumns(existingTables, includeId ? ["id"] : []);
|
|
332
403
|
if (columns === null) return null;
|
|
333
404
|
|
|
334
|
-
return { name, includeId, columns };
|
|
405
|
+
return { name, includeId, includeTimestamps, columns };
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** Interactive wizard for a many-to-many junction table pairing two existing tables. */
|
|
409
|
+
async function collectJunctionTableSpec(existingTables: ParsedTable[]): Promise<TableSpec | null> {
|
|
410
|
+
if (existingTables.length < 2) {
|
|
411
|
+
p.log.warn("Need at least 2 existing tables to create a many-to-many junction table.");
|
|
412
|
+
return null;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
const leftTable = await p.select({
|
|
416
|
+
message: "First table",
|
|
417
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: t.identifier })),
|
|
418
|
+
});
|
|
419
|
+
if (p.isCancel(leftTable)) return null;
|
|
420
|
+
|
|
421
|
+
const rightTable = await p.select({
|
|
422
|
+
message: "Second table",
|
|
423
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: t.identifier })),
|
|
424
|
+
});
|
|
425
|
+
if (p.isCancel(rightTable)) return null;
|
|
426
|
+
|
|
427
|
+
const defaultName = `${leftTable}_${rightTable}`;
|
|
428
|
+
const name = await p.text({
|
|
429
|
+
message: "Junction table name",
|
|
430
|
+
initialValue: defaultName,
|
|
431
|
+
validate: (value) => {
|
|
432
|
+
if (!value) return "Required.";
|
|
433
|
+
if (existingTables.some((t) => t.identifier === tableIdentifier(value))) {
|
|
434
|
+
return `"${tableIdentifier(value)}" already exists.`;
|
|
435
|
+
}
|
|
436
|
+
return undefined;
|
|
437
|
+
},
|
|
438
|
+
});
|
|
439
|
+
if (p.isCancel(name)) return null;
|
|
440
|
+
|
|
441
|
+
const onDelete = await p.select({
|
|
442
|
+
message: "Cascade behavior when either referenced row is deleted",
|
|
443
|
+
options: ON_DELETE_ACTIONS.map((a) => ({ value: a, label: a })),
|
|
444
|
+
initialValue: "cascade" as OnDeleteAction,
|
|
445
|
+
});
|
|
446
|
+
if (p.isCancel(onDelete)) return null;
|
|
447
|
+
|
|
448
|
+
const includeTimestamps = await p.confirm({
|
|
449
|
+
message: "Add createdAt / updatedAt timestamp columns?",
|
|
450
|
+
initialValue: true,
|
|
451
|
+
});
|
|
452
|
+
if (p.isCancel(includeTimestamps)) return null;
|
|
453
|
+
|
|
454
|
+
const addExtra = await p.confirm({
|
|
455
|
+
message: "Add extra attributes to the junction table (e.g. role, quantity)?",
|
|
456
|
+
initialValue: false,
|
|
457
|
+
});
|
|
458
|
+
if (p.isCancel(addExtra)) return null;
|
|
459
|
+
|
|
460
|
+
const baseSpec = buildJunctionTableSpec({ leftTable, rightTable, name, includeTimestamps, onDelete });
|
|
461
|
+
let extraColumns: ColumnSpec[] = [];
|
|
462
|
+
if (addExtra) {
|
|
463
|
+
const cols = await promptForColumns(
|
|
464
|
+
existingTables,
|
|
465
|
+
baseSpec.columns.map((c) => columnIdentifier(c.name))
|
|
466
|
+
);
|
|
467
|
+
if (cols === null) return null;
|
|
468
|
+
extraColumns = cols;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
return buildJunctionTableSpec({ leftTable, rightTable, name, includeTimestamps, onDelete, extraColumns });
|
|
335
472
|
}
|
|
336
473
|
|
|
337
474
|
async function runAddTable(args: string[]): Promise<void> {
|
|
338
475
|
p.intro("create-backon add-table");
|
|
339
476
|
if (!(await ensureSchemaSupport())) return;
|
|
340
477
|
|
|
341
|
-
const
|
|
478
|
+
const junctionFlag = args.includes("--junction");
|
|
479
|
+
const positional = args.filter((a) => a !== "--junction");
|
|
480
|
+
const [forcedName] = positional;
|
|
342
481
|
let existingTables = await readSchemaTables();
|
|
343
482
|
let first = true;
|
|
344
483
|
|
|
345
484
|
// eslint-disable-next-line no-constant-condition
|
|
346
485
|
while (true) {
|
|
347
|
-
const spec =
|
|
486
|
+
const spec =
|
|
487
|
+
first && junctionFlag
|
|
488
|
+
? await collectJunctionTableSpec(existingTables)
|
|
489
|
+
: await collectTableSpec(existingTables, first ? forcedName : undefined);
|
|
348
490
|
first = false;
|
|
349
491
|
if (!spec) {
|
|
350
492
|
p.cancel("Cancelled.");
|
|
@@ -366,6 +508,69 @@ async function runAddTable(args: string[]): Promise<void> {
|
|
|
366
508
|
p.outro("Done.");
|
|
367
509
|
}
|
|
368
510
|
|
|
511
|
+
async function runAddColumn(args: string[]): Promise<void> {
|
|
512
|
+
p.intro("create-backon add-column");
|
|
513
|
+
if (!(await ensureSchemaSupport())) return;
|
|
514
|
+
|
|
515
|
+
const existingTables = await readSchemaTables();
|
|
516
|
+
if (existingTables.length === 0) {
|
|
517
|
+
p.log.info("No tables yet — run `bun run add-table` first.");
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
const [forcedTable, forcedCol] = args;
|
|
522
|
+
let tableId: string;
|
|
523
|
+
if (forcedTable) {
|
|
524
|
+
const candidate = tableIdentifier(forcedTable);
|
|
525
|
+
const match = existingTables.find((t) => t.identifier === candidate || t.identifier === forcedTable);
|
|
526
|
+
if (!match) {
|
|
527
|
+
p.log.error(`No table "${forcedTable}" found.`);
|
|
528
|
+
return;
|
|
529
|
+
}
|
|
530
|
+
tableId = match.identifier;
|
|
531
|
+
} else {
|
|
532
|
+
const choice = await p.select({
|
|
533
|
+
message: "Add a column to which table?",
|
|
534
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` })),
|
|
535
|
+
});
|
|
536
|
+
if (p.isCancel(choice)) {
|
|
537
|
+
p.cancel("Cancelled.");
|
|
538
|
+
return;
|
|
539
|
+
}
|
|
540
|
+
tableId = choice;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
const target = existingTables.find((t) => t.identifier === tableId)!;
|
|
544
|
+
let colName = forcedCol;
|
|
545
|
+
if (!colName) {
|
|
546
|
+
const answer = await p.text({
|
|
547
|
+
message: "Column name",
|
|
548
|
+
placeholder: "e.g. avatarUrl",
|
|
549
|
+
validate: (value) => {
|
|
550
|
+
if (!value) return "Required.";
|
|
551
|
+
const key = columnIdentifier(value);
|
|
552
|
+
if (target.columns.some((c) => c.key === key)) return `"${key}" already exists on ${tableId}.`;
|
|
553
|
+
return undefined;
|
|
554
|
+
},
|
|
555
|
+
});
|
|
556
|
+
if (p.isCancel(answer)) {
|
|
557
|
+
p.cancel("Cancelled.");
|
|
558
|
+
return;
|
|
559
|
+
}
|
|
560
|
+
colName = answer;
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
const spec = await promptSingleColumn(colName, existingTables);
|
|
564
|
+
if (!spec) {
|
|
565
|
+
p.cancel("Cancelled.");
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
const { columnKey, filePath } = await addColumn(tableId, spec);
|
|
570
|
+
p.log.success(`Added column "${columnKey}" to "${tableId}" in ${filePath}.`);
|
|
571
|
+
p.outro("Run `bun run db:generate` to create a migration.");
|
|
572
|
+
}
|
|
573
|
+
|
|
369
574
|
async function runRemoveTable(args: string[]): Promise<void> {
|
|
370
575
|
p.intro("create-backon remove-table");
|
|
371
576
|
if (!(await ensureSchemaSupport())) return;
|
|
@@ -416,7 +621,7 @@ async function runRemoveTable(args: string[]): Promise<void> {
|
|
|
416
621
|
}
|
|
417
622
|
|
|
418
623
|
/** server-config's single-shot version of runAddTable() — no internal "add another?" loop, since runServerConfig()'s own while loop already re-shows state and re-prompts after every action. */
|
|
419
|
-
async function serverConfigAddTable(existingTables: ParsedTable[]): Promise<void> {
|
|
624
|
+
async function serverConfigAddTable(existingTables: ParsedTable[]): Promise<string | void> {
|
|
420
625
|
const spec = await collectTableSpec(existingTables);
|
|
421
626
|
if (!spec) {
|
|
422
627
|
p.cancel("Cancelled.");
|
|
@@ -424,21 +629,82 @@ async function serverConfigAddTable(existingTables: ParsedTable[]): Promise<void
|
|
|
424
629
|
}
|
|
425
630
|
const { filePath, identifier } = await addTable(spec);
|
|
426
631
|
p.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
|
|
632
|
+
return `Added table "${identifier}"`;
|
|
427
633
|
}
|
|
428
634
|
|
|
429
|
-
async function
|
|
635
|
+
async function serverConfigAddJunctionTable(existingTables: ParsedTable[]): Promise<string | void> {
|
|
636
|
+
const spec = await collectJunctionTableSpec(existingTables);
|
|
637
|
+
if (!spec) {
|
|
638
|
+
p.cancel("Cancelled.");
|
|
639
|
+
return;
|
|
640
|
+
}
|
|
641
|
+
const { filePath, identifier } = await addTable(spec);
|
|
642
|
+
p.log.success(`Added junction table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
|
|
643
|
+
return `Added junction table "${identifier}"`;
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
async function serverConfigAddColumn(existingTables: ParsedTable[], forcedTable?: ParsedTable): Promise<string | void> {
|
|
430
647
|
if (existingTables.length === 0) {
|
|
431
|
-
p.log.info("No tables yet.");
|
|
648
|
+
p.log.info("No tables yet — add a table first.");
|
|
432
649
|
return;
|
|
433
650
|
}
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
651
|
+
let target = forcedTable;
|
|
652
|
+
if (!target) {
|
|
653
|
+
const choice = await p.select({
|
|
654
|
+
message: "Add a column to which table?",
|
|
655
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` })),
|
|
656
|
+
});
|
|
657
|
+
if (p.isCancel(choice)) {
|
|
658
|
+
p.cancel("Cancelled.");
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
target = existingTables.find((t) => t.identifier === choice);
|
|
662
|
+
}
|
|
663
|
+
if (!target) return;
|
|
664
|
+
|
|
665
|
+
const colName = await p.text({
|
|
666
|
+
message: `New column name on "${target.identifier}"`,
|
|
667
|
+
placeholder: "e.g. avatarUrl",
|
|
668
|
+
validate: (value) => {
|
|
669
|
+
if (!value) return "Required.";
|
|
670
|
+
const key = columnIdentifier(value);
|
|
671
|
+
if (target!.columns.some((c) => c.key === key)) return `"${key}" already exists on ${target!.identifier}.`;
|
|
672
|
+
return undefined;
|
|
673
|
+
},
|
|
437
674
|
});
|
|
438
|
-
if (p.isCancel(
|
|
675
|
+
if (p.isCancel(colName)) {
|
|
676
|
+
p.cancel("Cancelled.");
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
const spec = await promptSingleColumn(colName, existingTables);
|
|
681
|
+
if (!spec) {
|
|
439
682
|
p.cancel("Cancelled.");
|
|
440
683
|
return;
|
|
441
684
|
}
|
|
685
|
+
|
|
686
|
+
const { columnKey, filePath } = await addColumn(target.identifier, spec);
|
|
687
|
+
p.log.success(`Added column "${columnKey}" to "${target.identifier}" in ${filePath}.`);
|
|
688
|
+
return `Added column "${target.identifier}.${columnKey}"`;
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
async function serverConfigRemoveTable(existingTables: ParsedTable[], forcedTable?: ParsedTable): Promise<string | void> {
|
|
692
|
+
if (existingTables.length === 0) {
|
|
693
|
+
p.log.info("No tables yet.");
|
|
694
|
+
return;
|
|
695
|
+
}
|
|
696
|
+
let choice = forcedTable?.identifier;
|
|
697
|
+
if (!choice) {
|
|
698
|
+
const picked = await p.select({
|
|
699
|
+
message: "Remove which table?",
|
|
700
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` })),
|
|
701
|
+
});
|
|
702
|
+
if (p.isCancel(picked)) {
|
|
703
|
+
p.cancel("Cancelled.");
|
|
704
|
+
return;
|
|
705
|
+
}
|
|
706
|
+
choice = picked;
|
|
707
|
+
}
|
|
442
708
|
const confirmed = await p.confirm({
|
|
443
709
|
message: `Remove table "${choice}" from schema.ts? Nothing is dropped from the actual database until you run a migration.`,
|
|
444
710
|
initialValue: false,
|
|
@@ -449,6 +715,7 @@ async function serverConfigRemoveTable(existingTables: ParsedTable[]): Promise<v
|
|
|
449
715
|
}
|
|
450
716
|
const { filePath } = await removeTable(choice);
|
|
451
717
|
p.log.success(`Removed "${choice}" from ${filePath}. Run \`bun run db:generate\` next.`);
|
|
718
|
+
return `Removed table "${choice}"`;
|
|
452
719
|
}
|
|
453
720
|
|
|
454
721
|
function suggestMethodName(verb: HttpVerb, path: string): string {
|
|
@@ -520,7 +787,7 @@ async function runAddMethod(): Promise<void> {
|
|
|
520
787
|
message: "Path (relative to this endpoint's mount)",
|
|
521
788
|
placeholder: defaultPath,
|
|
522
789
|
initialValue: defaultPath,
|
|
523
|
-
validate: (value) => (!value
|
|
790
|
+
validate: (value) => (!value?.startsWith("/") ? 'Must start with "/".' : undefined),
|
|
524
791
|
});
|
|
525
792
|
if (p.isCancel(path)) {
|
|
526
793
|
p.cancel("Cancelled.");
|
|
@@ -534,7 +801,7 @@ async function runAddMethod(): Promise<void> {
|
|
|
534
801
|
placeholder: defaultName,
|
|
535
802
|
initialValue: defaultName,
|
|
536
803
|
validate: (value) => {
|
|
537
|
-
if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
804
|
+
if (!value || !IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
538
805
|
if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
|
|
539
806
|
return undefined;
|
|
540
807
|
},
|
|
@@ -675,7 +942,7 @@ async function serverConfigAddMethod(summaries: EndpointSummary[]): Promise<void
|
|
|
675
942
|
message: "Path (relative to this endpoint's mount)",
|
|
676
943
|
placeholder: defaultPath,
|
|
677
944
|
initialValue: defaultPath,
|
|
678
|
-
validate: (value) => (!value
|
|
945
|
+
validate: (value) => (!value?.startsWith("/") ? 'Must start with "/".' : undefined),
|
|
679
946
|
});
|
|
680
947
|
if (p.isCancel(path)) {
|
|
681
948
|
p.cancel("Cancelled.");
|
|
@@ -688,7 +955,7 @@ async function serverConfigAddMethod(summaries: EndpointSummary[]): Promise<void
|
|
|
688
955
|
placeholder: defaultName,
|
|
689
956
|
initialValue: defaultName,
|
|
690
957
|
validate: (value) => {
|
|
691
|
-
if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
958
|
+
if (!value || !IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
692
959
|
if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
|
|
693
960
|
return undefined;
|
|
694
961
|
},
|
|
@@ -798,7 +1065,7 @@ async function serverConfigModifyMethod(summaries: EndpointSummary[]): Promise<v
|
|
|
798
1065
|
const path = await p.text({
|
|
799
1066
|
message: "Path (relative to this endpoint's mount)",
|
|
800
1067
|
initialValue: old.path,
|
|
801
|
-
validate: (value) => (!value
|
|
1068
|
+
validate: (value) => (!value?.startsWith("/") ? 'Must start with "/".' : undefined),
|
|
802
1069
|
});
|
|
803
1070
|
if (p.isCancel(path)) {
|
|
804
1071
|
p.cancel("Cancelled.");
|
|
@@ -809,7 +1076,7 @@ async function serverConfigModifyMethod(summaries: EndpointSummary[]): Promise<v
|
|
|
809
1076
|
message: "Name (controller export + service function)",
|
|
810
1077
|
initialValue: old.name,
|
|
811
1078
|
validate: (value) => {
|
|
812
|
-
if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
1079
|
+
if (!value || !IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
813
1080
|
if (others.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
|
|
814
1081
|
return undefined;
|
|
815
1082
|
},
|
|
@@ -850,6 +1117,87 @@ async function serverConfigModifyMethod(summaries: EndpointSummary[]): Promise<v
|
|
|
850
1117
|
}
|
|
851
1118
|
|
|
852
1119
|
async function runServerConfig(): Promise<void> {
|
|
1120
|
+
if (process.stdin.isTTY && process.stdout.isTTY) {
|
|
1121
|
+
await runServerConfigTui({
|
|
1122
|
+
loadSnapshot: async () => {
|
|
1123
|
+
const project = await detectProject();
|
|
1124
|
+
const dbStatus = await detectDbStatus();
|
|
1125
|
+
const schemaCapable = dbStatus.driver === "neon" || dbStatus.driver === "postgres";
|
|
1126
|
+
const [endpoints, tables, doctor] = await Promise.all([
|
|
1127
|
+
listEndpointsWithMethods(),
|
|
1128
|
+
schemaCapable ? readSchemaTables() : Promise.resolve([]),
|
|
1129
|
+
runDoctor(),
|
|
1130
|
+
]);
|
|
1131
|
+
return {
|
|
1132
|
+
root: project.root,
|
|
1133
|
+
framework: project.framework,
|
|
1134
|
+
language: project.ext === "ts" ? "TypeScript" : "JavaScript",
|
|
1135
|
+
dbStatus,
|
|
1136
|
+
schemaCapable,
|
|
1137
|
+
endpoints,
|
|
1138
|
+
tables,
|
|
1139
|
+
issues: doctor.issues,
|
|
1140
|
+
};
|
|
1141
|
+
},
|
|
1142
|
+
addEndpoint: async () => {
|
|
1143
|
+
await serverConfigAddEndpoint();
|
|
1144
|
+
},
|
|
1145
|
+
removeEndpoint: async (ep) => {
|
|
1146
|
+
const summaries = await listEndpointsWithMethods();
|
|
1147
|
+
if (ep) {
|
|
1148
|
+
const confirmed = await p.confirm({
|
|
1149
|
+
message: `Remove src/endpoints/${ep.route} and unmount it? This deletes the folder.`,
|
|
1150
|
+
initialValue: false,
|
|
1151
|
+
});
|
|
1152
|
+
if (!p.isCancel(confirmed) && confirmed) await removeRoute(ep.route);
|
|
1153
|
+
} else {
|
|
1154
|
+
await serverConfigRemoveEndpoint(summaries);
|
|
1155
|
+
}
|
|
1156
|
+
},
|
|
1157
|
+
addCrud: async (ep) => {
|
|
1158
|
+
if (!ep) {
|
|
1159
|
+
await serverConfigAddEndpoint();
|
|
1160
|
+
return;
|
|
1161
|
+
}
|
|
1162
|
+
logCrudResult(await addCrudMethods(ep.route));
|
|
1163
|
+
},
|
|
1164
|
+
addMethod: async () => {
|
|
1165
|
+
await serverConfigAddMethod(await listEndpointsWithMethods());
|
|
1166
|
+
},
|
|
1167
|
+
modifyMethod: async () => {
|
|
1168
|
+
await serverConfigModifyMethod(await listEndpointsWithMethods());
|
|
1169
|
+
},
|
|
1170
|
+
removeMethod: async () => {
|
|
1171
|
+
await serverConfigRemoveMethod(await listEndpointsWithMethods());
|
|
1172
|
+
},
|
|
1173
|
+
addTable: async (tables) => {
|
|
1174
|
+
if (await ensureSchemaSupport()) await serverConfigAddTable(tables);
|
|
1175
|
+
},
|
|
1176
|
+
addJunctionTable: async (tables) => {
|
|
1177
|
+
if (await ensureSchemaSupport()) await serverConfigAddJunctionTable(tables);
|
|
1178
|
+
},
|
|
1179
|
+
addColumn: async (tbl, tables) => {
|
|
1180
|
+
if (await ensureSchemaSupport()) await serverConfigAddColumn(tables, tbl);
|
|
1181
|
+
},
|
|
1182
|
+
removeTable: async (tbl, tables) => {
|
|
1183
|
+
if (await ensureSchemaSupport()) await serverConfigRemoveTable(tables, tbl);
|
|
1184
|
+
},
|
|
1185
|
+
generateClient: async () => {
|
|
1186
|
+
const { root, ext } = await detectProject();
|
|
1187
|
+
const res = spawnSync("bun", ["run", `scripts/generate-client.${ext}`], { cwd: root, encoding: "utf-8" });
|
|
1188
|
+
if (res.status !== 0) throw new Error((res.stderr || res.stdout || "generate-client failed").trim());
|
|
1189
|
+
return "Generated client/api." + ext;
|
|
1190
|
+
},
|
|
1191
|
+
generateDocs: async () => {
|
|
1192
|
+
const { root, ext } = await detectProject();
|
|
1193
|
+
const res = spawnSync("bun", ["run", `scripts/generate-docs.${ext}`], { cwd: root, encoding: "utf-8" });
|
|
1194
|
+
if (res.status !== 0) throw new Error((res.stderr || res.stdout || "generate-docs failed").trim());
|
|
1195
|
+
return "Generated openapi.json + docs.html";
|
|
1196
|
+
},
|
|
1197
|
+
});
|
|
1198
|
+
return;
|
|
1199
|
+
}
|
|
1200
|
+
|
|
853
1201
|
p.intro("create-backon server-config");
|
|
854
1202
|
|
|
855
1203
|
// eslint-disable-next-line no-constant-condition
|
|
@@ -873,6 +1221,8 @@ async function runServerConfig(): Promise<void> {
|
|
|
873
1221
|
{ value: "remove-method", label: "Remove a method" },
|
|
874
1222
|
{ value: "modify-method", label: "Modify a method" },
|
|
875
1223
|
{ value: "add-table", label: "Add a database table" },
|
|
1224
|
+
{ value: "add-junction", label: "Add a junction table (M:N)" },
|
|
1225
|
+
{ value: "add-column", label: "Add a column to a table" },
|
|
876
1226
|
{ value: "remove-table", label: "Remove a database table" },
|
|
877
1227
|
{ value: "exit", label: "Exit" },
|
|
878
1228
|
],
|
|
@@ -899,6 +1249,12 @@ async function runServerConfig(): Promise<void> {
|
|
|
899
1249
|
case "add-table":
|
|
900
1250
|
if (await ensureSchemaSupport()) await serverConfigAddTable(await readSchemaTables());
|
|
901
1251
|
break;
|
|
1252
|
+
case "add-junction":
|
|
1253
|
+
if (await ensureSchemaSupport()) await serverConfigAddJunctionTable(await readSchemaTables());
|
|
1254
|
+
break;
|
|
1255
|
+
case "add-column":
|
|
1256
|
+
if (await ensureSchemaSupport()) await serverConfigAddColumn(await readSchemaTables());
|
|
1257
|
+
break;
|
|
902
1258
|
case "remove-table":
|
|
903
1259
|
if (await ensureSchemaSupport()) await serverConfigRemoveTable(await readSchemaTables());
|
|
904
1260
|
break;
|
|
@@ -956,6 +1312,10 @@ async function main() {
|
|
|
956
1312
|
await runAddTable(rest);
|
|
957
1313
|
return;
|
|
958
1314
|
}
|
|
1315
|
+
if (subcommand && ADD_COLUMN_SUBCOMMANDS.has(subcommand)) {
|
|
1316
|
+
await runAddColumn(rest);
|
|
1317
|
+
return;
|
|
1318
|
+
}
|
|
959
1319
|
if (subcommand && REMOVE_TABLE_SUBCOMMANDS.has(subcommand)) {
|
|
960
1320
|
await runRemoveTable(rest);
|
|
961
1321
|
return;
|