@mednours/backon 0.6.0 → 0.7.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 +9 -6
- package/dist/auth-core.d.ts +25 -0
- package/dist/auth-core.d.ts.map +1 -0
- package/dist/create-app.d.ts +24 -0
- package/dist/create-app.d.ts.map +1 -0
- package/dist/define-route.d.ts +38 -0
- package/dist/define-route.d.ts.map +1 -0
- package/dist/error.d.ts +21 -0
- package/dist/error.d.ts.map +1 -0
- package/dist/express/create-app.d.ts +36 -0
- package/dist/express/create-app.d.ts.map +1 -0
- package/dist/express/define-route.d.ts +39 -0
- package/dist/express/define-route.d.ts.map +1 -0
- package/dist/express/index.d.ts +32 -0
- package/dist/express/index.d.ts.map +1 -0
- package/dist/express/index.js +496 -0
- package/dist/express/logger.d.ts +10 -0
- package/dist/express/logger.d.ts.map +1 -0
- package/dist/express/openapi.d.ts +21 -0
- package/dist/express/openapi.d.ts.map +1 -0
- package/dist/express/rate-limit.d.ts +17 -0
- package/dist/express/rate-limit.d.ts.map +1 -0
- package/dist/express/require-auth.d.ts +17 -0
- package/dist/express/require-auth.d.ts.map +1 -0
- package/dist/express/router-registry.d.ts +34 -0
- package/dist/express/router-registry.d.ts.map +1 -0
- package/dist/express/router.d.ts +11 -0
- package/dist/express/router.d.ts.map +1 -0
- package/dist/express/serve.d.ts +14 -0
- package/dist/express/serve.d.ts.map +1 -0
- package/dist/express/stream.d.ts +18 -0
- package/dist/express/stream.d.ts.map +1 -0
- package/dist/express/types.d.ts +33 -0
- package/dist/express/types.d.ts.map +1 -0
- package/dist/express/upload.d.ts +26 -0
- package/dist/express/upload.d.ts.map +1 -0
- package/dist/express/websocket.d.ts +25 -0
- package/dist/express/websocket.d.ts.map +1 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +429 -0
- package/dist/logger.d.ts +17 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/openapi-core.d.ts +51 -0
- package/dist/openapi-core.d.ts.map +1 -0
- package/dist/openapi.d.ts +22 -0
- package/dist/openapi.d.ts.map +1 -0
- package/dist/rate-limit-core.d.ts +27 -0
- package/dist/rate-limit-core.d.ts.map +1 -0
- package/dist/rate-limit.d.ts +27 -0
- package/dist/rate-limit.d.ts.map +1 -0
- package/dist/require-auth.d.ts +21 -0
- package/dist/require-auth.d.ts.map +1 -0
- package/dist/require-env.d.ts +22 -0
- package/dist/require-env.d.ts.map +1 -0
- package/dist/serve.d.ts +34 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/stream.d.ts +17 -0
- package/dist/stream.d.ts.map +1 -0
- package/dist/types.d.ts +26 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/upload.d.ts +25 -0
- package/dist/upload.d.ts.map +1 -0
- package/dist/websocket.d.ts +35 -0
- package/dist/websocket.d.ts.map +1 -0
- package/package.json +55 -24
- package/src/serve.ts +62 -12
- package/src/websocket.ts +34 -9
|
@@ -0,0 +1,496 @@
|
|
|
1
|
+
// src/express/create-app.ts
|
|
2
|
+
import express from "express";
|
|
3
|
+
import cors from "cors";
|
|
4
|
+
import helmet from "helmet";
|
|
5
|
+
import compression from "compression";
|
|
6
|
+
|
|
7
|
+
// src/error.ts
|
|
8
|
+
var AppError = class extends Error {
|
|
9
|
+
statusCode;
|
|
10
|
+
code;
|
|
11
|
+
details;
|
|
12
|
+
constructor(statusCode, code, message, details) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "AppError";
|
|
15
|
+
this.statusCode = statusCode;
|
|
16
|
+
this.code = code;
|
|
17
|
+
this.details = details;
|
|
18
|
+
}
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
// src/logger.ts
|
|
22
|
+
import pino from "pino";
|
|
23
|
+
var logger = pino({
|
|
24
|
+
level: process.env.LOG_LEVEL ?? "info"
|
|
25
|
+
});
|
|
26
|
+
|
|
27
|
+
// src/express/logger.ts
|
|
28
|
+
import { randomUUID } from "node:crypto";
|
|
29
|
+
function requestLogger(req, res, next) {
|
|
30
|
+
const requestId = req.header("x-request-id") ?? randomUUID();
|
|
31
|
+
res.locals.requestId = requestId;
|
|
32
|
+
res.setHeader("x-request-id", requestId);
|
|
33
|
+
const start = performance.now();
|
|
34
|
+
res.on("finish", () => {
|
|
35
|
+
const durationMs = Math.round(performance.now() - start);
|
|
36
|
+
logger.info(
|
|
37
|
+
{ requestId, method: req.method, path: req.path, status: res.statusCode, durationMs },
|
|
38
|
+
"request"
|
|
39
|
+
);
|
|
40
|
+
});
|
|
41
|
+
next();
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// src/express/router-registry.ts
|
|
45
|
+
var TRACKED_METHODS = ["get", "post", "put", "patch", "delete", "options", "head"];
|
|
46
|
+
function isTracked(value) {
|
|
47
|
+
if (value === null || typeof value !== "object" && typeof value !== "function") return false;
|
|
48
|
+
return Array.isArray(value.__backonEntries);
|
|
49
|
+
}
|
|
50
|
+
function trackRoutes(target) {
|
|
51
|
+
if (isTracked(target)) return target;
|
|
52
|
+
const tracked = target;
|
|
53
|
+
tracked.__backonEntries = [];
|
|
54
|
+
for (const method of TRACKED_METHODS) {
|
|
55
|
+
const original = tracked[method];
|
|
56
|
+
if (typeof original !== "function") continue;
|
|
57
|
+
const boundOriginal = original.bind(tracked);
|
|
58
|
+
tracked[method] = (path, ...handlers) => {
|
|
59
|
+
if (typeof path === "string" && handlers.length > 0) {
|
|
60
|
+
const last = handlers[handlers.length - 1];
|
|
61
|
+
tracked.__backonEntries.push({ type: "route", method, path, schema: last?.__backonRouteSchema });
|
|
62
|
+
}
|
|
63
|
+
return boundOriginal(path, ...handlers);
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
const originalUse = tracked.use;
|
|
67
|
+
if (typeof originalUse === "function") {
|
|
68
|
+
const boundUse = originalUse.bind(tracked);
|
|
69
|
+
tracked.use = (...args) => {
|
|
70
|
+
if (typeof args[0] === "string" && isTracked(args[1])) {
|
|
71
|
+
tracked.__backonEntries.push({ type: "mount", prefix: args[0], target: args[1] });
|
|
72
|
+
}
|
|
73
|
+
return boundUse(...args);
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
return tracked;
|
|
77
|
+
}
|
|
78
|
+
function joinPaths(prefix, path) {
|
|
79
|
+
const joined = `${prefix.replace(/\/$/, "")}/${path.replace(/^\//, "")}`;
|
|
80
|
+
return joined.replace(/\/+$/, "") || "/";
|
|
81
|
+
}
|
|
82
|
+
function collectRoutes(root, prefix = "") {
|
|
83
|
+
const results = [];
|
|
84
|
+
for (const entry of root.__backonEntries) {
|
|
85
|
+
if (entry.type === "route") {
|
|
86
|
+
results.push({ method: entry.method, path: joinPaths(prefix, entry.path), schema: entry.schema });
|
|
87
|
+
} else {
|
|
88
|
+
results.push(...collectRoutes(entry.target, joinPaths(prefix, entry.prefix)));
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return results;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/express/create-app.ts
|
|
95
|
+
var DEFAULT_BODY_LIMIT_BYTES = 1024 * 1024;
|
|
96
|
+
function resolveAllowedOrigins(options) {
|
|
97
|
+
if (options.allowedOrigins) return options.allowedOrigins;
|
|
98
|
+
const fromEnv = process.env.ALLOWED_ORIGINS;
|
|
99
|
+
return fromEnv ? fromEnv.split(",").map((origin) => origin.trim()) : [];
|
|
100
|
+
}
|
|
101
|
+
function createApp(options = {}) {
|
|
102
|
+
const app = trackRoutes(express());
|
|
103
|
+
app.use(requestLogger);
|
|
104
|
+
app.use(helmet());
|
|
105
|
+
const allowedOrigins = resolveAllowedOrigins(options);
|
|
106
|
+
app.use(cors({ origin: allowedOrigins.length ? allowedOrigins : false }));
|
|
107
|
+
app.use(compression());
|
|
108
|
+
app.use(express.json({ limit: options.bodyLimitBytes ?? DEFAULT_BODY_LIMIT_BYTES }));
|
|
109
|
+
app.get("/health", (_req, res) => {
|
|
110
|
+
res.json({ status: "ok" });
|
|
111
|
+
});
|
|
112
|
+
return app;
|
|
113
|
+
}
|
|
114
|
+
function attachErrorHandler(app) {
|
|
115
|
+
app.use((err, _req, res, _next) => {
|
|
116
|
+
if (err instanceof AppError) {
|
|
117
|
+
logger.warn(
|
|
118
|
+
{ requestId: res.locals.requestId, code: err.code, details: err.details },
|
|
119
|
+
err.message
|
|
120
|
+
);
|
|
121
|
+
res.status(err.statusCode).json({ error: { code: err.code, message: err.message, details: err.details } });
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
const status = err?.status ?? err?.statusCode;
|
|
125
|
+
if (status === 413) {
|
|
126
|
+
res.status(413).json({ error: { code: "payload_too_large", message: "Request body too large" } });
|
|
127
|
+
return;
|
|
128
|
+
}
|
|
129
|
+
logger.error({ requestId: res.locals.requestId, err }, "unhandled error");
|
|
130
|
+
res.status(500).json({ error: { code: "internal_error", message: "Something went wrong" } });
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// src/express/websocket.ts
|
|
135
|
+
import { WebSocketServer } from "ws";
|
|
136
|
+
var pending = /* @__PURE__ */ new WeakMap();
|
|
137
|
+
function defineWebSocket(app, path, handlers) {
|
|
138
|
+
const list = pending.get(app) ?? [];
|
|
139
|
+
list.push({ path, handlers });
|
|
140
|
+
pending.set(app, list);
|
|
141
|
+
}
|
|
142
|
+
function attachWebSockets(app, server) {
|
|
143
|
+
for (const { path, handlers } of pending.get(app) ?? []) {
|
|
144
|
+
const wss = new WebSocketServer({ server, path });
|
|
145
|
+
wss.on("connection", (ws, req) => {
|
|
146
|
+
handlers.onOpen?.(ws, req);
|
|
147
|
+
if (handlers.onMessage) ws.on("message", (data) => handlers.onMessage?.(ws, data));
|
|
148
|
+
if (handlers.onClose) ws.on("close", () => handlers.onClose?.(ws));
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
// src/express/serve.ts
|
|
154
|
+
function serve(app, port = Number(process.env.PORT) || 3e3) {
|
|
155
|
+
attachErrorHandler(app);
|
|
156
|
+
const server = app.listen(port, () => {
|
|
157
|
+
logger.info({ port }, "backon app listening");
|
|
158
|
+
});
|
|
159
|
+
attachWebSockets(app, server);
|
|
160
|
+
let shuttingDown = false;
|
|
161
|
+
const shutdown = (signal) => {
|
|
162
|
+
if (shuttingDown) return;
|
|
163
|
+
shuttingDown = true;
|
|
164
|
+
logger.info({ signal }, "shutting down");
|
|
165
|
+
server.close(() => process.exit(0));
|
|
166
|
+
};
|
|
167
|
+
process.on("SIGTERM", () => shutdown("SIGTERM"));
|
|
168
|
+
process.on("SIGINT", () => shutdown("SIGINT"));
|
|
169
|
+
return server;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// src/express/types.ts
|
|
173
|
+
function createContext(req, res) {
|
|
174
|
+
return {
|
|
175
|
+
req: {
|
|
176
|
+
method: req.method,
|
|
177
|
+
path: req.path,
|
|
178
|
+
header: (name) => req.header(name)
|
|
179
|
+
},
|
|
180
|
+
json: (data, status) => res.status(status ?? 200).json(data),
|
|
181
|
+
text: (data, status) => res.status(status ?? 200).type("text/plain").send(data),
|
|
182
|
+
header: (name, value) => {
|
|
183
|
+
res.setHeader(name, value);
|
|
184
|
+
},
|
|
185
|
+
get: (key) => res.locals[key],
|
|
186
|
+
set: (key, value) => {
|
|
187
|
+
res.locals[key] = value;
|
|
188
|
+
},
|
|
189
|
+
raw: { req, res }
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// src/express/define-route.ts
|
|
194
|
+
function defineRoute(schema, handler) {
|
|
195
|
+
const wrapped = async (req, res, next) => {
|
|
196
|
+
try {
|
|
197
|
+
let body = void 0;
|
|
198
|
+
let query = void 0;
|
|
199
|
+
let params = void 0;
|
|
200
|
+
if (schema.body) {
|
|
201
|
+
const parsed = schema.body.safeParse(req.body ?? {});
|
|
202
|
+
if (!parsed.success) {
|
|
203
|
+
throw new AppError(400, "invalid_body", "Request body failed validation", parsed.error.flatten());
|
|
204
|
+
}
|
|
205
|
+
body = parsed.data;
|
|
206
|
+
}
|
|
207
|
+
if (schema.query) {
|
|
208
|
+
const parsed = schema.query.safeParse(req.query);
|
|
209
|
+
if (!parsed.success) {
|
|
210
|
+
throw new AppError(400, "invalid_query", "Query params failed validation", parsed.error.flatten());
|
|
211
|
+
}
|
|
212
|
+
query = parsed.data;
|
|
213
|
+
}
|
|
214
|
+
if (schema.params) {
|
|
215
|
+
const parsed = schema.params.safeParse(req.params);
|
|
216
|
+
if (!parsed.success) {
|
|
217
|
+
throw new AppError(400, "invalid_params", "Route params failed validation", parsed.error.flatten());
|
|
218
|
+
}
|
|
219
|
+
params = parsed.data;
|
|
220
|
+
}
|
|
221
|
+
const ctx = createContext(req, res);
|
|
222
|
+
await handler(ctx, { body, query, params });
|
|
223
|
+
} catch (err) {
|
|
224
|
+
next(err);
|
|
225
|
+
}
|
|
226
|
+
};
|
|
227
|
+
wrapped.__backonRouteSchema = schema;
|
|
228
|
+
return wrapped;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// src/require-env.ts
|
|
232
|
+
function requireEnv(schema) {
|
|
233
|
+
const parsed = schema.safeParse(process.env);
|
|
234
|
+
if (!parsed.success) {
|
|
235
|
+
const issues = parsed.error.issues.map((issue) => ` - ${issue.path.join(".") || "(root)"}: ${issue.message}`).join("\n");
|
|
236
|
+
throw new Error(`Invalid environment variables:
|
|
237
|
+
${issues}`);
|
|
238
|
+
}
|
|
239
|
+
return parsed.data;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// src/auth-core.ts
|
|
243
|
+
import { verify } from "hono/jwt";
|
|
244
|
+
var DEFAULT_ALG = "HS256";
|
|
245
|
+
function verifyJwt(token, options) {
|
|
246
|
+
return verify(token, options.secret, options.alg ?? DEFAULT_ALG);
|
|
247
|
+
}
|
|
248
|
+
function extractBearerToken(header) {
|
|
249
|
+
if (!header) return void 0;
|
|
250
|
+
const [scheme, token] = header.split(" ");
|
|
251
|
+
if (scheme?.toLowerCase() !== "bearer" || !token) return void 0;
|
|
252
|
+
return token;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
// src/express/require-auth.ts
|
|
256
|
+
function requireAuth(options) {
|
|
257
|
+
return async function requireAuthMiddleware(req, res, next) {
|
|
258
|
+
const token = extractBearerToken(req.header("authorization"));
|
|
259
|
+
if (!token) {
|
|
260
|
+
next(new AppError(401, "unauthorized", "Missing or malformed Authorization header"));
|
|
261
|
+
return;
|
|
262
|
+
}
|
|
263
|
+
try {
|
|
264
|
+
res.locals.auth = await verifyJwt(token, options);
|
|
265
|
+
} catch {
|
|
266
|
+
next(new AppError(401, "unauthorized", "Invalid or expired token"));
|
|
267
|
+
return;
|
|
268
|
+
}
|
|
269
|
+
next();
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// src/rate-limit-core.ts
|
|
274
|
+
var RateLimiter = class {
|
|
275
|
+
constructor(windowMs, max) {
|
|
276
|
+
this.windowMs = windowMs;
|
|
277
|
+
this.max = max;
|
|
278
|
+
}
|
|
279
|
+
windowMs;
|
|
280
|
+
max;
|
|
281
|
+
buckets = /* @__PURE__ */ new Map();
|
|
282
|
+
checksSinceSweep = 0;
|
|
283
|
+
check(key, now = Date.now()) {
|
|
284
|
+
this.maybeSweep(now);
|
|
285
|
+
let bucket = this.buckets.get(key);
|
|
286
|
+
if (!bucket || bucket.resetAt <= now) {
|
|
287
|
+
bucket = { count: 0, resetAt: now + this.windowMs };
|
|
288
|
+
this.buckets.set(key, bucket);
|
|
289
|
+
}
|
|
290
|
+
bucket.count += 1;
|
|
291
|
+
if (bucket.count > this.max) {
|
|
292
|
+
return { allowed: false, retryAfterMs: bucket.resetAt - now };
|
|
293
|
+
}
|
|
294
|
+
return { allowed: true, retryAfterMs: 0 };
|
|
295
|
+
}
|
|
296
|
+
/** Opportunistic cleanup so long-lived processes don't accumulate one bucket per distinct key forever. */
|
|
297
|
+
maybeSweep(now) {
|
|
298
|
+
this.checksSinceSweep += 1;
|
|
299
|
+
if (this.checksSinceSweep < 1e3) return;
|
|
300
|
+
this.checksSinceSweep = 0;
|
|
301
|
+
for (const [key, bucket] of this.buckets) {
|
|
302
|
+
if (bucket.resetAt <= now) this.buckets.delete(key);
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
};
|
|
306
|
+
|
|
307
|
+
// src/express/rate-limit.ts
|
|
308
|
+
var DEFAULT_WINDOW_MS = 6e4;
|
|
309
|
+
var DEFAULT_MAX = 60;
|
|
310
|
+
function rateLimit(options = {}) {
|
|
311
|
+
const limiter = new RateLimiter(options.windowMs ?? DEFAULT_WINDOW_MS, options.max ?? DEFAULT_MAX);
|
|
312
|
+
const keyGenerator = options.keyGenerator ?? defaultKey;
|
|
313
|
+
return function rateLimitMiddleware(req, res, next) {
|
|
314
|
+
const result = limiter.check(keyGenerator(req));
|
|
315
|
+
if (!result.allowed) {
|
|
316
|
+
res.setHeader("Retry-After", String(Math.ceil(result.retryAfterMs / 1e3)));
|
|
317
|
+
next(new AppError(429, "rate_limited", "Too many requests", { retryAfterMs: result.retryAfterMs }));
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
next();
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
function defaultKey(req) {
|
|
324
|
+
return req.header("x-forwarded-for")?.split(",")[0]?.trim() ?? req.ip ?? "unknown";
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// src/express/router.ts
|
|
328
|
+
import { Router as expressRouter } from "express";
|
|
329
|
+
function Router(...args) {
|
|
330
|
+
return trackRoutes(expressRouter(...args));
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
// src/express/stream.ts
|
|
334
|
+
function defineStream(handler) {
|
|
335
|
+
return async (req, res, next) => {
|
|
336
|
+
try {
|
|
337
|
+
const ctx = createContext(req, res);
|
|
338
|
+
await handler(ctx, (chunk) => {
|
|
339
|
+
res.write(chunk);
|
|
340
|
+
});
|
|
341
|
+
res.end();
|
|
342
|
+
} catch (err) {
|
|
343
|
+
next(err);
|
|
344
|
+
}
|
|
345
|
+
};
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// src/express/upload.ts
|
|
349
|
+
import multer from "multer";
|
|
350
|
+
function baseMimeType(type) {
|
|
351
|
+
return type.split(";")[0]?.trim() ?? type;
|
|
352
|
+
}
|
|
353
|
+
function defineUpload(options, handler) {
|
|
354
|
+
const upload = multer({
|
|
355
|
+
storage: multer.memoryStorage(),
|
|
356
|
+
limits: options.maxFileSizeBytes !== void 0 ? { fileSize: options.maxFileSizeBytes } : void 0
|
|
357
|
+
});
|
|
358
|
+
const parseMultipart = upload.any();
|
|
359
|
+
return (req, res, next) => {
|
|
360
|
+
parseMultipart(req, res, async (err) => {
|
|
361
|
+
if (err) {
|
|
362
|
+
const code = err.code === "LIMIT_FILE_SIZE" ? "file_too_large" : "invalid_upload";
|
|
363
|
+
next(new AppError(400, code, err instanceof Error ? err.message : "Upload failed"));
|
|
364
|
+
return;
|
|
365
|
+
}
|
|
366
|
+
try {
|
|
367
|
+
const filesByField = {};
|
|
368
|
+
for (const file of req.files ?? []) {
|
|
369
|
+
if (options.allowedMimeTypes && !options.allowedMimeTypes.includes(baseMimeType(file.mimetype))) {
|
|
370
|
+
throw new AppError(400, "unsupported_file_type", `${file.originalname} has unsupported type "${file.mimetype}"`);
|
|
371
|
+
}
|
|
372
|
+
(filesByField[file.fieldname] ??= []).push(file);
|
|
373
|
+
}
|
|
374
|
+
const ctx = createContext(req, res);
|
|
375
|
+
await handler(ctx, { files: filesByField });
|
|
376
|
+
} catch (handlerErr) {
|
|
377
|
+
next(handlerErr);
|
|
378
|
+
}
|
|
379
|
+
});
|
|
380
|
+
};
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// src/openapi-core.ts
|
|
384
|
+
import { zodToJsonSchema } from "zod-to-json-schema";
|
|
385
|
+
function toOpenApiPath(path) {
|
|
386
|
+
return path.replace(/:([A-Za-z0-9_]+)/g, "{$1}");
|
|
387
|
+
}
|
|
388
|
+
function paramNames(path) {
|
|
389
|
+
return [...path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1]).filter((name) => name !== void 0);
|
|
390
|
+
}
|
|
391
|
+
function buildOperation(path, schema) {
|
|
392
|
+
const operation = { responses: { "200": { description: "Success" } } };
|
|
393
|
+
const parameters = [];
|
|
394
|
+
if (schema.params) {
|
|
395
|
+
const jsonSchema = zodToJsonSchema(schema.params, { target: "openApi3" });
|
|
396
|
+
for (const name of paramNames(path)) {
|
|
397
|
+
parameters.push({
|
|
398
|
+
name,
|
|
399
|
+
in: "path",
|
|
400
|
+
required: true,
|
|
401
|
+
schema: jsonSchema.properties?.[name] ?? { type: "string" }
|
|
402
|
+
});
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
if (schema.query) {
|
|
406
|
+
const jsonSchema = zodToJsonSchema(schema.query, { target: "openApi3" });
|
|
407
|
+
const required = new Set(jsonSchema.required ?? []);
|
|
408
|
+
for (const [name, propSchema] of Object.entries(jsonSchema.properties ?? {})) {
|
|
409
|
+
parameters.push({ name, in: "query", required: required.has(name), schema: propSchema });
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
if (parameters.length) operation.parameters = parameters;
|
|
413
|
+
if (schema.body) {
|
|
414
|
+
operation.requestBody = {
|
|
415
|
+
required: true,
|
|
416
|
+
content: { "application/json": { schema: zodToJsonSchema(schema.body, { target: "openApi3" }) } }
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
return operation;
|
|
420
|
+
}
|
|
421
|
+
function buildOpenApiDocument(routes, options) {
|
|
422
|
+
const paths = {};
|
|
423
|
+
for (const route of routes) {
|
|
424
|
+
if (!route.schema) continue;
|
|
425
|
+
const openApiPath = toOpenApiPath(route.path);
|
|
426
|
+
paths[openApiPath] ??= {};
|
|
427
|
+
paths[openApiPath][route.method.toLowerCase()] = buildOperation(route.path, route.schema);
|
|
428
|
+
}
|
|
429
|
+
return {
|
|
430
|
+
openapi: "3.0.3",
|
|
431
|
+
info: {
|
|
432
|
+
title: options.title ?? "API",
|
|
433
|
+
version: options.version ?? "0.1.0",
|
|
434
|
+
...options.description ? { description: options.description } : {}
|
|
435
|
+
},
|
|
436
|
+
paths
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
function pageShell(title, config) {
|
|
440
|
+
const fullConfig = { showDeveloperTools: "never", ...config };
|
|
441
|
+
return `<!doctype html>
|
|
442
|
+
<html>
|
|
443
|
+
<head>
|
|
444
|
+
<title>${title}</title>
|
|
445
|
+
<meta charset="utf-8" />
|
|
446
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
447
|
+
</head>
|
|
448
|
+
<body>
|
|
449
|
+
<div id="api-reference"></div>
|
|
450
|
+
<script src="https://cdn.jsdelivr.net/npm/@scalar/api-reference"></script>
|
|
451
|
+
<script>
|
|
452
|
+
Scalar.createApiReference("#api-reference", ${JSON.stringify(fullConfig)});
|
|
453
|
+
</script>
|
|
454
|
+
</body>
|
|
455
|
+
</html>
|
|
456
|
+
`;
|
|
457
|
+
}
|
|
458
|
+
function apiReferenceHtml(specUrl, title = "API Reference") {
|
|
459
|
+
return pageShell(title, { url: specUrl });
|
|
460
|
+
}
|
|
461
|
+
function apiReferenceHtmlInline(spec, title = "API Reference") {
|
|
462
|
+
return pageShell(title, { content: spec });
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
// src/express/openapi.ts
|
|
466
|
+
function generateOpenApiSpec(app, options = {}) {
|
|
467
|
+
const routes = collectRoutes(app);
|
|
468
|
+
return buildOpenApiDocument(routes, options);
|
|
469
|
+
}
|
|
470
|
+
function serveApiDocs(app, path = "/docs", options = {}) {
|
|
471
|
+
const specPath = `${path}/openapi.json`;
|
|
472
|
+
app.get(specPath, (_req, res) => res.json(generateOpenApiSpec(app, options)));
|
|
473
|
+
app.get(
|
|
474
|
+
path,
|
|
475
|
+
(_req, res) => res.type("html").send(apiReferenceHtmlInline(generateOpenApiSpec(app, options), options.title))
|
|
476
|
+
);
|
|
477
|
+
}
|
|
478
|
+
export {
|
|
479
|
+
AppError,
|
|
480
|
+
Router,
|
|
481
|
+
apiReferenceHtml,
|
|
482
|
+
apiReferenceHtmlInline,
|
|
483
|
+
attachErrorHandler,
|
|
484
|
+
createApp,
|
|
485
|
+
defineRoute,
|
|
486
|
+
defineStream,
|
|
487
|
+
defineUpload,
|
|
488
|
+
defineWebSocket,
|
|
489
|
+
generateOpenApiSpec,
|
|
490
|
+
logger,
|
|
491
|
+
rateLimit,
|
|
492
|
+
requireAuth,
|
|
493
|
+
requireEnv,
|
|
494
|
+
serve,
|
|
495
|
+
serveApiDocs
|
|
496
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
/**
|
|
3
|
+
* Express equivalent of the Hono requestLogger: attaches/reuses a request
|
|
4
|
+
* id and logs one line per request. Express doesn't have Hono's
|
|
5
|
+
* `await next()` continuation model, so this listens for the 'finish'
|
|
6
|
+
* event on the response instead of wrapping next() — that fires once the
|
|
7
|
+
* response has actually been sent, whichever code path sent it.
|
|
8
|
+
*/
|
|
9
|
+
export declare function requestLogger(req: Request, res: Response, next: NextFunction): void;
|
|
10
|
+
//# sourceMappingURL=logger.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../../src/express/logger.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAG/D;;;;;;GAMG;AACH,wBAAgB,aAAa,CAAC,GAAG,EAAE,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,QAe5E"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { Express } from "express";
|
|
2
|
+
import { type OpenApiOptions } from "../openapi-core";
|
|
3
|
+
/**
|
|
4
|
+
* Reads every route recorded by trackRoutes() (see router-registry.ts) —
|
|
5
|
+
* meaning createApp()'s own app, and any @mednours/backon/express Router()
|
|
6
|
+
* mounted onto it — and builds an OpenAPI document from whichever ones
|
|
7
|
+
* were wrapped in defineRoute(), the only ones carrying a schema.
|
|
8
|
+
*/
|
|
9
|
+
export declare function generateOpenApiSpec(app: Express, options?: OpenApiOptions): Record<string, unknown>;
|
|
10
|
+
/**
|
|
11
|
+
* Mounts two routes: the OpenAPI document itself as JSON, and a page that
|
|
12
|
+
* renders it. The page embeds the document directly rather than fetching it
|
|
13
|
+
* from the JSON route — one less request, and it keeps working if the JSON
|
|
14
|
+
* route is ever removed or renamed. Call after every other route is
|
|
15
|
+
* registered on `app` — routes added afterward won't be reflected in
|
|
16
|
+
* either.
|
|
17
|
+
*
|
|
18
|
+
* serveApiDocs(app, "/docs", { title: "My API" });
|
|
19
|
+
*/
|
|
20
|
+
export declare function serveApiDocs(app: Express, path?: string, options?: OpenApiOptions): void;
|
|
21
|
+
//# sourceMappingURL=openapi.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openapi.d.ts","sourceRoot":"","sources":["../../src/express/openapi.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACvC,OAAO,EAGL,KAAK,cAAc,EAEpB,MAAM,iBAAiB,CAAC;AAGzB;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,OAAO,EAAE,OAAO,GAAE,cAAmB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAGvG;AAED;;;;;;;;;GASG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,SAAU,EAAE,OAAO,GAAE,cAAmB,GAAG,IAAI,CAM7F"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
export interface RateLimitOptions {
|
|
3
|
+
/** Window size in ms. Defaults to 60_000 (1 minute). */
|
|
4
|
+
windowMs?: number;
|
|
5
|
+
/** Max requests allowed per key within the window. Defaults to 60. */
|
|
6
|
+
max?: number;
|
|
7
|
+
/** How to derive the bucket key from a request. Defaults to the caller's IP. */
|
|
8
|
+
keyGenerator?: (req: Request) => string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Express equivalent of the Hono rateLimit(): same in-memory token-bucket
|
|
12
|
+
* limiter, same per-process caveat (see rate-limit-core.ts), calls
|
|
13
|
+
* next(AppError(429, "rate_limited")) once a key exceeds `max` requests in
|
|
14
|
+
* the current window, with a Retry-After header set to when it resets.
|
|
15
|
+
*/
|
|
16
|
+
export declare function rateLimit(options?: RateLimitOptions): (req: Request, res: Response, next: NextFunction) => void;
|
|
17
|
+
//# sourceMappingURL=rate-limit.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"rate-limit.d.ts","sourceRoot":"","sources":["../../src/express/rate-limit.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAI/D,MAAM,WAAW,gBAAgB;IAC/B,wDAAwD;IACxD,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,gFAAgF;IAChF,YAAY,CAAC,EAAE,CAAC,GAAG,EAAE,OAAO,KAAK,MAAM,CAAC;CACzC;AAKD;;;;;GAKG;AACH,wBAAgB,SAAS,CAAC,OAAO,GAAE,gBAAqB,IAIlB,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,UASpF"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import { type VerifyJwtOptions } from "../auth-core";
|
|
3
|
+
/**
|
|
4
|
+
* Express equivalent of the Hono requireAuth: verifies a bearer JWT and
|
|
5
|
+
* stashes the decoded payload on res.locals.auth — readable via
|
|
6
|
+
* `c.get("auth")` in a defineRoute handler (BackonContext.get() reads
|
|
7
|
+
* res.locals) or directly as `res.locals.auth` in plain Express middleware.
|
|
8
|
+
* Calls next(AppError(401, "unauthorized")) on a missing, malformed, or
|
|
9
|
+
* invalid token; requires attachErrorHandler(app) to be registered
|
|
10
|
+
* downstream (serve() does this automatically — see create-app.ts).
|
|
11
|
+
*
|
|
12
|
+
* Verification only, same as the Hono version — issuing tokens is left to
|
|
13
|
+
* the consuming project. Apply per-route or per-router, not necessarily
|
|
14
|
+
* globally.
|
|
15
|
+
*/
|
|
16
|
+
export declare function requireAuth(options: VerifyJwtOptions): (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
17
|
+
//# sourceMappingURL=require-auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"require-auth.d.ts","sourceRoot":"","sources":["../../src/express/require-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE/D,OAAO,EAAiC,KAAK,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAEpF;;;;;;;;;;;;GAYG;AACH,wBAAgB,WAAW,CAAC,OAAO,EAAE,gBAAgB,IACP,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,mBAgB5F"}
|
|
@@ -0,0 +1,34 @@
|
|
|
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
|
+
export type MountEntry = {
|
|
14
|
+
type: "route";
|
|
15
|
+
method: string;
|
|
16
|
+
path: string;
|
|
17
|
+
schema?: unknown;
|
|
18
|
+
} | {
|
|
19
|
+
type: "mount";
|
|
20
|
+
prefix: string;
|
|
21
|
+
target: TrackedRouter;
|
|
22
|
+
};
|
|
23
|
+
export interface TrackedRouter {
|
|
24
|
+
__backonEntries: MountEntry[];
|
|
25
|
+
}
|
|
26
|
+
/** Wraps get/post/put/patch/delete/use on an Express app or Router, delegating to the real method in every case. */
|
|
27
|
+
export declare function trackRoutes<T extends object>(target: T): T & TrackedRouter;
|
|
28
|
+
/** Recursively resolves every tracked route to its full path, following mount entries down through nested routers. */
|
|
29
|
+
export declare function collectRoutes(root: TrackedRouter, prefix?: string): Array<{
|
|
30
|
+
method: string;
|
|
31
|
+
path: string;
|
|
32
|
+
schema?: unknown;
|
|
33
|
+
}>;
|
|
34
|
+
//# sourceMappingURL=router-registry.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router-registry.d.ts","sourceRoot":"","sources":["../../src/express/router-registry.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;GAWG;AAEH,MAAM,MAAM,UAAU,GAClB;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,GACjE;IAAE,IAAI,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,aAAa,CAAA;CAAE,CAAC;AAE7D,MAAM,WAAW,aAAa;IAC5B,eAAe,EAAE,UAAU,EAAE,CAAC;CAC/B;AAYD,oHAAoH;AACpH,wBAAgB,WAAW,CAAC,CAAC,SAAS,MAAM,EAAE,MAAM,EAAE,CAAC,GAAG,CAAC,GAAG,aAAa,CAmC1E;AAOD,sHAAsH;AACtH,wBAAgB,aAAa,CAC3B,IAAI,EAAE,aAAa,EACnB,MAAM,SAAK,GACV,KAAK,CAAC;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,OAAO,CAAA;CAAE,CAAC,CAU3D"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { Router as expressRouter, type Router as ExpressRouterType } from "express";
|
|
2
|
+
import { type TrackedRouter } from "./router-registry";
|
|
3
|
+
/**
|
|
4
|
+
* Same as Express's own Router() in every way that matters at runtime —
|
|
5
|
+
* this calls it directly — but instrumented so generateOpenApiSpec() can
|
|
6
|
+
* walk the route tree it produces. Exported from @mednours/backon/express
|
|
7
|
+
* instead of importing Router from 'express' directly is what makes that
|
|
8
|
+
* tracking possible; both behave identically otherwise.
|
|
9
|
+
*/
|
|
10
|
+
export declare function Router(...args: Parameters<typeof expressRouter>): ExpressRouterType & TrackedRouter;
|
|
11
|
+
//# sourceMappingURL=router.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"router.d.ts","sourceRoot":"","sources":["../../src/express/router.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,IAAI,aAAa,EAAE,KAAK,MAAM,IAAI,iBAAiB,EAAE,MAAM,SAAS,CAAC;AACpF,OAAO,EAAe,KAAK,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAEpE;;;;;;GAMG;AACH,wBAAgB,MAAM,CAAC,GAAG,IAAI,EAAE,UAAU,CAAC,OAAO,aAAa,CAAC,GAAG,iBAAiB,GAAG,aAAa,CAEnG"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { Express } from "express";
|
|
2
|
+
/**
|
|
3
|
+
* Starts the app on Node's http server (via Express's own app.listen) and
|
|
4
|
+
* wires graceful shutdown, same contract as the Hono adapter's serve().
|
|
5
|
+
*
|
|
6
|
+
* Also calls attachErrorHandler(app) first — see the note on createApp()
|
|
7
|
+
* for why that can't happen until every route is registered. When not
|
|
8
|
+
* using this serve() (e.g. exporting the app for a serverless platform or a
|
|
9
|
+
* supertest suite), call attachErrorHandler(app) directly instead — and, if
|
|
10
|
+
* any defineWebSocket() routes were registered, attachWebSockets(app,
|
|
11
|
+
* server) too, once a real http.Server exists.
|
|
12
|
+
*/
|
|
13
|
+
export declare function serve(app: Express, port?: number): import("node:http").Server<typeof import("node:http").IncomingMessage, typeof import("node:http").ServerResponse>;
|
|
14
|
+
//# sourceMappingURL=serve.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serve.d.ts","sourceRoot":"","sources":["../../src/express/serve.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAKvC;;;;;;;;;;GAUG;AACH,wBAAgB,KAAK,CAAC,GAAG,EAAE,OAAO,EAAE,IAAI,GAAE,MAAyC,qHAoBlF"}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { Request, Response, NextFunction } from "express";
|
|
2
|
+
import { type BackonContext } from "./types";
|
|
3
|
+
export type StreamWriter = (chunk: string | Uint8Array) => void;
|
|
4
|
+
/**
|
|
5
|
+
* Same contract as the Hono defineStream: the handler writes chunks as they
|
|
6
|
+
* become available instead of returning one body all at once. Underneath,
|
|
7
|
+
* this is just res.write() — Node's response object is a writable stream
|
|
8
|
+
* regardless of any framework sitting on top of it.
|
|
9
|
+
*
|
|
10
|
+
* app.get("/export", defineStream(async (c, write) => {
|
|
11
|
+
* for (const row of rows) write(JSON.stringify(row) + "\n");
|
|
12
|
+
* }));
|
|
13
|
+
*
|
|
14
|
+
* Set a Content-Type via c.header() before the first write() if the default
|
|
15
|
+
* (left to the browser/client to infer) isn't right for what's being sent.
|
|
16
|
+
*/
|
|
17
|
+
export declare function defineStream(handler: (c: BackonContext, write: StreamWriter) => Promise<void> | void): (req: Request, res: Response, next: NextFunction) => Promise<void>;
|
|
18
|
+
//# sourceMappingURL=stream.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream.d.ts","sourceRoot":"","sources":["../../src/express/stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC/D,OAAO,EAAiB,KAAK,aAAa,EAAE,MAAM,SAAS,CAAC;AAE5D,MAAM,MAAM,YAAY,GAAG,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,KAAK,IAAI,CAAC;AAEhE;;;;;;;;;;;;GAYG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,CAAC,CAAC,EAAE,aAAa,EAAE,KAAK,EAAE,YAAY,KAAK,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,IACrF,KAAK,OAAO,EAAE,KAAK,QAAQ,EAAE,MAAM,YAAY,KAAG,OAAO,CAAC,IAAI,CAAC,CAW9E"}
|