create-backon 0.6.2 → 0.9.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 +102 -12
- package/dist/cli.js +1240 -0
- package/package.json +10 -6
- package/src/add-method.ts +101 -0
- package/src/add-route.ts +11 -9
- package/src/cli.ts +145 -3
- package/src/colors.ts +25 -0
- package/src/generate.ts +17 -6
- package/src/prompts.ts +26 -0
- package/src/route-methods.ts +76 -0
- package/src/templates/base.ts +89 -5
- package/src/templates/route.ts +143 -64
package/package.json
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-backon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"type": "module",
|
|
5
|
-
"description": "Scaffolds a new backend project on backon — like `bun create vite@latest`, but for a consistent controller/routes/services backend layout.",
|
|
5
|
+
"description": "Scaffolds a new backend project on backon — like `bun create vite@latest`, but for a consistent controller/routes/services backend layout. Runs via bunx/bun create or npx/npm create.",
|
|
6
6
|
"license": "MIT",
|
|
7
7
|
"homepage": "https://github.com/mednours/backon/tree/main/packages/create-backon#readme",
|
|
8
8
|
"repository": {
|
|
@@ -12,22 +12,26 @@
|
|
|
12
12
|
},
|
|
13
13
|
"bugs": "https://github.com/mednours/backon/issues",
|
|
14
14
|
"engines": {
|
|
15
|
-
"bun": ">=1.3.0"
|
|
15
|
+
"bun": ">=1.3.0",
|
|
16
|
+
"node": ">=18.0.0"
|
|
16
17
|
},
|
|
17
18
|
"bin": {
|
|
18
|
-
"create-backon": "./
|
|
19
|
+
"create-backon": "./dist/cli.js"
|
|
19
20
|
},
|
|
20
|
-
"files": ["src"],
|
|
21
|
+
"files": ["src", "dist"],
|
|
21
22
|
"scripts": {
|
|
22
23
|
"start": "bun run src/cli.ts",
|
|
23
24
|
"test": "bun test",
|
|
24
|
-
"typecheck": "tsc --noEmit"
|
|
25
|
+
"typecheck": "tsc --noEmit",
|
|
26
|
+
"build": "rm -rf dist && esbuild src/cli.ts --bundle --platform=node --format=esm --target=node18 --packages=external --banner:js=\"#!/usr/bin/env node\" --outfile=dist/cli.js && chmod +x dist/cli.js",
|
|
27
|
+
"prepublishOnly": "bun run typecheck && bun run test && bun run build"
|
|
25
28
|
},
|
|
26
29
|
"dependencies": {
|
|
27
30
|
"@clack/prompts": "^0.9.1"
|
|
28
31
|
},
|
|
29
32
|
"devDependencies": {
|
|
30
33
|
"@types/bun": "latest",
|
|
34
|
+
"esbuild": "^0.28.2",
|
|
31
35
|
"typescript": "^5.7.2"
|
|
32
36
|
}
|
|
33
37
|
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { readFile, writeFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { detectProject } from "./detect";
|
|
4
|
+
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
5
|
+
import { parseRouteMethods } from "./route-methods";
|
|
6
|
+
import {
|
|
7
|
+
controllerImports,
|
|
8
|
+
renderControllerMethod,
|
|
9
|
+
renderServiceMethod,
|
|
10
|
+
routeMountLine,
|
|
11
|
+
serviceImports,
|
|
12
|
+
type MethodSpec,
|
|
13
|
+
} from "./templates/route";
|
|
14
|
+
|
|
15
|
+
export interface AddMethodResult {
|
|
16
|
+
route: string;
|
|
17
|
+
root: string;
|
|
18
|
+
filesWritten: string[];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// The exact placeholder comment each blank file starts with — see
|
|
22
|
+
// templates/route.ts. Stripped the first time a real method lands, wherever
|
|
23
|
+
// it happens to sit in the file (start of controller.ts/services.ts, but
|
|
24
|
+
// mid-file in routes.ts, after the Router()/Hono() line).
|
|
25
|
+
const PLACEHOLDER_PATTERN = /\/\/ No (?:routes|methods) yet[^\n]*\n\n?/;
|
|
26
|
+
|
|
27
|
+
function stripPlaceholder(content: string): string {
|
|
28
|
+
return content.replace(PLACEHOLDER_PATTERN, "");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** Inserts any of importLines not already present, right after the file's existing leading import block. */
|
|
32
|
+
function ensureImports(content: string, importLines: string[]): string {
|
|
33
|
+
const stripped = stripPlaceholder(content);
|
|
34
|
+
const missing = importLines.filter((line) => !stripped.includes(line));
|
|
35
|
+
if (missing.length === 0) return stripped;
|
|
36
|
+
|
|
37
|
+
const lines = stripped.split("\n");
|
|
38
|
+
let insertAt = 0;
|
|
39
|
+
while (insertAt < lines.length && lines[insertAt]?.startsWith("import ")) insertAt++;
|
|
40
|
+
lines.splice(insertAt, 0, ...missing);
|
|
41
|
+
return lines.join("\n");
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function appendBlock(content: string, block: string): string {
|
|
45
|
+
const trimmed = content.replace(/\n+$/, "");
|
|
46
|
+
return trimmed ? `${trimmed}\n\n${block}\n` : `${block}\n`;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Adds one HTTP method to an already-mounted, already-blank-or-partial
|
|
51
|
+
* endpoint: appends a defineRoute() export (with whatever params/body/query
|
|
52
|
+
* schemas this method declares — params auto-derived from the path, body
|
|
53
|
+
* and query left as TODO placeholders same as the old fixed scaffold did)
|
|
54
|
+
* to the controller, a matching service function typed via z.infer, and
|
|
55
|
+
* the route mount line. All three files are read fresh off disk first, so
|
|
56
|
+
* this is safe to call repeatedly, or after the previous method's stub was
|
|
57
|
+
* hand-edited.
|
|
58
|
+
*/
|
|
59
|
+
export async function addMethod(route: string, spec: MethodSpec, cwd: string = process.cwd()): Promise<AddMethodResult> {
|
|
60
|
+
const { root, framework, language, ext } = await detectProject(cwd);
|
|
61
|
+
|
|
62
|
+
const { contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
63
|
+
const mounted = parseMountedRoutes(indexContents);
|
|
64
|
+
if (!mounted.includes(route)) {
|
|
65
|
+
throw new Error(`"${route}" isn't mounted in src/endpoints/index.${ext} — add it first with \`bun run add-route\`.`);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const routeDir = join(root, "src/endpoints", route);
|
|
69
|
+
const controllerPath = join(routeDir, `${route}.controller.${ext}`);
|
|
70
|
+
const routesPath = join(routeDir, `${route}.routes.${ext}`);
|
|
71
|
+
const servicesPath = join(routeDir, `${route}.services.${ext}`);
|
|
72
|
+
|
|
73
|
+
const [controllerContents, routesContents, servicesContents] = await Promise.all([
|
|
74
|
+
readFile(controllerPath, "utf-8"),
|
|
75
|
+
readFile(routesPath, "utf-8"),
|
|
76
|
+
readFile(servicesPath, "utf-8"),
|
|
77
|
+
]);
|
|
78
|
+
|
|
79
|
+
const existing = parseRouteMethods(routesContents);
|
|
80
|
+
if (existing.some((m) => m.name === spec.name)) {
|
|
81
|
+
throw new Error(`"${spec.name}" is already used in ${controllerPath} — pick a different name.`);
|
|
82
|
+
}
|
|
83
|
+
if (existing.some((m) => m.verb === spec.verb && m.path === spec.path)) {
|
|
84
|
+
throw new Error(`${spec.verb.toUpperCase()} ${spec.path} is already mounted in ${routesPath}.`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const newController = appendBlock(ensureImports(controllerContents, controllerImports(route, framework)), renderControllerMethod(spec));
|
|
88
|
+
const newRoutes = appendBlock(
|
|
89
|
+
ensureImports(routesContents, [`import * as controller from "./${route}.controller";`]),
|
|
90
|
+
routeMountLine(route, spec)
|
|
91
|
+
);
|
|
92
|
+
const newServices = appendBlock(ensureImports(servicesContents, serviceImports(route, spec, language)), renderServiceMethod(spec, language));
|
|
93
|
+
|
|
94
|
+
await Promise.all([
|
|
95
|
+
writeFile(controllerPath, newController),
|
|
96
|
+
writeFile(routesPath, newRoutes),
|
|
97
|
+
writeFile(servicesPath, newServices),
|
|
98
|
+
]);
|
|
99
|
+
|
|
100
|
+
return { route, root, filesWritten: [controllerPath, routesPath, servicesPath] };
|
|
101
|
+
}
|
package/src/add-route.ts
CHANGED
|
@@ -4,7 +4,7 @@ import { detectProject } from "./detect";
|
|
|
4
4
|
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
5
5
|
import { toKebabCase } from "./prompts";
|
|
6
6
|
import { renderEndpointsIndex } from "./templates/base";
|
|
7
|
-
import {
|
|
7
|
+
import { renderBlankController, renderBlankRoutes, renderBlankServices } from "./templates/route";
|
|
8
8
|
|
|
9
9
|
export interface AddRouteResult {
|
|
10
10
|
route: string;
|
|
@@ -18,11 +18,13 @@ async function write(path: string, contents: string): Promise<void> {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
/**
|
|
21
|
-
* Adds a single route to an already-scaffolded backon project: detects
|
|
22
|
-
* project's framework/language from its package.json, writes the same
|
|
23
|
-
* controller/routes/services trio generateProject() would have
|
|
24
|
-
* this route at scaffold time
|
|
25
|
-
*
|
|
21
|
+
* Adds a single blank route to an already-scaffolded backon project: detects
|
|
22
|
+
* the project's framework/language from its package.json, writes the same
|
|
23
|
+
* blank controller/routes/services trio generateProject() would have
|
|
24
|
+
* written for this route at scaffold time (zero methods — see
|
|
25
|
+
* templates/route.ts), and regenerates src/endpoints/index.<ext> so the new
|
|
26
|
+
* route is mounted alongside whatever was already there. Use
|
|
27
|
+
* `add-method` afterward to give it an actual GET/POST/etc.
|
|
26
28
|
*/
|
|
27
29
|
export async function addRoute(rawName: string, cwd: string = process.cwd()): Promise<AddRouteResult> {
|
|
28
30
|
const route = toKebabCase(rawName);
|
|
@@ -55,9 +57,9 @@ export async function addRoute(rawName: string, cwd: string = process.cwd()): Pr
|
|
|
55
57
|
const routeDir = join(endpointsDir, route);
|
|
56
58
|
const filesWritten: string[] = [];
|
|
57
59
|
const files: Array<[string, string]> = [
|
|
58
|
-
[join(routeDir, `${route}.controller.${ext}`),
|
|
59
|
-
[join(routeDir, `${route}.routes.${ext}`),
|
|
60
|
-
[join(routeDir, `${route}.services.${ext}`),
|
|
60
|
+
[join(routeDir, `${route}.controller.${ext}`), renderBlankController()],
|
|
61
|
+
[join(routeDir, `${route}.routes.${ext}`), renderBlankRoutes(route, framework, language)],
|
|
62
|
+
[join(routeDir, `${route}.services.${ext}`), renderBlankServices()],
|
|
61
63
|
];
|
|
62
64
|
|
|
63
65
|
for (const [path, contents] of files) {
|
package/src/cli.ts
CHANGED
|
@@ -1,4 +1,12 @@
|
|
|
1
|
-
|
|
1
|
+
// No shebang here on purpose — the published bin is the bundled
|
|
2
|
+
// dist/cli.js esbuild produces (see package.json's "build" script), which
|
|
3
|
+
// gets its own "#!/usr/bin/env node" shebang from esbuild's --banner flag.
|
|
4
|
+
// A shebang on *this* file would end up duplicated as the bundle's second
|
|
5
|
+
// line (esbuild carries a source shebang straight through), which Node
|
|
6
|
+
// rejects outright — a shebang only means anything as a file's literal
|
|
7
|
+
// first line. Local dev (`bun run src/cli.ts`, the "start" script) doesn't
|
|
8
|
+
// need a shebang either; `bun run` executes the given file directly, it
|
|
9
|
+
// doesn't rely on the OS reading a shebang the way `./cli.ts` would.
|
|
2
10
|
import * as p from "@clack/prompts";
|
|
3
11
|
import { runPrompts } from "./prompts";
|
|
4
12
|
import { generateProject } from "./generate";
|
|
@@ -6,11 +14,15 @@ import { addRoute } from "./add-route";
|
|
|
6
14
|
import { removeRoute } from "./remove-route";
|
|
7
15
|
import { listRoutes } from "./list-routes";
|
|
8
16
|
import { runDoctor } from "./doctor";
|
|
17
|
+
import { addMethod } from "./add-method";
|
|
18
|
+
import { formatEndpointsDashboard, listEndpointsWithMethods } from "./route-methods";
|
|
19
|
+
import { HTTP_VERBS, paramNamesFromPath, pascalCase, type HttpVerb, type MethodSpec } from "./templates/route";
|
|
9
20
|
|
|
10
21
|
const ADD_ROUTE_SUBCOMMANDS = new Set(["add-route", "route"]);
|
|
11
22
|
const REMOVE_ROUTE_SUBCOMMANDS = new Set(["remove-route", "rm-route"]);
|
|
12
23
|
const LIST_ROUTES_SUBCOMMANDS = new Set(["list-routes", "routes"]);
|
|
13
24
|
const DOCTOR_SUBCOMMANDS = new Set(["doctor"]);
|
|
25
|
+
const ADD_METHOD_SUBCOMMANDS = new Set(["add-method", "method"]);
|
|
14
26
|
|
|
15
27
|
async function promptForRouteName(introText: string): Promise<string> {
|
|
16
28
|
p.intro(introText);
|
|
@@ -35,7 +47,8 @@ async function runAddRoute(args: string[]): Promise<void> {
|
|
|
35
47
|
}
|
|
36
48
|
|
|
37
49
|
const { route, root, filesWritten } = await addRoute(name);
|
|
38
|
-
p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files) in ${root}`);
|
|
50
|
+
p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files, no methods yet) in ${root}`);
|
|
51
|
+
p.log.info("Run `bun run add-method` to give it a GET/POST/etc.");
|
|
39
52
|
}
|
|
40
53
|
|
|
41
54
|
async function runRemoveRoute(args: string[]): Promise<void> {
|
|
@@ -64,7 +77,8 @@ async function runListRoutes(): Promise<void> {
|
|
|
64
77
|
p.log.info(`No routes mounted in ${root}.`);
|
|
65
78
|
return;
|
|
66
79
|
}
|
|
67
|
-
|
|
80
|
+
const summaries = await listEndpointsWithMethods();
|
|
81
|
+
p.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
68
82
|
}
|
|
69
83
|
|
|
70
84
|
async function runDoctorCommand(): Promise<void> {
|
|
@@ -77,6 +91,130 @@ async function runDoctorCommand(): Promise<void> {
|
|
|
77
91
|
process.exitCode = 1;
|
|
78
92
|
}
|
|
79
93
|
|
|
94
|
+
function suggestMethodName(verb: HttpVerb, path: string): string {
|
|
95
|
+
const params = paramNamesFromPath(path);
|
|
96
|
+
if (verb === "get" && params.length === 0) return "list";
|
|
97
|
+
if (verb === "get") return `getBy${pascalCase(params[0] ?? "id")}`;
|
|
98
|
+
if (verb === "post") return "create";
|
|
99
|
+
if (verb === "put" || verb === "patch") return "update";
|
|
100
|
+
return "remove";
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const IDENTIFIER_PATTERN = /^[a-zA-Z_$][a-zA-Z0-9_$]*$/;
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Interactive, loops until the user's done: shows every endpoint and the
|
|
107
|
+
* methods it already has (colored by verb), then either picks one to add
|
|
108
|
+
* to or spins up a new blank one, then walks through verb/path/name/schema
|
|
109
|
+
* choices for a single method. Kept separate from add-route/remove-route on
|
|
110
|
+
* purpose — those stay simple whole-endpoint create/delete for scripted use.
|
|
111
|
+
*/
|
|
112
|
+
async function runAddMethod(): Promise<void> {
|
|
113
|
+
p.intro("create-backon add-method");
|
|
114
|
+
|
|
115
|
+
// eslint-disable-next-line no-constant-condition
|
|
116
|
+
while (true) {
|
|
117
|
+
const { root, routes } = await listRoutes();
|
|
118
|
+
const summaries = await listEndpointsWithMethods();
|
|
119
|
+
p.note(formatEndpointsDashboard(summaries), `Endpoints in ${root}`);
|
|
120
|
+
|
|
121
|
+
const routeChoice = await p.select({
|
|
122
|
+
message: "Add a method to which endpoint?",
|
|
123
|
+
options: [
|
|
124
|
+
...routes.map((route) => ({ value: route, label: route })),
|
|
125
|
+
{ value: "__new__", label: "+ New blank endpoint" },
|
|
126
|
+
],
|
|
127
|
+
});
|
|
128
|
+
if (p.isCancel(routeChoice)) {
|
|
129
|
+
p.cancel("Cancelled.");
|
|
130
|
+
return;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
let route = routeChoice;
|
|
134
|
+
if (route === "__new__") {
|
|
135
|
+
const name = await p.text({
|
|
136
|
+
message: "New endpoint name",
|
|
137
|
+
placeholder: "e.g. users",
|
|
138
|
+
validate: (value) => (!value ? "Required." : undefined),
|
|
139
|
+
});
|
|
140
|
+
if (p.isCancel(name)) {
|
|
141
|
+
p.cancel("Cancelled.");
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const added = await addRoute(name);
|
|
145
|
+
route = added.route;
|
|
146
|
+
p.log.success(`Added blank endpoint src/endpoints/${route}`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const verb = await p.select({
|
|
150
|
+
message: "HTTP method",
|
|
151
|
+
options: HTTP_VERBS.map((v) => ({ value: v, label: v.toUpperCase() })),
|
|
152
|
+
});
|
|
153
|
+
if (p.isCancel(verb)) {
|
|
154
|
+
p.cancel("Cancelled.");
|
|
155
|
+
return;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const defaultPath = verb === "get" || verb === "post" ? "/" : "/:id";
|
|
159
|
+
const path = await p.text({
|
|
160
|
+
message: "Path (relative to this endpoint's mount)",
|
|
161
|
+
placeholder: defaultPath,
|
|
162
|
+
initialValue: defaultPath,
|
|
163
|
+
validate: (value) => (!value.startsWith("/") ? 'Must start with "/".' : undefined),
|
|
164
|
+
});
|
|
165
|
+
if (p.isCancel(path)) {
|
|
166
|
+
p.cancel("Cancelled.");
|
|
167
|
+
return;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const existingMethods = summaries.find((s) => s.route === route)?.methods ?? [];
|
|
171
|
+
const defaultName = suggestMethodName(verb, path);
|
|
172
|
+
const name = await p.text({
|
|
173
|
+
message: "Name (controller export + service function)",
|
|
174
|
+
placeholder: defaultName,
|
|
175
|
+
initialValue: defaultName,
|
|
176
|
+
validate: (value) => {
|
|
177
|
+
if (!IDENTIFIER_PATTERN.test(value)) return "Must be a valid identifier.";
|
|
178
|
+
if (existingMethods.some((m) => m.name === value)) return `"${value}" is already used in this endpoint.`;
|
|
179
|
+
return undefined;
|
|
180
|
+
},
|
|
181
|
+
});
|
|
182
|
+
if (p.isCancel(name)) {
|
|
183
|
+
p.cancel("Cancelled.");
|
|
184
|
+
return;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
let needsBody = false;
|
|
188
|
+
if (verb === "post" || verb === "put" || verb === "patch") {
|
|
189
|
+
const answer = await p.confirm({ message: "Validate a request body?", initialValue: true });
|
|
190
|
+
if (p.isCancel(answer)) {
|
|
191
|
+
p.cancel("Cancelled.");
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
needsBody = answer;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const needsQuery = await p.confirm({ message: "Validate query params?", initialValue: false });
|
|
198
|
+
if (p.isCancel(needsQuery)) {
|
|
199
|
+
p.cancel("Cancelled.");
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const spec: MethodSpec = { verb, path, name, needsBody, needsQuery };
|
|
204
|
+
try {
|
|
205
|
+
const { filesWritten } = await addMethod(route, spec);
|
|
206
|
+
p.log.success(`Added ${verb.toUpperCase()} ${path} → ${name} in src/endpoints/${route} (${filesWritten.length} files)`);
|
|
207
|
+
} catch (err) {
|
|
208
|
+
p.log.error(err instanceof Error ? err.message : String(err));
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const again = await p.confirm({ message: "Add another method?", initialValue: true });
|
|
212
|
+
if (p.isCancel(again) || !again) break;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
p.outro("Done.");
|
|
216
|
+
}
|
|
217
|
+
|
|
80
218
|
async function runScaffold(): Promise<void> {
|
|
81
219
|
const answers = await runPrompts();
|
|
82
220
|
const { root, filesWritten } = await generateProject(answers);
|
|
@@ -106,6 +244,10 @@ async function main() {
|
|
|
106
244
|
await runDoctorCommand();
|
|
107
245
|
return;
|
|
108
246
|
}
|
|
247
|
+
if (subcommand && ADD_METHOD_SUBCOMMANDS.has(subcommand)) {
|
|
248
|
+
await runAddMethod();
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
109
251
|
|
|
110
252
|
await runScaffold();
|
|
111
253
|
}
|
package/src/colors.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { HttpVerb } from "./templates/route";
|
|
2
|
+
|
|
3
|
+
// Standard REST-tooling convention (Scalar, Postman, Insomnia all agree on
|
|
4
|
+
// roughly this mapping) — GET blue/cyan, POST green, PUT/PATCH amber,
|
|
5
|
+
// DELETE red. Plain ANSI codes rather than a new dependency: create-backon
|
|
6
|
+
// only depends on @clack/prompts today, and this is five lines.
|
|
7
|
+
const VERB_CODES: Record<HttpVerb, string> = {
|
|
8
|
+
get: "36",
|
|
9
|
+
post: "32",
|
|
10
|
+
put: "33",
|
|
11
|
+
patch: "35",
|
|
12
|
+
delete: "31",
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
const RESET = "\x1b[0m";
|
|
16
|
+
|
|
17
|
+
export function colorVerb(verb: HttpVerb): string {
|
|
18
|
+
const label = verb.toUpperCase().padEnd(6);
|
|
19
|
+
const code = VERB_CODES[verb];
|
|
20
|
+
return code ? `\x1b[${code}m${label}${RESET}` : label;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function dim(text: string): string {
|
|
24
|
+
return `\x1b[2m${text}${RESET}`;
|
|
25
|
+
}
|
package/src/generate.ts
CHANGED
|
@@ -12,8 +12,9 @@ import {
|
|
|
12
12
|
renderPackageJson,
|
|
13
13
|
renderReadme,
|
|
14
14
|
renderTsconfig,
|
|
15
|
+
renderVercelJson,
|
|
15
16
|
} from "./templates/base";
|
|
16
|
-
import {
|
|
17
|
+
import { renderBlankController, renderBlankRoutes, renderBlankServices } from "./templates/route";
|
|
17
18
|
import { renderDbFile } from "./templates/db";
|
|
18
19
|
|
|
19
20
|
async function write(path: string, contents: string): Promise<void> {
|
|
@@ -91,8 +92,13 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
|
|
|
91
92
|
? [join(root, "jsconfig.json"), renderJsconfig()]
|
|
92
93
|
: [join(root, "tsconfig.json"), renderTsconfig()],
|
|
93
94
|
[join(root, "README.md"), renderReadme(readmeAnswers)],
|
|
94
|
-
[
|
|
95
|
-
|
|
95
|
+
[
|
|
96
|
+
join(root, ".gitignore"),
|
|
97
|
+
`node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\n${
|
|
98
|
+
answers.deployTarget === "vercel" ? ".vercel\n" : ""
|
|
99
|
+
}`,
|
|
100
|
+
],
|
|
101
|
+
[join(root, `src/app.${ext}`), renderAppTs(packageName, answers.framework, answers.deployTarget)],
|
|
96
102
|
[join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
|
|
97
103
|
[
|
|
98
104
|
join(root, `src/middleware/example.middleware.${ext}`),
|
|
@@ -100,14 +106,19 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
|
|
|
100
106
|
],
|
|
101
107
|
[join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
|
|
102
108
|
[join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
|
|
109
|
+
...(answers.deployTarget === "vercel"
|
|
110
|
+
? ([[join(root, "vercel.json"), renderVercelJson()]] as Array<[string, string]>)
|
|
111
|
+
: []),
|
|
103
112
|
];
|
|
104
113
|
|
|
114
|
+
// Every route starts blank (no methods wired) — `bun run add-method` adds
|
|
115
|
+
// them one at a time afterward. See templates/route.ts for why.
|
|
105
116
|
for (const route of answers.routes) {
|
|
106
117
|
const dir = join(root, "src/endpoints", route);
|
|
107
118
|
files.push(
|
|
108
|
-
[join(dir, `${route}.controller.${ext}`),
|
|
109
|
-
[join(dir, `${route}.routes.${ext}`),
|
|
110
|
-
[join(dir, `${route}.services.${ext}`),
|
|
119
|
+
[join(dir, `${route}.controller.${ext}`), renderBlankController()],
|
|
120
|
+
[join(dir, `${route}.routes.${ext}`), renderBlankRoutes(route, answers.framework, answers.language)],
|
|
121
|
+
[join(dir, `${route}.services.${ext}`), renderBlankServices()]
|
|
111
122
|
);
|
|
112
123
|
}
|
|
113
124
|
|
package/src/prompts.ts
CHANGED
|
@@ -3,6 +3,7 @@ import * as p from "@clack/prompts";
|
|
|
3
3
|
export type DbChoice = "neon" | "postgres" | "sqlite" | "none";
|
|
4
4
|
export type Framework = "hono" | "express";
|
|
5
5
|
export type Language = "typescript" | "javascript";
|
|
6
|
+
export type DeployTarget = "vercel" | "node" | "local" | "undecided";
|
|
6
7
|
|
|
7
8
|
export interface Answers {
|
|
8
9
|
projectName: string;
|
|
@@ -11,6 +12,11 @@ export interface Answers {
|
|
|
11
12
|
db: DbChoice;
|
|
12
13
|
routes: string[];
|
|
13
14
|
copyEnv: boolean;
|
|
15
|
+
// Optional, defaults to "undecided" wherever it's read — generateProject()
|
|
16
|
+
// and its templates all treat a missing value the same as "undecided", so
|
|
17
|
+
// existing callers that build an Answers object without this field (tests,
|
|
18
|
+
// any external embedder) keep working unchanged.
|
|
19
|
+
deployTarget?: DeployTarget;
|
|
14
20
|
}
|
|
15
21
|
|
|
16
22
|
function bail(): never {
|
|
@@ -72,6 +78,25 @@ export async function runPrompts(): Promise<Answers> {
|
|
|
72
78
|
});
|
|
73
79
|
if (p.isCancel(db)) bail();
|
|
74
80
|
|
|
81
|
+
const deployTarget = await p.select({
|
|
82
|
+
message: "Where's this headed?",
|
|
83
|
+
options: [
|
|
84
|
+
{
|
|
85
|
+
value: "vercel",
|
|
86
|
+
label: "Vercel",
|
|
87
|
+
hint: "adds vercel.json + a default export so it deploys with zero config",
|
|
88
|
+
},
|
|
89
|
+
{
|
|
90
|
+
value: "node",
|
|
91
|
+
label: "Another Node/Bun host",
|
|
92
|
+
hint: "Render, Railway, Fly, a VPS — index.ts's serve() already listens on PORT, nothing extra needed",
|
|
93
|
+
},
|
|
94
|
+
{ value: "local", label: "Local / self-hosted only", hint: "no deploy scaffolding added" },
|
|
95
|
+
{ value: "undecided", label: "Not sure yet", hint: "same as local for now — figure it out later" },
|
|
96
|
+
],
|
|
97
|
+
});
|
|
98
|
+
if (p.isCancel(deployTarget)) bail();
|
|
99
|
+
|
|
75
100
|
const copyEnv = await p.confirm({
|
|
76
101
|
message: "Create .env from .env.example now?",
|
|
77
102
|
initialValue: true,
|
|
@@ -100,5 +125,6 @@ export async function runPrompts(): Promise<Answers> {
|
|
|
100
125
|
db: db as DbChoice,
|
|
101
126
|
routes,
|
|
102
127
|
copyEnv: copyEnv as boolean,
|
|
128
|
+
deployTarget: deployTarget as DeployTarget,
|
|
103
129
|
};
|
|
104
130
|
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { colorVerb, dim } from "./colors";
|
|
4
|
+
import { detectProject } from "./detect";
|
|
5
|
+
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
6
|
+
import type { HttpVerb } from "./templates/route";
|
|
7
|
+
|
|
8
|
+
export interface EndpointMethod {
|
|
9
|
+
verb: HttpVerb;
|
|
10
|
+
path: string;
|
|
11
|
+
/** The controller export / service function name this method calls into. */
|
|
12
|
+
name: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface EndpointSummary {
|
|
16
|
+
route: string;
|
|
17
|
+
methods: EndpointMethod[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// Matches exactly what routeMountLine() in templates/route.ts generates:
|
|
21
|
+
// usersRoutes.get("/", controller.list);
|
|
22
|
+
// usersRoutes.post("/", controller.create);
|
|
23
|
+
// Shared here so the dashboard (add-method) and list-routes read mount lines
|
|
24
|
+
// the same way instead of two regexes drifting apart.
|
|
25
|
+
const METHOD_MOUNT_PATTERN = /\.(get|post|put|patch|delete)\(\s*"([^"]*)"\s*,\s*controller\.(\w+)\s*\)/g;
|
|
26
|
+
|
|
27
|
+
export function parseRouteMethods(routesFileContents: string): EndpointMethod[] {
|
|
28
|
+
const methods: EndpointMethod[] = [];
|
|
29
|
+
for (const match of routesFileContents.matchAll(METHOD_MOUNT_PATTERN)) {
|
|
30
|
+
const [, verb, path, name] = match;
|
|
31
|
+
if (verb && path !== undefined && name) {
|
|
32
|
+
methods.push({ verb: verb as HttpVerb, path, name });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return methods;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Every endpoint currently mounted in src/endpoints/index.<ext>, with the
|
|
40
|
+
* HTTP methods each one's own *.routes.<ext> file actually wires up right
|
|
41
|
+
* now — the same "what's real on disk" read doctor.ts does, rather than
|
|
42
|
+
* anything add-method itself remembers, so this stays correct even after
|
|
43
|
+
* hand-edits.
|
|
44
|
+
*/
|
|
45
|
+
export async function listEndpointsWithMethods(cwd: string = process.cwd()): Promise<EndpointSummary[]> {
|
|
46
|
+
const { root, ext } = await detectProject(cwd);
|
|
47
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
48
|
+
const routes = parseMountedRoutes(contents);
|
|
49
|
+
|
|
50
|
+
const summaries: EndpointSummary[] = [];
|
|
51
|
+
for (const route of routes) {
|
|
52
|
+
const routesFilePath = join(root, "src/endpoints", route, `${route}.routes.${ext}`);
|
|
53
|
+
let routesFileContents: string;
|
|
54
|
+
try {
|
|
55
|
+
routesFileContents = await readFile(routesFilePath, "utf-8");
|
|
56
|
+
} catch {
|
|
57
|
+
summaries.push({ route, methods: [] });
|
|
58
|
+
continue;
|
|
59
|
+
}
|
|
60
|
+
summaries.push({ route, methods: parseRouteMethods(routesFileContents) });
|
|
61
|
+
}
|
|
62
|
+
return summaries;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Plain-text dashboard: every endpoint, and every method it actually has right now, colored by verb. */
|
|
66
|
+
export function formatEndpointsDashboard(summaries: EndpointSummary[]): string {
|
|
67
|
+
if (summaries.length === 0) return dim("No endpoints yet.");
|
|
68
|
+
|
|
69
|
+
return summaries
|
|
70
|
+
.map(({ route, methods }) => {
|
|
71
|
+
if (methods.length === 0) return `${route}\n ${dim("(no methods yet)")}`;
|
|
72
|
+
const lines = methods.map((m) => ` ${colorVerb(m.verb)} ${m.path} ${dim(`→ ${m.name}`)}`);
|
|
73
|
+
return `${route}\n${lines.join("\n")}`;
|
|
74
|
+
})
|
|
75
|
+
.join("\n\n");
|
|
76
|
+
}
|