create-backon 0.6.2 → 0.10.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 +141 -12
- package/dist/cli.js +1675 -0
- package/package.json +10 -6
- package/src/add-method.ts +101 -0
- package/src/add-route.ts +11 -9
- package/src/cli.ts +512 -3
- package/src/colors.ts +35 -0
- package/src/db-status.ts +117 -0
- package/src/generate.ts +17 -6
- package/src/prompts.ts +26 -0
- package/src/remove-method.ts +100 -0
- package/src/route-methods.ts +100 -0
- package/src/templates/base.ts +95 -5
- package/src/templates/route.ts +143 -64
package/dist/cli.js
ADDED
|
@@ -0,0 +1,1675 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/cli.ts
|
|
4
|
+
import * as p2 from "@clack/prompts";
|
|
5
|
+
|
|
6
|
+
// src/prompts.ts
|
|
7
|
+
import * as p from "@clack/prompts";
|
|
8
|
+
function bail() {
|
|
9
|
+
p.cancel("Cancelled.");
|
|
10
|
+
process.exit(0);
|
|
11
|
+
}
|
|
12
|
+
function toKebabCase(input) {
|
|
13
|
+
return input.trim().replace(/([a-z0-9])([A-Z])/g, "$1-$2").replace(/[\s_]+/g, "-").toLowerCase();
|
|
14
|
+
}
|
|
15
|
+
async function runPrompts() {
|
|
16
|
+
p.intro("create-backon");
|
|
17
|
+
const projectName = await p.text({
|
|
18
|
+
message: 'Project name (or "." to scaffold into the current directory)',
|
|
19
|
+
placeholder: "my-api",
|
|
20
|
+
validate: (value) => {
|
|
21
|
+
if (!value) return "Required.";
|
|
22
|
+
if (value === ".") return void 0;
|
|
23
|
+
if (!/^[a-z0-9-]+$/.test(value)) {
|
|
24
|
+
return 'Lowercase letters, numbers, and hyphens only (or "." for the current directory).';
|
|
25
|
+
}
|
|
26
|
+
return void 0;
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
if (p.isCancel(projectName)) bail();
|
|
30
|
+
const framework = await p.select({
|
|
31
|
+
message: "Framework",
|
|
32
|
+
options: [
|
|
33
|
+
{ value: "hono", label: "Hono", hint: "faster, runs anywhere \u2014 Bun, edge, serverless" },
|
|
34
|
+
{ value: "express", label: "Express" }
|
|
35
|
+
]
|
|
36
|
+
});
|
|
37
|
+
if (p.isCancel(framework)) bail();
|
|
38
|
+
const language = await p.select({
|
|
39
|
+
message: "Language",
|
|
40
|
+
options: [
|
|
41
|
+
{ value: "typescript", label: "TypeScript" },
|
|
42
|
+
{ value: "javascript", label: "JavaScript" }
|
|
43
|
+
]
|
|
44
|
+
});
|
|
45
|
+
if (p.isCancel(language)) bail();
|
|
46
|
+
const db = await p.select({
|
|
47
|
+
message: "Database",
|
|
48
|
+
options: [
|
|
49
|
+
{ value: "neon", label: "Neon", hint: "serverless Postgres \u2014 matches a Vercel deploy" },
|
|
50
|
+
{ value: "postgres", label: "Postgres", hint: "local/self-hosted \u2014 dev or a long-running server only" },
|
|
51
|
+
{ value: "sqlite", label: "SQLite", hint: "local dev only" },
|
|
52
|
+
{ value: "none", label: "None", hint: "empty db.ts stub, wire it up later" }
|
|
53
|
+
]
|
|
54
|
+
});
|
|
55
|
+
if (p.isCancel(db)) bail();
|
|
56
|
+
const deployTarget = await p.select({
|
|
57
|
+
message: "Where's this headed?",
|
|
58
|
+
options: [
|
|
59
|
+
{
|
|
60
|
+
value: "vercel",
|
|
61
|
+
label: "Vercel",
|
|
62
|
+
hint: "adds vercel.json + a default export so it deploys with zero config"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
value: "node",
|
|
66
|
+
label: "Another Node/Bun host",
|
|
67
|
+
hint: "Render, Railway, Fly, a VPS \u2014 index.ts's serve() already listens on PORT, nothing extra needed"
|
|
68
|
+
},
|
|
69
|
+
{ value: "local", label: "Local / self-hosted only", hint: "no deploy scaffolding added" },
|
|
70
|
+
{ value: "undecided", label: "Not sure yet", hint: "same as local for now \u2014 figure it out later" }
|
|
71
|
+
]
|
|
72
|
+
});
|
|
73
|
+
if (p.isCancel(deployTarget)) bail();
|
|
74
|
+
const copyEnv = await p.confirm({
|
|
75
|
+
message: "Create .env from .env.example now?",
|
|
76
|
+
initialValue: true
|
|
77
|
+
});
|
|
78
|
+
if (p.isCancel(copyEnv)) bail();
|
|
79
|
+
const routes = [];
|
|
80
|
+
p.log.step("Add routes one at a time. Leave the name blank to finish.");
|
|
81
|
+
while (true) {
|
|
82
|
+
const name = await p.text({
|
|
83
|
+
message: routes.length === 0 ? "Route name" : "Another route? (blank to finish)",
|
|
84
|
+
placeholder: routes.length === 0 ? "e.g. users" : ""
|
|
85
|
+
});
|
|
86
|
+
if (p.isCancel(name)) bail();
|
|
87
|
+
if (!name) break;
|
|
88
|
+
routes.push(toKebabCase(name));
|
|
89
|
+
}
|
|
90
|
+
p.outro(`Scaffolding ${projectName}...`);
|
|
91
|
+
return {
|
|
92
|
+
projectName,
|
|
93
|
+
framework,
|
|
94
|
+
language,
|
|
95
|
+
db,
|
|
96
|
+
routes,
|
|
97
|
+
copyEnv,
|
|
98
|
+
deployTarget
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// src/generate.ts
|
|
103
|
+
import { mkdir, readdir, writeFile } from "node:fs/promises";
|
|
104
|
+
import { basename, dirname, join } from "node:path";
|
|
105
|
+
|
|
106
|
+
// src/templates/route.ts
|
|
107
|
+
function pascalCase(name) {
|
|
108
|
+
return name.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
109
|
+
}
|
|
110
|
+
function camelCase(name) {
|
|
111
|
+
const [first, ...rest] = name.split("-");
|
|
112
|
+
return [first, ...rest.map((part) => part.charAt(0).toUpperCase() + part.slice(1))].join("");
|
|
113
|
+
}
|
|
114
|
+
var HTTP_VERBS = ["get", "post", "put", "patch", "delete"];
|
|
115
|
+
function paramNamesFromPath(path) {
|
|
116
|
+
return [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]).filter((name) => name !== void 0);
|
|
117
|
+
}
|
|
118
|
+
var PLACEHOLDER_COMMENT = "// No methods yet \u2014 run `bun run add-method` to add one.";
|
|
119
|
+
function renderBlankController() {
|
|
120
|
+
return `${PLACEHOLDER_COMMENT}
|
|
121
|
+
`;
|
|
122
|
+
}
|
|
123
|
+
function renderBlankRoutes(route, framework, language) {
|
|
124
|
+
const varName = `${camelCase(route)}Routes`;
|
|
125
|
+
if (framework === "express") {
|
|
126
|
+
return `import { Router } from "@mednours/backon/express";
|
|
127
|
+
|
|
128
|
+
export const ${varName} = Router();
|
|
129
|
+
|
|
130
|
+
${PLACEHOLDER_COMMENT}
|
|
131
|
+
`;
|
|
132
|
+
}
|
|
133
|
+
if (language === "javascript") {
|
|
134
|
+
return `import { Hono } from "@mednours/backon";
|
|
135
|
+
|
|
136
|
+
export const ${varName} = new Hono();
|
|
137
|
+
|
|
138
|
+
${PLACEHOLDER_COMMENT}
|
|
139
|
+
`;
|
|
140
|
+
}
|
|
141
|
+
return `import { Hono, type Env } from "@mednours/backon";
|
|
142
|
+
|
|
143
|
+
export const ${varName} = new Hono<Env>();
|
|
144
|
+
|
|
145
|
+
${PLACEHOLDER_COMMENT}
|
|
146
|
+
`;
|
|
147
|
+
}
|
|
148
|
+
function renderBlankServices() {
|
|
149
|
+
return `// No routes yet \u2014 service functions land here as methods are added via \`bun run add-method\`.
|
|
150
|
+
`;
|
|
151
|
+
}
|
|
152
|
+
function defaultServiceReturn(spec) {
|
|
153
|
+
const { verb, needsBody } = spec;
|
|
154
|
+
const hasParams = paramNamesFromPath(spec.path).length > 0;
|
|
155
|
+
if (verb === "get" && !hasParams) return "return [];";
|
|
156
|
+
if (verb === "get") return "return null; // TODO: fetch the real record";
|
|
157
|
+
if (verb === "post") return needsBody ? "return { id: crypto.randomUUID(), ...body };" : "return { id: crypto.randomUUID() };";
|
|
158
|
+
if (verb === "put" || verb === "patch") return needsBody ? "return { ...params, ...body };" : "return { ...params };";
|
|
159
|
+
return "return { success: true };";
|
|
160
|
+
}
|
|
161
|
+
function serviceCallArgs(spec) {
|
|
162
|
+
const args = [];
|
|
163
|
+
if (paramNamesFromPath(spec.path).length > 0) args.push("params");
|
|
164
|
+
if (spec.needsBody) args.push("body");
|
|
165
|
+
if (spec.needsQuery) args.push("query");
|
|
166
|
+
return args;
|
|
167
|
+
}
|
|
168
|
+
function serviceParamList(spec) {
|
|
169
|
+
const parts = [];
|
|
170
|
+
if (paramNamesFromPath(spec.path).length > 0) parts.push(`params: z.infer<typeof ${spec.name}ParamsSchema>`);
|
|
171
|
+
if (spec.needsBody) parts.push(`body: z.infer<typeof ${spec.name}BodySchema>`);
|
|
172
|
+
if (spec.needsQuery) parts.push(`query: z.infer<typeof ${spec.name}QuerySchema>`);
|
|
173
|
+
return parts.join(", ");
|
|
174
|
+
}
|
|
175
|
+
function controllerImports(route, framework) {
|
|
176
|
+
const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
177
|
+
return [`import { z } from "zod";`, `import { defineRoute } from "${backonImport}";`, `import * as service from "./${route}.services";`];
|
|
178
|
+
}
|
|
179
|
+
function renderControllerMethod(spec) {
|
|
180
|
+
const paramNames = paramNamesFromPath(spec.path);
|
|
181
|
+
const lines = [];
|
|
182
|
+
if (paramNames.length > 0) {
|
|
183
|
+
const shape = paramNames.map((name) => `${name}: z.string()`).join(", ");
|
|
184
|
+
lines.push(`export const ${spec.name}ParamsSchema = z.object({ ${shape} });`);
|
|
185
|
+
}
|
|
186
|
+
if (spec.needsBody) {
|
|
187
|
+
lines.push(`// TODO: replace with the real shape of "${spec.name}"'s request body`);
|
|
188
|
+
lines.push(`export const ${spec.name}BodySchema = z.object({});`);
|
|
189
|
+
}
|
|
190
|
+
if (spec.needsQuery) {
|
|
191
|
+
lines.push(`// TODO: replace with the real shape of "${spec.name}"'s query params`);
|
|
192
|
+
lines.push(`export const ${spec.name}QuerySchema = z.object({});`);
|
|
193
|
+
}
|
|
194
|
+
const schemaEntries = [];
|
|
195
|
+
if (paramNames.length > 0) schemaEntries.push(`params: ${spec.name}ParamsSchema`);
|
|
196
|
+
if (spec.needsBody) schemaEntries.push(`body: ${spec.name}BodySchema`);
|
|
197
|
+
if (spec.needsQuery) schemaEntries.push(`query: ${spec.name}QuerySchema`);
|
|
198
|
+
const schemaObject = schemaEntries.length > 0 ? `{ ${schemaEntries.join(", ")} }` : "{}";
|
|
199
|
+
const callArgs = serviceCallArgs(spec).join(", ");
|
|
200
|
+
const status = spec.verb === "post" ? ", 201" : "";
|
|
201
|
+
lines.push(
|
|
202
|
+
`export const ${spec.name} = defineRoute(${schemaObject}, async (c, { body, query, params }) => {`,
|
|
203
|
+
` const result = await service.${spec.name}(${callArgs});`,
|
|
204
|
+
` return c.json(result${status});`,
|
|
205
|
+
`});`
|
|
206
|
+
);
|
|
207
|
+
return lines.join("\n");
|
|
208
|
+
}
|
|
209
|
+
function routeMountLine(route, spec) {
|
|
210
|
+
return `${camelCase(route)}Routes.${spec.verb}("${spec.path}", controller.${spec.name});`;
|
|
211
|
+
}
|
|
212
|
+
function serviceImports(route, spec, language) {
|
|
213
|
+
if (language === "javascript") return [];
|
|
214
|
+
const imports = [`import type { z } from "zod";`];
|
|
215
|
+
const named = [];
|
|
216
|
+
if (paramNamesFromPath(spec.path).length > 0) named.push(`${spec.name}ParamsSchema`);
|
|
217
|
+
if (spec.needsBody) named.push(`${spec.name}BodySchema`);
|
|
218
|
+
if (spec.needsQuery) named.push(`${spec.name}QuerySchema`);
|
|
219
|
+
if (named.length > 0) imports.push(`import type { ${named.join(", ")} } from "./${route}.controller";`);
|
|
220
|
+
return imports;
|
|
221
|
+
}
|
|
222
|
+
function renderServiceMethod(spec, language) {
|
|
223
|
+
const ext = language === "javascript" ? "js" : "ts";
|
|
224
|
+
const argList = language === "javascript" ? serviceCallArgs(spec).join(", ") : serviceParamList(spec);
|
|
225
|
+
return `// TODO: replace with real data access (see src/config/db.${ext})
|
|
226
|
+
export async function ${spec.name}(${argList}) {
|
|
227
|
+
${defaultServiceReturn(spec)}
|
|
228
|
+
}`;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/templates/db.ts
|
|
232
|
+
var TEMPLATES = {
|
|
233
|
+
neon: {
|
|
234
|
+
file: `import { drizzle } from "drizzle-orm/neon-http";
|
|
235
|
+
import { neon } from "@neondatabase/serverless";
|
|
236
|
+
|
|
237
|
+
if (!process.env.DATABASE_URL) {
|
|
238
|
+
throw new Error("DATABASE_URL is required (Neon connection string)");
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
const sql = neon(process.env.DATABASE_URL);
|
|
242
|
+
|
|
243
|
+
export const db = drizzle(sql);
|
|
244
|
+
`,
|
|
245
|
+
dependencies: {
|
|
246
|
+
"drizzle-orm": "^0.38.2",
|
|
247
|
+
"@neondatabase/serverless": "^0.10.4"
|
|
248
|
+
},
|
|
249
|
+
envVars: "DATABASE_URL=postgres://user:password@ep-example-123456.us-east-2.aws.neon.tech/dbname?sslmode=require\n",
|
|
250
|
+
readmeNote: "Uses Neon's HTTP driver \u2014 no connection pooling to manage, which is what makes it safe to use from serverless functions (e.g. Vercel)."
|
|
251
|
+
},
|
|
252
|
+
postgres: {
|
|
253
|
+
file: `import { drizzle } from "drizzle-orm/node-postgres";
|
|
254
|
+
import { Pool } from "pg";
|
|
255
|
+
|
|
256
|
+
// NOTE: this pooled connection is for local dev or a long-running server
|
|
257
|
+
// (Docker, a VPS, Render, etc). It is NOT safe to use as-is on Vercel
|
|
258
|
+
// serverless functions \u2014 each cold start can open a new connection until
|
|
259
|
+
// the database's connection limit is exhausted. Use the "neon" db option
|
|
260
|
+
// instead for serverless deploys.
|
|
261
|
+
|
|
262
|
+
if (!process.env.DATABASE_URL) {
|
|
263
|
+
throw new Error("DATABASE_URL is required");
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const pool = new Pool({ connectionString: process.env.DATABASE_URL });
|
|
267
|
+
|
|
268
|
+
export const db = drizzle(pool);
|
|
269
|
+
`,
|
|
270
|
+
dependencies: {
|
|
271
|
+
"drizzle-orm": "^0.38.2",
|
|
272
|
+
pg: "^8.13.1"
|
|
273
|
+
},
|
|
274
|
+
envVars: "DATABASE_URL=postgres://user:password@localhost:5432/dbname\n",
|
|
275
|
+
readmeNote: "Pooled Postgres connection \u2014 fine for local dev or a long-running server, NOT safe as-is on Vercel serverless functions (connection pool exhaustion on cold starts). Use Neon for serverless deploys."
|
|
276
|
+
},
|
|
277
|
+
sqlite: {
|
|
278
|
+
file: `import { drizzle } from "drizzle-orm/bun-sqlite";
|
|
279
|
+
import { Database } from "bun:sqlite";
|
|
280
|
+
|
|
281
|
+
// NOTE: local dev only. A serverless function's filesystem is ephemeral \u2014
|
|
282
|
+
// this file won't persist between invocations if deployed as-is.
|
|
283
|
+
|
|
284
|
+
const sqlite = new Database(process.env.DATABASE_URL ?? "./dev.db");
|
|
285
|
+
|
|
286
|
+
export const db = drizzle(sqlite);
|
|
287
|
+
`,
|
|
288
|
+
dependencies: {
|
|
289
|
+
"drizzle-orm": "^0.38.2"
|
|
290
|
+
},
|
|
291
|
+
envVars: "DATABASE_URL=./dev.db\n",
|
|
292
|
+
readmeNote: "Local file-based SQLite \u2014 for local dev only, not for a serverless deploy target."
|
|
293
|
+
},
|
|
294
|
+
none: {
|
|
295
|
+
file: `// No database configured yet. Wire up a real client here \u2014 e.g. one of
|
|
296
|
+
// the neon/postgres/sqlite variants this CLI can also generate \u2014 and
|
|
297
|
+
// export it as \`db\` so src/endpoints/*/*.services.ts can import it.
|
|
298
|
+
|
|
299
|
+
export const db = undefined;
|
|
300
|
+
`,
|
|
301
|
+
dependencies: {},
|
|
302
|
+
envVars: "",
|
|
303
|
+
readmeNote: "No database configured. src/config/db.ts is an empty stub."
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
function renderDbFile(db) {
|
|
307
|
+
return TEMPLATES[db].file;
|
|
308
|
+
}
|
|
309
|
+
function dbDependencies(db) {
|
|
310
|
+
return TEMPLATES[db].dependencies;
|
|
311
|
+
}
|
|
312
|
+
function dbEnvVars(db) {
|
|
313
|
+
return TEMPLATES[db].envVars;
|
|
314
|
+
}
|
|
315
|
+
function dbReadmeNote(db) {
|
|
316
|
+
return TEMPLATES[db].readmeNote;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// src/templates/base.ts
|
|
320
|
+
function renderIndexTs(framework) {
|
|
321
|
+
const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
322
|
+
const call = framework === "express" ? "serve(app);" : "await serve(app);";
|
|
323
|
+
return `import { serve } from "${backonImport}";
|
|
324
|
+
import { app } from "./src/app";
|
|
325
|
+
|
|
326
|
+
${call}
|
|
327
|
+
`;
|
|
328
|
+
}
|
|
329
|
+
function renderAppTs(projectName, framework, deployTarget) {
|
|
330
|
+
const defaultExport = deployTarget === "vercel" ? `
|
|
331
|
+
// Vercel deploys straight from this export \u2014 see vercel.json.
|
|
332
|
+
export default app;
|
|
333
|
+
` : "";
|
|
334
|
+
if (framework === "express") {
|
|
335
|
+
return `import { createApp, serveApiDocs } from "@mednours/backon/express";
|
|
336
|
+
import { endpoints } from "./endpoints";
|
|
337
|
+
import { exampleMiddleware } from "./middleware/example.middleware";
|
|
338
|
+
|
|
339
|
+
export const app = createApp();
|
|
340
|
+
|
|
341
|
+
app.use(exampleMiddleware);
|
|
342
|
+
app.use("/", endpoints);
|
|
343
|
+
|
|
344
|
+
serveApiDocs(app, "/docs", { title: "${projectName}" });
|
|
345
|
+
${defaultExport}`;
|
|
346
|
+
}
|
|
347
|
+
return `import { createApp, serveApiDocs } from "@mednours/backon";
|
|
348
|
+
import { endpoints } from "./endpoints";
|
|
349
|
+
import { exampleMiddleware } from "./middleware/example.middleware";
|
|
350
|
+
|
|
351
|
+
export const app = createApp();
|
|
352
|
+
|
|
353
|
+
app.use("*", exampleMiddleware);
|
|
354
|
+
app.route("/", endpoints);
|
|
355
|
+
|
|
356
|
+
serveApiDocs(app, "/docs", { title: "${projectName}" });
|
|
357
|
+
${defaultExport}`;
|
|
358
|
+
}
|
|
359
|
+
function renderVercelJson() {
|
|
360
|
+
return `{
|
|
361
|
+
"$schema": "https://openapi.vercel.sh/vercel.json",
|
|
362
|
+
"bunVersion": "1.x"
|
|
363
|
+
}
|
|
364
|
+
`;
|
|
365
|
+
}
|
|
366
|
+
function renderExampleMiddleware(framework, language) {
|
|
367
|
+
if (framework === "express") {
|
|
368
|
+
if (language === "javascript") {
|
|
369
|
+
return `/**
|
|
370
|
+
* Example middleware, just to show the pattern \u2014 stamps a request-start
|
|
371
|
+
* timestamp onto res.locals. Error handling, request logging, secure
|
|
372
|
+
* headers, CORS, and the request body size limit are already wired into
|
|
373
|
+
* createApp() by backon itself; a separate
|
|
374
|
+
* error.middleware.js is only needed to override that default behavior.
|
|
375
|
+
*
|
|
376
|
+
* This is plain Express middleware (req, res, next), not backon's
|
|
377
|
+
* BackonContext \u2014 that wrapper only exists inside defineRoute() handlers.
|
|
378
|
+
* Middleware always operates at the framework's own layer. (Also: Express
|
|
379
|
+
* middleware can't safely set a response header after calling next() \u2014 by
|
|
380
|
+
* then the response may already be sent \u2014 which is why this demonstrates
|
|
381
|
+
* res.locals instead of a header.)
|
|
382
|
+
*
|
|
383
|
+
* @param {import("@mednours/backon/express").Request} req
|
|
384
|
+
* @param {import("@mednours/backon/express").Response} res
|
|
385
|
+
* @param {import("@mednours/backon/express").NextFunction} next
|
|
386
|
+
*/
|
|
387
|
+
export function exampleMiddleware(req, res, next) {
|
|
388
|
+
res.locals.requestStartedAt = Date.now();
|
|
389
|
+
next();
|
|
390
|
+
}
|
|
391
|
+
`;
|
|
392
|
+
}
|
|
393
|
+
return `import type { Request, Response, NextFunction } from "@mednours/backon/express";
|
|
394
|
+
|
|
395
|
+
/**
|
|
396
|
+
* Example middleware, just to show the pattern \u2014 stamps a request-start
|
|
397
|
+
* timestamp onto res.locals. Error handling, request logging, secure
|
|
398
|
+
* headers, CORS, and the request body size limit are already wired into
|
|
399
|
+
* createApp() by backon itself; a separate
|
|
400
|
+
* error.middleware.ts is only needed to override that default behavior.
|
|
401
|
+
*
|
|
402
|
+
* This is plain Express middleware (req, res, next), not backon's
|
|
403
|
+
* BackonContext \u2014 that wrapper only exists inside defineRoute() handlers.
|
|
404
|
+
* Middleware always operates at the framework's own layer. (Also: Express
|
|
405
|
+
* middleware can't safely set a response header after calling next() \u2014 by
|
|
406
|
+
* then the response may already be sent \u2014 which is why this demonstrates
|
|
407
|
+
* res.locals instead of a header.)
|
|
408
|
+
*/
|
|
409
|
+
export function exampleMiddleware(req: Request, res: Response, next: NextFunction) {
|
|
410
|
+
res.locals.requestStartedAt = Date.now();
|
|
411
|
+
next();
|
|
412
|
+
}
|
|
413
|
+
`;
|
|
414
|
+
}
|
|
415
|
+
if (language === "javascript") {
|
|
416
|
+
return `/**
|
|
417
|
+
* Example middleware, just to show the pattern \u2014 adds a response-time
|
|
418
|
+
* header. Error handling, request logging, secure headers, CORS, and the
|
|
419
|
+
* request body size limit are already wired into createApp() by backon
|
|
420
|
+
* itself; a separate error.middleware.js is only needed to override that
|
|
421
|
+
* default behavior.
|
|
422
|
+
*
|
|
423
|
+
* @param {import("@mednours/backon").BackonContext} c
|
|
424
|
+
* @param {import("@mednours/backon").Next} next
|
|
425
|
+
*/
|
|
426
|
+
export async function exampleMiddleware(c, next) {
|
|
427
|
+
const start = performance.now();
|
|
428
|
+
await next();
|
|
429
|
+
c.header("x-response-time-ms", String(Math.round(performance.now() - start)));
|
|
430
|
+
}
|
|
431
|
+
`;
|
|
432
|
+
}
|
|
433
|
+
return `import type { Next } from "@mednours/backon";
|
|
434
|
+
import type { BackonContext } from "@mednours/backon";
|
|
435
|
+
|
|
436
|
+
/**
|
|
437
|
+
* Example middleware, just to show the pattern \u2014 adds a response-time
|
|
438
|
+
* header. Error handling, request logging, secure headers, CORS, and the
|
|
439
|
+
* request body size limit are already wired into createApp() by backon
|
|
440
|
+
* itself; a separate error.middleware.ts is only needed to override that
|
|
441
|
+
* default behavior.
|
|
442
|
+
*/
|
|
443
|
+
export async function exampleMiddleware(c: BackonContext, next: Next) {
|
|
444
|
+
const start = performance.now();
|
|
445
|
+
await next();
|
|
446
|
+
c.header("x-response-time-ms", String(Math.round(performance.now() - start)));
|
|
447
|
+
}
|
|
448
|
+
`;
|
|
449
|
+
}
|
|
450
|
+
function renderEndpointsIndex(framework, routes) {
|
|
451
|
+
const imports = routes.map((route) => `import { ${camelCase(route)}Routes } from "./${route}/${route}.routes";`).join("\n");
|
|
452
|
+
if (framework === "express") {
|
|
453
|
+
const mounts2 = routes.map((route) => `endpoints.use("/${route}", ${camelCase(route)}Routes);`).join("\n");
|
|
454
|
+
return `import { Router } from "@mednours/backon/express";
|
|
455
|
+
${imports}
|
|
456
|
+
|
|
457
|
+
export const endpoints = Router();
|
|
458
|
+
|
|
459
|
+
${mounts2}
|
|
460
|
+
`;
|
|
461
|
+
}
|
|
462
|
+
const mounts = routes.map((route) => `endpoints.route("/${route}", ${camelCase(route)}Routes);`).join("\n");
|
|
463
|
+
return `import { Hono } from "@mednours/backon";
|
|
464
|
+
${imports}
|
|
465
|
+
|
|
466
|
+
export const endpoints = new Hono();
|
|
467
|
+
|
|
468
|
+
${mounts}
|
|
469
|
+
`;
|
|
470
|
+
}
|
|
471
|
+
function renderGenerateDocsScript(projectName, framework) {
|
|
472
|
+
const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
473
|
+
return `import { writeFileSync } from "node:fs";
|
|
474
|
+
import { generateOpenApiSpec, apiReferenceHtmlInline } from "${backonImport}";
|
|
475
|
+
import { app } from "../src/app";
|
|
476
|
+
|
|
477
|
+
const spec = generateOpenApiSpec(app, { title: "${projectName}", version: "0.1.0" });
|
|
478
|
+
writeFileSync("openapi.json", JSON.stringify(spec, null, 2));
|
|
479
|
+
writeFileSync("docs.html", apiReferenceHtmlInline(spec, "${projectName}"));
|
|
480
|
+
|
|
481
|
+
console.log("Wrote openapi.json and docs.html");
|
|
482
|
+
`;
|
|
483
|
+
}
|
|
484
|
+
function renderEnvExample(db) {
|
|
485
|
+
return `PORT=3000
|
|
486
|
+
ALLOWED_ORIGINS=
|
|
487
|
+
${dbEnvVars(db)}`;
|
|
488
|
+
}
|
|
489
|
+
function renderTsconfig() {
|
|
490
|
+
return `{
|
|
491
|
+
"compilerOptions": {
|
|
492
|
+
"target": "ESNext",
|
|
493
|
+
"module": "ESNext",
|
|
494
|
+
"moduleResolution": "bundler",
|
|
495
|
+
"lib": ["ESNext"],
|
|
496
|
+
"types": ["bun"],
|
|
497
|
+
"strict": true,
|
|
498
|
+
"esModuleInterop": true,
|
|
499
|
+
"skipLibCheck": true,
|
|
500
|
+
"forceConsistentCasingInFileNames": true,
|
|
501
|
+
"resolveJsonModule": true,
|
|
502
|
+
"isolatedModules": true,
|
|
503
|
+
"noEmit": true,
|
|
504
|
+
"allowJs": false
|
|
505
|
+
},
|
|
506
|
+
"include": ["index.ts", "src", "scripts"]
|
|
507
|
+
}
|
|
508
|
+
`;
|
|
509
|
+
}
|
|
510
|
+
function renderJsconfig() {
|
|
511
|
+
return `{
|
|
512
|
+
"compilerOptions": {
|
|
513
|
+
"target": "ESNext",
|
|
514
|
+
"module": "ESNext",
|
|
515
|
+
"moduleResolution": "bundler",
|
|
516
|
+
"lib": ["ESNext"],
|
|
517
|
+
"checkJs": false,
|
|
518
|
+
"allowJs": true
|
|
519
|
+
},
|
|
520
|
+
"include": ["index.js", "src", "scripts"]
|
|
521
|
+
}
|
|
522
|
+
`;
|
|
523
|
+
}
|
|
524
|
+
function renderPackageJson(projectName, framework, language, db) {
|
|
525
|
+
const ext = language === "javascript" ? "js" : "ts";
|
|
526
|
+
const dependencies = framework === "express" ? {
|
|
527
|
+
"@mednours/backon": "latest",
|
|
528
|
+
express: "^4.21.0",
|
|
529
|
+
cors: "^2.8.5",
|
|
530
|
+
helmet: "^8.0.0",
|
|
531
|
+
compression: "^1.7.5",
|
|
532
|
+
zod: "^3.24.1",
|
|
533
|
+
...dbDependencies(db)
|
|
534
|
+
} : {
|
|
535
|
+
"@mednours/backon": "latest",
|
|
536
|
+
hono: "^4.6.14",
|
|
537
|
+
zod: "^3.24.1",
|
|
538
|
+
...dbDependencies(db)
|
|
539
|
+
};
|
|
540
|
+
const devDependencies = language === "javascript" ? {} : framework === "express" ? { "@types/bun": "latest", "@types/express": "^4.17.21", typescript: "^5.7.2" } : { "@types/bun": "latest", typescript: "^5.7.2" };
|
|
541
|
+
const scripts = {
|
|
542
|
+
dev: `bun run --watch index.${ext}`,
|
|
543
|
+
start: `bun run index.${ext}`,
|
|
544
|
+
test: "bun test",
|
|
545
|
+
// Thin aliases over `bunx create-backon <subcommand>` — running
|
|
546
|
+
// `bun run add-route users` from inside the project is shorter than
|
|
547
|
+
// remembering the create-backon invocation, and bun forwards extra
|
|
548
|
+
// arguments (like the route name) straight through without needing
|
|
549
|
+
// a `--` separator.
|
|
550
|
+
"add-route": "bunx create-backon add-route",
|
|
551
|
+
"add-method": "bunx create-backon add-method",
|
|
552
|
+
"remove-route": "bunx create-backon remove-route",
|
|
553
|
+
"list-routes": "bunx create-backon list-routes",
|
|
554
|
+
doctor: "bunx create-backon doctor",
|
|
555
|
+
// project: read-only overview (db status, endpoints, methods, doctor
|
|
556
|
+
// summary). server-config: the interactive manager for actually
|
|
557
|
+
// changing endpoints/methods — add/remove/modify, without needing to
|
|
558
|
+
// remember which of the individual subcommands above does what.
|
|
559
|
+
project: "bunx create-backon project",
|
|
560
|
+
"server-config": "bunx create-backon server-config",
|
|
561
|
+
docs: `bun run scripts/generate-docs.${ext}`
|
|
562
|
+
};
|
|
563
|
+
if (language === "typescript") {
|
|
564
|
+
scripts.typecheck = "tsc --noEmit";
|
|
565
|
+
}
|
|
566
|
+
const pkg = {
|
|
567
|
+
name: projectName,
|
|
568
|
+
version: "0.1.0",
|
|
569
|
+
private: true,
|
|
570
|
+
type: "module",
|
|
571
|
+
scripts,
|
|
572
|
+
dependencies,
|
|
573
|
+
devDependencies
|
|
574
|
+
};
|
|
575
|
+
return `${JSON.stringify(pkg, null, 2)}
|
|
576
|
+
`;
|
|
577
|
+
}
|
|
578
|
+
function renderDeploySection(deployTarget, ext) {
|
|
579
|
+
switch (deployTarget) {
|
|
580
|
+
case "vercel":
|
|
581
|
+
return `## Deploying
|
|
582
|
+
|
|
583
|
+
Set up for [Vercel](https://vercel.com)'s zero-config Hono/Express support:
|
|
584
|
+
\`src/app.${ext}\` has a default export (Vercel deploys straight from it,
|
|
585
|
+
bypassing \`index.${ext}\`/\`serve()\` \u2014 those keep working locally exactly as
|
|
586
|
+
before), and \`vercel.json\` pins the Bun runtime so the deployed function
|
|
587
|
+
matches local dev. Connect the repo on [vercel.com/new](https://vercel.com/new)
|
|
588
|
+
or run \`vercel deploy\` \u2014 no other configuration needed. \`vercel dev\` runs it
|
|
589
|
+
locally the same way it'll run once deployed.
|
|
590
|
+
`;
|
|
591
|
+
case "node":
|
|
592
|
+
return `## Deploying
|
|
593
|
+
|
|
594
|
+
No deploy-specific files here \u2014 \`index.${ext}\` calls \`serve(app)\`, which
|
|
595
|
+
listens on \`PORT\` (see \`.env.example\`) wherever it's run. That's what
|
|
596
|
+
Render, Railway, Fly, a plain VPS, or any other Node/Bun host expects: point
|
|
597
|
+
the platform's start command at \`bun run start\` (or \`bun run index.${ext}\`)
|
|
598
|
+
and set \`PORT\`/your database env vars in its dashboard.
|
|
599
|
+
`;
|
|
600
|
+
case "local":
|
|
601
|
+
return `## Deploying
|
|
602
|
+
|
|
603
|
+
Not set up for a specific host \u2014 \`bun run start\` runs \`index.${ext}\`, which
|
|
604
|
+
listens on \`PORT\` (see \`.env.example\`). Point any Node/Bun-capable host's
|
|
605
|
+
start command at that when you're ready.
|
|
606
|
+
`;
|
|
607
|
+
default:
|
|
608
|
+
return `## Deploying
|
|
609
|
+
|
|
610
|
+
Not decided yet \u2014 \`index.${ext}\` already calls \`serve(app)\`, listening on
|
|
611
|
+
\`PORT\` (see \`.env.example\`), which is all most Node/Bun hosts need. For
|
|
612
|
+
[Vercel](https://vercel.com) specifically, add a default export to
|
|
613
|
+
\`src/app.${ext}\` (\`export default app;\`) and a \`vercel.json\` with
|
|
614
|
+
\`{ "bunVersion": "1.x" }\` \u2014 or re-run \`create-backon\` and pick Vercel to get
|
|
615
|
+
both for free.
|
|
616
|
+
`;
|
|
617
|
+
}
|
|
618
|
+
}
|
|
619
|
+
function renderReadme(answers) {
|
|
620
|
+
const routeList = answers.routes.length ? answers.routes.map((route) => `- \`src/endpoints/${route}/\``).join("\n") : "- (none yet \u2014 add one under src/endpoints/)";
|
|
621
|
+
const backonImport = answers.framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
622
|
+
const languageLabel = answers.language === "javascript" ? "JavaScript" : "TypeScript";
|
|
623
|
+
const ext = answers.language === "javascript" ? "js" : "ts";
|
|
624
|
+
return `# ${answers.projectName}
|
|
625
|
+
|
|
626
|
+
Generated by \`create-backon\` (${answers.framework}, ${languageLabel}).
|
|
627
|
+
|
|
628
|
+
## Getting started
|
|
629
|
+
|
|
630
|
+
\`\`\`
|
|
631
|
+
bun install
|
|
632
|
+
cp .env.example .env # fill in real values
|
|
633
|
+
bun run dev
|
|
634
|
+
\`\`\`
|
|
635
|
+
|
|
636
|
+
Once running, \`http://localhost:3000/docs\` has a live API reference for
|
|
637
|
+
every route added via \`defineRoute\` \u2014 \`bun run docs\` also writes the same
|
|
638
|
+
document to \`openapi.json\`/\`docs.html\` on disk, for CI or static hosting.
|
|
639
|
+
|
|
640
|
+
## Database: ${answers.db}
|
|
641
|
+
|
|
642
|
+
${dbReadmeNote(answers.db)}
|
|
643
|
+
|
|
644
|
+
## Routes
|
|
645
|
+
|
|
646
|
+
${routeList}
|
|
647
|
+
|
|
648
|
+
Each route folder follows the same shape: \`*.routes.${answers.language === "javascript" ? "js" : "ts"}\` wires HTTP
|
|
649
|
+
methods to controller functions, \`*.controller.${answers.language === "javascript" ? "js" : "ts"}\` validates the
|
|
650
|
+
request (via \`defineRoute\` from \`${backonImport}\`) and calls into
|
|
651
|
+
\`*.services.${answers.language === "javascript" ? "js" : "ts"}\`, which is where real data access belongs.
|
|
652
|
+
|
|
653
|
+
${renderDeploySection(answers.deployTarget, ext)}`;
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
// src/generate.ts
|
|
657
|
+
async function write(path, contents) {
|
|
658
|
+
await mkdir(dirname(path), { recursive: true });
|
|
659
|
+
await writeFile(path, contents);
|
|
660
|
+
}
|
|
661
|
+
var IGNORABLE_ENTRIES = /* @__PURE__ */ new Set([
|
|
662
|
+
".git",
|
|
663
|
+
".gitignore",
|
|
664
|
+
".github",
|
|
665
|
+
".idea",
|
|
666
|
+
".vscode",
|
|
667
|
+
".DS_Store",
|
|
668
|
+
"LICENSE",
|
|
669
|
+
"LICENSE.md",
|
|
670
|
+
"README.md"
|
|
671
|
+
]);
|
|
672
|
+
async function ensureSafeToWrite(root) {
|
|
673
|
+
let entries;
|
|
674
|
+
try {
|
|
675
|
+
entries = await readdir(root);
|
|
676
|
+
} catch (err) {
|
|
677
|
+
if (err.code === "ENOENT") return;
|
|
678
|
+
throw err;
|
|
679
|
+
}
|
|
680
|
+
const meaningful = entries.filter((name) => !IGNORABLE_ENTRIES.has(name));
|
|
681
|
+
if (meaningful.length > 0) {
|
|
682
|
+
const shown = meaningful.slice(0, 5).join(", ") + (meaningful.length > 5 ? ", ..." : "");
|
|
683
|
+
throw new Error(
|
|
684
|
+
`Refusing to scaffold into ${root} \u2014 it already has files in it (${shown}). Clear it out first, or pick an empty/new directory.`
|
|
685
|
+
);
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
async function generateProject(answers, cwd = process.cwd()) {
|
|
689
|
+
const root = answers.projectName === "." ? cwd : join(cwd, answers.projectName);
|
|
690
|
+
const packageName = answers.projectName === "." ? basename(root) || "app" : answers.projectName;
|
|
691
|
+
const readmeAnswers = { ...answers, projectName: packageName };
|
|
692
|
+
const ext = answers.language === "javascript" ? "js" : "ts";
|
|
693
|
+
await ensureSafeToWrite(root);
|
|
694
|
+
const filesWritten = [];
|
|
695
|
+
const files = [
|
|
696
|
+
[join(root, `index.${ext}`), renderIndexTs(answers.framework)],
|
|
697
|
+
[join(root, ".env.example"), renderEnvExample(answers.db)],
|
|
698
|
+
...answers.copyEnv ? [[join(root, ".env"), renderEnvExample(answers.db)]] : [],
|
|
699
|
+
[join(root, "package.json"), renderPackageJson(packageName, answers.framework, answers.language, answers.db)],
|
|
700
|
+
answers.language === "javascript" ? [join(root, "jsconfig.json"), renderJsconfig()] : [join(root, "tsconfig.json"), renderTsconfig()],
|
|
701
|
+
[join(root, "README.md"), renderReadme(readmeAnswers)],
|
|
702
|
+
[
|
|
703
|
+
join(root, ".gitignore"),
|
|
704
|
+
`node_modules/
|
|
705
|
+
dist/
|
|
706
|
+
*.log
|
|
707
|
+
.env
|
|
708
|
+
.env.local
|
|
709
|
+
openapi.json
|
|
710
|
+
docs.html
|
|
711
|
+
${answers.deployTarget === "vercel" ? ".vercel\n" : ""}`
|
|
712
|
+
],
|
|
713
|
+
[join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
|
|
714
|
+
[join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
|
|
715
|
+
[
|
|
716
|
+
join(root, `src/middleware/example.middleware.${ext}`),
|
|
717
|
+
renderExampleMiddleware(answers.framework, answers.language)
|
|
718
|
+
],
|
|
719
|
+
[join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
|
|
720
|
+
[join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
|
|
721
|
+
...answers.deployTarget === "vercel" ? [[join(root, "vercel.json"), renderVercelJson()]] : []
|
|
722
|
+
];
|
|
723
|
+
for (const route of answers.routes) {
|
|
724
|
+
const dir = join(root, "src/endpoints", route);
|
|
725
|
+
files.push(
|
|
726
|
+
[join(dir, `${route}.controller.${ext}`), renderBlankController()],
|
|
727
|
+
[join(dir, `${route}.routes.${ext}`), renderBlankRoutes(route, answers.framework, answers.language)],
|
|
728
|
+
[join(dir, `${route}.services.${ext}`), renderBlankServices()]
|
|
729
|
+
);
|
|
730
|
+
}
|
|
731
|
+
for (const [path, contents] of files) {
|
|
732
|
+
await write(path, contents);
|
|
733
|
+
filesWritten.push(path);
|
|
734
|
+
}
|
|
735
|
+
return { root, filesWritten };
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
// src/add-route.ts
|
|
739
|
+
import { mkdir as mkdir2, readdir as readdir2, writeFile as writeFile2 } from "node:fs/promises";
|
|
740
|
+
import { dirname as dirname2, join as join4 } from "node:path";
|
|
741
|
+
|
|
742
|
+
// src/detect.ts
|
|
743
|
+
import { readFile } from "node:fs/promises";
|
|
744
|
+
import { join as join2 } from "node:path";
|
|
745
|
+
async function detectProject(cwd = process.cwd()) {
|
|
746
|
+
const pkgPath = join2(cwd, "package.json");
|
|
747
|
+
let raw;
|
|
748
|
+
try {
|
|
749
|
+
raw = await readFile(pkgPath, "utf-8");
|
|
750
|
+
} catch (err) {
|
|
751
|
+
if (err.code === "ENOENT") {
|
|
752
|
+
throw new Error(`No package.json found in ${cwd} \u2014 run this from a project created by \`bun create backon\`.`);
|
|
753
|
+
}
|
|
754
|
+
throw err;
|
|
755
|
+
}
|
|
756
|
+
let pkg;
|
|
757
|
+
try {
|
|
758
|
+
pkg = JSON.parse(raw);
|
|
759
|
+
} catch {
|
|
760
|
+
throw new Error(`Couldn't parse ${pkgPath} as JSON.`);
|
|
761
|
+
}
|
|
762
|
+
const dependencies = pkg.dependencies ?? {};
|
|
763
|
+
const devDependencies = pkg.devDependencies ?? {};
|
|
764
|
+
if (!dependencies["@mednours/backon"]) {
|
|
765
|
+
throw new Error(`${cwd} doesn't look like a backon project \u2014 package.json has no "@mednours/backon" dependency.`);
|
|
766
|
+
}
|
|
767
|
+
const framework = dependencies.express ? "express" : "hono";
|
|
768
|
+
const language = devDependencies.typescript ? "typescript" : "javascript";
|
|
769
|
+
const ext = language === "javascript" ? "js" : "ts";
|
|
770
|
+
return { root: cwd, framework, language, ext };
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
// src/endpoints-index.ts
|
|
774
|
+
import { readFile as readFile2 } from "node:fs/promises";
|
|
775
|
+
import { join as join3 } from "node:path";
|
|
776
|
+
var MOUNT_PATTERN = /endpoints\.(?:route|use)\("\/([a-z0-9-]+)"/g;
|
|
777
|
+
function parseMountedRoutes(indexContents) {
|
|
778
|
+
const routes = [];
|
|
779
|
+
for (const match of indexContents.matchAll(MOUNT_PATTERN)) {
|
|
780
|
+
routes.push(match[1]);
|
|
781
|
+
}
|
|
782
|
+
return routes;
|
|
783
|
+
}
|
|
784
|
+
async function readEndpointsIndex(root, ext) {
|
|
785
|
+
const path = join3(root, "src/endpoints", `index.${ext}`);
|
|
786
|
+
let contents;
|
|
787
|
+
try {
|
|
788
|
+
contents = await readFile2(path, "utf-8");
|
|
789
|
+
} catch (err) {
|
|
790
|
+
if (err.code === "ENOENT") {
|
|
791
|
+
throw new Error(`${path} doesn't exist \u2014 is this a backon project?`);
|
|
792
|
+
}
|
|
793
|
+
throw err;
|
|
794
|
+
}
|
|
795
|
+
return { path, contents };
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// src/add-route.ts
|
|
799
|
+
async function write2(path, contents) {
|
|
800
|
+
await mkdir2(dirname2(path), { recursive: true });
|
|
801
|
+
await writeFile2(path, contents);
|
|
802
|
+
}
|
|
803
|
+
async function addRoute(rawName, cwd = process.cwd()) {
|
|
804
|
+
const route = toKebabCase(rawName);
|
|
805
|
+
if (!route) {
|
|
806
|
+
throw new Error("Route name can't be empty.");
|
|
807
|
+
}
|
|
808
|
+
const { root, framework, language, ext } = await detectProject(cwd);
|
|
809
|
+
const endpointsDir = join4(root, "src/endpoints");
|
|
810
|
+
let dirEntries;
|
|
811
|
+
try {
|
|
812
|
+
dirEntries = await readdir2(endpointsDir);
|
|
813
|
+
} catch (err) {
|
|
814
|
+
if (err.code === "ENOENT") {
|
|
815
|
+
throw new Error(`${endpointsDir} doesn't exist \u2014 is this a backon project?`);
|
|
816
|
+
}
|
|
817
|
+
throw err;
|
|
818
|
+
}
|
|
819
|
+
if (dirEntries.includes(route)) {
|
|
820
|
+
throw new Error(`src/endpoints/${route} already exists.`);
|
|
821
|
+
}
|
|
822
|
+
const { path: indexPath, contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
823
|
+
const existingRoutes = parseMountedRoutes(indexContents);
|
|
824
|
+
if (existingRoutes.includes(route)) {
|
|
825
|
+
throw new Error(`"${route}" is already mounted in ${indexPath}.`);
|
|
826
|
+
}
|
|
827
|
+
const routeDir = join4(endpointsDir, route);
|
|
828
|
+
const filesWritten = [];
|
|
829
|
+
const files = [
|
|
830
|
+
[join4(routeDir, `${route}.controller.${ext}`), renderBlankController()],
|
|
831
|
+
[join4(routeDir, `${route}.routes.${ext}`), renderBlankRoutes(route, framework, language)],
|
|
832
|
+
[join4(routeDir, `${route}.services.${ext}`), renderBlankServices()]
|
|
833
|
+
];
|
|
834
|
+
for (const [path, contents] of files) {
|
|
835
|
+
await write2(path, contents);
|
|
836
|
+
filesWritten.push(path);
|
|
837
|
+
}
|
|
838
|
+
const allRoutes = [...existingRoutes, route];
|
|
839
|
+
await writeFile2(indexPath, renderEndpointsIndex(framework, allRoutes));
|
|
840
|
+
filesWritten.push(indexPath);
|
|
841
|
+
return { route, root, filesWritten };
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
// src/remove-route.ts
|
|
845
|
+
import { rm, writeFile as writeFile3 } from "node:fs/promises";
|
|
846
|
+
import { join as join5 } from "node:path";
|
|
847
|
+
async function removeRoute(rawName, cwd = process.cwd()) {
|
|
848
|
+
const route = toKebabCase(rawName);
|
|
849
|
+
if (!route) {
|
|
850
|
+
throw new Error("Route name can't be empty.");
|
|
851
|
+
}
|
|
852
|
+
const { root, framework, ext } = await detectProject(cwd);
|
|
853
|
+
const { path: indexPath, contents } = await readEndpointsIndex(root, ext);
|
|
854
|
+
const mounted = parseMountedRoutes(contents);
|
|
855
|
+
if (!mounted.includes(route)) {
|
|
856
|
+
throw new Error(`"${route}" isn't mounted in ${indexPath} \u2014 nothing to remove.`);
|
|
857
|
+
}
|
|
858
|
+
const remaining = mounted.filter((name) => name !== route);
|
|
859
|
+
await writeFile3(indexPath, renderEndpointsIndex(framework, remaining));
|
|
860
|
+
const removedDir = join5(root, "src/endpoints", route);
|
|
861
|
+
await rm(removedDir, { recursive: true, force: true });
|
|
862
|
+
return { route, root, removedDir };
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
// src/list-routes.ts
|
|
866
|
+
async function listRoutes(cwd = process.cwd()) {
|
|
867
|
+
const { root, ext } = await detectProject(cwd);
|
|
868
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
869
|
+
return { root, routes: parseMountedRoutes(contents) };
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
// src/doctor.ts
|
|
873
|
+
import { access, readdir as readdir3 } from "node:fs/promises";
|
|
874
|
+
import { join as join6 } from "node:path";
|
|
875
|
+
var ROUTE_FILE_SUFFIXES = ["controller", "routes", "services"];
|
|
876
|
+
async function runDoctor(cwd = process.cwd()) {
|
|
877
|
+
const { root, ext } = await detectProject(cwd);
|
|
878
|
+
const endpointsDir = join6(root, "src/endpoints");
|
|
879
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
880
|
+
const mounted = new Set(parseMountedRoutes(contents));
|
|
881
|
+
const dirents = await readdir3(endpointsDir, { withFileTypes: true }).catch((err) => {
|
|
882
|
+
if (err.code === "ENOENT") return [];
|
|
883
|
+
throw err;
|
|
884
|
+
});
|
|
885
|
+
const folders = dirents.filter((d) => d.isDirectory()).map((d) => d.name);
|
|
886
|
+
const folderSet = new Set(folders);
|
|
887
|
+
const issues = [];
|
|
888
|
+
for (const route of mounted) {
|
|
889
|
+
if (!folderSet.has(route)) {
|
|
890
|
+
issues.push({
|
|
891
|
+
kind: "dangling-mount",
|
|
892
|
+
route,
|
|
893
|
+
detail: `index.${ext} mounts "/${route}" but src/endpoints/${route}/ doesn't exist.`
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
}
|
|
897
|
+
for (const route of folders) {
|
|
898
|
+
if (!mounted.has(route)) {
|
|
899
|
+
issues.push({
|
|
900
|
+
kind: "orphaned-folder",
|
|
901
|
+
route,
|
|
902
|
+
detail: `src/endpoints/${route}/ exists but isn't mounted in index.${ext}.`
|
|
903
|
+
});
|
|
904
|
+
}
|
|
905
|
+
for (const suffix of ROUTE_FILE_SUFFIXES) {
|
|
906
|
+
const filePath = join6(endpointsDir, route, `${route}.${suffix}.${ext}`);
|
|
907
|
+
try {
|
|
908
|
+
await access(filePath);
|
|
909
|
+
} catch {
|
|
910
|
+
issues.push({ kind: "missing-file", route, detail: `${filePath} is missing.` });
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
return { root, issues };
|
|
915
|
+
}
|
|
916
|
+
|
|
917
|
+
// src/add-method.ts
|
|
918
|
+
import { readFile as readFile4, writeFile as writeFile4 } from "node:fs/promises";
|
|
919
|
+
import { join as join8 } from "node:path";
|
|
920
|
+
|
|
921
|
+
// src/route-methods.ts
|
|
922
|
+
import { readFile as readFile3 } from "node:fs/promises";
|
|
923
|
+
import { join as join7 } from "node:path";
|
|
924
|
+
|
|
925
|
+
// src/colors.ts
|
|
926
|
+
var VERB_CODES = {
|
|
927
|
+
get: "36",
|
|
928
|
+
post: "32",
|
|
929
|
+
put: "33",
|
|
930
|
+
patch: "35",
|
|
931
|
+
delete: "31"
|
|
932
|
+
};
|
|
933
|
+
var RESET = "\x1B[0m";
|
|
934
|
+
function colorVerb(verb) {
|
|
935
|
+
const label = verb.toUpperCase().padEnd(6);
|
|
936
|
+
const code = VERB_CODES[verb];
|
|
937
|
+
return code ? `\x1B[${code}m${label}${RESET}` : label;
|
|
938
|
+
}
|
|
939
|
+
function dim(text3) {
|
|
940
|
+
return `\x1B[2m${text3}${RESET}`;
|
|
941
|
+
}
|
|
942
|
+
function ok(text3) {
|
|
943
|
+
return `\x1B[32m${text3}${RESET}`;
|
|
944
|
+
}
|
|
945
|
+
function warn(text3) {
|
|
946
|
+
return `\x1B[33m${text3}${RESET}`;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
// src/route-methods.ts
|
|
950
|
+
var METHOD_MOUNT_PATTERN = /\.(get|post|put|patch|delete)\(\s*"([^"]*)"\s*,\s*controller\.(\w+)\s*\)/g;
|
|
951
|
+
function parseRouteMethods(routesFileContents) {
|
|
952
|
+
const methods = [];
|
|
953
|
+
for (const match of routesFileContents.matchAll(METHOD_MOUNT_PATTERN)) {
|
|
954
|
+
const [, verb, path, name] = match;
|
|
955
|
+
if (verb && path !== void 0 && name) {
|
|
956
|
+
methods.push({ verb, path, name });
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
return methods;
|
|
960
|
+
}
|
|
961
|
+
async function detectMethodValidation(route, name, cwd = process.cwd()) {
|
|
962
|
+
const { root, ext } = await detectProject(cwd);
|
|
963
|
+
const controllerPath = join7(root, "src/endpoints", route, `${route}.controller.${ext}`);
|
|
964
|
+
const contents = await readFile3(controllerPath, "utf-8");
|
|
965
|
+
return {
|
|
966
|
+
needsBody: contents.includes(`export const ${name}BodySchema`),
|
|
967
|
+
needsQuery: contents.includes(`export const ${name}QuerySchema`)
|
|
968
|
+
};
|
|
969
|
+
}
|
|
970
|
+
async function listEndpointsWithMethods(cwd = process.cwd()) {
|
|
971
|
+
const { root, ext } = await detectProject(cwd);
|
|
972
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
973
|
+
const routes = parseMountedRoutes(contents);
|
|
974
|
+
const summaries = [];
|
|
975
|
+
for (const route of routes) {
|
|
976
|
+
const routesFilePath = join7(root, "src/endpoints", route, `${route}.routes.${ext}`);
|
|
977
|
+
let routesFileContents;
|
|
978
|
+
try {
|
|
979
|
+
routesFileContents = await readFile3(routesFilePath, "utf-8");
|
|
980
|
+
} catch {
|
|
981
|
+
summaries.push({ route, methods: [] });
|
|
982
|
+
continue;
|
|
983
|
+
}
|
|
984
|
+
summaries.push({ route, methods: parseRouteMethods(routesFileContents) });
|
|
985
|
+
}
|
|
986
|
+
return summaries;
|
|
987
|
+
}
|
|
988
|
+
function formatEndpointsDashboard(summaries) {
|
|
989
|
+
if (summaries.length === 0) return dim("No endpoints yet.");
|
|
990
|
+
return summaries.map(({ route, methods }) => {
|
|
991
|
+
if (methods.length === 0) return `${route}
|
|
992
|
+
${dim("(no methods yet)")}`;
|
|
993
|
+
const lines = methods.map((m) => ` ${colorVerb(m.verb)} ${m.path} ${dim(`\u2192 ${m.name}`)}`);
|
|
994
|
+
return `${route}
|
|
995
|
+
${lines.join("\n")}`;
|
|
996
|
+
}).join("\n\n");
|
|
997
|
+
}
|
|
998
|
+
|
|
999
|
+
// src/add-method.ts
|
|
1000
|
+
var PLACEHOLDER_PATTERN = /\/\/ No (?:routes|methods) yet[^\n]*\n\n?/;
|
|
1001
|
+
function stripPlaceholder(content) {
|
|
1002
|
+
return content.replace(PLACEHOLDER_PATTERN, "");
|
|
1003
|
+
}
|
|
1004
|
+
function ensureImports(content, importLines) {
|
|
1005
|
+
const stripped = stripPlaceholder(content);
|
|
1006
|
+
const missing = importLines.filter((line) => !stripped.includes(line));
|
|
1007
|
+
if (missing.length === 0) return stripped;
|
|
1008
|
+
const lines = stripped.split("\n");
|
|
1009
|
+
let insertAt = 0;
|
|
1010
|
+
while (insertAt < lines.length && lines[insertAt]?.startsWith("import ")) insertAt++;
|
|
1011
|
+
lines.splice(insertAt, 0, ...missing);
|
|
1012
|
+
return lines.join("\n");
|
|
1013
|
+
}
|
|
1014
|
+
function appendBlock(content, block) {
|
|
1015
|
+
const trimmed = content.replace(/\n+$/, "");
|
|
1016
|
+
return trimmed ? `${trimmed}
|
|
1017
|
+
|
|
1018
|
+
${block}
|
|
1019
|
+
` : `${block}
|
|
1020
|
+
`;
|
|
1021
|
+
}
|
|
1022
|
+
async function addMethod(route, spec, cwd = process.cwd()) {
|
|
1023
|
+
const { root, framework, language, ext } = await detectProject(cwd);
|
|
1024
|
+
const { contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
1025
|
+
const mounted = parseMountedRoutes(indexContents);
|
|
1026
|
+
if (!mounted.includes(route)) {
|
|
1027
|
+
throw new Error(`"${route}" isn't mounted in src/endpoints/index.${ext} \u2014 add it first with \`bun run add-route\`.`);
|
|
1028
|
+
}
|
|
1029
|
+
const routeDir = join8(root, "src/endpoints", route);
|
|
1030
|
+
const controllerPath = join8(routeDir, `${route}.controller.${ext}`);
|
|
1031
|
+
const routesPath = join8(routeDir, `${route}.routes.${ext}`);
|
|
1032
|
+
const servicesPath = join8(routeDir, `${route}.services.${ext}`);
|
|
1033
|
+
const [controllerContents, routesContents, servicesContents] = await Promise.all([
|
|
1034
|
+
readFile4(controllerPath, "utf-8"),
|
|
1035
|
+
readFile4(routesPath, "utf-8"),
|
|
1036
|
+
readFile4(servicesPath, "utf-8")
|
|
1037
|
+
]);
|
|
1038
|
+
const existing = parseRouteMethods(routesContents);
|
|
1039
|
+
if (existing.some((m) => m.name === spec.name)) {
|
|
1040
|
+
throw new Error(`"${spec.name}" is already used in ${controllerPath} \u2014 pick a different name.`);
|
|
1041
|
+
}
|
|
1042
|
+
if (existing.some((m) => m.verb === spec.verb && m.path === spec.path)) {
|
|
1043
|
+
throw new Error(`${spec.verb.toUpperCase()} ${spec.path} is already mounted in ${routesPath}.`);
|
|
1044
|
+
}
|
|
1045
|
+
const newController = appendBlock(ensureImports(controllerContents, controllerImports(route, framework)), renderControllerMethod(spec));
|
|
1046
|
+
const newRoutes = appendBlock(
|
|
1047
|
+
ensureImports(routesContents, [`import * as controller from "./${route}.controller";`]),
|
|
1048
|
+
routeMountLine(route, spec)
|
|
1049
|
+
);
|
|
1050
|
+
const newServices = appendBlock(ensureImports(servicesContents, serviceImports(route, spec, language)), renderServiceMethod(spec, language));
|
|
1051
|
+
await Promise.all([
|
|
1052
|
+
writeFile4(controllerPath, newController),
|
|
1053
|
+
writeFile4(routesPath, newRoutes),
|
|
1054
|
+
writeFile4(servicesPath, newServices)
|
|
1055
|
+
]);
|
|
1056
|
+
return { route, root, filesWritten: [controllerPath, routesPath, servicesPath] };
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
// src/remove-method.ts
|
|
1060
|
+
import { readFile as readFile5, writeFile as writeFile5 } from "node:fs/promises";
|
|
1061
|
+
import { join as join9 } from "node:path";
|
|
1062
|
+
function removeBlock(content, matches) {
|
|
1063
|
+
const blocks = content.split(/\n\n+/);
|
|
1064
|
+
const index = blocks.findIndex(matches);
|
|
1065
|
+
if (index === -1) return content;
|
|
1066
|
+
blocks.splice(index, 1);
|
|
1067
|
+
const joined = blocks.filter((b) => b.length > 0).join("\n\n");
|
|
1068
|
+
return joined ? `${joined}
|
|
1069
|
+
` : "";
|
|
1070
|
+
}
|
|
1071
|
+
async function removeMethod(route, verb, path, cwd = process.cwd()) {
|
|
1072
|
+
const { root, framework, language, ext } = await detectProject(cwd);
|
|
1073
|
+
const { contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
1074
|
+
const mounted = parseMountedRoutes(indexContents);
|
|
1075
|
+
if (!mounted.includes(route)) {
|
|
1076
|
+
throw new Error(`"${route}" isn't mounted in src/endpoints/index.${ext}.`);
|
|
1077
|
+
}
|
|
1078
|
+
const routeDir = join9(root, "src/endpoints", route);
|
|
1079
|
+
const controllerPath = join9(routeDir, `${route}.controller.${ext}`);
|
|
1080
|
+
const routesPath = join9(routeDir, `${route}.routes.${ext}`);
|
|
1081
|
+
const servicesPath = join9(routeDir, `${route}.services.${ext}`);
|
|
1082
|
+
const [controllerContents, routesContents, servicesContents] = await Promise.all([
|
|
1083
|
+
readFile5(controllerPath, "utf-8"),
|
|
1084
|
+
readFile5(routesPath, "utf-8"),
|
|
1085
|
+
readFile5(servicesPath, "utf-8")
|
|
1086
|
+
]);
|
|
1087
|
+
const existing = parseRouteMethods(routesContents);
|
|
1088
|
+
const match = existing.find((m) => m.verb === verb && m.path === path);
|
|
1089
|
+
if (!match) {
|
|
1090
|
+
throw new Error(`${verb.toUpperCase()} ${path} isn't mounted in ${routesPath}.`);
|
|
1091
|
+
}
|
|
1092
|
+
const { name } = match;
|
|
1093
|
+
if (existing.length === 1) {
|
|
1094
|
+
await Promise.all([
|
|
1095
|
+
writeFile5(controllerPath, renderBlankController()),
|
|
1096
|
+
writeFile5(routesPath, renderBlankRoutes(route, framework, language)),
|
|
1097
|
+
writeFile5(servicesPath, renderBlankServices())
|
|
1098
|
+
]);
|
|
1099
|
+
return { route, root, removed: match };
|
|
1100
|
+
}
|
|
1101
|
+
const expectedMountLine = routeMountLine(route, { verb, path, name, needsBody: false, needsQuery: false });
|
|
1102
|
+
const newController = removeBlock(controllerContents, (block) => block.includes(`export const ${name} = defineRoute(`));
|
|
1103
|
+
const newRoutes = removeBlock(routesContents, (block) => block.trim() === expectedMountLine);
|
|
1104
|
+
const newServices = removeBlock(servicesContents, (block) => block.includes(`export async function ${name}(`));
|
|
1105
|
+
await Promise.all([
|
|
1106
|
+
writeFile5(controllerPath, newController),
|
|
1107
|
+
writeFile5(routesPath, newRoutes),
|
|
1108
|
+
writeFile5(servicesPath, newServices)
|
|
1109
|
+
]);
|
|
1110
|
+
return { route, root, removed: match };
|
|
1111
|
+
}
|
|
1112
|
+
|
|
1113
|
+
// src/db-status.ts
|
|
1114
|
+
import { readFile as readFile6 } from "node:fs/promises";
|
|
1115
|
+
import { join as join10 } from "node:path";
|
|
1116
|
+
var DRIVER_SIGNATURES = [
|
|
1117
|
+
["drizzle-orm/neon-http", "neon"],
|
|
1118
|
+
["drizzle-orm/node-postgres", "postgres"],
|
|
1119
|
+
["drizzle-orm/bun-sqlite", "sqlite"]
|
|
1120
|
+
];
|
|
1121
|
+
function detectDriver(dbFileContents) {
|
|
1122
|
+
for (const [signature, driver] of DRIVER_SIGNATURES) {
|
|
1123
|
+
if (dbFileContents.includes(signature)) return driver;
|
|
1124
|
+
}
|
|
1125
|
+
if (dbFileContents.includes("No database configured yet")) return "none";
|
|
1126
|
+
return "custom";
|
|
1127
|
+
}
|
|
1128
|
+
function parseEnvValue(envContents, key) {
|
|
1129
|
+
const match = envContents.match(new RegExp(`^${key}=(.*)$`, "m"));
|
|
1130
|
+
const value = match?.[1]?.trim();
|
|
1131
|
+
return value ? value : void 0;
|
|
1132
|
+
}
|
|
1133
|
+
async function detectDbStatus(cwd = process.cwd()) {
|
|
1134
|
+
const { root, ext } = await detectProject(cwd);
|
|
1135
|
+
let dbFileContents;
|
|
1136
|
+
try {
|
|
1137
|
+
dbFileContents = await readFile6(join10(root, "src/config", `db.${ext}`), "utf-8");
|
|
1138
|
+
} catch {
|
|
1139
|
+
dbFileContents = void 0;
|
|
1140
|
+
}
|
|
1141
|
+
const driver = dbFileContents === void 0 ? "missing" : detectDriver(dbFileContents);
|
|
1142
|
+
let envContents = "";
|
|
1143
|
+
let envFileExists = true;
|
|
1144
|
+
try {
|
|
1145
|
+
envContents = await readFile6(join10(root, ".env"), "utf-8");
|
|
1146
|
+
} catch {
|
|
1147
|
+
envFileExists = false;
|
|
1148
|
+
}
|
|
1149
|
+
const databaseUrl = parseEnvValue(envContents, "DATABASE_URL");
|
|
1150
|
+
if (driver === "missing") {
|
|
1151
|
+
return { driver, envFileExists, ready: "unknown", summary: warn("src/config/db file not found.") };
|
|
1152
|
+
}
|
|
1153
|
+
if (driver === "custom") {
|
|
1154
|
+
return {
|
|
1155
|
+
driver,
|
|
1156
|
+
envFileExists,
|
|
1157
|
+
ready: "unknown",
|
|
1158
|
+
summary: `${dim("custom")} \u2014 src/config/db has been hand-edited, can't tell you its status here.`
|
|
1159
|
+
};
|
|
1160
|
+
}
|
|
1161
|
+
if (driver === "none") {
|
|
1162
|
+
return { driver, envFileExists, ready: true, summary: dim("none \u2014 no database configured.") };
|
|
1163
|
+
}
|
|
1164
|
+
if (driver === "sqlite") {
|
|
1165
|
+
const path = databaseUrl ?? "./dev.db";
|
|
1166
|
+
return { driver, envFileExists, ready: true, summary: `${ok("sqlite")} \u2014 using ${path}.` };
|
|
1167
|
+
}
|
|
1168
|
+
if (databaseUrl) {
|
|
1169
|
+
return { driver, envFileExists, ready: true, summary: `${ok(driver)} \u2014 DATABASE_URL is set in .env.` };
|
|
1170
|
+
}
|
|
1171
|
+
return {
|
|
1172
|
+
driver,
|
|
1173
|
+
envFileExists,
|
|
1174
|
+
ready: false,
|
|
1175
|
+
summary: `${warn(driver)} \u2014 DATABASE_URL missing from .env${envFileExists ? "" : " (no .env file)"}; src/config/db.ts will throw at startup until it's set.`
|
|
1176
|
+
};
|
|
1177
|
+
}
|
|
1178
|
+
|
|
1179
|
+
// src/cli.ts
|
|
1180
|
+
var ADD_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-route", "route"]);
|
|
1181
|
+
var REMOVE_ROUTE_SUBCOMMANDS = /* @__PURE__ */ new Set(["remove-route", "rm-route"]);
|
|
1182
|
+
var LIST_ROUTES_SUBCOMMANDS = /* @__PURE__ */ new Set(["list-routes", "routes"]);
|
|
1183
|
+
var DOCTOR_SUBCOMMANDS = /* @__PURE__ */ new Set(["doctor"]);
|
|
1184
|
+
var ADD_METHOD_SUBCOMMANDS = /* @__PURE__ */ new Set(["add-method", "method"]);
|
|
1185
|
+
var PROJECT_SUBCOMMANDS = /* @__PURE__ */ new Set(["project"]);
|
|
1186
|
+
var SERVER_CONFIG_SUBCOMMANDS = /* @__PURE__ */ new Set(["server-config"]);
|
|
1187
|
+
async function promptForRouteName(introText) {
|
|
1188
|
+
p2.intro(introText);
|
|
1189
|
+
const answer = await p2.text({
|
|
1190
|
+
message: "Route name",
|
|
1191
|
+
placeholder: "e.g. users",
|
|
1192
|
+
validate: (value) => !value ? "Required." : void 0
|
|
1193
|
+
});
|
|
1194
|
+
if (p2.isCancel(answer)) {
|
|
1195
|
+
p2.cancel("Cancelled.");
|
|
1196
|
+
process.exit(0);
|
|
1197
|
+
}
|
|
1198
|
+
return answer;
|
|
1199
|
+
}
|
|
1200
|
+
async function runAddRoute(args) {
|
|
1201
|
+
let [name] = args;
|
|
1202
|
+
if (!name) {
|
|
1203
|
+
name = await promptForRouteName("create-backon add-route");
|
|
1204
|
+
p2.outro(`Adding ${name}...`);
|
|
1205
|
+
}
|
|
1206
|
+
const { route, root, filesWritten } = await addRoute(name);
|
|
1207
|
+
p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
|
|
1208
|
+
p2.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
|
|
1209
|
+
}
|
|
1210
|
+
async function runRemoveRoute(args) {
|
|
1211
|
+
let [name] = args;
|
|
1212
|
+
if (!name) {
|
|
1213
|
+
name = await promptForRouteName("create-backon remove-route");
|
|
1214
|
+
}
|
|
1215
|
+
const shouldRemove = await p2.confirm({
|
|
1216
|
+
message: `Remove src/endpoints/${name} and unmount it? This deletes the folder.`,
|
|
1217
|
+
initialValue: false
|
|
1218
|
+
});
|
|
1219
|
+
if (p2.isCancel(shouldRemove) || !shouldRemove) {
|
|
1220
|
+
p2.cancel("Cancelled.");
|
|
1221
|
+
process.exit(0);
|
|
1222
|
+
}
|
|
1223
|
+
const { route, root, removedDir } = await removeRoute(name);
|
|
1224
|
+
p2.log.success(`Removed ${removedDir} and unmounted "${route}" in ${root}`);
|
|
1225
|
+
}
|
|
1226
|
+
async function runListRoutes() {
|
|
1227
|
+
const { root, routes } = await listRoutes();
|
|
1228
|
+
if (routes.length === 0) {
|
|
1229
|
+
p2.log.info(`No routes mounted in ${root}.`);
|
|
1230
|
+
return;
|
|
1231
|
+
}
|
|
1232
|
+
const summaries = await listEndpointsWithMethods();
|
|
1233
|
+
p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
1234
|
+
}
|
|
1235
|
+
async function runDoctorCommand() {
|
|
1236
|
+
const { root, issues } = await runDoctor();
|
|
1237
|
+
if (issues.length === 0) {
|
|
1238
|
+
p2.log.success(`No issues found in ${root}.`);
|
|
1239
|
+
return;
|
|
1240
|
+
}
|
|
1241
|
+
p2.log.warn(`${issues.length} issue(s) found in ${root}:
|
|
1242
|
+
${issues.map((issue) => ` - ${issue.detail}`).join("\n")}`);
|
|
1243
|
+
process.exitCode = 1;
|
|
1244
|
+
}
|
|
1245
|
+
async function runProjectOverview() {
|
|
1246
|
+
p2.intro("create-backon project");
|
|
1247
|
+
const { root } = await detectProject();
|
|
1248
|
+
const dbStatus = await detectDbStatus();
|
|
1249
|
+
const summaries = await listEndpointsWithMethods();
|
|
1250
|
+
const { issues } = await runDoctor();
|
|
1251
|
+
p2.note(dbStatus.summary, "Database");
|
|
1252
|
+
p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
1253
|
+
if (issues.length > 0) {
|
|
1254
|
+
p2.log.warn(`${issues.length} issue(s) between src/endpoints/ and index \u2014 run \`bun run doctor\` for details.`);
|
|
1255
|
+
} else {
|
|
1256
|
+
p2.log.success("No drift between src/endpoints/ and index.");
|
|
1257
|
+
}
|
|
1258
|
+
p2.outro("Manage endpoints and methods with `bun run server-config`.");
|
|
1259
|
+
}
|
|
1260
|
+
function suggestMethodName(verb, path) {
|
|
1261
|
+
const params = paramNamesFromPath(path);
|
|
1262
|
+
if (verb === "get" && params.length === 0) return "list";
|
|
1263
|
+
if (verb === "get") return `getBy${pascalCase(params[0] ?? "id")}`;
|
|
1264
|
+
if (verb === "post") return "create";
|
|
1265
|
+
if (verb === "put" || verb === "patch") return "update";
|
|
1266
|
+
return "remove";
|
|
1267
|
+
}
|
|
1268
|
+
var IDENTIFIER_PATTERN = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
1269
|
+
async function runAddMethod() {
|
|
1270
|
+
p2.intro("create-backon add-method");
|
|
1271
|
+
while (true) {
|
|
1272
|
+
const { root, routes } = await listRoutes();
|
|
1273
|
+
const summaries = await listEndpointsWithMethods();
|
|
1274
|
+
p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
1275
|
+
const routeChoice = await p2.select({
|
|
1276
|
+
message: "Add a method to which endpoint?",
|
|
1277
|
+
options: [
|
|
1278
|
+
...routes.map((route2) => ({ value: route2, label: route2 })),
|
|
1279
|
+
{ value: "__new__", label: "+ New blank endpoint" }
|
|
1280
|
+
]
|
|
1281
|
+
});
|
|
1282
|
+
if (p2.isCancel(routeChoice)) {
|
|
1283
|
+
p2.cancel("Cancelled.");
|
|
1284
|
+
return;
|
|
1285
|
+
}
|
|
1286
|
+
let route = routeChoice;
|
|
1287
|
+
if (route === "__new__") {
|
|
1288
|
+
const name2 = await p2.text({
|
|
1289
|
+
message: "New endpoint name",
|
|
1290
|
+
placeholder: "e.g. users",
|
|
1291
|
+
validate: (value) => !value ? "Required." : void 0
|
|
1292
|
+
});
|
|
1293
|
+
if (p2.isCancel(name2)) {
|
|
1294
|
+
p2.cancel("Cancelled.");
|
|
1295
|
+
return;
|
|
1296
|
+
}
|
|
1297
|
+
const added = await addRoute(name2);
|
|
1298
|
+
route = added.route;
|
|
1299
|
+
p2.log.success(`Added blank endpoint src/endpoints/${route}`);
|
|
1300
|
+
}
|
|
1301
|
+
const verb = await p2.select({
|
|
1302
|
+
message: "HTTP method",
|
|
1303
|
+
options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() }))
|
|
1304
|
+
});
|
|
1305
|
+
if (p2.isCancel(verb)) {
|
|
1306
|
+
p2.cancel("Cancelled.");
|
|
1307
|
+
return;
|
|
1308
|
+
}
|
|
1309
|
+
const defaultPath = verb === "get" || verb === "post" ? "/" : "/:id";
|
|
1310
|
+
const path = await p2.text({
|
|
1311
|
+
message: "Path (relative to this endpoint's mount)",
|
|
1312
|
+
placeholder: defaultPath,
|
|
1313
|
+
initialValue: defaultPath,
|
|
1314
|
+
validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
|
|
1315
|
+
});
|
|
1316
|
+
if (p2.isCancel(path)) {
|
|
1317
|
+
p2.cancel("Cancelled.");
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1320
|
+
const existingMethods = summaries.find((s) => s.route === route)?.methods ?? [];
|
|
1321
|
+
const defaultName = suggestMethodName(verb, path);
|
|
1322
|
+
const name = await p2.text({
|
|
1323
|
+
message: "Name (controller export + service function)",
|
|
1324
|
+
placeholder: defaultName,
|
|
1325
|
+
initialValue: defaultName,
|
|
1326
|
+
validate: (value) => {
|
|
1327
|
+
if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
1328
|
+
if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
|
|
1329
|
+
return void 0;
|
|
1330
|
+
}
|
|
1331
|
+
});
|
|
1332
|
+
if (p2.isCancel(name)) {
|
|
1333
|
+
p2.cancel("Cancelled.");
|
|
1334
|
+
return;
|
|
1335
|
+
}
|
|
1336
|
+
let needsBody = false;
|
|
1337
|
+
if (verb === "post" || verb === "put" || verb === "patch") {
|
|
1338
|
+
const answer = await p2.confirm({ message: "Validate a request body?", initialValue: true });
|
|
1339
|
+
if (p2.isCancel(answer)) {
|
|
1340
|
+
p2.cancel("Cancelled.");
|
|
1341
|
+
return;
|
|
1342
|
+
}
|
|
1343
|
+
needsBody = answer;
|
|
1344
|
+
}
|
|
1345
|
+
const needsQuery = await p2.confirm({ message: "Validate query params?", initialValue: false });
|
|
1346
|
+
if (p2.isCancel(needsQuery)) {
|
|
1347
|
+
p2.cancel("Cancelled.");
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
const spec = { verb, path, name, needsBody, needsQuery };
|
|
1351
|
+
try {
|
|
1352
|
+
const { filesWritten } = await addMethod(route, spec);
|
|
1353
|
+
p2.log.success(`Added ${verb.toUpperCase()} ${path} \u2192 ${name} in src/endpoints/${route} (${filesWritten.length} files)`);
|
|
1354
|
+
} catch (err) {
|
|
1355
|
+
p2.log.error(err instanceof Error ? err.message : String(err));
|
|
1356
|
+
}
|
|
1357
|
+
const again = await p2.confirm({ message: "Add another method?", initialValue: true });
|
|
1358
|
+
if (p2.isCancel(again) || !again) break;
|
|
1359
|
+
}
|
|
1360
|
+
p2.outro("Done.");
|
|
1361
|
+
}
|
|
1362
|
+
async function serverConfigAddEndpoint() {
|
|
1363
|
+
const name = await p2.text({
|
|
1364
|
+
message: "New endpoint name",
|
|
1365
|
+
placeholder: "e.g. users",
|
|
1366
|
+
validate: (value) => !value ? "Required." : void 0
|
|
1367
|
+
});
|
|
1368
|
+
if (p2.isCancel(name)) {
|
|
1369
|
+
p2.cancel("Cancelled.");
|
|
1370
|
+
return;
|
|
1371
|
+
}
|
|
1372
|
+
const { route, filesWritten } = await addRoute(name);
|
|
1373
|
+
p2.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet).`);
|
|
1374
|
+
}
|
|
1375
|
+
async function serverConfigRemoveEndpoint(summaries) {
|
|
1376
|
+
if (summaries.length === 0) {
|
|
1377
|
+
p2.log.info("No endpoints yet.");
|
|
1378
|
+
return;
|
|
1379
|
+
}
|
|
1380
|
+
const route = await p2.select({
|
|
1381
|
+
message: "Remove which endpoint?",
|
|
1382
|
+
options: summaries.map((s) => ({ value: s.route, label: s.route }))
|
|
1383
|
+
});
|
|
1384
|
+
if (p2.isCancel(route)) {
|
|
1385
|
+
p2.cancel("Cancelled.");
|
|
1386
|
+
return;
|
|
1387
|
+
}
|
|
1388
|
+
const confirmed = await p2.confirm({
|
|
1389
|
+
message: `Remove src/endpoints/${route} and unmount it? This deletes the folder.`,
|
|
1390
|
+
initialValue: false
|
|
1391
|
+
});
|
|
1392
|
+
if (p2.isCancel(confirmed) || !confirmed) {
|
|
1393
|
+
p2.cancel("Cancelled.");
|
|
1394
|
+
return;
|
|
1395
|
+
}
|
|
1396
|
+
const { removedDir } = await removeRoute(route);
|
|
1397
|
+
p2.log.success(`Removed ${removedDir}.`);
|
|
1398
|
+
}
|
|
1399
|
+
async function serverConfigAddMethod(summaries) {
|
|
1400
|
+
const routeChoice = await p2.select({
|
|
1401
|
+
message: "Add a method to which endpoint?",
|
|
1402
|
+
options: [
|
|
1403
|
+
...summaries.map((s) => ({ value: s.route, label: s.route })),
|
|
1404
|
+
{ value: "__new__", label: "+ New blank endpoint" }
|
|
1405
|
+
]
|
|
1406
|
+
});
|
|
1407
|
+
if (p2.isCancel(routeChoice)) {
|
|
1408
|
+
p2.cancel("Cancelled.");
|
|
1409
|
+
return;
|
|
1410
|
+
}
|
|
1411
|
+
let route = routeChoice;
|
|
1412
|
+
let existingMethods = summaries.find((s) => s.route === route)?.methods ?? [];
|
|
1413
|
+
if (route === "__new__") {
|
|
1414
|
+
const name2 = await p2.text({
|
|
1415
|
+
message: "New endpoint name",
|
|
1416
|
+
placeholder: "e.g. users",
|
|
1417
|
+
validate: (value) => !value ? "Required." : void 0
|
|
1418
|
+
});
|
|
1419
|
+
if (p2.isCancel(name2)) {
|
|
1420
|
+
p2.cancel("Cancelled.");
|
|
1421
|
+
return;
|
|
1422
|
+
}
|
|
1423
|
+
const added = await addRoute(name2);
|
|
1424
|
+
route = added.route;
|
|
1425
|
+
existingMethods = [];
|
|
1426
|
+
p2.log.success(`Added blank endpoint src/endpoints/${route}`);
|
|
1427
|
+
}
|
|
1428
|
+
const verb = await p2.select({
|
|
1429
|
+
message: "HTTP method",
|
|
1430
|
+
options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() }))
|
|
1431
|
+
});
|
|
1432
|
+
if (p2.isCancel(verb)) {
|
|
1433
|
+
p2.cancel("Cancelled.");
|
|
1434
|
+
return;
|
|
1435
|
+
}
|
|
1436
|
+
const defaultPath = verb === "get" || verb === "post" ? "/" : "/:id";
|
|
1437
|
+
const path = await p2.text({
|
|
1438
|
+
message: "Path (relative to this endpoint's mount)",
|
|
1439
|
+
placeholder: defaultPath,
|
|
1440
|
+
initialValue: defaultPath,
|
|
1441
|
+
validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
|
|
1442
|
+
});
|
|
1443
|
+
if (p2.isCancel(path)) {
|
|
1444
|
+
p2.cancel("Cancelled.");
|
|
1445
|
+
return;
|
|
1446
|
+
}
|
|
1447
|
+
const defaultName = suggestMethodName(verb, path);
|
|
1448
|
+
const name = await p2.text({
|
|
1449
|
+
message: "Name (controller export + service function)",
|
|
1450
|
+
placeholder: defaultName,
|
|
1451
|
+
initialValue: defaultName,
|
|
1452
|
+
validate: (value) => {
|
|
1453
|
+
if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
1454
|
+
if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
|
|
1455
|
+
return void 0;
|
|
1456
|
+
}
|
|
1457
|
+
});
|
|
1458
|
+
if (p2.isCancel(name)) {
|
|
1459
|
+
p2.cancel("Cancelled.");
|
|
1460
|
+
return;
|
|
1461
|
+
}
|
|
1462
|
+
let needsBody = false;
|
|
1463
|
+
if (verb === "post" || verb === "put" || verb === "patch") {
|
|
1464
|
+
const answer = await p2.confirm({ message: "Validate a request body?", initialValue: true });
|
|
1465
|
+
if (p2.isCancel(answer)) {
|
|
1466
|
+
p2.cancel("Cancelled.");
|
|
1467
|
+
return;
|
|
1468
|
+
}
|
|
1469
|
+
needsBody = answer;
|
|
1470
|
+
}
|
|
1471
|
+
const needsQuery = await p2.confirm({ message: "Validate query params?", initialValue: false });
|
|
1472
|
+
if (p2.isCancel(needsQuery)) {
|
|
1473
|
+
p2.cancel("Cancelled.");
|
|
1474
|
+
return;
|
|
1475
|
+
}
|
|
1476
|
+
const spec = { verb, path, name, needsBody, needsQuery };
|
|
1477
|
+
const { filesWritten } = await addMethod(route, spec);
|
|
1478
|
+
p2.log.success(`Added ${verb.toUpperCase()} ${path} \u2192 ${name} in src/endpoints/${route} (${filesWritten.length} files)`);
|
|
1479
|
+
}
|
|
1480
|
+
async function selectEndpointWithMethods(summaries, message) {
|
|
1481
|
+
const withMethods = summaries.filter((s) => s.methods.length > 0);
|
|
1482
|
+
if (withMethods.length === 0) {
|
|
1483
|
+
p2.log.info("No methods yet \u2014 add one first.");
|
|
1484
|
+
return null;
|
|
1485
|
+
}
|
|
1486
|
+
const route = await p2.select({
|
|
1487
|
+
message,
|
|
1488
|
+
options: withMethods.map((s) => ({ value: s.route, label: s.route }))
|
|
1489
|
+
});
|
|
1490
|
+
if (p2.isCancel(route)) {
|
|
1491
|
+
p2.cancel("Cancelled.");
|
|
1492
|
+
return null;
|
|
1493
|
+
}
|
|
1494
|
+
return withMethods.find((s) => s.route === route) ?? null;
|
|
1495
|
+
}
|
|
1496
|
+
async function selectMethod(endpoint, message) {
|
|
1497
|
+
const choice = await p2.select({
|
|
1498
|
+
message,
|
|
1499
|
+
options: endpoint.methods.map((m) => ({
|
|
1500
|
+
value: `${m.verb}:${m.path}`,
|
|
1501
|
+
label: `${m.verb.toUpperCase()} ${m.path} \u2192 ${m.name}`
|
|
1502
|
+
}))
|
|
1503
|
+
});
|
|
1504
|
+
if (p2.isCancel(choice)) {
|
|
1505
|
+
p2.cancel("Cancelled.");
|
|
1506
|
+
return null;
|
|
1507
|
+
}
|
|
1508
|
+
const [verb, path] = choice.split(/:(.*)/s);
|
|
1509
|
+
return endpoint.methods.find((m) => m.verb === verb && m.path === path) ?? null;
|
|
1510
|
+
}
|
|
1511
|
+
async function serverConfigRemoveMethod(summaries) {
|
|
1512
|
+
const endpoint = await selectEndpointWithMethods(summaries, "Remove a method from which endpoint?");
|
|
1513
|
+
if (!endpoint) return;
|
|
1514
|
+
const method = await selectMethod(endpoint, "Remove which method?");
|
|
1515
|
+
if (!method) return;
|
|
1516
|
+
const confirmed = await p2.confirm({
|
|
1517
|
+
message: `Remove ${method.verb.toUpperCase()} ${method.path} (${method.name}) from ${endpoint.route}?`,
|
|
1518
|
+
initialValue: false
|
|
1519
|
+
});
|
|
1520
|
+
if (p2.isCancel(confirmed) || !confirmed) {
|
|
1521
|
+
p2.cancel("Cancelled.");
|
|
1522
|
+
return;
|
|
1523
|
+
}
|
|
1524
|
+
const { removed } = await removeMethod(endpoint.route, method.verb, method.path);
|
|
1525
|
+
p2.log.success(`Removed ${removed.verb.toUpperCase()} ${removed.path} (${removed.name}) from src/endpoints/${endpoint.route}.`);
|
|
1526
|
+
}
|
|
1527
|
+
async function serverConfigModifyMethod(summaries) {
|
|
1528
|
+
const endpoint = await selectEndpointWithMethods(summaries, "Modify a method on which endpoint?");
|
|
1529
|
+
if (!endpoint) return;
|
|
1530
|
+
const old = await selectMethod(endpoint, "Modify which method?");
|
|
1531
|
+
if (!old) return;
|
|
1532
|
+
const { needsBody: oldNeedsBody, needsQuery: oldNeedsQuery } = await detectMethodValidation(endpoint.route, old.name);
|
|
1533
|
+
const others = endpoint.methods.filter((m) => m !== old);
|
|
1534
|
+
const verb = await p2.select({
|
|
1535
|
+
message: "HTTP method",
|
|
1536
|
+
initialValue: old.verb,
|
|
1537
|
+
options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() }))
|
|
1538
|
+
});
|
|
1539
|
+
if (p2.isCancel(verb)) {
|
|
1540
|
+
p2.cancel("Cancelled.");
|
|
1541
|
+
return;
|
|
1542
|
+
}
|
|
1543
|
+
const path = await p2.text({
|
|
1544
|
+
message: "Path (relative to this endpoint's mount)",
|
|
1545
|
+
initialValue: old.path,
|
|
1546
|
+
validate: (value) => !value.startsWith("/") ? 'Must start with "/".' : void 0
|
|
1547
|
+
});
|
|
1548
|
+
if (p2.isCancel(path)) {
|
|
1549
|
+
p2.cancel("Cancelled.");
|
|
1550
|
+
return;
|
|
1551
|
+
}
|
|
1552
|
+
const name = await p2.text({
|
|
1553
|
+
message: "Name (controller export + service function)",
|
|
1554
|
+
initialValue: old.name,
|
|
1555
|
+
validate: (value) => {
|
|
1556
|
+
if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
1557
|
+
if (others.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
|
|
1558
|
+
return void 0;
|
|
1559
|
+
}
|
|
1560
|
+
});
|
|
1561
|
+
if (p2.isCancel(name)) {
|
|
1562
|
+
p2.cancel("Cancelled.");
|
|
1563
|
+
return;
|
|
1564
|
+
}
|
|
1565
|
+
if (others.some((m) => m.verb === verb && m.path === path)) {
|
|
1566
|
+
p2.log.error(`${verb.toUpperCase()} ${path} is already used by another method on this endpoint.`);
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
let needsBody = false;
|
|
1570
|
+
if (verb === "post" || verb === "put" || verb === "patch") {
|
|
1571
|
+
const answer = await p2.confirm({ message: "Validate a request body?", initialValue: oldNeedsBody });
|
|
1572
|
+
if (p2.isCancel(answer)) {
|
|
1573
|
+
p2.cancel("Cancelled.");
|
|
1574
|
+
return;
|
|
1575
|
+
}
|
|
1576
|
+
needsBody = answer;
|
|
1577
|
+
}
|
|
1578
|
+
const needsQuery = await p2.confirm({ message: "Validate query params?", initialValue: oldNeedsQuery });
|
|
1579
|
+
if (p2.isCancel(needsQuery)) {
|
|
1580
|
+
p2.cancel("Cancelled.");
|
|
1581
|
+
return;
|
|
1582
|
+
}
|
|
1583
|
+
await removeMethod(endpoint.route, old.verb, old.path);
|
|
1584
|
+
const { filesWritten } = await addMethod(endpoint.route, { verb, path, name, needsBody, needsQuery });
|
|
1585
|
+
p2.log.success(
|
|
1586
|
+
`Updated src/endpoints/${endpoint.route}: ${old.verb.toUpperCase()} ${old.path} \u2192 ${verb.toUpperCase()} ${path} (${name}), ${filesWritten.length} files touched.`
|
|
1587
|
+
);
|
|
1588
|
+
}
|
|
1589
|
+
async function runServerConfig() {
|
|
1590
|
+
p2.intro("create-backon server-config");
|
|
1591
|
+
while (true) {
|
|
1592
|
+
const { root } = await detectProject();
|
|
1593
|
+
const summaries = await listEndpointsWithMethods();
|
|
1594
|
+
p2.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
1595
|
+
const action = await p2.select({
|
|
1596
|
+
message: "What do you want to do?",
|
|
1597
|
+
options: [
|
|
1598
|
+
{ value: "add-endpoint", label: "Add a new endpoint" },
|
|
1599
|
+
{ value: "remove-endpoint", label: "Remove an endpoint" },
|
|
1600
|
+
{ value: "add-method", label: "Add a method" },
|
|
1601
|
+
{ value: "remove-method", label: "Remove a method" },
|
|
1602
|
+
{ value: "modify-method", label: "Modify a method" },
|
|
1603
|
+
{ value: "exit", label: "Exit" }
|
|
1604
|
+
]
|
|
1605
|
+
});
|
|
1606
|
+
if (p2.isCancel(action) || action === "exit") break;
|
|
1607
|
+
try {
|
|
1608
|
+
switch (action) {
|
|
1609
|
+
case "add-endpoint":
|
|
1610
|
+
await serverConfigAddEndpoint();
|
|
1611
|
+
break;
|
|
1612
|
+
case "remove-endpoint":
|
|
1613
|
+
await serverConfigRemoveEndpoint(summaries);
|
|
1614
|
+
break;
|
|
1615
|
+
case "add-method":
|
|
1616
|
+
await serverConfigAddMethod(summaries);
|
|
1617
|
+
break;
|
|
1618
|
+
case "remove-method":
|
|
1619
|
+
await serverConfigRemoveMethod(summaries);
|
|
1620
|
+
break;
|
|
1621
|
+
case "modify-method":
|
|
1622
|
+
await serverConfigModifyMethod(summaries);
|
|
1623
|
+
break;
|
|
1624
|
+
}
|
|
1625
|
+
} catch (err) {
|
|
1626
|
+
p2.log.error(err instanceof Error ? err.message : String(err));
|
|
1627
|
+
}
|
|
1628
|
+
}
|
|
1629
|
+
p2.outro("Done.");
|
|
1630
|
+
}
|
|
1631
|
+
async function runScaffold() {
|
|
1632
|
+
const answers = await runPrompts();
|
|
1633
|
+
const { root, filesWritten } = await generateProject(answers);
|
|
1634
|
+
const nextSteps = answers.projectName === "." ? "bun install\nbun run dev" : `cd ${answers.projectName}
|
|
1635
|
+
bun install
|
|
1636
|
+
bun run dev`;
|
|
1637
|
+
p2.note(nextSteps, "Next steps");
|
|
1638
|
+
p2.log.success(`Wrote ${filesWritten.length} files to ${root}`);
|
|
1639
|
+
}
|
|
1640
|
+
async function main() {
|
|
1641
|
+
const [subcommand, ...rest] = process.argv.slice(2);
|
|
1642
|
+
if (subcommand && ADD_ROUTE_SUBCOMMANDS.has(subcommand)) {
|
|
1643
|
+
await runAddRoute(rest);
|
|
1644
|
+
return;
|
|
1645
|
+
}
|
|
1646
|
+
if (subcommand && REMOVE_ROUTE_SUBCOMMANDS.has(subcommand)) {
|
|
1647
|
+
await runRemoveRoute(rest);
|
|
1648
|
+
return;
|
|
1649
|
+
}
|
|
1650
|
+
if (subcommand && LIST_ROUTES_SUBCOMMANDS.has(subcommand)) {
|
|
1651
|
+
await runListRoutes();
|
|
1652
|
+
return;
|
|
1653
|
+
}
|
|
1654
|
+
if (subcommand && DOCTOR_SUBCOMMANDS.has(subcommand)) {
|
|
1655
|
+
await runDoctorCommand();
|
|
1656
|
+
return;
|
|
1657
|
+
}
|
|
1658
|
+
if (subcommand && ADD_METHOD_SUBCOMMANDS.has(subcommand)) {
|
|
1659
|
+
await runAddMethod();
|
|
1660
|
+
return;
|
|
1661
|
+
}
|
|
1662
|
+
if (subcommand && PROJECT_SUBCOMMANDS.has(subcommand)) {
|
|
1663
|
+
await runProjectOverview();
|
|
1664
|
+
return;
|
|
1665
|
+
}
|
|
1666
|
+
if (subcommand && SERVER_CONFIG_SUBCOMMANDS.has(subcommand)) {
|
|
1667
|
+
await runServerConfig();
|
|
1668
|
+
return;
|
|
1669
|
+
}
|
|
1670
|
+
await runScaffold();
|
|
1671
|
+
}
|
|
1672
|
+
main().catch((err) => {
|
|
1673
|
+
console.error(err);
|
|
1674
|
+
process.exit(1);
|
|
1675
|
+
});
|