create-backon 0.3.0 → 0.6.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 +94 -14
- package/package.json +1 -1
- package/src/add-route.ts +4 -21
- package/src/cli.ts +72 -11
- package/src/doctor.ts +73 -0
- package/src/endpoints-index.ts +37 -0
- package/src/generate.ts +4 -1
- package/src/list-routes.ts +14 -0
- package/src/prompts.ts +9 -1
- package/src/remove-route.ts +41 -0
- package/src/templates/base.ts +39 -10
- package/src/templates/db.ts +1 -1
package/README.md
CHANGED
|
@@ -20,8 +20,9 @@ bunx create-backon
|
|
|
20
20
|
Prompts for a project name (or `.` to scaffold into the current directory,
|
|
21
21
|
same as `bun create vite@latest .`), a framework (Hono or Express), a
|
|
22
22
|
language (TypeScript or JavaScript), a database (Neon, Postgres, SQLite, or
|
|
23
|
-
none — via [Drizzle](https://orm.drizzle.team)),
|
|
24
|
-
|
|
23
|
+
none — via [Drizzle](https://orm.drizzle.team)), whether to create `.env`
|
|
24
|
+
from `.env.example` right away (default yes — skips the manual `cp` step),
|
|
25
|
+
and any number of routes, then generates:
|
|
25
26
|
|
|
26
27
|
```
|
|
27
28
|
my-api/
|
|
@@ -43,11 +44,11 @@ my-api/
|
|
|
43
44
|
Each route's `*.routes.ts` wires HTTP methods to controller functions,
|
|
44
45
|
`*.controller.ts` validates the request via `defineRoute` (from
|
|
45
46
|
`@mednours/backon` or `@mednours/backon/express`, depending on the
|
|
46
|
-
framework
|
|
47
|
-
|
|
47
|
+
framework picked) and calls into `*.services.ts`, which is where real data
|
|
48
|
+
access belongs. In JavaScript mode every file is generated without any
|
|
48
49
|
TypeScript-only syntax (no `import type`, no generics, no type
|
|
49
|
-
annotations) —
|
|
50
|
-
|
|
50
|
+
annotations) — generated files are genuinely plain JavaScript rather than
|
|
51
|
+
TypeScript with the types stripped, with JSDoc `@param` comments on the one
|
|
51
52
|
generated function (the example middleware) that would otherwise have had
|
|
52
53
|
a type annotation, so editors still get intellisense without requiring
|
|
53
54
|
TypeScript as a dependency.
|
|
@@ -59,22 +60,33 @@ running this right after `git init` on a fresh repo doesn't get blocked.
|
|
|
59
60
|
|
|
60
61
|
## Adding a route to an existing project
|
|
61
62
|
|
|
62
|
-
Re-running the full generator isn't the way to add one more route to
|
|
63
|
-
|
|
64
|
-
from inside the project:
|
|
63
|
+
Re-running the full generator isn't the way to add one more route to an
|
|
64
|
+
already-scaffolded project. Every generated project's `package.json`
|
|
65
|
+
includes a script for this, so from inside the project:
|
|
65
66
|
|
|
66
67
|
```
|
|
67
|
-
|
|
68
|
+
bun run add-route users
|
|
68
69
|
```
|
|
69
70
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
71
|
+
`bun run` forwards `users` straight through, no `--` needed. Leave the name
|
|
72
|
+
off and it prompts for one:
|
|
73
|
+
|
|
74
|
+
```
|
|
75
|
+
bun run add-route
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
The same command also works outside a generated `package.json`, or for a
|
|
79
|
+
project scaffolded before this script existed:
|
|
73
80
|
|
|
74
81
|
```
|
|
75
|
-
bunx create-backon add-route
|
|
82
|
+
bunx create-backon add-route users
|
|
76
83
|
```
|
|
77
84
|
|
|
85
|
+
(`bun create backon add-route users` also works — `bun create` forwards
|
|
86
|
+
extra arguments straight through. `route` works as a shorthand for
|
|
87
|
+
`add-route` either way, and `bun run add-route` is exactly this command
|
|
88
|
+
under a shorter name.)
|
|
89
|
+
|
|
78
90
|
It reads the project's own `package.json` to figure out whether it's
|
|
79
91
|
Hono or Express, TypeScript or JavaScript — no need to answer those again
|
|
80
92
|
— then writes `src/endpoints/users/users.controller.ts` (or `.routes`,
|
|
@@ -84,6 +96,74 @@ to the ones that were already there. It refuses to run outside a backon
|
|
|
84
96
|
project, refuses a route name whose folder already exists, and refuses a
|
|
85
97
|
name that's already mounted.
|
|
86
98
|
|
|
99
|
+
## Removing a route
|
|
100
|
+
|
|
101
|
+
The undo for `add-route`:
|
|
102
|
+
|
|
103
|
+
```
|
|
104
|
+
bun run remove-route users
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
or directly:
|
|
108
|
+
|
|
109
|
+
```
|
|
110
|
+
bunx create-backon remove-route users
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
(`rm-route` also works.) Leave the name off to be prompted for one. Either
|
|
114
|
+
way, confirmation is required before anything is deleted — this removes
|
|
115
|
+
`src/endpoints/users/` and unmounts it from `src/endpoints/index.ts`.
|
|
116
|
+
Refuses if the route isn't currently mounted, rather than guessing at
|
|
117
|
+
deleting a folder that was never wired up.
|
|
118
|
+
|
|
119
|
+
## Listing routes
|
|
120
|
+
|
|
121
|
+
```
|
|
122
|
+
bun run list-routes
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
or `bunx create-backon list-routes` (`routes` also works). Read-only —
|
|
126
|
+
prints every route currently mounted in `src/endpoints/index.ts`.
|
|
127
|
+
|
|
128
|
+
## Checking a project for drift
|
|
129
|
+
|
|
130
|
+
```
|
|
131
|
+
bun run doctor
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
or `bunx create-backon doctor`. Compares what's actually in
|
|
135
|
+
`src/endpoints/` against what `index.<ext>` mounts, and flags three things:
|
|
136
|
+
a route folder that exists but isn't mounted (an orphan), a mount in
|
|
137
|
+
`index.<ext>` pointing at a folder that's gone (dangling), and a route
|
|
138
|
+
folder missing one of its three expected files. This kind of drift usually
|
|
139
|
+
comes from hand-editing `index.ts`, deleting a route folder without using
|
|
140
|
+
`remove-route`, or copy-pasting a route folder without wiring it up.
|
|
141
|
+
`doctor` only reports issues — it doesn't fix them — and exits non-zero if
|
|
142
|
+
it finds any, so it's usable in a pre-commit hook or CI step.
|
|
143
|
+
|
|
144
|
+
## Generating API docs
|
|
145
|
+
|
|
146
|
+
Every generated project includes a `docs` script:
|
|
147
|
+
|
|
148
|
+
```
|
|
149
|
+
bun run docs
|
|
150
|
+
```
|
|
151
|
+
|
|
152
|
+
Writes `openapi.json` (built from the Zod schemas already passed to
|
|
153
|
+
`defineRoute()` across every route) and `docs.html` (a rendered reference
|
|
154
|
+
page, [Scalar](https://github.com/scalar/scalar), pointed at that spec) to
|
|
155
|
+
the project root. Both come from `scripts/generate-docs.<ext>`, generated
|
|
156
|
+
alongside everything else — it imports `src/app` directly rather than
|
|
157
|
+
starting a real server, so `bun run docs` works without anything listening
|
|
158
|
+
on a port. Both output files are build artifacts, not source, so they're in
|
|
159
|
+
the generated `.gitignore` by default.
|
|
160
|
+
|
|
161
|
+
This is separate from `serveApiDocs(app)` (documented in
|
|
162
|
+
[coding-with-backon.md](../../docs/coding-with-backon.md)), which mounts the
|
|
163
|
+
same spec and reference page as live routes on a running server instead of
|
|
164
|
+
writing them to disk — useful for CI, static hosting, or feeding the spec
|
|
165
|
+
into an external tool, where `serveApiDocs`'s live routes don't apply.
|
|
166
|
+
|
|
87
167
|
## Requirements
|
|
88
168
|
|
|
89
169
|
Bun >= 1.3.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-backon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Scaffolds a new backend project on backon — like `bun create vite@latest`, but for a consistent controller/routes/services backend layout.",
|
|
6
6
|
"license": "MIT",
|
package/src/add-route.ts
CHANGED
|
@@ -1,15 +1,11 @@
|
|
|
1
|
-
import { mkdir,
|
|
1
|
+
import { mkdir, readdir, writeFile } from "node:fs/promises";
|
|
2
2
|
import { dirname, join } from "node:path";
|
|
3
3
|
import { detectProject } from "./detect";
|
|
4
|
+
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
4
5
|
import { toKebabCase } from "./prompts";
|
|
5
6
|
import { renderEndpointsIndex } from "./templates/base";
|
|
6
7
|
import { renderController, renderRoutes, renderServices } from "./templates/route";
|
|
7
8
|
|
|
8
|
-
// Matches the two shapes renderEndpointsIndex() ever generates:
|
|
9
|
-
// endpoints.route("/telemetry", telemetryRoutes); (hono)
|
|
10
|
-
// endpoints.use("/telemetry", telemetryRoutes); (express)
|
|
11
|
-
const MOUNT_PATTERN = /endpoints\.(?:route|use)\("\/([a-z0-9-]+)"/g;
|
|
12
|
-
|
|
13
9
|
export interface AddRouteResult {
|
|
14
10
|
route: string;
|
|
15
11
|
root: string;
|
|
@@ -50,21 +46,8 @@ export async function addRoute(rawName: string, cwd: string = process.cwd()): Pr
|
|
|
50
46
|
throw new Error(`src/endpoints/${route} already exists.`);
|
|
51
47
|
}
|
|
52
48
|
|
|
53
|
-
const indexPath =
|
|
54
|
-
|
|
55
|
-
try {
|
|
56
|
-
indexContents = await readFile(indexPath, "utf-8");
|
|
57
|
-
} catch (err) {
|
|
58
|
-
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
59
|
-
throw new Error(`${indexPath} doesn't exist — is this a backon project?`);
|
|
60
|
-
}
|
|
61
|
-
throw err;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
const existingRoutes: string[] = [];
|
|
65
|
-
for (const match of indexContents.matchAll(MOUNT_PATTERN)) {
|
|
66
|
-
existingRoutes.push(match[1]);
|
|
67
|
-
}
|
|
49
|
+
const { path: indexPath, contents: indexContents } = await readEndpointsIndex(root, ext);
|
|
50
|
+
const existingRoutes = parseMountedRoutes(indexContents);
|
|
68
51
|
if (existingRoutes.includes(route)) {
|
|
69
52
|
throw new Error(`"${route}" is already mounted in ${indexPath}.`);
|
|
70
53
|
}
|
package/src/cli.ts
CHANGED
|
@@ -3,24 +3,34 @@ import * as p from "@clack/prompts";
|
|
|
3
3
|
import { runPrompts } from "./prompts";
|
|
4
4
|
import { generateProject } from "./generate";
|
|
5
5
|
import { addRoute } from "./add-route";
|
|
6
|
+
import { removeRoute } from "./remove-route";
|
|
7
|
+
import { listRoutes } from "./list-routes";
|
|
8
|
+
import { runDoctor } from "./doctor";
|
|
6
9
|
|
|
7
10
|
const ADD_ROUTE_SUBCOMMANDS = new Set(["add-route", "route"]);
|
|
11
|
+
const REMOVE_ROUTE_SUBCOMMANDS = new Set(["remove-route", "rm-route"]);
|
|
12
|
+
const LIST_ROUTES_SUBCOMMANDS = new Set(["list-routes", "routes"]);
|
|
13
|
+
const DOCTOR_SUBCOMMANDS = new Set(["doctor"]);
|
|
14
|
+
|
|
15
|
+
async function promptForRouteName(introText: string): Promise<string> {
|
|
16
|
+
p.intro(introText);
|
|
17
|
+
const answer = await p.text({
|
|
18
|
+
message: "Route name",
|
|
19
|
+
placeholder: "e.g. users",
|
|
20
|
+
validate: (value) => (!value ? "Required." : undefined),
|
|
21
|
+
});
|
|
22
|
+
if (p.isCancel(answer)) {
|
|
23
|
+
p.cancel("Cancelled.");
|
|
24
|
+
process.exit(0);
|
|
25
|
+
}
|
|
26
|
+
return answer;
|
|
27
|
+
}
|
|
8
28
|
|
|
9
29
|
async function runAddRoute(args: string[]): Promise<void> {
|
|
10
30
|
let [name] = args;
|
|
11
31
|
|
|
12
32
|
if (!name) {
|
|
13
|
-
|
|
14
|
-
const answer = await p.text({
|
|
15
|
-
message: "Route name",
|
|
16
|
-
placeholder: "e.g. users",
|
|
17
|
-
validate: (value) => (!value ? "Required." : undefined),
|
|
18
|
-
});
|
|
19
|
-
if (p.isCancel(answer)) {
|
|
20
|
-
p.cancel("Cancelled.");
|
|
21
|
-
process.exit(0);
|
|
22
|
-
}
|
|
23
|
-
name = answer;
|
|
33
|
+
name = await promptForRouteName("create-backon add-route");
|
|
24
34
|
p.outro(`Adding ${name}...`);
|
|
25
35
|
}
|
|
26
36
|
|
|
@@ -28,6 +38,45 @@ async function runAddRoute(args: string[]): Promise<void> {
|
|
|
28
38
|
p.log.success(`Added src/endpoints/${route} (${filesWritten.length} files) in ${root}`);
|
|
29
39
|
}
|
|
30
40
|
|
|
41
|
+
async function runRemoveRoute(args: string[]): Promise<void> {
|
|
42
|
+
let [name] = args;
|
|
43
|
+
|
|
44
|
+
if (!name) {
|
|
45
|
+
name = await promptForRouteName("create-backon remove-route");
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const shouldRemove = await p.confirm({
|
|
49
|
+
message: `Remove src/endpoints/${name} and unmount it? This deletes the folder.`,
|
|
50
|
+
initialValue: false,
|
|
51
|
+
});
|
|
52
|
+
if (p.isCancel(shouldRemove) || !shouldRemove) {
|
|
53
|
+
p.cancel("Cancelled.");
|
|
54
|
+
process.exit(0);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const { route, root, removedDir } = await removeRoute(name);
|
|
58
|
+
p.log.success(`Removed ${removedDir} and unmounted "${route}" in ${root}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function runListRoutes(): Promise<void> {
|
|
62
|
+
const { root, routes } = await listRoutes();
|
|
63
|
+
if (routes.length === 0) {
|
|
64
|
+
p.log.info(`No routes mounted in ${root}.`);
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
p.log.info(`Routes mounted in ${root}:\n${routes.map((route) => ` - ${route}`).join("\n")}`);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function runDoctorCommand(): Promise<void> {
|
|
71
|
+
const { root, issues } = await runDoctor();
|
|
72
|
+
if (issues.length === 0) {
|
|
73
|
+
p.log.success(`No issues found in ${root}.`);
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
p.log.warn(`${issues.length} issue(s) found in ${root}:\n${issues.map((issue) => ` - ${issue.detail}`).join("\n")}`);
|
|
77
|
+
process.exitCode = 1;
|
|
78
|
+
}
|
|
79
|
+
|
|
31
80
|
async function runScaffold(): Promise<void> {
|
|
32
81
|
const answers = await runPrompts();
|
|
33
82
|
const { root, filesWritten } = await generateProject(answers);
|
|
@@ -45,6 +94,18 @@ async function main() {
|
|
|
45
94
|
await runAddRoute(rest);
|
|
46
95
|
return;
|
|
47
96
|
}
|
|
97
|
+
if (subcommand && REMOVE_ROUTE_SUBCOMMANDS.has(subcommand)) {
|
|
98
|
+
await runRemoveRoute(rest);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (subcommand && LIST_ROUTES_SUBCOMMANDS.has(subcommand)) {
|
|
102
|
+
await runListRoutes();
|
|
103
|
+
return;
|
|
104
|
+
}
|
|
105
|
+
if (subcommand && DOCTOR_SUBCOMMANDS.has(subcommand)) {
|
|
106
|
+
await runDoctorCommand();
|
|
107
|
+
return;
|
|
108
|
+
}
|
|
48
109
|
|
|
49
110
|
await runScaffold();
|
|
50
111
|
}
|
package/src/doctor.ts
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { access, readdir } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
import { detectProject } from "./detect";
|
|
4
|
+
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
5
|
+
|
|
6
|
+
export type DoctorIssueKind = "dangling-mount" | "orphaned-folder" | "missing-file";
|
|
7
|
+
|
|
8
|
+
export interface DoctorIssue {
|
|
9
|
+
kind: DoctorIssueKind;
|
|
10
|
+
route: string;
|
|
11
|
+
detail: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface DoctorResult {
|
|
15
|
+
root: string;
|
|
16
|
+
issues: DoctorIssue[];
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const ROUTE_FILE_SUFFIXES = ["controller", "routes", "services"] as const;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Checks src/endpoints/ for drift between what's on disk and what
|
|
23
|
+
* index.<ext> actually mounts — the kind of thing that creeps in from
|
|
24
|
+
* hand-editing index.ts, an interrupted addRoute()/removeRoute(), or
|
|
25
|
+
* copy-pasting a route folder without wiring it up. Read-only; reports
|
|
26
|
+
* issues, doesn't fix them.
|
|
27
|
+
*/
|
|
28
|
+
export async function runDoctor(cwd: string = process.cwd()): Promise<DoctorResult> {
|
|
29
|
+
const { root, ext } = await detectProject(cwd);
|
|
30
|
+
const endpointsDir = join(root, "src/endpoints");
|
|
31
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
32
|
+
const mounted = new Set(parseMountedRoutes(contents));
|
|
33
|
+
|
|
34
|
+
const dirents = await readdir(endpointsDir, { withFileTypes: true }).catch((err) => {
|
|
35
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];
|
|
36
|
+
throw err;
|
|
37
|
+
});
|
|
38
|
+
const folders = dirents.filter((d) => d.isDirectory()).map((d) => d.name);
|
|
39
|
+
const folderSet = new Set(folders);
|
|
40
|
+
|
|
41
|
+
const issues: DoctorIssue[] = [];
|
|
42
|
+
|
|
43
|
+
for (const route of mounted) {
|
|
44
|
+
if (!folderSet.has(route)) {
|
|
45
|
+
issues.push({
|
|
46
|
+
kind: "dangling-mount",
|
|
47
|
+
route,
|
|
48
|
+
detail: `index.${ext} mounts "/${route}" but src/endpoints/${route}/ doesn't exist.`,
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
for (const route of folders) {
|
|
54
|
+
if (!mounted.has(route)) {
|
|
55
|
+
issues.push({
|
|
56
|
+
kind: "orphaned-folder",
|
|
57
|
+
route,
|
|
58
|
+
detail: `src/endpoints/${route}/ exists but isn't mounted in index.${ext}.`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
for (const suffix of ROUTE_FILE_SUFFIXES) {
|
|
63
|
+
const filePath = join(endpointsDir, route, `${route}.${suffix}.${ext}`);
|
|
64
|
+
try {
|
|
65
|
+
await access(filePath);
|
|
66
|
+
} catch {
|
|
67
|
+
issues.push({ kind: "missing-file", route, detail: `${filePath} is missing.` });
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return { root, issues };
|
|
73
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import { readFile } from "node:fs/promises";
|
|
2
|
+
import { join } from "node:path";
|
|
3
|
+
|
|
4
|
+
// Matches the two shapes renderEndpointsIndex() ever generates:
|
|
5
|
+
// endpoints.route("/telemetry", telemetryRoutes); (hono)
|
|
6
|
+
// endpoints.use("/telemetry", telemetryRoutes); (express)
|
|
7
|
+
// Shared by add-route/remove-route/list-routes/doctor so all four agree on
|
|
8
|
+
// what "mounted" means by reading the same file the same way, instead of
|
|
9
|
+
// four copies of this regex drifting apart over time.
|
|
10
|
+
const MOUNT_PATTERN = /endpoints\.(?:route|use)\("\/([a-z0-9-]+)"/g;
|
|
11
|
+
|
|
12
|
+
export function parseMountedRoutes(indexContents: string): string[] {
|
|
13
|
+
const routes: string[] = [];
|
|
14
|
+
for (const match of indexContents.matchAll(MOUNT_PATTERN)) {
|
|
15
|
+
routes.push(match[1]);
|
|
16
|
+
}
|
|
17
|
+
return routes;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface EndpointsIndexFile {
|
|
21
|
+
path: string;
|
|
22
|
+
contents: string;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function readEndpointsIndex(root: string, ext: "ts" | "js"): Promise<EndpointsIndexFile> {
|
|
26
|
+
const path = join(root, "src/endpoints", `index.${ext}`);
|
|
27
|
+
let contents: string;
|
|
28
|
+
try {
|
|
29
|
+
contents = await readFile(path, "utf-8");
|
|
30
|
+
} catch (err) {
|
|
31
|
+
if ((err as NodeJS.ErrnoException).code === "ENOENT") {
|
|
32
|
+
throw new Error(`${path} doesn't exist — is this a backon project?`);
|
|
33
|
+
}
|
|
34
|
+
throw err;
|
|
35
|
+
}
|
|
36
|
+
return { path, contents };
|
|
37
|
+
}
|
package/src/generate.ts
CHANGED
|
@@ -6,6 +6,7 @@ import {
|
|
|
6
6
|
renderEndpointsIndex,
|
|
7
7
|
renderEnvExample,
|
|
8
8
|
renderExampleMiddleware,
|
|
9
|
+
renderGenerateDocsScript,
|
|
9
10
|
renderIndexTs,
|
|
10
11
|
renderJsconfig,
|
|
11
12
|
renderPackageJson,
|
|
@@ -84,12 +85,13 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
|
|
|
84
85
|
const files: Array<[string, string]> = [
|
|
85
86
|
[join(root, `index.${ext}`), renderIndexTs(answers.framework)],
|
|
86
87
|
[join(root, ".env.example"), renderEnvExample(answers.db)],
|
|
88
|
+
...(answers.copyEnv ? ([[join(root, ".env"), renderEnvExample(answers.db)]] as Array<[string, string]>) : []),
|
|
87
89
|
[join(root, "package.json"), renderPackageJson(packageName, answers.framework, answers.language, answers.db)],
|
|
88
90
|
answers.language === "javascript"
|
|
89
91
|
? [join(root, "jsconfig.json"), renderJsconfig()]
|
|
90
92
|
: [join(root, "tsconfig.json"), renderTsconfig()],
|
|
91
93
|
[join(root, "README.md"), renderReadme(readmeAnswers)],
|
|
92
|
-
[join(root, ".gitignore"), "node_modules/\ndist/\n*.log\n.env\n.env.local\n"],
|
|
94
|
+
[join(root, ".gitignore"), "node_modules/\ndist/\n*.log\n.env\n.env.local\nopenapi.json\ndocs.html\n"],
|
|
93
95
|
[join(root, `src/app.${ext}`), renderAppTs(answers.framework)],
|
|
94
96
|
[join(root, `src/config/db.${ext}`), renderDbFile(answers.db)],
|
|
95
97
|
[
|
|
@@ -97,6 +99,7 @@ export async function generateProject(answers: Answers, cwd: string = process.cw
|
|
|
97
99
|
renderExampleMiddleware(answers.framework, answers.language),
|
|
98
100
|
],
|
|
99
101
|
[join(root, `src/endpoints/index.${ext}`), renderEndpointsIndex(answers.framework, answers.routes)],
|
|
102
|
+
[join(root, `scripts/generate-docs.${ext}`), renderGenerateDocsScript(packageName, answers.framework)],
|
|
100
103
|
];
|
|
101
104
|
|
|
102
105
|
for (const route of answers.routes) {
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { detectProject } from "./detect";
|
|
2
|
+
import { parseMountedRoutes, readEndpointsIndex } from "./endpoints-index";
|
|
3
|
+
|
|
4
|
+
export interface ListRoutesResult {
|
|
5
|
+
root: string;
|
|
6
|
+
routes: string[];
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** Read-only: what's actually mounted in src/endpoints/index.<ext> right now. */
|
|
10
|
+
export async function listRoutes(cwd: string = process.cwd()): Promise<ListRoutesResult> {
|
|
11
|
+
const { root, ext } = await detectProject(cwd);
|
|
12
|
+
const { contents } = await readEndpointsIndex(root, ext);
|
|
13
|
+
return { root, routes: parseMountedRoutes(contents) };
|
|
14
|
+
}
|
package/src/prompts.ts
CHANGED
|
@@ -10,6 +10,7 @@ export interface Answers {
|
|
|
10
10
|
language: Language;
|
|
11
11
|
db: DbChoice;
|
|
12
12
|
routes: string[];
|
|
13
|
+
copyEnv: boolean;
|
|
13
14
|
}
|
|
14
15
|
|
|
15
16
|
function bail(): never {
|
|
@@ -71,8 +72,14 @@ export async function runPrompts(): Promise<Answers> {
|
|
|
71
72
|
});
|
|
72
73
|
if (p.isCancel(db)) bail();
|
|
73
74
|
|
|
75
|
+
const copyEnv = await p.confirm({
|
|
76
|
+
message: "Create .env from .env.example now?",
|
|
77
|
+
initialValue: true,
|
|
78
|
+
});
|
|
79
|
+
if (p.isCancel(copyEnv)) bail();
|
|
80
|
+
|
|
74
81
|
const routes: string[] = [];
|
|
75
|
-
p.log.step("Add routes one at a time. Leave the name blank
|
|
82
|
+
p.log.step("Add routes one at a time. Leave the name blank to finish.");
|
|
76
83
|
// eslint-disable-next-line no-constant-condition
|
|
77
84
|
while (true) {
|
|
78
85
|
const name = await p.text({
|
|
@@ -92,5 +99,6 @@ export async function runPrompts(): Promise<Answers> {
|
|
|
92
99
|
language: language as Language,
|
|
93
100
|
db: db as DbChoice,
|
|
94
101
|
routes,
|
|
102
|
+
copyEnv: copyEnv as boolean,
|
|
95
103
|
};
|
|
96
104
|
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { rm, 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 { toKebabCase } from "./prompts";
|
|
6
|
+
import { renderEndpointsIndex } from "./templates/base";
|
|
7
|
+
|
|
8
|
+
export interface RemoveRouteResult {
|
|
9
|
+
route: string;
|
|
10
|
+
root: string;
|
|
11
|
+
removedDir: string;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* The undo for addRoute(): unmounts the route from src/endpoints/index.<ext>
|
|
16
|
+
* and deletes its folder. Refuses if the route isn't currently mounted,
|
|
17
|
+
* rather than silently deleting an orphaned folder that was never wired up
|
|
18
|
+
* — that's what `doctor` is for.
|
|
19
|
+
*/
|
|
20
|
+
export async function removeRoute(rawName: string, cwd: string = process.cwd()): Promise<RemoveRouteResult> {
|
|
21
|
+
const route = toKebabCase(rawName);
|
|
22
|
+
if (!route) {
|
|
23
|
+
throw new Error("Route name can't be empty.");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const { root, framework, ext } = await detectProject(cwd);
|
|
27
|
+
const { path: indexPath, contents } = await readEndpointsIndex(root, ext);
|
|
28
|
+
|
|
29
|
+
const mounted = parseMountedRoutes(contents);
|
|
30
|
+
if (!mounted.includes(route)) {
|
|
31
|
+
throw new Error(`"${route}" isn't mounted in ${indexPath} — nothing to remove.`);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const remaining = mounted.filter((name) => name !== route);
|
|
35
|
+
await writeFile(indexPath, renderEndpointsIndex(framework, remaining));
|
|
36
|
+
|
|
37
|
+
const removedDir = join(root, "src/endpoints", route);
|
|
38
|
+
await rm(removedDir, { recursive: true, force: true });
|
|
39
|
+
|
|
40
|
+
return { route, root, removedDir };
|
|
41
|
+
}
|
package/src/templates/base.ts
CHANGED
|
@@ -49,8 +49,8 @@ export function renderExampleMiddleware(framework: Framework, language: Language
|
|
|
49
49
|
* Example middleware, just to show the pattern — stamps a request-start
|
|
50
50
|
* timestamp onto res.locals. Error handling, request logging, secure
|
|
51
51
|
* headers, CORS, and the request body size limit are already wired into
|
|
52
|
-
* createApp() by backon itself;
|
|
53
|
-
* error.middleware.js
|
|
52
|
+
* createApp() by backon itself; a separate
|
|
53
|
+
* error.middleware.js is only needed to override that default behavior.
|
|
54
54
|
*
|
|
55
55
|
* This is plain Express middleware (req, res, next), not backon's
|
|
56
56
|
* BackonContext — that wrapper only exists inside defineRoute() handlers.
|
|
@@ -75,8 +75,8 @@ export function exampleMiddleware(req, res, next) {
|
|
|
75
75
|
* Example middleware, just to show the pattern — stamps a request-start
|
|
76
76
|
* timestamp onto res.locals. Error handling, request logging, secure
|
|
77
77
|
* headers, CORS, and the request body size limit are already wired into
|
|
78
|
-
* createApp() by backon itself;
|
|
79
|
-
* error.middleware.ts
|
|
78
|
+
* createApp() by backon itself; a separate
|
|
79
|
+
* error.middleware.ts is only needed to override that default behavior.
|
|
80
80
|
*
|
|
81
81
|
* This is plain Express middleware (req, res, next), not backon's
|
|
82
82
|
* BackonContext — that wrapper only exists inside defineRoute() handlers.
|
|
@@ -97,8 +97,8 @@ export function exampleMiddleware(req: Request, res: Response, next: NextFunctio
|
|
|
97
97
|
* Example middleware, just to show the pattern — adds a response-time
|
|
98
98
|
* header. Error handling, request logging, secure headers, CORS, and the
|
|
99
99
|
* request body size limit are already wired into createApp() by backon
|
|
100
|
-
* itself;
|
|
101
|
-
*
|
|
100
|
+
* itself; a separate error.middleware.js is only needed to override that
|
|
101
|
+
* default behavior.
|
|
102
102
|
*
|
|
103
103
|
* @param {import("@mednours/backon").BackonContext} c
|
|
104
104
|
* @param {import("@mednours/backon").Next} next
|
|
@@ -117,8 +117,8 @@ import type { BackonContext } from "@mednours/backon";
|
|
|
117
117
|
* Example middleware, just to show the pattern — adds a response-time
|
|
118
118
|
* header. Error handling, request logging, secure headers, CORS, and the
|
|
119
119
|
* request body size limit are already wired into createApp() by backon
|
|
120
|
-
* itself;
|
|
121
|
-
*
|
|
120
|
+
* itself; a separate error.middleware.ts is only needed to override that
|
|
121
|
+
* default behavior.
|
|
122
122
|
*/
|
|
123
123
|
export async function exampleMiddleware(c: BackonContext, next: Next) {
|
|
124
124
|
const start = performance.now();
|
|
@@ -154,6 +154,25 @@ ${mounts}
|
|
|
154
154
|
`;
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
+
// Not language-aware, same reasoning as renderIndexTs/renderAppTs above: no
|
|
158
|
+
// type annotations, so the same content is valid JS or TS. Imports "../src/app"
|
|
159
|
+
// rather than starting the server, so running this doesn't require anything
|
|
160
|
+
// to be listening — generateOpenApiSpec() only needs the app's routes
|
|
161
|
+
// registered, which happens at import time.
|
|
162
|
+
export function renderGenerateDocsScript(projectName: string, framework: Framework): string {
|
|
163
|
+
const backonImport = framework === "express" ? "@mednours/backon/express" : "@mednours/backon";
|
|
164
|
+
return `import { writeFileSync } from "node:fs";
|
|
165
|
+
import { generateOpenApiSpec, apiReferenceHtml } from "${backonImport}";
|
|
166
|
+
import { app } from "../src/app";
|
|
167
|
+
|
|
168
|
+
const spec = generateOpenApiSpec(app, { title: "${projectName}", version: "0.1.0" });
|
|
169
|
+
writeFileSync("openapi.json", JSON.stringify(spec, null, 2));
|
|
170
|
+
writeFileSync("docs.html", apiReferenceHtml("./openapi.json", "${projectName}"));
|
|
171
|
+
|
|
172
|
+
console.log("Wrote openapi.json and docs.html");
|
|
173
|
+
`;
|
|
174
|
+
}
|
|
175
|
+
|
|
157
176
|
export function renderEnvExample(db: Answers["db"]): string {
|
|
158
177
|
return `PORT=3000
|
|
159
178
|
ALLOWED_ORIGINS=
|
|
@@ -177,7 +196,7 @@ export function renderTsconfig(): string {
|
|
|
177
196
|
"noEmit": true,
|
|
178
197
|
"allowJs": false
|
|
179
198
|
},
|
|
180
|
-
"include": ["index.ts", "src"]
|
|
199
|
+
"include": ["index.ts", "src", "scripts"]
|
|
181
200
|
}
|
|
182
201
|
`;
|
|
183
202
|
}
|
|
@@ -200,7 +219,7 @@ export function renderJsconfig(): string {
|
|
|
200
219
|
"checkJs": false,
|
|
201
220
|
"allowJs": true
|
|
202
221
|
},
|
|
203
|
-
"include": ["index.js", "src"]
|
|
222
|
+
"include": ["index.js", "src", "scripts"]
|
|
204
223
|
}
|
|
205
224
|
`;
|
|
206
225
|
}
|
|
@@ -245,6 +264,16 @@ export function renderPackageJson(
|
|
|
245
264
|
dev: `bun run --watch index.${ext}`,
|
|
246
265
|
start: `bun run index.${ext}`,
|
|
247
266
|
test: "bun test",
|
|
267
|
+
// Thin aliases over `bunx create-backon <subcommand>` — running
|
|
268
|
+
// `bun run add-route users` from inside the project is shorter than
|
|
269
|
+
// remembering the create-backon invocation, and bun forwards extra
|
|
270
|
+
// arguments (like the route name) straight through without needing
|
|
271
|
+
// a `--` separator.
|
|
272
|
+
"add-route": "bunx create-backon add-route",
|
|
273
|
+
"remove-route": "bunx create-backon remove-route",
|
|
274
|
+
"list-routes": "bunx create-backon list-routes",
|
|
275
|
+
doctor: "bunx create-backon doctor",
|
|
276
|
+
docs: `bun run scripts/generate-docs.${ext}`,
|
|
248
277
|
};
|
|
249
278
|
if (language === "typescript") {
|
|
250
279
|
scripts.typecheck = "tsc --noEmit";
|
package/src/templates/db.ts
CHANGED
|
@@ -39,7 +39,7 @@ import { Pool } from "pg";
|
|
|
39
39
|
// NOTE: this pooled connection is for local dev or a long-running server
|
|
40
40
|
// (Docker, a VPS, Render, etc). It is NOT safe to use as-is on Vercel
|
|
41
41
|
// serverless functions — each cold start can open a new connection until
|
|
42
|
-
//
|
|
42
|
+
// the database's connection limit is exhausted. Use the "neon" db option
|
|
43
43
|
// instead for serverless deploys.
|
|
44
44
|
|
|
45
45
|
if (!process.env.DATABASE_URL) {
|