@mednours/backon 0.2.0 → 0.4.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 +96 -5
- package/package.json +13 -4
- package/src/create-app.ts +7 -7
- package/src/define-route.ts +16 -4
- package/src/express/create-app.ts +15 -11
- package/src/express/define-route.ts +14 -2
- package/src/express/index.ts +19 -7
- package/src/express/openapi.ts +27 -0
- package/src/express/require-auth.ts +3 -2
- package/src/express/router-registry.ts +89 -0
- package/src/express/router.ts +13 -0
- package/src/express/serve.ts +6 -2
- package/src/express/stream.ts +31 -0
- package/src/express/upload.ts +67 -0
- package/src/express/websocket.ts +47 -0
- package/src/index.ts +17 -4
- package/src/logger.ts +2 -2
- package/src/openapi-core.ts +115 -0
- package/src/openapi.ts +38 -0
- package/src/require-auth.ts +4 -3
- package/src/serve.ts +6 -1
- package/src/stream.ts +26 -0
- package/src/types.ts +1 -1
- package/src/upload.ts +62 -0
- package/src/websocket.ts +28 -0
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ Opinionated backend framework wrapper for Bun. Two adapters, same names,
|
|
|
4
4
|
same JSON error shape, same defaults — pick per project:
|
|
5
5
|
|
|
6
6
|
- `@mednours/backon` (default export) — wraps [Hono](https://hono.dev)
|
|
7
|
-
- `@mednours/backon/express` — wraps [Express](https://expressjs.com); requires `express`, `cors`, `helmet`, and `compression` as peer dependencies in
|
|
7
|
+
- `@mednours/backon/express` — wraps [Express](https://expressjs.com); requires `express`, `cors`, `helmet`, and `compression` as peer dependencies in the consuming project
|
|
8
8
|
|
|
9
9
|
## Install
|
|
10
10
|
|
|
@@ -42,7 +42,7 @@ serve(app);
|
|
|
42
42
|
|
|
43
43
|
## `defineRoute(schema, handler)`
|
|
44
44
|
|
|
45
|
-
Validates `body`/`query`/`params` against Zod schemas before
|
|
45
|
+
Validates `body`/`query`/`params` against Zod schemas before the handler runs, and hands the handler already-parsed, typed data. On failure it throws `AppError(400, "invalid_body" | "invalid_query" | "invalid_params", ...)` with the Zod error attached as `details`, caught automatically by `createApp()`'s error handler.
|
|
46
46
|
|
|
47
47
|
```ts
|
|
48
48
|
app.post(
|
|
@@ -57,7 +57,7 @@ app.post(
|
|
|
57
57
|
|
|
58
58
|
Runs on Bun's native server (Express adapter: Node's http server via Express's own `app.listen`) with graceful shutdown wired to `SIGTERM`/`SIGINT` — new connections stop being accepted and in-flight requests finish before exit.
|
|
59
59
|
|
|
60
|
-
**Express-specific:** `serve(app)` also registers the central error handler
|
|
60
|
+
**Express-specific:** `serve(app)` also registers the central error handler. Do this *after* every route is registered, not inside `createApp()` — Express's error-handling middleware only catches errors from routes registered *before* it, the opposite of Hono's `onError()`. When not using this `serve()` (wrapping the app for a serverless platform, or a `supertest` suite), call `attachErrorHandler(app)` directly, after every route.
|
|
61
61
|
|
|
62
62
|
```ts
|
|
63
63
|
import { createApp, defineRoute, serve } from "@mednours/backon/express";
|
|
@@ -93,9 +93,9 @@ export const env = requireEnv(
|
|
|
93
93
|
|
|
94
94
|
## `requireAuth(options)`
|
|
95
95
|
|
|
96
|
-
Verifies a bearer JWT and makes the decoded payload available on the context — `c.get("auth")` (Hono) or `res.locals.auth` (Express, or `c.get("auth")` inside a `defineRoute` handler). Throws `AppError(401, "unauthorized", ...)` if the header is missing, malformed, or the token fails verification (bad signature, expired, wrong algorithm). Built on `hono/jwt` rather than a new dependency, since `hono` is already a hard dependency of this package regardless of which
|
|
96
|
+
Verifies a bearer JWT and makes the decoded payload available on the context — `c.get("auth")` (Hono) or `res.locals.auth` (Express, or `c.get("auth")` inside a `defineRoute` handler). Throws `AppError(401, "unauthorized", ...)` if the header is missing, malformed, or the token fails verification (bad signature, expired, wrong algorithm). Built on `hono/jwt` rather than a new dependency, since `hono` is already a hard dependency of this package regardless of which adapter is in use.
|
|
97
97
|
|
|
98
|
-
This is verification only — issuing tokens (login, signup, refresh rotation, revocation) is left to
|
|
98
|
+
This is verification only — issuing tokens (login, signup, refresh rotation, revocation) is left to the consuming project, since that's genuinely different per project and baking in an opinion there risks being wrong for whatever actually uses it. The algorithm defaults to `HS256` and must be set explicitly rather than trusted from the token's own header — trusting that is how `alg: none` and algorithm-confusion attacks work.
|
|
99
99
|
|
|
100
100
|
```ts
|
|
101
101
|
import { requireAuth } from "@mednours/backon";
|
|
@@ -116,6 +116,97 @@ import { rateLimit } from "@mednours/backon";
|
|
|
116
116
|
app.use("/auth/login", rateLimit({ windowMs: 60_000, max: 5 })); // tighter limit on a login route
|
|
117
117
|
```
|
|
118
118
|
|
|
119
|
+
## `defineWebSocket(handlers)`
|
|
120
|
+
|
|
121
|
+
Registers a WebSocket route with `onOpen`/`onMessage`/`onClose` handlers, each getting a `ws` handle with `.send()`/`.close()`.
|
|
122
|
+
|
|
123
|
+
On Hono, the handshake happens at `Bun.serve()`'s own level (an HTTP upgrade, not an ordinary request/response cycle), so this only works with the `serve()` this package exports — it passes `hono/bun`'s websocket handler into `Bun.serve()` under the hood. Register it like any other route:
|
|
124
|
+
|
|
125
|
+
```ts
|
|
126
|
+
app.get("/ws", defineWebSocket({
|
|
127
|
+
onMessage: (ws, data) => ws.send(`echo: ${data}`),
|
|
128
|
+
}));
|
|
129
|
+
```
|
|
130
|
+
|
|
131
|
+
On Express, there is no route-level concept of an HTTP upgrade — only the `ws` package's own server has one, and that server doesn't exist until `serve()` is actually listening. The signature differs slightly to reflect this: it takes `app` and a `path` instead of being handed to `app.get()`, and can be called any time before `serve()`.
|
|
132
|
+
|
|
133
|
+
```ts
|
|
134
|
+
import { defineWebSocket, serve } from "@mednours/backon/express";
|
|
135
|
+
|
|
136
|
+
defineWebSocket(app, "/ws", {
|
|
137
|
+
onMessage: (ws, data) => ws.send(`echo: ${data}`),
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
serve(app); // attaches a WebSocketServer per registered path once the real http.Server exists
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
## `defineStream(handler)`
|
|
144
|
+
|
|
145
|
+
Registers a route that writes its response in chunks as they become available, instead of building one body in memory and returning it all at once — server-sent events, a large export, anything too slow or too big to buffer first. The handler gets a `write(chunk)` function.
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
app.get("/export", defineStream(async (c, write) => {
|
|
149
|
+
for (const row of rows) await write(JSON.stringify(row) + "\n");
|
|
150
|
+
}));
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
Set a Content-Type via `c.header()` before the first `write()` if the default (left to the client to infer) isn't right for what's being sent.
|
|
154
|
+
|
|
155
|
+
## `defineUpload(options, handler)`
|
|
156
|
+
|
|
157
|
+
Parses a `multipart/form-data` request, validating each file against `maxFileSizeBytes`/`allowedMimeTypes` before the handler runs — the same "validate first, throw `AppError(400, ...)` on failure" contract as `defineRoute()`, just for files instead of a JSON body. Fields uploaded more than once under the same name all land under that field's array, so `files.avatar` is always an array, even with one file. MIME type checks compare only the base type, ignoring parameters like `;charset=utf-8` on the Content-Type header.
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
app.post(
|
|
161
|
+
"/avatar",
|
|
162
|
+
defineUpload(
|
|
163
|
+
{ maxFileSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ["image/png", "image/jpeg"] },
|
|
164
|
+
async (c, { files }) => c.json({ uploaded: files.avatar.length })
|
|
165
|
+
)
|
|
166
|
+
);
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
On Express, this is built on `multer` with in-memory storage (never written to disk — the handler decides what happens to the data), since Express has no built-in multipart parser the way Hono's `c.req.parseBody()` is. `multer` is an optional peer dependency, only required when `defineUpload` is actually used.
|
|
170
|
+
|
|
171
|
+
## `generateOpenApiSpec(app)` / `serveApiDocs(app, path, options)`
|
|
172
|
+
|
|
173
|
+
Builds an OpenAPI 3.0 document from the routes registered on `app`, using the same Zod schemas `defineRoute()` validates against — the spec is derived from the schemas actually enforced at runtime instead of a hand-written document that can drift out of sync with them. A route with no schema (a plain handler, `/health`, a WebSocket route) is skipped, since there is nothing to describe past its existence.
|
|
174
|
+
|
|
175
|
+
`serveApiDocs` mounts the document as JSON plus a rendered reference page built on [Scalar](https://github.com/scalar/scalar), loaded from a CDN rather than bundled as a dependency. Call it after every other route is registered, same registration-order rule as anything else reading the app's route table.
|
|
176
|
+
|
|
177
|
+
```ts
|
|
178
|
+
import { serveApiDocs } from "@mednours/backon";
|
|
179
|
+
|
|
180
|
+
serveApiDocs(app, "/docs", { title: "My API" });
|
|
181
|
+
// GET /docs/openapi.json -> the raw spec
|
|
182
|
+
// GET /docs -> a rendered API reference page
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
`apiReferenceHtml(specUrl, title?)`, the page `serveApiDocs` renders, is also exported directly — useful for a build step that writes the spec and the reference page to static files instead of serving them from a running app:
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { writeFileSync } from "node:fs";
|
|
189
|
+
import { generateOpenApiSpec, apiReferenceHtml } from "@mednours/backon";
|
|
190
|
+
import { app } from "./src/app";
|
|
191
|
+
|
|
192
|
+
writeFileSync("openapi.json", JSON.stringify(generateOpenApiSpec(app, { title: "My API" }), null, 2));
|
|
193
|
+
writeFileSync("docs.html", apiReferenceHtml("./openapi.json", "My API"));
|
|
194
|
+
```
|
|
195
|
+
|
|
196
|
+
On Express, routes are read from a registry `createApp()` and `Router()` (exported from `@mednours/backon/express`) both populate as routes are added — using Express's own unwrapped `express.Router()` instead means those routes won't appear in the generated spec.
|
|
197
|
+
|
|
198
|
+
```ts
|
|
199
|
+
import { createApp, Router, defineRoute, serveApiDocs, serve } from "@mednours/backon/express";
|
|
200
|
+
|
|
201
|
+
const app = createApp();
|
|
202
|
+
const users = Router();
|
|
203
|
+
users.get("/", defineRoute({}, (c) => c.json({ users: [] })));
|
|
204
|
+
app.use("/users", users);
|
|
205
|
+
|
|
206
|
+
serveApiDocs(app, "/docs", { title: "My API" });
|
|
207
|
+
serve(app);
|
|
208
|
+
```
|
|
209
|
+
|
|
119
210
|
## Requirements
|
|
120
211
|
|
|
121
212
|
Bun >= 1.3. This package ships TypeScript source directly (no build step) since it's Bun-only by design.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mednours/backon",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Opinionated backend framework wrapper for Bun. Wraps Hono (default) or Express (via @mednours/backon/express) with the same baked-in security, logging, and validation defaults.",
|
|
6
6
|
"license": "MIT",
|
|
@@ -33,19 +33,24 @@
|
|
|
33
33
|
"dependencies": {
|
|
34
34
|
"hono": "^4.6.14",
|
|
35
35
|
"pino": "^9.5.0",
|
|
36
|
-
"zod": "^3.
|
|
36
|
+
"zod": "^3.25.28",
|
|
37
|
+
"zod-to-json-schema": "^3.25.2"
|
|
37
38
|
},
|
|
38
39
|
"peerDependencies": {
|
|
39
40
|
"express": "^4.21.0",
|
|
40
41
|
"cors": "^2.8.5",
|
|
41
42
|
"helmet": "^8.0.0",
|
|
42
|
-
"compression": "^1.7.5"
|
|
43
|
+
"compression": "^1.7.5",
|
|
44
|
+
"ws": "^8.18.0",
|
|
45
|
+
"multer": "^1.4.5"
|
|
43
46
|
},
|
|
44
47
|
"peerDependenciesMeta": {
|
|
45
48
|
"express": { "optional": true },
|
|
46
49
|
"cors": { "optional": true },
|
|
47
50
|
"helmet": { "optional": true },
|
|
48
|
-
"compression": { "optional": true }
|
|
51
|
+
"compression": { "optional": true },
|
|
52
|
+
"ws": { "optional": true },
|
|
53
|
+
"multer": { "optional": true }
|
|
49
54
|
},
|
|
50
55
|
"devDependencies": {
|
|
51
56
|
"@types/bun": "latest",
|
|
@@ -53,11 +58,15 @@
|
|
|
53
58
|
"@types/cors": "^2.8.17",
|
|
54
59
|
"@types/compression": "^1.7.5",
|
|
55
60
|
"@types/supertest": "^6.0.2",
|
|
61
|
+
"@types/ws": "^8.5.13",
|
|
62
|
+
"@types/multer": "^1.4.12",
|
|
56
63
|
"typescript": "^5.7.2",
|
|
57
64
|
"express": "^4.21.0",
|
|
58
65
|
"cors": "^2.8.5",
|
|
59
66
|
"helmet": "^8.0.0",
|
|
60
67
|
"compression": "^1.7.5",
|
|
68
|
+
"ws": "^8.18.0",
|
|
69
|
+
"multer": "^1.4.5-lts.1",
|
|
61
70
|
"supertest": "^7.0.0"
|
|
62
71
|
}
|
|
63
72
|
}
|
package/src/create-app.ts
CHANGED
|
@@ -33,8 +33,8 @@ function resolveAllowedOrigins(options: CreateAppOptions): string[] {
|
|
|
33
33
|
* that turns AppError (or anything else) into a consistent JSON shape.
|
|
34
34
|
*
|
|
35
35
|
* This is the "small opinionated helpers" layer agreed on for v1 — enough to
|
|
36
|
-
*
|
|
37
|
-
*
|
|
36
|
+
* justify a dedicated package instead of importing hono directly, without
|
|
37
|
+
* trying to cover every possible use case up front.
|
|
38
38
|
*/
|
|
39
39
|
export function createApp(options: CreateAppOptions = {}) {
|
|
40
40
|
const app = new Hono<Env>();
|
|
@@ -59,14 +59,14 @@ export function createApp(options: CreateAppOptions = {}) {
|
|
|
59
59
|
|
|
60
60
|
// Registered here, before createApp() returns, so it always gets the
|
|
61
61
|
// middleware above (logging, secure headers, CORS, compression, body
|
|
62
|
-
// limit). It deliberately does NOT get middleware
|
|
63
|
-
//
|
|
62
|
+
// limit). It deliberately does NOT get middleware added afterward in the
|
|
63
|
+
// project's own app.ts (app.use('*', someMiddleware) only wraps routes
|
|
64
64
|
// registered after that call) — verified by hand, this is Hono's own
|
|
65
65
|
// registration-order behavior, not something backon adds. That's the
|
|
66
66
|
// right default for a liveness check: an uptime monitor shouldn't get
|
|
67
|
-
// blocked by app-specific middleware like auth.
|
|
68
|
-
//
|
|
69
|
-
//
|
|
67
|
+
// blocked by app-specific middleware like auth. For /health behind its
|
|
68
|
+
// own middleware too, register a separate route instead of relying on
|
|
69
|
+
// this one.
|
|
70
70
|
app.get("/health", (c) => c.json({ status: "ok" }));
|
|
71
71
|
|
|
72
72
|
app.onError((err, c) => {
|
package/src/define-route.ts
CHANGED
|
@@ -2,7 +2,7 @@ import type { ZodType } from "zod";
|
|
|
2
2
|
import { AppError } from "./error";
|
|
3
3
|
import type { BackonContext } from "./types";
|
|
4
4
|
|
|
5
|
-
/** Zod schemas for the parts of a request worth validating. All optional — skip
|
|
5
|
+
/** Zod schemas for the parts of a request worth validating. All optional — skip whatever isn't needed. */
|
|
6
6
|
export interface RouteSchema<B = undefined, Q = undefined, P = undefined> {
|
|
7
7
|
body?: ZodType<B>;
|
|
8
8
|
query?: ZodType<Q>;
|
|
@@ -20,15 +20,25 @@ export type RouteHandler<B, Q, P> = (
|
|
|
20
20
|
data: RouteData<B, Q, P>
|
|
21
21
|
) => Response | Promise<Response>;
|
|
22
22
|
|
|
23
|
+
/** A defineRoute()-wrapped handler, carrying its own schema for generateOpenApiSpec() to read back later. */
|
|
24
|
+
export interface RouteHandlerFn {
|
|
25
|
+
(c: BackonContext): Promise<Response>;
|
|
26
|
+
__backonRouteSchema?: RouteSchema<unknown, unknown, unknown>;
|
|
27
|
+
}
|
|
28
|
+
|
|
23
29
|
/**
|
|
24
30
|
* Wraps a handler with request validation against zod schemas. On failure,
|
|
25
31
|
* throws AppError(400, ...) with the zod error attached as `details` —
|
|
26
32
|
* createApp()'s error handler turns that into the standard error JSON shape,
|
|
27
33
|
* so individual routes never write their own "if invalid, return 400" code.
|
|
28
34
|
*
|
|
35
|
+
* The schema is also attached to the returned function as
|
|
36
|
+
* `__backonRouteSchema`, purely for generateOpenApiSpec() to read back —
|
|
37
|
+
* nothing about validation depends on it.
|
|
38
|
+
*
|
|
29
39
|
* Usage in a *.controller.ts file:
|
|
30
40
|
*
|
|
31
|
-
*
|
|
41
|
+
* const getTelemetry = defineRoute(
|
|
32
42
|
* { query: z.object({ deviceId: z.string() }) },
|
|
33
43
|
* async (c, { query }) => c.json({ deviceId: query.deviceId })
|
|
34
44
|
* );
|
|
@@ -36,8 +46,8 @@ export type RouteHandler<B, Q, P> = (
|
|
|
36
46
|
export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
37
47
|
schema: RouteSchema<B, Q, P>,
|
|
38
48
|
handler: RouteHandler<B, Q, P>
|
|
39
|
-
) {
|
|
40
|
-
|
|
49
|
+
): RouteHandlerFn {
|
|
50
|
+
const wrapped: RouteHandlerFn = async (c: BackonContext): Promise<Response> => {
|
|
41
51
|
let body = undefined as B;
|
|
42
52
|
let query = undefined as Q;
|
|
43
53
|
let params = undefined as P;
|
|
@@ -71,4 +81,6 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
|
71
81
|
|
|
72
82
|
return handler(c, { body, query, params });
|
|
73
83
|
};
|
|
84
|
+
wrapped.__backonRouteSchema = schema as RouteSchema<unknown, unknown, unknown>;
|
|
85
|
+
return wrapped;
|
|
74
86
|
}
|
|
@@ -5,6 +5,7 @@ import compression from "compression";
|
|
|
5
5
|
import { AppError } from "../error";
|
|
6
6
|
import { logger } from "../logger";
|
|
7
7
|
import { requestLogger } from "./logger";
|
|
8
|
+
import { trackRoutes } from "./router-registry";
|
|
8
9
|
|
|
9
10
|
export interface CreateAppOptions {
|
|
10
11
|
/** Allowed CORS origins. Defaults to ALLOWED_ORIGINS env var (comma-separated), closed by default. */
|
|
@@ -31,16 +32,19 @@ function resolveAllowedOrigins(options: CreateAppOptions): string[] {
|
|
|
31
32
|
* 4-argument signature and only lets it catch errors from routes/middleware
|
|
32
33
|
* registered BEFORE it — the opposite of Hono's onError(), which is
|
|
33
34
|
* registration-order-independent. If the error handler were added here,
|
|
34
|
-
* inside createApp(), it would never see errors from
|
|
35
|
-
* afterward in
|
|
36
|
-
* `serve()` calls attachErrorHandler()
|
|
37
|
-
* server, once
|
|
38
|
-
*
|
|
39
|
-
* serverless handler or a supertest suite — call attachErrorHandler(app)
|
|
40
|
-
*
|
|
35
|
+
* inside createApp(), it would never see errors from routes added
|
|
36
|
+
* afterward in the project's own app.ts, exactly the routes it exists to
|
|
37
|
+
* catch. `serve()` calls attachErrorHandler() automatically, right before
|
|
38
|
+
* starting the server, once every route is guaranteed to already be
|
|
39
|
+
* registered. When not using backon's serve() — e.g. wrapping this app for
|
|
40
|
+
* a serverless handler or a supertest suite — call attachErrorHandler(app)
|
|
41
|
+
* directly, after every route, before the app is used.
|
|
41
42
|
*/
|
|
42
43
|
export function createApp(options: CreateAppOptions = {}): Express {
|
|
43
|
-
|
|
44
|
+
// Instrumented before anything else is registered, so every route this
|
|
45
|
+
// app (or a Router() mounted onto it) adds afterward — including /health
|
|
46
|
+
// below — is tracked for generateOpenApiSpec(). See router-registry.ts.
|
|
47
|
+
const app = trackRoutes(express());
|
|
44
48
|
|
|
45
49
|
app.use(requestLogger);
|
|
46
50
|
app.use(helmet());
|
|
@@ -51,9 +55,9 @@ export function createApp(options: CreateAppOptions = {}): Express {
|
|
|
51
55
|
app.use(compression());
|
|
52
56
|
app.use(express.json({ limit: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES }));
|
|
53
57
|
|
|
54
|
-
// Same reasoning as the Hono version's /health: registered before
|
|
55
|
-
//
|
|
56
|
-
//
|
|
58
|
+
// Same reasoning as the Hono version's /health: registered before any
|
|
59
|
+
// project-specific middleware, so it gets logging/security/CORS/compression
|
|
60
|
+
// but nothing added afterward. Right default for a liveness check.
|
|
57
61
|
app.get("/health", (_req, res) => {
|
|
58
62
|
res.json({ status: "ok" });
|
|
59
63
|
});
|
|
@@ -28,17 +28,27 @@ export type RouteHandler<B, Q, P> = (
|
|
|
28
28
|
data: RouteData<B, Q, P>
|
|
29
29
|
) => unknown | Promise<unknown>;
|
|
30
30
|
|
|
31
|
+
/** A defineRoute()-wrapped Express handler, carrying its own schema for generateOpenApiSpec() to read back later. */
|
|
32
|
+
export interface RouteHandlerFn {
|
|
33
|
+
(req: Request, res: Response, next: NextFunction): Promise<void>;
|
|
34
|
+
__backonRouteSchema?: RouteSchema<unknown, unknown, unknown>;
|
|
35
|
+
}
|
|
36
|
+
|
|
31
37
|
/**
|
|
32
38
|
* Same contract as the Hono defineRoute: validates body/query/params
|
|
33
39
|
* against zod schemas and throws AppError(400, ...) on failure. Requires
|
|
34
40
|
* createApp()'s express.json() middleware to have already run so
|
|
35
41
|
* req.body is parsed — see create-app.ts.
|
|
42
|
+
*
|
|
43
|
+
* The schema is also attached to the returned function as
|
|
44
|
+
* `__backonRouteSchema`, purely for generateOpenApiSpec() to read back —
|
|
45
|
+
* nothing about validation depends on it.
|
|
36
46
|
*/
|
|
37
47
|
export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
38
48
|
schema: RouteSchema<B, Q, P>,
|
|
39
49
|
handler: RouteHandler<B, Q, P>
|
|
40
|
-
) {
|
|
41
|
-
|
|
50
|
+
): RouteHandlerFn {
|
|
51
|
+
const wrapped: RouteHandlerFn = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
42
52
|
try {
|
|
43
53
|
let body = undefined as B;
|
|
44
54
|
let query = undefined as Q;
|
|
@@ -74,4 +84,6 @@ export function defineRoute<B = undefined, Q = undefined, P = undefined>(
|
|
|
74
84
|
next(err);
|
|
75
85
|
}
|
|
76
86
|
};
|
|
87
|
+
wrapped.__backonRouteSchema = schema as RouteSchema<unknown, unknown, unknown>;
|
|
88
|
+
return wrapped;
|
|
77
89
|
}
|
package/src/express/index.ts
CHANGED
|
@@ -21,13 +21,25 @@ export type { RateLimitOptions } from "./rate-limit";
|
|
|
21
21
|
|
|
22
22
|
export type { BackonContext } from "./types";
|
|
23
23
|
|
|
24
|
+
export { Router } from "./router";
|
|
25
|
+
|
|
24
26
|
/**
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
29
|
-
* always operates at the framework's own req/res/next layer, there's no
|
|
30
|
-
* getting around that by wrapping it.
|
|
27
|
+
* Request/Response/NextFunction are for writing plain Express middleware
|
|
28
|
+
* itself — BackonContext only exists inside defineRoute() handlers,
|
|
29
|
+
* middleware always operates at the framework's own req/res/next layer,
|
|
30
|
+
* there's no getting around that by wrapping it.
|
|
31
31
|
*/
|
|
32
|
-
export { Router } from "express";
|
|
33
32
|
export type { Request, Response, NextFunction } from "express";
|
|
33
|
+
|
|
34
|
+
export { defineWebSocket } from "./websocket";
|
|
35
|
+
export type { WebSocketHandlers } from "./websocket";
|
|
36
|
+
|
|
37
|
+
export { defineStream } from "./stream";
|
|
38
|
+
export type { StreamWriter } from "./stream";
|
|
39
|
+
|
|
40
|
+
export { defineUpload } from "./upload";
|
|
41
|
+
export type { UploadOptions, UploadHandler } from "./upload";
|
|
42
|
+
|
|
43
|
+
export { generateOpenApiSpec, serveApiDocs } from "./openapi";
|
|
44
|
+
export type { OpenApiOptions } from "../openapi-core";
|
|
45
|
+
export { apiReferenceHtml } from "../openapi-core";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { Express } from "express";
|
|
2
|
+
import { buildOpenApiDocument, apiReferenceHtml, type OpenApiOptions, type CollectedRoute } from "../openapi-core";
|
|
3
|
+
import { collectRoutes, type TrackedRouter } from "./router-registry";
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Reads every route recorded by trackRoutes() (see router-registry.ts) —
|
|
7
|
+
* meaning createApp()'s own app, and any @mednours/backon/express Router()
|
|
8
|
+
* mounted onto it — and builds an OpenAPI document from whichever ones
|
|
9
|
+
* were wrapped in defineRoute(), the only ones carrying a schema.
|
|
10
|
+
*/
|
|
11
|
+
export function generateOpenApiSpec(app: Express, options: OpenApiOptions = {}): Record<string, unknown> {
|
|
12
|
+
const routes = collectRoutes(app as unknown as TrackedRouter) as CollectedRoute[];
|
|
13
|
+
return buildOpenApiDocument(routes, options);
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Mounts two routes: the OpenAPI document itself as JSON, and a page that
|
|
18
|
+
* renders it. Call after every other route is registered on `app` —
|
|
19
|
+
* routes added afterward won't be reflected in either.
|
|
20
|
+
*
|
|
21
|
+
* serveApiDocs(app, "/docs", { title: "My API" });
|
|
22
|
+
*/
|
|
23
|
+
export function serveApiDocs(app: Express, path = "/docs", options: OpenApiOptions = {}): void {
|
|
24
|
+
const specPath = `${path}/openapi.json`;
|
|
25
|
+
app.get(specPath, (_req, res) => res.json(generateOpenApiSpec(app, options)));
|
|
26
|
+
app.get(path, (_req, res) => res.type("html").send(apiReferenceHtml(specPath, options.title)));
|
|
27
|
+
}
|
|
@@ -9,10 +9,11 @@ import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "../auth-co
|
|
|
9
9
|
* res.locals) or directly as `res.locals.auth` in plain Express middleware.
|
|
10
10
|
* Calls next(AppError(401, "unauthorized")) on a missing, malformed, or
|
|
11
11
|
* invalid token; requires attachErrorHandler(app) to be registered
|
|
12
|
-
* downstream (serve() does this
|
|
12
|
+
* downstream (serve() does this automatically — see create-app.ts).
|
|
13
13
|
*
|
|
14
14
|
* Verification only, same as the Hono version — issuing tokens is left to
|
|
15
|
-
*
|
|
15
|
+
* the consuming project. Apply per-route or per-router, not necessarily
|
|
16
|
+
* globally.
|
|
16
17
|
*/
|
|
17
18
|
export function requireAuth(options: VerifyJwtOptions) {
|
|
18
19
|
return async function requireAuthMiddleware(req: Request, res: Response, next: NextFunction) {
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Backs generateOpenApiSpec() on the Express adapter. Express's own router
|
|
3
|
+
* tree (app._router.stack) is undocumented, version-specific, and awkward
|
|
4
|
+
* to walk correctly through nested Router() mounts — reconstructing a
|
|
5
|
+
* mount's full path from its compiled matching regexp is lossy in general.
|
|
6
|
+
* Rather than reflect into that, backon's own Router() (exported from
|
|
7
|
+
* @mednours/backon/express instead of express directly) and createApp()'s
|
|
8
|
+
* returned app both get instrumented here: every get/post/put/patch/delete
|
|
9
|
+
* call records its own path, method, and schema (if any); every use(prefix,
|
|
10
|
+
* subRouter) call records the mount so the full path can be composed by
|
|
11
|
+
* simple string concatenation, not regexp decoding.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
export type MountEntry =
|
|
15
|
+
| { type: "route"; method: string; path: string; schema?: unknown }
|
|
16
|
+
| { type: "mount"; prefix: string; target: TrackedRouter };
|
|
17
|
+
|
|
18
|
+
export interface TrackedRouter {
|
|
19
|
+
__backonEntries: MountEntry[];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const TRACKED_METHODS = ["get", "post", "put", "patch", "delete", "options", "head"] as const;
|
|
23
|
+
|
|
24
|
+
function isTracked(value: unknown): value is TrackedRouter {
|
|
25
|
+
// An Express app or Router() instance is itself a callable function, not
|
|
26
|
+
// a plain object — `typeof` on either is "function", so both need
|
|
27
|
+
// accepting here, not just "object".
|
|
28
|
+
if (value === null || (typeof value !== "object" && typeof value !== "function")) return false;
|
|
29
|
+
return Array.isArray((value as TrackedRouter).__backonEntries);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Wraps get/post/put/patch/delete/use on an Express app or Router, delegating to the real method in every case. */
|
|
33
|
+
export function trackRoutes<T extends object>(target: T): T & TrackedRouter {
|
|
34
|
+
if (isTracked(target)) return target;
|
|
35
|
+
|
|
36
|
+
const tracked = target as T & TrackedRouter;
|
|
37
|
+
tracked.__backonEntries = [];
|
|
38
|
+
|
|
39
|
+
for (const method of TRACKED_METHODS) {
|
|
40
|
+
const original = (tracked as Record<string, unknown>)[method];
|
|
41
|
+
if (typeof original !== "function") continue;
|
|
42
|
+
const boundOriginal = original.bind(tracked);
|
|
43
|
+
(tracked as Record<string, unknown>)[method] = (path: unknown, ...handlers: unknown[]) => {
|
|
44
|
+
// Express overloads .get() specifically: called with a single
|
|
45
|
+
// argument, it's a settings getter (`app.get('query parser fn')`),
|
|
46
|
+
// not a route — Express's own lazy router init calls it that way
|
|
47
|
+
// internally. Only handlers.length > 0 is ever a real registration.
|
|
48
|
+
if (typeof path === "string" && handlers.length > 0) {
|
|
49
|
+
const last = handlers[handlers.length - 1] as { __backonRouteSchema?: unknown } | undefined;
|
|
50
|
+
tracked.__backonEntries.push({ type: "route", method, path, schema: last?.__backonRouteSchema });
|
|
51
|
+
}
|
|
52
|
+
return boundOriginal(path, ...handlers);
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const originalUse = (tracked as Record<string, unknown>).use;
|
|
57
|
+
if (typeof originalUse === "function") {
|
|
58
|
+
const boundUse = originalUse.bind(tracked);
|
|
59
|
+
(tracked as Record<string, unknown>).use = (...args: unknown[]) => {
|
|
60
|
+
if (typeof args[0] === "string" && isTracked(args[1])) {
|
|
61
|
+
tracked.__backonEntries.push({ type: "mount", prefix: args[0], target: args[1] });
|
|
62
|
+
}
|
|
63
|
+
return boundUse(...args);
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
return tracked;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function joinPaths(prefix: string, path: string): string {
|
|
71
|
+
const joined = `${prefix.replace(/\/$/, "")}/${path.replace(/^\//, "")}`;
|
|
72
|
+
return joined.replace(/\/+$/, "") || "/";
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Recursively resolves every tracked route to its full path, following mount entries down through nested routers. */
|
|
76
|
+
export function collectRoutes(
|
|
77
|
+
root: TrackedRouter,
|
|
78
|
+
prefix = ""
|
|
79
|
+
): Array<{ method: string; path: string; schema?: unknown }> {
|
|
80
|
+
const results: Array<{ method: string; path: string; schema?: unknown }> = [];
|
|
81
|
+
for (const entry of root.__backonEntries) {
|
|
82
|
+
if (entry.type === "route") {
|
|
83
|
+
results.push({ method: entry.method, path: joinPaths(prefix, entry.path), schema: entry.schema });
|
|
84
|
+
} else {
|
|
85
|
+
results.push(...collectRoutes(entry.target, joinPaths(prefix, entry.prefix)));
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
return results;
|
|
89
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Router as expressRouter, type Router as ExpressRouterType } from "express";
|
|
2
|
+
import { trackRoutes, type TrackedRouter } from "./router-registry";
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Same as Express's own Router() in every way that matters at runtime —
|
|
6
|
+
* this calls it directly — but instrumented so generateOpenApiSpec() can
|
|
7
|
+
* walk the route tree it produces. Exported from @mednours/backon/express
|
|
8
|
+
* instead of importing Router from 'express' directly is what makes that
|
|
9
|
+
* tracking possible; both behave identically otherwise.
|
|
10
|
+
*/
|
|
11
|
+
export function Router(...args: Parameters<typeof expressRouter>): ExpressRouterType & TrackedRouter {
|
|
12
|
+
return trackRoutes(expressRouter(...args));
|
|
13
|
+
}
|
package/src/express/serve.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Express } from "express";
|
|
2
2
|
import { attachErrorHandler } from "./create-app";
|
|
3
|
+
import { attachWebSockets } from "./websocket";
|
|
3
4
|
import { logger } from "../logger";
|
|
4
5
|
|
|
5
6
|
/**
|
|
@@ -7,9 +8,11 @@ import { logger } from "../logger";
|
|
|
7
8
|
* wires graceful shutdown, same contract as the Hono adapter's serve().
|
|
8
9
|
*
|
|
9
10
|
* Also calls attachErrorHandler(app) first — see the note on createApp()
|
|
10
|
-
* for why that can't happen until every route is registered.
|
|
11
|
+
* for why that can't happen until every route is registered. When not
|
|
11
12
|
* using this serve() (e.g. exporting the app for a serverless platform or a
|
|
12
|
-
* supertest suite), call attachErrorHandler(app)
|
|
13
|
+
* supertest suite), call attachErrorHandler(app) directly instead — and, if
|
|
14
|
+
* any defineWebSocket() routes were registered, attachWebSockets(app,
|
|
15
|
+
* server) too, once a real http.Server exists.
|
|
13
16
|
*/
|
|
14
17
|
export function serve(app: Express, port: number = Number(process.env.PORT) || 3000) {
|
|
15
18
|
attachErrorHandler(app);
|
|
@@ -17,6 +20,7 @@ export function serve(app: Express, port: number = Number(process.env.PORT) || 3
|
|
|
17
20
|
const server = app.listen(port, () => {
|
|
18
21
|
logger.info({ port }, "backon app listening");
|
|
19
22
|
});
|
|
23
|
+
attachWebSockets(app, server);
|
|
20
24
|
|
|
21
25
|
let shuttingDown = false;
|
|
22
26
|
const shutdown = (signal: string) => {
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import { createContext, type BackonContext } from "./types";
|
|
3
|
+
|
|
4
|
+
export type StreamWriter = (chunk: string | Uint8Array) => void;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Same contract as the Hono defineStream: the handler writes chunks as they
|
|
8
|
+
* become available instead of returning one body all at once. Underneath,
|
|
9
|
+
* this is just res.write() — Node's response object is a writable stream
|
|
10
|
+
* regardless of any framework sitting on top of it.
|
|
11
|
+
*
|
|
12
|
+
* app.get("/export", defineStream(async (c, write) => {
|
|
13
|
+
* for (const row of rows) write(JSON.stringify(row) + "\n");
|
|
14
|
+
* }));
|
|
15
|
+
*
|
|
16
|
+
* Set a Content-Type via c.header() before the first write() if the default
|
|
17
|
+
* (left to the browser/client to infer) isn't right for what's being sent.
|
|
18
|
+
*/
|
|
19
|
+
export function defineStream(handler: (c: BackonContext, write: StreamWriter) => Promise<void> | void) {
|
|
20
|
+
return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
|
21
|
+
try {
|
|
22
|
+
const ctx = createContext(req, res);
|
|
23
|
+
await handler(ctx, (chunk) => {
|
|
24
|
+
res.write(chunk);
|
|
25
|
+
});
|
|
26
|
+
res.end();
|
|
27
|
+
} catch (err) {
|
|
28
|
+
next(err);
|
|
29
|
+
}
|
|
30
|
+
};
|
|
31
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import multer, { type Multer } from "multer";
|
|
3
|
+
import { AppError } from "../error";
|
|
4
|
+
import { createContext, type BackonContext } from "./types";
|
|
5
|
+
|
|
6
|
+
/** Content-Type headers can carry parameters ("text/plain;charset=utf-8") — comparisons only care about the type itself. */
|
|
7
|
+
function baseMimeType(type: string): string {
|
|
8
|
+
return type.split(";")[0]?.trim() ?? type;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface UploadOptions {
|
|
12
|
+
/** Rejects any file over this size with a 400. Unset means no limit. */
|
|
13
|
+
maxFileSizeBytes?: number;
|
|
14
|
+
/** Rejects any file whose type isn't in this list with a 400. Unset means no restriction. */
|
|
15
|
+
allowedMimeTypes?: string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type UploadHandler = (
|
|
19
|
+
c: BackonContext,
|
|
20
|
+
data: { files: Record<string, Express.Multer.File[]> }
|
|
21
|
+
) => unknown | Promise<unknown>;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Same contract as the Hono defineUpload: parses a multipart/form-data
|
|
25
|
+
* request, validates each file against maxFileSizeBytes/allowedMimeTypes,
|
|
26
|
+
* throws AppError(400, ...) on the first violation. Built on multer (kept
|
|
27
|
+
* in memory, not written to disk — same "handler decides what happens to
|
|
28
|
+
* the data" philosophy as everything else here) since Express has no
|
|
29
|
+
* built-in multipart parser the way Hono's c.req.parseBody() is.
|
|
30
|
+
*
|
|
31
|
+
* app.post("/avatar", defineUpload(
|
|
32
|
+
* { maxFileSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ["image/png", "image/jpeg"] },
|
|
33
|
+
* async (c, { files }) => c.json({ uploaded: files.avatar.length })
|
|
34
|
+
* ));
|
|
35
|
+
*/
|
|
36
|
+
export function defineUpload(options: UploadOptions, handler: UploadHandler) {
|
|
37
|
+
const upload: Multer = multer({
|
|
38
|
+
storage: multer.memoryStorage(),
|
|
39
|
+
limits: options.maxFileSizeBytes !== undefined ? { fileSize: options.maxFileSizeBytes } : undefined,
|
|
40
|
+
});
|
|
41
|
+
const parseMultipart = upload.any();
|
|
42
|
+
|
|
43
|
+
return (req: Request, res: Response, next: NextFunction): void => {
|
|
44
|
+
parseMultipart(req, res, async (err: unknown) => {
|
|
45
|
+
if (err) {
|
|
46
|
+
const code = (err as { code?: string }).code === "LIMIT_FILE_SIZE" ? "file_too_large" : "invalid_upload";
|
|
47
|
+
next(new AppError(400, code, err instanceof Error ? err.message : "Upload failed"));
|
|
48
|
+
return;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
try {
|
|
52
|
+
const filesByField: Record<string, Express.Multer.File[]> = {};
|
|
53
|
+
for (const file of (req.files as Express.Multer.File[]) ?? []) {
|
|
54
|
+
if (options.allowedMimeTypes && !options.allowedMimeTypes.includes(baseMimeType(file.mimetype))) {
|
|
55
|
+
throw new AppError(400, "unsupported_file_type", `${file.originalname} has unsupported type "${file.mimetype}"`);
|
|
56
|
+
}
|
|
57
|
+
(filesByField[file.fieldname] ??= []).push(file);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const ctx = createContext(req, res);
|
|
61
|
+
await handler(ctx, { files: filesByField });
|
|
62
|
+
} catch (handlerErr) {
|
|
63
|
+
next(handlerErr);
|
|
64
|
+
}
|
|
65
|
+
});
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Server } from "node:http";
|
|
2
|
+
import type { IncomingMessage } from "node:http";
|
|
3
|
+
import { WebSocketServer, type WebSocket, type RawData } from "ws";
|
|
4
|
+
|
|
5
|
+
/** Handlers for one WebSocket route. `ws.send()`/`ws.close()` match the shape the Hono adapter's handlers get, too. */
|
|
6
|
+
export interface WebSocketHandlers {
|
|
7
|
+
onOpen?: (ws: WebSocket, req: IncomingMessage) => void;
|
|
8
|
+
onMessage?: (ws: WebSocket, data: RawData) => void;
|
|
9
|
+
onClose?: (ws: WebSocket) => void;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
interface PendingRegistration {
|
|
13
|
+
path: string;
|
|
14
|
+
handlers: WebSocketHandlers;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const pending = new WeakMap<object, PendingRegistration[]>();
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Registers a WebSocket route. Unlike Hono's version, this can't be
|
|
21
|
+
* registered as a normal GET route — Express has no route-level concept of
|
|
22
|
+
* an HTTP upgrade, only `ws`'s own server does, and that server doesn't
|
|
23
|
+
* exist until serve() has actually started listening. Call this on `app`
|
|
24
|
+
* any time before serve(); it's wired up once serve() has a real
|
|
25
|
+
* http.Server to attach to:
|
|
26
|
+
*
|
|
27
|
+
* defineWebSocket(app, "/ws", {
|
|
28
|
+
* onMessage: (ws, data) => ws.send(`echo: ${data}`),
|
|
29
|
+
* });
|
|
30
|
+
*/
|
|
31
|
+
export function defineWebSocket(app: object, path: string, handlers: WebSocketHandlers): void {
|
|
32
|
+
const list = pending.get(app) ?? [];
|
|
33
|
+
list.push({ path, handlers });
|
|
34
|
+
pending.set(app, list);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Called by serve() once the real http.Server exists — attaches one `ws` WebSocketServer per registered path. */
|
|
38
|
+
export function attachWebSockets(app: object, server: Server): void {
|
|
39
|
+
for (const { path, handlers } of pending.get(app) ?? []) {
|
|
40
|
+
const wss = new WebSocketServer({ server, path });
|
|
41
|
+
wss.on("connection", (ws, req) => {
|
|
42
|
+
handlers.onOpen?.(ws, req);
|
|
43
|
+
if (handlers.onMessage) ws.on("message", (data) => handlers.onMessage?.(ws, data));
|
|
44
|
+
if (handlers.onClose) ws.on("close", () => handlers.onClose?.(ws));
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -19,13 +19,26 @@ export type { VerifyJwtOptions } from "./auth-core";
|
|
|
19
19
|
export { rateLimit } from "./rate-limit";
|
|
20
20
|
export type { RateLimitOptions } from "./rate-limit";
|
|
21
21
|
|
|
22
|
+
export { defineWebSocket } from "./websocket";
|
|
23
|
+
export type { WebSocketHandlers } from "./websocket";
|
|
24
|
+
|
|
25
|
+
export { defineStream } from "./stream";
|
|
26
|
+
export type { StreamWriter } from "./stream";
|
|
27
|
+
|
|
28
|
+
export { defineUpload } from "./upload";
|
|
29
|
+
export type { UploadOptions, UploadHandler } from "./upload";
|
|
30
|
+
|
|
31
|
+
export { generateOpenApiSpec, serveApiDocs } from "./openapi";
|
|
32
|
+
export type { OpenApiOptions } from "./openapi";
|
|
33
|
+
export { apiReferenceHtml } from "./openapi-core";
|
|
34
|
+
|
|
22
35
|
export type { BackonContext, Env } from "./types";
|
|
23
36
|
|
|
24
37
|
/**
|
|
25
|
-
* Re-exported so generated projects (and anything
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
*
|
|
38
|
+
* Re-exported so generated projects (and anything built on backon) never
|
|
39
|
+
* need to depend on 'hono' directly, even for the parts backon doesn't add
|
|
40
|
+
* opinions to yet — like building a sub-router with `new Hono()` for a
|
|
41
|
+
* single resource's routes.
|
|
29
42
|
*/
|
|
30
43
|
export { Hono } from "hono";
|
|
31
44
|
export type { Next } from "hono";
|
package/src/logger.ts
CHANGED
|
@@ -5,8 +5,8 @@ import type { Env } from "./types";
|
|
|
5
5
|
|
|
6
6
|
/**
|
|
7
7
|
* Structured logger. pino instead of console.log because it's fast enough to
|
|
8
|
-
* leave on in production and gives
|
|
9
|
-
* console.log output
|
|
8
|
+
* leave on in production and gives structured (JSON) lines for free —
|
|
9
|
+
* console.log output isn't queryable later, structured log lines are.
|
|
10
10
|
*/
|
|
11
11
|
export const logger = pino({
|
|
12
12
|
level: process.env.LOG_LEVEL ?? "info",
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
2
|
+
import type { ZodType } from "zod";
|
|
3
|
+
|
|
4
|
+
export interface OpenApiOptions {
|
|
5
|
+
/** Defaults to "API". */
|
|
6
|
+
title?: string;
|
|
7
|
+
/** Defaults to "0.1.0". */
|
|
8
|
+
version?: string;
|
|
9
|
+
description?: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RouteSchemaLike {
|
|
13
|
+
body?: ZodType<unknown>;
|
|
14
|
+
query?: ZodType<unknown>;
|
|
15
|
+
params?: ZodType<unknown>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface CollectedRoute {
|
|
19
|
+
method: string;
|
|
20
|
+
path: string;
|
|
21
|
+
schema?: RouteSchemaLike;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Converts a framework's own param syntax (Hono and Express both use `:id`) to OpenAPI's `{id}`. */
|
|
25
|
+
export function toOpenApiPath(path: string): string {
|
|
26
|
+
return path.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function paramNames(path: string): string[] {
|
|
30
|
+
return [...path.matchAll(/:([A-Za-z0-9_]+)/g)]
|
|
31
|
+
.map((match) => match[1])
|
|
32
|
+
.filter((name): name is string => name !== undefined);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function buildOperation(path: string, schema: RouteSchemaLike): Record<string, unknown> {
|
|
36
|
+
const operation: Record<string, unknown> = { responses: { "200": { description: "Success" } } };
|
|
37
|
+
const parameters: unknown[] = [];
|
|
38
|
+
|
|
39
|
+
if (schema.params) {
|
|
40
|
+
const jsonSchema = zodToJsonSchema(schema.params, { target: "openApi3" }) as Record<string, any>;
|
|
41
|
+
for (const name of paramNames(path)) {
|
|
42
|
+
parameters.push({
|
|
43
|
+
name,
|
|
44
|
+
in: "path",
|
|
45
|
+
required: true,
|
|
46
|
+
schema: jsonSchema.properties?.[name] ?? { type: "string" },
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
if (schema.query) {
|
|
52
|
+
const jsonSchema = zodToJsonSchema(schema.query, { target: "openApi3" }) as Record<string, any>;
|
|
53
|
+
const required = new Set(jsonSchema.required ?? []);
|
|
54
|
+
for (const [name, propSchema] of Object.entries(jsonSchema.properties ?? {})) {
|
|
55
|
+
parameters.push({ name, in: "query", required: required.has(name), schema: propSchema });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
if (parameters.length) operation.parameters = parameters;
|
|
60
|
+
|
|
61
|
+
if (schema.body) {
|
|
62
|
+
operation.requestBody = {
|
|
63
|
+
required: true,
|
|
64
|
+
content: { "application/json": { schema: zodToJsonSchema(schema.body, { target: "openApi3" }) } },
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
return operation;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Builds an OpenAPI 3.0 document from a flat list of routes, each carrying
|
|
73
|
+
* the same Zod schema defineRoute() validates against — the spec is derived
|
|
74
|
+
* from the schemas actually enforced at runtime instead of a hand-written
|
|
75
|
+
* document that can drift out of sync with them. A route with no schema
|
|
76
|
+
* (a plain handler, /health, a WebSocket route) is skipped, since there is
|
|
77
|
+
* nothing to describe past its existence.
|
|
78
|
+
*/
|
|
79
|
+
export function buildOpenApiDocument(routes: CollectedRoute[], options: OpenApiOptions): Record<string, unknown> {
|
|
80
|
+
const paths: Record<string, Record<string, unknown>> = {};
|
|
81
|
+
|
|
82
|
+
for (const route of routes) {
|
|
83
|
+
if (!route.schema) continue;
|
|
84
|
+
const openApiPath = toOpenApiPath(route.path);
|
|
85
|
+
paths[openApiPath] ??= {};
|
|
86
|
+
paths[openApiPath][route.method.toLowerCase()] = buildOperation(route.path, route.schema);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
return {
|
|
90
|
+
openapi: "3.0.3",
|
|
91
|
+
info: {
|
|
92
|
+
title: options.title ?? "API",
|
|
93
|
+
version: options.version ?? "0.1.0",
|
|
94
|
+
...(options.description ? { description: options.description } : {}),
|
|
95
|
+
},
|
|
96
|
+
paths,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** A minimal page that renders an OpenAPI document with Scalar, loaded from a CDN rather than bundled as a dependency. */
|
|
101
|
+
export function apiReferenceHtml(specUrl: string, title = "API Reference"): string {
|
|
102
|
+
return `<!doctype html>
|
|
103
|
+
<html>
|
|
104
|
+
<head>
|
|
105
|
+
<title>${title}</title>
|
|
106
|
+
<meta charset="utf-8" />
|
|
107
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
108
|
+
</head>
|
|
109
|
+
<body>
|
|
110
|
+
<script id="api-reference" data-url="${specUrl}"></script>
|
|
111
|
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
112
|
+
</body>
|
|
113
|
+
</html>
|
|
114
|
+
`;
|
|
115
|
+
}
|
package/src/openapi.ts
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { Hono } from "hono";
|
|
2
|
+
import { buildOpenApiDocument, apiReferenceHtml, type OpenApiOptions, type CollectedRoute } from "./openapi-core";
|
|
3
|
+
import type { RouteHandlerFn } from "./define-route";
|
|
4
|
+
|
|
5
|
+
export type { OpenApiOptions };
|
|
6
|
+
|
|
7
|
+
const HTTP_METHODS = new Set(["get", "post", "put", "patch", "delete", "options", "head"]);
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Reads every route registered on `app` (including ones mounted through
|
|
11
|
+
* nested `.route()` calls, since Hono copies a sub-app's own route entries
|
|
12
|
+
* onto the parent) and builds an OpenAPI document from whichever ones were
|
|
13
|
+
* wrapped in defineRoute() — those are the only ones carrying a schema.
|
|
14
|
+
*/
|
|
15
|
+
export function generateOpenApiSpec(app: Hono<any>, options: OpenApiOptions = {}): Record<string, unknown> {
|
|
16
|
+
const routes: CollectedRoute[] = app.routes
|
|
17
|
+
.filter((route) => HTTP_METHODS.has(route.method.toLowerCase()))
|
|
18
|
+
.map((route) => ({
|
|
19
|
+
method: route.method,
|
|
20
|
+
path: route.path,
|
|
21
|
+
schema: (route.handler as RouteHandlerFn).__backonRouteSchema,
|
|
22
|
+
}));
|
|
23
|
+
|
|
24
|
+
return buildOpenApiDocument(routes, options);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Mounts two routes: the OpenAPI document itself as JSON, and a page that
|
|
29
|
+
* renders it. Call after every other route is registered — same
|
|
30
|
+
* registration-order rule as any other route reading from `app.routes`.
|
|
31
|
+
*
|
|
32
|
+
* serveApiDocs(app, "/docs", { title: "My API" });
|
|
33
|
+
*/
|
|
34
|
+
export function serveApiDocs(app: Hono<any>, path = "/docs", options: OpenApiOptions = {}): void {
|
|
35
|
+
const specPath = `${path}/openapi.json`;
|
|
36
|
+
app.get(specPath, (c) => c.json(generateOpenApiSpec(app, options)));
|
|
37
|
+
app.get(path, (c) => c.html(apiReferenceHtml(specPath, options.title)));
|
|
38
|
+
}
|
package/src/require-auth.ts
CHANGED
|
@@ -12,9 +12,10 @@ import { extractBearerToken, verifyJwt, type VerifyJwtOptions } from "./auth-cor
|
|
|
12
12
|
* same as any other AppError.
|
|
13
13
|
*
|
|
14
14
|
* This is verification only: issuing tokens (login, signup, refresh
|
|
15
|
-
* rotation, revocation) is left to
|
|
16
|
-
* per project and baking in an opinion there risks
|
|
17
|
-
* project actually uses it. Apply it per-route or
|
|
15
|
+
* rotation, revocation) is left to the consuming project, since that's
|
|
16
|
+
* genuinely different per project and baking in an opinion there risks
|
|
17
|
+
* being wrong for whatever project actually uses it. Apply it per-route or
|
|
18
|
+
* per-group, not globally:
|
|
18
19
|
*
|
|
19
20
|
* protectedRoutes.use("*", requireAuth({ secret: process.env.JWT_SECRET! }));
|
|
20
21
|
*/
|
package/src/serve.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { Hono } from "hono";
|
|
2
|
+
import { websocket } from "hono/bun";
|
|
2
3
|
import { logger } from "./logger";
|
|
3
4
|
import type { Env } from "./types";
|
|
4
5
|
|
|
@@ -7,9 +8,13 @@ import type { Env } from "./types";
|
|
|
7
8
|
* SIGTERM/SIGINT, stop accepting new connections, let in-flight requests
|
|
8
9
|
* finish, then exit. Matters for zero-downtime deploys — without this, a
|
|
9
10
|
* deploy or restart can cut off requests mid-flight.
|
|
11
|
+
*
|
|
12
|
+
* Also passes hono/bun's own websocket handler into Bun.serve() — needed
|
|
13
|
+
* for any defineWebSocket() route to actually complete its upgrade
|
|
14
|
+
* handshake, and harmless when there are none.
|
|
10
15
|
*/
|
|
11
16
|
export function serve(app: Hono<Env>, port: number = Number(process.env.PORT) || 3000) {
|
|
12
|
-
const server = Bun.serve({ fetch: app.fetch, port });
|
|
17
|
+
const server = Bun.serve({ fetch: app.fetch, websocket, port });
|
|
13
18
|
logger.info({ port }, "backon app listening");
|
|
14
19
|
|
|
15
20
|
let shuttingDown = false;
|
package/src/stream.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { stream as honoStream } from "hono/streaming";
|
|
2
|
+
import type { BackonContext } from "./types";
|
|
3
|
+
|
|
4
|
+
export type StreamWriter = (chunk: string | Uint8Array) => Promise<void>;
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Registers a route that writes its response in chunks as they become
|
|
8
|
+
* available, instead of building one body in memory and returning it all at
|
|
9
|
+
* once — server-sent events, a large export, anything too slow or too big
|
|
10
|
+
* to buffer first.
|
|
11
|
+
*
|
|
12
|
+
* app.get("/export", defineStream(async (c, write) => {
|
|
13
|
+
* for (const row of rows) await write(JSON.stringify(row) + "\n");
|
|
14
|
+
* }));
|
|
15
|
+
*
|
|
16
|
+
* Set a Content-Type via c.header() before the first write() if the default
|
|
17
|
+
* (left to the browser/client to infer) isn't right for what's being sent.
|
|
18
|
+
*/
|
|
19
|
+
export function defineStream(handler: (c: BackonContext, write: StreamWriter) => Promise<void>) {
|
|
20
|
+
return (c: BackonContext) =>
|
|
21
|
+
honoStream(c, async (s) => {
|
|
22
|
+
await handler(c, async (chunk) => {
|
|
23
|
+
await s.write(chunk);
|
|
24
|
+
});
|
|
25
|
+
});
|
|
26
|
+
}
|
package/src/types.ts
CHANGED
|
@@ -20,7 +20,7 @@ export interface Env {
|
|
|
20
20
|
* (the seam that would let an Express adapter produce the same shape) only
|
|
21
21
|
* gets designed once that adapter is actually being built. Guessing at that
|
|
22
22
|
* abstraction now, before a second implementation exists to validate it
|
|
23
|
-
* against,
|
|
23
|
+
* against, tends to mean rebuilding it anyway. Until then, this alias
|
|
24
24
|
* exists so call sites already say `BackonContext` instead of `Context`,
|
|
25
25
|
* which is the only part that needs to stay stable.
|
|
26
26
|
*/
|
package/src/upload.ts
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { AppError } from "./error";
|
|
2
|
+
import type { BackonContext } from "./types";
|
|
3
|
+
|
|
4
|
+
/** Content-Type headers can carry parameters ("text/plain;charset=utf-8") — comparisons only care about the type itself. */
|
|
5
|
+
function baseMimeType(type: string): string {
|
|
6
|
+
return type.split(";")[0]?.trim() ?? type;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export interface UploadOptions {
|
|
10
|
+
/** Rejects any file over this size with a 400. Unset means no limit. */
|
|
11
|
+
maxFileSizeBytes?: number;
|
|
12
|
+
/** Rejects any file whose type isn't in this list with a 400. Unset means no restriction. */
|
|
13
|
+
allowedMimeTypes?: string[];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export type UploadHandler = (
|
|
17
|
+
c: BackonContext,
|
|
18
|
+
data: { files: Record<string, File[]> }
|
|
19
|
+
) => Response | Promise<Response>;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Parses a multipart/form-data request, validating each file against
|
|
23
|
+
* `maxFileSizeBytes`/`allowedMimeTypes` before the handler runs — the same
|
|
24
|
+
* "validate first, throw AppError(400, ...) on failure" contract as
|
|
25
|
+
* defineRoute(), just for files instead of a JSON body. Fields uploaded more
|
|
26
|
+
* than once under the same name all land under that field's array, same as
|
|
27
|
+
* a single file — `files.avatar` is always an array, even with one file.
|
|
28
|
+
*
|
|
29
|
+
* app.post("/avatar", defineUpload(
|
|
30
|
+
* { maxFileSizeBytes: 2 * 1024 * 1024, allowedMimeTypes: ["image/png", "image/jpeg"] },
|
|
31
|
+
* async (c, { files }) => c.json({ uploaded: files.avatar.length })
|
|
32
|
+
* ));
|
|
33
|
+
*/
|
|
34
|
+
export function defineUpload(options: UploadOptions, handler: UploadHandler) {
|
|
35
|
+
return async (c: BackonContext): Promise<Response> => {
|
|
36
|
+
const raw = await c.req.parseBody({ all: true });
|
|
37
|
+
const files: Record<string, File[]> = {};
|
|
38
|
+
|
|
39
|
+
for (const [field, value] of Object.entries(raw)) {
|
|
40
|
+
const values = Array.isArray(value) ? value : [value];
|
|
41
|
+
const fileValues = values.filter((entry): entry is File => entry instanceof File);
|
|
42
|
+
if (fileValues.length === 0) continue;
|
|
43
|
+
|
|
44
|
+
for (const file of fileValues) {
|
|
45
|
+
if (options.maxFileSizeBytes !== undefined && file.size > options.maxFileSizeBytes) {
|
|
46
|
+
throw new AppError(
|
|
47
|
+
400,
|
|
48
|
+
"file_too_large",
|
|
49
|
+
`${file.name} is ${file.size} bytes, over the ${options.maxFileSizeBytes} byte limit`
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
if (options.allowedMimeTypes && !options.allowedMimeTypes.includes(baseMimeType(file.type))) {
|
|
53
|
+
throw new AppError(400, "unsupported_file_type", `${file.name} has unsupported type "${file.type}"`);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
files[field] = fileValues;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return handler(c, { files });
|
|
61
|
+
};
|
|
62
|
+
}
|
package/src/websocket.ts
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { upgradeWebSocket } from "hono/bun";
|
|
2
|
+
import type { WSContext, WSMessageReceive } from "hono/ws";
|
|
3
|
+
|
|
4
|
+
/** Handlers for one WebSocket route. `ws.send()`/`ws.close()` match the shape the Express adapter's handlers get, too. */
|
|
5
|
+
export interface WebSocketHandlers {
|
|
6
|
+
onOpen?: (ws: WSContext) => void;
|
|
7
|
+
onMessage?: (ws: WSContext, data: WSMessageReceive) => void;
|
|
8
|
+
onClose?: (ws: WSContext) => void;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Registers a WebSocket route. The handshake happens at Bun.serve()'s own
|
|
13
|
+
* level (an HTTP upgrade, not an ordinary request/response cycle), which is
|
|
14
|
+
* why this only works with the serve() this package exports — it passes
|
|
15
|
+
* hono/bun's own websocket handler into Bun.serve() so the upgrade can
|
|
16
|
+
* actually happen. Register it like any other route:
|
|
17
|
+
*
|
|
18
|
+
* app.get("/ws", defineWebSocket({
|
|
19
|
+
* onMessage: (ws, data) => ws.send(`echo: ${data}`),
|
|
20
|
+
* }));
|
|
21
|
+
*/
|
|
22
|
+
export function defineWebSocket(handlers: WebSocketHandlers) {
|
|
23
|
+
return upgradeWebSocket(() => ({
|
|
24
|
+
onOpen: (_event, ws) => handlers.onOpen?.(ws),
|
|
25
|
+
onMessage: (event, ws) => handlers.onMessage?.(ws, event.data),
|
|
26
|
+
onClose: (_event, ws) => handlers.onClose?.(ws),
|
|
27
|
+
}));
|
|
28
|
+
}
|