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.
- package/README.md +101 -3
- package/dist/cli.js +965 -52
- package/package.json +3 -2
- package/src/add-method.ts +26 -27
- package/src/ast-edit.ts +224 -0
- package/src/cli.ts +347 -2
- package/src/crud-scaffold.ts +62 -0
- package/src/generate.ts +11 -2
- package/src/remove-method.ts +27 -29
- package/src/schema-edit.ts +253 -0
- package/src/templates/base.ts +258 -7
- package/src/templates/db.ts +35 -4
- package/src/templates/route.ts +5 -2
- package/src/templates/schema.ts +160 -0
package/src/cli.ts
CHANGED
|
@@ -7,6 +7,8 @@
|
|
|
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 { readFile } from "node:fs/promises";
|
|
11
|
+
import { join } from "node:path";
|
|
10
12
|
import * as p from "@clack/prompts";
|
|
11
13
|
import { runPrompts } from "./prompts";
|
|
12
14
|
import { generateProject } from "./generate";
|
|
@@ -18,6 +20,7 @@ import { addMethod } from "./add-method";
|
|
|
18
20
|
import { removeMethod } from "./remove-method";
|
|
19
21
|
import { detectDbStatus } from "./db-status";
|
|
20
22
|
import { detectProject } from "./detect";
|
|
23
|
+
import { addCrudMethods } from "./crud-scaffold";
|
|
21
24
|
import {
|
|
22
25
|
detectMethodValidation,
|
|
23
26
|
formatEndpointsDashboard,
|
|
@@ -26,6 +29,8 @@ import {
|
|
|
26
29
|
type EndpointSummary,
|
|
27
30
|
} from "./route-methods";
|
|
28
31
|
import { HTTP_VERBS, paramNamesFromPath, pascalCase, type HttpVerb, type MethodSpec } from "./templates/route";
|
|
32
|
+
import { addTable, removeTable, parseSchemaTables, formatTablesDashboard, type ParsedTable } from "./schema-edit";
|
|
33
|
+
import { COLUMN_TYPES, columnIdentifier, tableIdentifier, type ColumnSpec, type ColumnType, type TableSpec } from "./templates/schema";
|
|
29
34
|
|
|
30
35
|
const ADD_ROUTE_SUBCOMMANDS = new Set(["add-route", "route"]);
|
|
31
36
|
const REMOVE_ROUTE_SUBCOMMANDS = new Set(["remove-route", "rm-route"]);
|
|
@@ -43,6 +48,8 @@ const ADD_METHOD_SUBCOMMANDS = new Set(["add-method", "method"]);
|
|
|
43
48
|
// wanted to look.
|
|
44
49
|
const PROJECT_SUBCOMMANDS = new Set(["project"]);
|
|
45
50
|
const SERVER_CONFIG_SUBCOMMANDS = new Set(["server-config"]);
|
|
51
|
+
const ADD_TABLE_SUBCOMMANDS = new Set(["add-table", "table"]);
|
|
52
|
+
const REMOVE_TABLE_SUBCOMMANDS = new Set(["remove-table", "rm-table"]);
|
|
46
53
|
|
|
47
54
|
async function promptForRouteName(introText: string): Promise<string> {
|
|
48
55
|
p.intro(introText);
|
|
@@ -58,17 +65,42 @@ async function promptForRouteName(introText: string): Promise<string> {
|
|
|
58
65
|
return answer;
|
|
59
66
|
}
|
|
60
67
|
|
|
68
|
+
/** Shared by every "just added a CRUD set" log line, interactive or scripted. */
|
|
69
|
+
function logCrudResult(result: Awaited<ReturnType<typeof addCrudMethods>>): void {
|
|
70
|
+
const skippedNote = result.skipped.length ? ` (skipped, already there: ${result.skipped.join(", ")})` : "";
|
|
71
|
+
p.log.success(`Added CRUD methods to ${result.route}: ${result.added.join(", ") || "none"}${skippedNote}`);
|
|
72
|
+
}
|
|
73
|
+
|
|
61
74
|
async function runAddRoute(args: string[]): Promise<void> {
|
|
62
|
-
|
|
75
|
+
const crudFlagIndex = args.indexOf("--crud");
|
|
76
|
+
const withCrud = crudFlagIndex !== -1;
|
|
77
|
+
const positional = withCrud ? args.filter((_, i) => i !== crudFlagIndex) : args;
|
|
78
|
+
let [name] = positional;
|
|
63
79
|
|
|
80
|
+
let interactive = false;
|
|
64
81
|
if (!name) {
|
|
82
|
+
interactive = true;
|
|
65
83
|
name = await promptForRouteName("create-backon add-route");
|
|
66
84
|
p.outro(`Adding ${name}...`);
|
|
67
85
|
}
|
|
68
86
|
|
|
69
87
|
const { route, root, filesWritten } = await addRoute(name);
|
|
70
88
|
p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
|
|
71
|
-
|
|
89
|
+
|
|
90
|
+
let scaffoldCrud = withCrud;
|
|
91
|
+
if (!withCrud && interactive) {
|
|
92
|
+
const answer = await p.confirm({
|
|
93
|
+
message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
|
|
94
|
+
initialValue: false,
|
|
95
|
+
});
|
|
96
|
+
scaffoldCrud = !p.isCancel(answer) && answer;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (scaffoldCrud) {
|
|
100
|
+
logCrudResult(await addCrudMethods(route, root));
|
|
101
|
+
} else {
|
|
102
|
+
p.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
|
|
103
|
+
}
|
|
72
104
|
}
|
|
73
105
|
|
|
74
106
|
async function runRemoveRoute(args: string[]): Promise<void> {
|
|
@@ -136,6 +168,289 @@ async function runProjectOverview(): Promise<void> {
|
|
|
136
168
|
p.outro("Manage endpoints and methods with `bun run server-config`.");
|
|
137
169
|
}
|
|
138
170
|
|
|
171
|
+
// ---------------------------------------------------------------------------
|
|
172
|
+
// add-table / remove-table / server-config's table actions — schema.ts's
|
|
173
|
+
// interactive editor. Gated to "neon"/"postgres" (the only two db choices
|
|
174
|
+
// schema.ts/drizzle.config.ts get scaffolded for — see templates/db.ts's
|
|
175
|
+
// hasSchemaSupport field); SQLite and "none" fail with a clear message
|
|
176
|
+
// rather than silently no-opping.
|
|
177
|
+
// ---------------------------------------------------------------------------
|
|
178
|
+
|
|
179
|
+
async function ensureSchemaSupport(): Promise<boolean> {
|
|
180
|
+
const status = await detectDbStatus();
|
|
181
|
+
if (status.driver === "neon" || status.driver === "postgres") return true;
|
|
182
|
+
p.log.error(
|
|
183
|
+
`Schema management needs a "neon" or "postgres" db driver (src/config/db reports "${status.driver}") — ` +
|
|
184
|
+
`SQLite and "none" use a different schema dialect (or none at all) and aren't supported here yet.`
|
|
185
|
+
);
|
|
186
|
+
return false;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function readSchemaTables(): Promise<ParsedTable[]> {
|
|
190
|
+
const { root, ext } = await detectProject();
|
|
191
|
+
try {
|
|
192
|
+
const contents = await readFile(join(root, "src/config", `schema.${ext}`), "utf-8");
|
|
193
|
+
return parseSchemaTables(contents);
|
|
194
|
+
} catch {
|
|
195
|
+
return [];
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** Type-specific "does this column get a default?" question — returns a pre-rendered modifier fragment (see ColumnSpec.defaultExpr's doc comment), "" for none, or null if cancelled. */
|
|
200
|
+
async function promptDefaultExpr(type: ColumnType): Promise<string | null> {
|
|
201
|
+
if (type === "timestamp") {
|
|
202
|
+
const v = await p.confirm({ message: "Default to now()?", initialValue: false });
|
|
203
|
+
if (p.isCancel(v)) return null;
|
|
204
|
+
return v ? ".defaultNow()" : "";
|
|
205
|
+
}
|
|
206
|
+
if (type === "uuid") {
|
|
207
|
+
const v = await p.confirm({ message: "Default to a random UUID?", initialValue: false });
|
|
208
|
+
if (p.isCancel(v)) return null;
|
|
209
|
+
return v ? ".defaultRandom()" : "";
|
|
210
|
+
}
|
|
211
|
+
if (type === "boolean") {
|
|
212
|
+
const v = await p.select({
|
|
213
|
+
message: "Default value",
|
|
214
|
+
options: [
|
|
215
|
+
{ value: "none", label: "None" },
|
|
216
|
+
{ value: "true", label: "true" },
|
|
217
|
+
{ value: "false", label: "false" },
|
|
218
|
+
],
|
|
219
|
+
initialValue: "none",
|
|
220
|
+
});
|
|
221
|
+
if (p.isCancel(v)) return null;
|
|
222
|
+
return v === "none" ? "" : `.default(${v})`;
|
|
223
|
+
}
|
|
224
|
+
// text / integer
|
|
225
|
+
const v = await p.text({
|
|
226
|
+
message: "Default value (blank for none)",
|
|
227
|
+
placeholder: type === "integer" ? "e.g. 0" : "e.g. pending",
|
|
228
|
+
});
|
|
229
|
+
if (p.isCancel(v)) return null;
|
|
230
|
+
if (!v) return "";
|
|
231
|
+
if (type === "integer") {
|
|
232
|
+
const n = Number(v);
|
|
233
|
+
if (Number.isNaN(n)) {
|
|
234
|
+
p.log.warn(`"${v}" isn't a number — skipping the default.`);
|
|
235
|
+
return "";
|
|
236
|
+
}
|
|
237
|
+
return `.default(${n})`;
|
|
238
|
+
}
|
|
239
|
+
return `.default(${JSON.stringify(v)})`;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** 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> {
|
|
244
|
+
const columns: ColumnSpec[] = [];
|
|
245
|
+
p.log.step("Add columns one at a time. Leave the name blank to finish.");
|
|
246
|
+
// eslint-disable-next-line no-constant-condition
|
|
247
|
+
while (true) {
|
|
248
|
+
const nameProbe = await p.text({
|
|
249
|
+
message: columns.length === 0 ? "Column name" : "Another column? (blank to finish)",
|
|
250
|
+
placeholder: columns.length === 0 ? "e.g. email" : "",
|
|
251
|
+
});
|
|
252
|
+
if (p.isCancel(nameProbe)) return null;
|
|
253
|
+
if (!nameProbe) break;
|
|
254
|
+
|
|
255
|
+
const key = columnIdentifier(nameProbe);
|
|
256
|
+
if (columns.some((c) => columnIdentifier(c.name) === key)) {
|
|
257
|
+
p.log.error(`"${key}" is already a column on this table.`);
|
|
258
|
+
continue;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
let references: string | undefined;
|
|
262
|
+
if (existingTables.length > 0) {
|
|
263
|
+
const refChoice = await p.select({
|
|
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 });
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
return columns;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Full table-collection flow: name (unless `forcedName` came from a CLI arg), the id-column question, then promptForColumns(). Returns null on cancel. */
|
|
301
|
+
async function collectTableSpec(existingTables: ParsedTable[], forcedName?: string): Promise<TableSpec | null> {
|
|
302
|
+
let name = forcedName;
|
|
303
|
+
if (name) {
|
|
304
|
+
const id = tableIdentifier(name);
|
|
305
|
+
if (existingTables.some((t) => t.identifier === id)) {
|
|
306
|
+
p.log.error(`"${id}" already exists.`);
|
|
307
|
+
return null;
|
|
308
|
+
}
|
|
309
|
+
} else {
|
|
310
|
+
const answer = await p.text({
|
|
311
|
+
message: "New table name",
|
|
312
|
+
placeholder: "e.g. users",
|
|
313
|
+
validate: (value) => {
|
|
314
|
+
if (!value) return "Required.";
|
|
315
|
+
if (existingTables.some((t) => t.identifier === tableIdentifier(value))) {
|
|
316
|
+
return `"${tableIdentifier(value)}" already exists.`;
|
|
317
|
+
}
|
|
318
|
+
return undefined;
|
|
319
|
+
},
|
|
320
|
+
});
|
|
321
|
+
if (p.isCancel(answer)) return null;
|
|
322
|
+
name = answer;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const includeId = await p.confirm({
|
|
326
|
+
message: "Add an auto-increment id primary key column?",
|
|
327
|
+
initialValue: true,
|
|
328
|
+
});
|
|
329
|
+
if (p.isCancel(includeId)) return null;
|
|
330
|
+
|
|
331
|
+
const columns = await promptForColumns(existingTables);
|
|
332
|
+
if (columns === null) return null;
|
|
333
|
+
|
|
334
|
+
return { name, includeId, columns };
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
async function runAddTable(args: string[]): Promise<void> {
|
|
338
|
+
p.intro("create-backon add-table");
|
|
339
|
+
if (!(await ensureSchemaSupport())) return;
|
|
340
|
+
|
|
341
|
+
const [forcedName] = args;
|
|
342
|
+
let existingTables = await readSchemaTables();
|
|
343
|
+
let first = true;
|
|
344
|
+
|
|
345
|
+
// eslint-disable-next-line no-constant-condition
|
|
346
|
+
while (true) {
|
|
347
|
+
const spec = await collectTableSpec(existingTables, first ? forcedName : undefined);
|
|
348
|
+
first = false;
|
|
349
|
+
if (!spec) {
|
|
350
|
+
p.cancel("Cancelled.");
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
try {
|
|
355
|
+
const { filePath, identifier } = await addTable(spec);
|
|
356
|
+
p.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` to create a migration for it.`);
|
|
357
|
+
existingTables = await readSchemaTables();
|
|
358
|
+
} catch (err) {
|
|
359
|
+
p.log.error(err instanceof Error ? err.message : String(err));
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const again = await p.confirm({ message: "Add another table?", initialValue: false });
|
|
363
|
+
if (p.isCancel(again) || !again) break;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
p.outro("Done.");
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function runRemoveTable(args: string[]): Promise<void> {
|
|
370
|
+
p.intro("create-backon remove-table");
|
|
371
|
+
if (!(await ensureSchemaSupport())) return;
|
|
372
|
+
|
|
373
|
+
const existingTables = await readSchemaTables();
|
|
374
|
+
if (existingTables.length === 0) {
|
|
375
|
+
p.log.info("No tables yet.");
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
const [forcedName] = args;
|
|
380
|
+
let identifier: string;
|
|
381
|
+
if (forcedName) {
|
|
382
|
+
identifier = tableIdentifier(forcedName);
|
|
383
|
+
if (!existingTables.some((t) => t.identifier === identifier)) {
|
|
384
|
+
p.log.error(`No table "${identifier}" found.`);
|
|
385
|
+
return;
|
|
386
|
+
}
|
|
387
|
+
} else {
|
|
388
|
+
const choice = await p.select({
|
|
389
|
+
message: "Remove which table?",
|
|
390
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` })),
|
|
391
|
+
});
|
|
392
|
+
if (p.isCancel(choice)) {
|
|
393
|
+
p.cancel("Cancelled.");
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
identifier = choice;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
const confirmed = await p.confirm({
|
|
400
|
+
message: `Remove table "${identifier}" from schema.ts? This only edits the file — nothing is dropped from the actual database until you run a migration.`,
|
|
401
|
+
initialValue: false,
|
|
402
|
+
});
|
|
403
|
+
if (p.isCancel(confirmed) || !confirmed) {
|
|
404
|
+
p.cancel("Cancelled.");
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
try {
|
|
409
|
+
const { filePath } = await removeTable(identifier);
|
|
410
|
+
p.log.success(`Removed "${identifier}" from ${filePath}. Run \`bun run db:generate\` to create a migration for this change.`);
|
|
411
|
+
} catch (err) {
|
|
412
|
+
p.log.error(err instanceof Error ? err.message : String(err));
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
p.outro("Done.");
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** 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> {
|
|
420
|
+
const spec = await collectTableSpec(existingTables);
|
|
421
|
+
if (!spec) {
|
|
422
|
+
p.cancel("Cancelled.");
|
|
423
|
+
return;
|
|
424
|
+
}
|
|
425
|
+
const { filePath, identifier } = await addTable(spec);
|
|
426
|
+
p.log.success(`Added table "${identifier}" to ${filePath}. Run \`bun run db:generate\` next.`);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
async function serverConfigRemoveTable(existingTables: ParsedTable[]): Promise<void> {
|
|
430
|
+
if (existingTables.length === 0) {
|
|
431
|
+
p.log.info("No tables yet.");
|
|
432
|
+
return;
|
|
433
|
+
}
|
|
434
|
+
const choice = await p.select({
|
|
435
|
+
message: "Remove which table?",
|
|
436
|
+
options: existingTables.map((t) => ({ value: t.identifier, label: `${t.identifier} (${t.columns.length} columns)` })),
|
|
437
|
+
});
|
|
438
|
+
if (p.isCancel(choice)) {
|
|
439
|
+
p.cancel("Cancelled.");
|
|
440
|
+
return;
|
|
441
|
+
}
|
|
442
|
+
const confirmed = await p.confirm({
|
|
443
|
+
message: `Remove table "${choice}" from schema.ts? Nothing is dropped from the actual database until you run a migration.`,
|
|
444
|
+
initialValue: false,
|
|
445
|
+
});
|
|
446
|
+
if (p.isCancel(confirmed) || !confirmed) {
|
|
447
|
+
p.cancel("Cancelled.");
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
const { filePath } = await removeTable(choice);
|
|
451
|
+
p.log.success(`Removed "${choice}" from ${filePath}. Run \`bun run db:generate\` next.`);
|
|
452
|
+
}
|
|
453
|
+
|
|
139
454
|
function suggestMethodName(verb: HttpVerb, path: string): string {
|
|
140
455
|
const params = paramNamesFromPath(path);
|
|
141
456
|
if (verb === "get" && params.length === 0) return "list";
|
|
@@ -280,6 +595,14 @@ async function serverConfigAddEndpoint(): Promise<void> {
|
|
|
280
595
|
}
|
|
281
596
|
const { route, filesWritten } = await addRoute(name);
|
|
282
597
|
p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet).`);
|
|
598
|
+
|
|
599
|
+
const scaffoldCrud = await p.confirm({
|
|
600
|
+
message: "Scaffold standard CRUD methods now (list, create, getById, update, remove)?",
|
|
601
|
+
initialValue: false,
|
|
602
|
+
});
|
|
603
|
+
if (!p.isCancel(scaffoldCrud) && scaffoldCrud) {
|
|
604
|
+
logCrudResult(await addCrudMethods(route));
|
|
605
|
+
}
|
|
283
606
|
}
|
|
284
607
|
|
|
285
608
|
async function serverConfigRemoveEndpoint(summaries: EndpointSummary[]): Promise<void> {
|
|
@@ -535,6 +858,12 @@ async function runServerConfig(): Promise<void> {
|
|
|
535
858
|
const summaries = await listEndpointsWithMethods();
|
|
536
859
|
p.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
537
860
|
|
|
861
|
+
const dbStatus = await detectDbStatus();
|
|
862
|
+
const schemaCapable = dbStatus.driver === "neon" || dbStatus.driver === "postgres";
|
|
863
|
+
if (schemaCapable) {
|
|
864
|
+
p.note(formatTablesDashboard(await readSchemaTables()), "Database tables");
|
|
865
|
+
}
|
|
866
|
+
|
|
538
867
|
const action = await p.select({
|
|
539
868
|
message: "What do you want to do?",
|
|
540
869
|
options: [
|
|
@@ -543,6 +872,8 @@ async function runServerConfig(): Promise<void> {
|
|
|
543
872
|
{ value: "add-method", label: "Add a method" },
|
|
544
873
|
{ value: "remove-method", label: "Remove a method" },
|
|
545
874
|
{ value: "modify-method", label: "Modify a method" },
|
|
875
|
+
{ value: "add-table", label: "Add a database table" },
|
|
876
|
+
{ value: "remove-table", label: "Remove a database table" },
|
|
546
877
|
{ value: "exit", label: "Exit" },
|
|
547
878
|
],
|
|
548
879
|
});
|
|
@@ -565,6 +896,12 @@ async function runServerConfig(): Promise<void> {
|
|
|
565
896
|
case "modify-method":
|
|
566
897
|
await serverConfigModifyMethod(summaries);
|
|
567
898
|
break;
|
|
899
|
+
case "add-table":
|
|
900
|
+
if (await ensureSchemaSupport()) await serverConfigAddTable(await readSchemaTables());
|
|
901
|
+
break;
|
|
902
|
+
case "remove-table":
|
|
903
|
+
if (await ensureSchemaSupport()) await serverConfigRemoveTable(await readSchemaTables());
|
|
904
|
+
break;
|
|
568
905
|
}
|
|
569
906
|
} catch (err) {
|
|
570
907
|
p.log.error(err instanceof Error ? err.message : String(err));
|
|
@@ -615,6 +952,14 @@ async function main() {
|
|
|
615
952
|
await runServerConfig();
|
|
616
953
|
return;
|
|
617
954
|
}
|
|
955
|
+
if (subcommand && ADD_TABLE_SUBCOMMANDS.has(subcommand)) {
|
|
956
|
+
await runAddTable(rest);
|
|
957
|
+
return;
|
|
958
|
+
}
|
|
959
|
+
if (subcommand && REMOVE_TABLE_SUBCOMMANDS.has(subcommand)) {
|
|
960
|
+
await runRemoveTable(rest);
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
618
963
|
|
|
619
964
|
await runScaffold();
|
|
620
965
|
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { addMethod } from "./add-method";
|
|
2
|
+
import { listEndpointsWithMethods } from "./route-methods";
|
|
3
|
+
import type { MethodSpec } from "./templates/route";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* The standard REST five — list/create/getById/update/remove — named to
|
|
7
|
+
* match exactly what `add-method`'s own name-suggestion logic
|
|
8
|
+
* (suggestMethodName in cli.ts) already produces for GET /, POST /,
|
|
9
|
+
* GET /:id, PUT /:id, DELETE /:id. Not a new convention, just all five of
|
|
10
|
+
* an existing one applied at once instead of one at a time.
|
|
11
|
+
*/
|
|
12
|
+
export const CRUD_METHOD_SPECS: readonly MethodSpec[] = [
|
|
13
|
+
{ verb: "get", path: "/", name: "list", needsBody: false, needsQuery: false },
|
|
14
|
+
{ verb: "post", path: "/", name: "create", needsBody: true, needsQuery: false },
|
|
15
|
+
{ verb: "get", path: "/:id", name: "getById", needsBody: false, needsQuery: false },
|
|
16
|
+
{ verb: "put", path: "/:id", name: "update", needsBody: true, needsQuery: false },
|
|
17
|
+
{ verb: "delete", path: "/:id", name: "remove", needsBody: false, needsQuery: false },
|
|
18
|
+
];
|
|
19
|
+
|
|
20
|
+
export interface AddCrudMethodsResult {
|
|
21
|
+
route: string;
|
|
22
|
+
/** Method names actually written. */
|
|
23
|
+
added: string[];
|
|
24
|
+
/** Method names skipped because the endpoint already had a same-name method, or something already mounted at that verb+path. */
|
|
25
|
+
skipped: string[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Adds the standard CRUD_METHOD_SPECS set to an already-mounted endpoint,
|
|
30
|
+
* via addMethod() — the exact same codegen a manual `add-method` run
|
|
31
|
+
* produces, just five calls run in sequence instead of one at a time.
|
|
32
|
+
* Sequential on purpose: addMethod() reads all three of an endpoint's files
|
|
33
|
+
* fresh off disk on every call, so firing five in parallel at the same
|
|
34
|
+
* endpoint would have them race on stale reads and clobber each other.
|
|
35
|
+
*
|
|
36
|
+
* Any of the five that would collide with a method the endpoint already has
|
|
37
|
+
* (same name, or the same verb+path already mounted) is skipped rather than
|
|
38
|
+
* failing the whole batch — this makes it safe to run on an endpoint that
|
|
39
|
+
* already has some hand-added methods, e.g. re-running it after removing
|
|
40
|
+
* just "remove" to get the other four without erroring on the four that are
|
|
41
|
+
* already there.
|
|
42
|
+
*/
|
|
43
|
+
export async function addCrudMethods(route: string, cwd: string = process.cwd()): Promise<AddCrudMethodsResult> {
|
|
44
|
+
const summaries = await listEndpointsWithMethods(cwd);
|
|
45
|
+
const existing = [...(summaries.find((s) => s.route === route)?.methods ?? [])];
|
|
46
|
+
|
|
47
|
+
const added: string[] = [];
|
|
48
|
+
const skipped: string[] = [];
|
|
49
|
+
|
|
50
|
+
for (const spec of CRUD_METHOD_SPECS) {
|
|
51
|
+
const collides = existing.some((m) => m.name === spec.name || (m.verb === spec.verb && m.path === spec.path));
|
|
52
|
+
if (collides) {
|
|
53
|
+
skipped.push(spec.name);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
await addMethod(route, spec, cwd);
|
|
57
|
+
added.push(spec.name);
|
|
58
|
+
existing.push({ verb: spec.verb, path: spec.path, name: spec.name });
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return { route, added, skipped };
|
|
62
|
+
}
|
package/src/generate.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
renderEndpointsIndex,
|
|
7
7
|
renderEnvExample,
|
|
8
8
|
renderExampleMiddleware,
|
|
9
|
+
renderGenerateClientScript,
|
|
9
10
|
renderGenerateDocsScript,
|
|
10
11
|
renderIndexTs,
|
|
11
12
|
renderJsconfig,
|
|
@@ -15,7 +16,8 @@ import {
|
|
|
15
16
|
renderVercelJson,
|
|
16
17
|
} from "./templates/base";
|
|
17
18
|
import { renderBlankController, renderBlankRoutes, renderBlankServices } from "./templates/route";
|
|
18
|
-
import { renderDbFile } from "./templates/db";
|
|
19
|
+
import { dbHasSchemaSupport, renderDbFile } from "./templates/db";
|
|
20
|
+
import { renderBlankSchema, renderDrizzleConfig } from "./templates/schema";
|
|
19
21
|
|
|
20
22
|
async function write(path: string, contents: string): Promise<void> {
|
|
21
23
|
await mkdir(dirname(path), { recursive: true });
|
|
@@ -94,18 +96,25 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
|
|
|
94
96
|
[join(root, "README.md"), renderReadme(readmeAnswers)],
|
|
95
97
|
[
|
|
96
98
|
join(root, ".gitignore"),
|
|
97
|
-
`node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\n${
|
|
99
|
+
`node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\nclient/\n${
|
|
98
100
|
answers.deployTarget === "vercel" ? ".vercel\n" : ""
|
|
99
101
|
}`,
|
|
100
102
|
],
|
|
101
103
|
[join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
|
|
102
104
|
[join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
|
|
105
|
+
...(dbHasSchemaSupport(answers.db)
|
|
106
|
+
? ([
|
|
107
|
+
[join(root, `src/config/schema.${ext}`), renderBlankSchema()],
|
|
108
|
+
[join(root, "drizzle.config.ts"), renderDrizzleConfig(ext)],
|
|
109
|
+
] as Array<[string, string]>)
|
|
110
|
+
: []),
|
|
103
111
|
[
|
|
104
112
|
join(root, `src/middleware/example.middleware.${ext}`),
|
|
105
113
|
renderExampleMiddleware(answers.framework, answers.language),
|
|
106
114
|
],
|
|
107
115
|
[join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
|
|
108
116
|
[join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
|
|
117
|
+
[join(root, `scripts/generate-client.${ext}`), renderGenerateClientScript(answers.language)],
|
|
109
118
|
...(answers.deployTarget === "vercel"
|
|
110
119
|
? ([[join(root, "vercel.json"), renderVercelJson()]] as Array<[string, string]>)
|
|
111
120
|
: []),
|
package/src/remove-method.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { readFile, writeFile } from "node:fs/promises";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { editSource, removeControllerMethod, removeRouteMount, removeServiceMethod } from "./ast-edit";
|
|
3
4
|
import { detectProject } from "./detect";
|
|
4
5
|
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
5
6
|
import { parseRouteMethods } from "./route-methods";
|
|
6
|
-
import { renderBlankController, renderBlankRoutes, renderBlankServices,
|
|
7
|
+
import { renderBlankController, renderBlankRoutes, renderBlankServices, type HttpVerb } from "./templates/route";
|
|
7
8
|
|
|
8
9
|
export interface RemoveMethodResult {
|
|
9
10
|
route: string;
|
|
@@ -11,32 +12,25 @@ export interface RemoveMethodResult {
|
|
|
11
12
|
removed: { verb: HttpVerb; path: string; name: string };
|
|
12
13
|
}
|
|
13
14
|
|
|
14
|
-
/**
|
|
15
|
-
* addMethod() appends each method as its own \n\n-delimited block (see
|
|
16
|
-
* appendBlock() in add-method.ts) — imports/the Router()-or-Hono()
|
|
17
|
-
* declaration are their own leading block, then one block per method, in
|
|
18
|
-
* insertion order, nothing else in between. That's what makes this safe:
|
|
19
|
-
* find the one block matching the predicate and drop it, leaving every
|
|
20
|
-
* other block (including the leading one) untouched.
|
|
21
|
-
*/
|
|
22
|
-
function removeBlock(content: string, matches: (block: string) => boolean): string {
|
|
23
|
-
const blocks = content.split(/\n\n+/);
|
|
24
|
-
const index = blocks.findIndex(matches);
|
|
25
|
-
if (index === -1) return content;
|
|
26
|
-
blocks.splice(index, 1);
|
|
27
|
-
const joined = blocks.filter((b) => b.length > 0).join("\n\n");
|
|
28
|
-
return joined ? `${joined}\n` : "";
|
|
29
|
-
}
|
|
30
|
-
|
|
31
15
|
/**
|
|
32
16
|
* The undo for addMethod(): strips one method's mount line from
|
|
33
17
|
* *.routes.<ext>, its defineRoute() export (plus any params/body/query
|
|
34
|
-
* schema consts) from *.controller.<ext>, and its matching function
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* endpoint, not globally).
|
|
18
|
+
* schema consts) from *.controller.<ext>, and its matching function (plus
|
|
19
|
+
* its now-unused schema-type import, if any) from *.services.<ext>.
|
|
20
|
+
* Identified by verb+path, the same pair addMethod() itself refuses to let
|
|
21
|
+
* collide — not by name alone, since two different verb/path pairs could
|
|
22
|
+
* theoretically end up with the same name checked against different
|
|
23
|
+
* endpoints (name uniqueness is only enforced per endpoint, not globally).
|
|
24
|
+
*
|
|
25
|
+
* Every removal goes through ast-edit.ts's ts-morph helpers, which find
|
|
26
|
+
* each method's statements by their actual declared/exported name — the
|
|
27
|
+
* same uniqueness addMethod() enforces — rather than by which \n\n-
|
|
28
|
+
* delimited block of text they happen to sit in. That matters because
|
|
29
|
+
* parseRouteMethods() (used above to confirm the method exists) reads
|
|
30
|
+
* mount lines with a lenient regex that tolerates reformatting; the old
|
|
31
|
+
* text-block removal required an exact line match after that same
|
|
32
|
+
* reformatting and could silently fail to find anything to remove, leaving
|
|
33
|
+
* the controller/services files changed but the route still mounted.
|
|
40
34
|
*
|
|
41
35
|
* Removing the last method on an endpoint resets all three files back to
|
|
42
36
|
* their blank, freshly-scaffolded shape (renderBlank*()) rather than
|
|
@@ -84,11 +78,15 @@ export async function removeMethod(
|
|
|
84
78
|
return { route, root, removed: match };
|
|
85
79
|
}
|
|
86
80
|
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const newRoutes =
|
|
91
|
-
|
|
81
|
+
const newController = editSource(controllerPath, controllerContents, (_project, sourceFile) => {
|
|
82
|
+
removeControllerMethod(sourceFile, name);
|
|
83
|
+
});
|
|
84
|
+
const newRoutes = editSource(routesPath, routesContents, (_project, sourceFile) => {
|
|
85
|
+
removeRouteMount(sourceFile, name);
|
|
86
|
+
});
|
|
87
|
+
const newServices = editSource(servicesPath, servicesContents, (_project, sourceFile) => {
|
|
88
|
+
removeServiceMethod(sourceFile, name);
|
|
89
|
+
});
|
|
92
90
|
|
|
93
91
|
await Promise.all([
|
|
94
92
|
writeFile(controllerPath, newController),
|