burger-api 0.9.6 → 1.0.0-beta
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 +84 -241
- package/dist/src/adapter/bun/index.d.ts +14 -0
- package/dist/src/adapter/bun/index.js +73 -0
- package/dist/src/adapter/bun/types.d.ts +15 -0
- package/dist/src/adapter/bun/types.js +1 -0
- package/dist/src/adapter/index.d.ts +1 -0
- package/dist/src/adapter/index.js +1 -0
- package/dist/src/adapter/types.d.ts +49 -0
- package/dist/src/adapter/types.js +1 -0
- package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
- package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
- package/dist/src/adapter/web-standard/index.d.ts +8 -0
- package/dist/src/adapter/web-standard/index.js +7 -0
- package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
- package/dist/src/analysis/route-access-analyzer.js +287 -0
- package/dist/src/chain/chain.d.ts +16 -0
- package/dist/src/chain/chain.js +17 -0
- package/dist/src/chain/flattener.d.ts +3 -0
- package/dist/src/chain/flattener.js +78 -0
- package/dist/src/chain/node.d.ts +25 -0
- package/dist/src/chain/node.js +1 -0
- package/dist/src/compiler/conventions.d.ts +67 -0
- package/dist/src/compiler/conventions.js +129 -0
- package/dist/src/compiler/index.d.ts +13 -0
- package/dist/src/compiler/index.js +11 -0
- package/dist/src/compiler/module-loader.d.ts +75 -0
- package/dist/src/compiler/module-loader.js +276 -0
- package/dist/src/compiler/route-module.d.ts +97 -0
- package/dist/src/compiler/route-module.js +1 -0
- package/dist/src/compiler/route-tree.d.ts +19 -0
- package/dist/src/compiler/route-tree.js +28 -0
- package/dist/src/compiler/scanner.d.ts +42 -0
- package/dist/src/compiler/scanner.js +201 -0
- package/dist/src/context/context-set.d.ts +26 -0
- package/dist/src/context/context-set.js +45 -0
- package/dist/src/context/context.d.ts +357 -0
- package/dist/src/context/context.js +401 -0
- package/dist/src/context/query-parser.d.ts +23 -0
- package/dist/src/context/query-parser.js +132 -0
- package/dist/src/context/route-access.d.ts +7 -0
- package/dist/src/context/route-access.js +18 -0
- package/dist/src/context/types.d.ts +62 -0
- package/dist/src/context/types.js +5 -0
- package/dist/src/core/asset-mime.d.ts +9 -0
- package/dist/src/core/asset-mime.js +35 -0
- package/dist/src/core/assets.d.ts +30 -0
- package/dist/src/core/assets.js +67 -0
- package/dist/src/core/docs-providers.d.ts +13 -0
- package/dist/src/core/docs-providers.js +89 -0
- package/dist/src/core/embedded-assets.d.ts +18 -0
- package/dist/src/core/embedded-assets.js +13 -0
- package/dist/src/core/openapi.d.ts +9 -10
- package/dist/src/core/openapi.js +333 -127
- package/dist/src/core/page-router.d.ts +13 -17
- package/dist/src/core/page-router.js +86 -55
- package/dist/src/core/server.d.ts +20 -11
- package/dist/src/core/server.js +41 -45
- package/dist/src/errors/forbidden.d.ts +14 -0
- package/dist/src/errors/forbidden.js +16 -0
- package/dist/src/errors/http-error.d.ts +47 -0
- package/dist/src/errors/http-error.js +146 -0
- package/dist/src/errors/method-not-allowed.d.ts +13 -0
- package/dist/src/errors/method-not-allowed.js +15 -0
- package/dist/src/errors/not-found.d.ts +14 -0
- package/dist/src/errors/not-found.js +16 -0
- package/dist/src/errors/unauthorized.d.ts +14 -0
- package/dist/src/errors/unauthorized.js +16 -0
- package/dist/src/index.d.ts +263 -50
- package/dist/src/index.js +919 -332
- package/dist/src/lifecycle/executor.d.ts +64 -0
- package/dist/src/lifecycle/executor.js +201 -0
- package/dist/src/lifecycle/hook-runner.d.ts +11 -0
- package/dist/src/lifecycle/hook-runner.js +156 -0
- package/dist/src/lifecycle/jit.d.ts +50 -0
- package/dist/src/lifecycle/jit.js +258 -0
- package/dist/src/lifecycle/transform.d.ts +26 -0
- package/dist/src/lifecycle/transform.js +99 -0
- package/dist/src/lifecycle/types.d.ts +135 -0
- package/dist/src/lifecycle/types.js +1 -0
- package/dist/src/plugin/composer.d.ts +3 -0
- package/dist/src/plugin/composer.js +28 -0
- package/dist/src/plugin/registry.d.ts +25 -0
- package/dist/src/plugin/registry.js +107 -0
- package/dist/src/plugin/types.d.ts +20 -0
- package/dist/src/plugin/types.js +1 -0
- package/dist/src/router/allow-cache.d.ts +20 -0
- package/dist/src/router/allow-cache.js +26 -0
- package/dist/src/router/compiler.d.ts +39 -0
- package/dist/src/router/compiler.js +817 -0
- package/dist/src/router/define.d.ts +67 -0
- package/dist/src/router/define.js +34 -0
- package/dist/src/router/index.d.ts +6 -0
- package/dist/src/router/index.js +5 -0
- package/dist/src/router/param-extract.d.ts +33 -0
- package/dist/src/router/param-extract.js +87 -0
- package/dist/src/router/regex-matcher.d.ts +42 -0
- package/dist/src/router/regex-matcher.js +216 -0
- package/dist/src/router/router.d.ts +201 -0
- package/dist/src/router/router.js +600 -0
- package/dist/src/router/static-map.d.ts +39 -0
- package/dist/src/router/static-map.js +48 -0
- package/dist/src/router/trie.d.ts +69 -0
- package/dist/src/router/trie.js +572 -0
- package/dist/src/router/types.d.ts +104 -0
- package/dist/src/router/types.js +1 -0
- package/dist/src/runtime/capabilities.d.ts +29 -0
- package/dist/src/runtime/capabilities.js +48 -0
- package/dist/src/types/index.d.ts +260 -109
- package/dist/src/types/index.js +1 -1
- package/dist/src/types/inference.d.ts +78 -0
- package/dist/src/types/inference.js +20 -0
- package/dist/src/types/openapi-config.d.ts +164 -0
- package/dist/src/types/openapi-config.js +8 -0
- package/dist/src/utils/env.d.ts +13 -0
- package/dist/src/utils/env.js +24 -0
- package/dist/src/utils/fs.d.ts +29 -0
- package/dist/src/utils/fs.js +75 -0
- package/dist/src/utils/index.d.ts +1 -1
- package/dist/src/utils/index.js +2 -2
- package/dist/src/utils/pathConversion.js +13 -7
- package/dist/src/utils/response.d.ts +42 -6
- package/dist/src/utils/response.js +172 -7
- package/dist/src/utils/routing.d.ts +32 -13
- package/dist/src/utils/routing.js +41 -18
- package/dist/src/utils/thenable.d.ts +8 -0
- package/dist/src/utils/thenable.js +12 -0
- package/dist/src/utils/timing-safe.d.ts +9 -0
- package/dist/src/utils/timing-safe.js +20 -0
- package/dist/src/utils/wildcard.d.ts +2 -9
- package/dist/src/utils/wildcard.js +20 -58
- package/dist/src/validation/adapter.d.ts +54 -0
- package/dist/src/validation/adapter.js +75 -0
- package/dist/src/validation/adapters/standard.d.ts +11 -0
- package/dist/src/validation/adapters/standard.js +110 -0
- package/dist/src/validation/adapters/zod.d.ts +9 -0
- package/dist/src/validation/adapters/zod.js +128 -0
- package/dist/src/validation/cache.d.ts +26 -0
- package/dist/src/validation/cache.js +35 -0
- package/dist/src/validation/coerce.d.ts +28 -0
- package/dist/src/validation/coerce.js +176 -0
- package/dist/src/validation/compiler.d.ts +27 -0
- package/dist/src/validation/compiler.js +191 -0
- package/dist/src/validation/error.d.ts +69 -0
- package/dist/src/validation/error.js +137 -0
- package/dist/src/validation/index.d.ts +16 -0
- package/dist/src/validation/index.js +12 -0
- package/dist/src/validation/response.d.ts +25 -0
- package/dist/src/validation/response.js +79 -0
- package/dist/src/validation/types.d.ts +148 -0
- package/dist/src/validation/types.js +6 -0
- package/dist/src/validation/validator.d.ts +39 -0
- package/dist/src/validation/validator.js +441 -0
- package/dist/src/ws/adapter.d.ts +219 -0
- package/dist/src/ws/adapter.js +623 -0
- package/dist/src/ws/compiler.d.ts +37 -0
- package/dist/src/ws/compiler.js +156 -0
- package/dist/src/ws/index.d.ts +11 -0
- package/dist/src/ws/index.js +8 -0
- package/dist/src/ws/platform.d.ts +81 -0
- package/dist/src/ws/platform.js +113 -0
- package/dist/src/ws/router.d.ts +48 -0
- package/dist/src/ws/router.js +174 -0
- package/dist/src/ws/scanner.d.ts +97 -0
- package/dist/src/ws/scanner.js +193 -0
- package/dist/src/ws/types.d.ts +380 -0
- package/dist/src/ws/types.js +213 -0
- package/package.json +72 -59
- package/dist/src/core/api-router.d.ts +0 -65
- package/dist/src/core/api-router.js +0 -264
- package/dist/src/core/swagger-ui.d.ts +0 -1
- package/dist/src/core/swagger-ui.js +0 -33
- package/dist/src/middleware/validator.d.ts +0 -14
- package/dist/src/middleware/validator.js +0 -133
- package/dist/src/utils/error.d.ts +0 -17
- package/dist/src/utils/error.js +0 -63
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import { applyTransform } from './transform.js';
|
|
2
|
+
import { dispatchOnError, globalErrorFinisher } from './executor.js';
|
|
3
|
+
import { validateResponse } from '../validation/response.js';
|
|
4
|
+
import { isJsonContentType } from '../validation/validator.js';
|
|
5
|
+
import { resolveDebug } from '../utils/env.js';
|
|
6
|
+
/**
|
|
7
|
+
* Capability probe: `new Function` is forbidden on several WinterCG runtimes
|
|
8
|
+
* (Cloudflare Workers throws "Code generation from strings disallowed for
|
|
9
|
+
* this context"). Probed once per process; a negative result disables JIT and
|
|
10
|
+
* the interpreter pipeline stays the fallback.
|
|
11
|
+
*/
|
|
12
|
+
let jitCapability = null;
|
|
13
|
+
export function canUseJit() {
|
|
14
|
+
if (jitCapability === null) {
|
|
15
|
+
try {
|
|
16
|
+
new Function('return 0')();
|
|
17
|
+
jitCapability = true;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
jitCapability = false;
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return jitCapability;
|
|
24
|
+
}
|
|
25
|
+
/** Test seam: forget the cached probe result. */
|
|
26
|
+
export function resetJitProbe() {
|
|
27
|
+
jitCapability = null;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* True when `fn` is declared `async` (or is an async generator). An
|
|
31
|
+
* async-declared function always returns a promise, so its call site must
|
|
32
|
+
* await unconditionally.
|
|
33
|
+
*/
|
|
34
|
+
export function isAsyncFunction(fn) {
|
|
35
|
+
if (typeof fn !== 'function')
|
|
36
|
+
return false;
|
|
37
|
+
const name = fn.constructor?.name;
|
|
38
|
+
return name === 'AsyncFunction' || name === 'AsyncGeneratorFunction';
|
|
39
|
+
}
|
|
40
|
+
const MAY_RETURN_PROMISE_CACHE = new WeakMap();
|
|
41
|
+
const MATCH_ARROW = /^(?:[\w$]+|\([\w$\s,.[\]{}:]*\))\s*=>([\s\S]*)$/;
|
|
42
|
+
const MATCH_FUNCTION = /^(?:function(?:\s+[\w$]+)?|[\w$]+)\s*\([\w$\s,.[\]{}:]*\)\s*(\{[\s\S]*\})$/;
|
|
43
|
+
const MATCH_LITERAL = /^(?:true|false|null|undefined|-?\d+(?:\.\d+)?|'[^'\\]*'|"[^"\\]*")$/;
|
|
44
|
+
/**
|
|
45
|
+
* Conservative source-level proof that `fn` can NEVER return a promise,
|
|
46
|
+
* cached per function. Only two shapes are proven safe: a block body with no
|
|
47
|
+
* `return` token (the call yields `undefined`) and an arrow with a literal
|
|
48
|
+
* expression body. Everything else (a `return`, native code, unparseable
|
|
49
|
+
* source) reports `true`, so the generated code keeps its thenable check and
|
|
50
|
+
* behavior cannot drift.
|
|
51
|
+
*/
|
|
52
|
+
export function mayReturnPromise(fn) {
|
|
53
|
+
if (typeof fn !== 'function')
|
|
54
|
+
return true;
|
|
55
|
+
const cached = MAY_RETURN_PROMISE_CACHE.get(fn);
|
|
56
|
+
if (cached !== undefined)
|
|
57
|
+
return cached;
|
|
58
|
+
let result = true;
|
|
59
|
+
try {
|
|
60
|
+
const literal = Function.prototype.toString.call(fn).trim();
|
|
61
|
+
const arrow = MATCH_ARROW.exec(literal);
|
|
62
|
+
const body = (arrow?.[1] ?? MATCH_FUNCTION.exec(literal)?.[1])?.trimStart();
|
|
63
|
+
const blockWithoutReturn = !!body &&
|
|
64
|
+
body.startsWith('{') &&
|
|
65
|
+
body.endsWith('}') &&
|
|
66
|
+
!/\breturn\b/.test(body);
|
|
67
|
+
const literalArrow = !!arrow && body !== undefined && MATCH_LITERAL.test(body);
|
|
68
|
+
result =
|
|
69
|
+
literal.includes('[native code]') ||
|
|
70
|
+
!(blockWithoutReturn || literalArrow);
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
result = true;
|
|
74
|
+
}
|
|
75
|
+
MAY_RETURN_PROMISE_CACHE.set(fn, result);
|
|
76
|
+
return result;
|
|
77
|
+
}
|
|
78
|
+
/** A thenable guard emitted after a call whose result may be a promise. */
|
|
79
|
+
function thenableGuard(target) {
|
|
80
|
+
return (`if(${target}!=null&&typeof ${target}.then==='function')` +
|
|
81
|
+
`{${target}=await ${target};}`);
|
|
82
|
+
}
|
|
83
|
+
/**
|
|
84
|
+
* Compiles a frozen {@link HookPlan} into a single function via
|
|
85
|
+
* `new Function`, unrolling the chains `executeHookPlan` walks per request.
|
|
86
|
+
*
|
|
87
|
+
* Semantics contract (same as lifecycle/executor.ts):
|
|
88
|
+
*
|
|
89
|
+
* transform → validation → beforeRoute* → handler → response-validation?
|
|
90
|
+
* → afterRoute* → mapResponse*
|
|
91
|
+
* any throw → dispatchOnError (nearest-first onError chain)
|
|
92
|
+
*
|
|
93
|
+
* - Sync-first: a step proven not to return a promise is called without
|
|
94
|
+
* `await`; otherwise a conditional thenable guard is emitted. The generated
|
|
95
|
+
* function becomes `async` only when a call actually needs `await`; the
|
|
96
|
+
* error path always returns `dispatchOnError`'s promise.
|
|
97
|
+
* - Forward hooks: `Response` short-circuits the remaining hooks and the
|
|
98
|
+
* handler (the response still flows through collected mappers, response
|
|
99
|
+
* validation, afterRoute and mapResponse); a function return is an
|
|
100
|
+
* after-mapper applied in reverse collection order.
|
|
101
|
+
* - Response hooks: `Response` replaces; `(res)=>Response` transforms.
|
|
102
|
+
* - Cold stages (transform, validation, response validation, error dispatch)
|
|
103
|
+
* delegate to the same shared functions the interpreter uses, so behavior
|
|
104
|
+
* cannot drift; only hot chains are unrolled.
|
|
105
|
+
* - Dependencies ride in one captured object `D`; no user function source is
|
|
106
|
+
* ever interpolated into the generated code.
|
|
107
|
+
*
|
|
108
|
+
* @returns the compiled dispatcher, or `null` when there is nothing worth
|
|
109
|
+
* compiling or dynamic code generation is unavailable.
|
|
110
|
+
*/
|
|
111
|
+
export function compileJitHookPlan(plan, debug, handler) {
|
|
112
|
+
// Empty plan: call the handler directly (works where `new Function` is
|
|
113
|
+
// banned). A plan with onError hooks is not empty — this function owns the
|
|
114
|
+
// error dispatch and keeps the try/catch wrapper.
|
|
115
|
+
if (plan.onError.length === 0 &&
|
|
116
|
+
plan.transform === undefined &&
|
|
117
|
+
plan.validation === undefined &&
|
|
118
|
+
plan.validators?.response === undefined &&
|
|
119
|
+
plan.beforeRoute.length === 0 &&
|
|
120
|
+
plan.afterRoute.length === 0 &&
|
|
121
|
+
plan.mapResponse.length === 0) {
|
|
122
|
+
return (ctx, handler) => handler(ctx);
|
|
123
|
+
}
|
|
124
|
+
if (!canUseJit())
|
|
125
|
+
return null;
|
|
126
|
+
const bLen = plan.beforeRoute.length;
|
|
127
|
+
const aLen = plan.afterRoute.length;
|
|
128
|
+
const mLen = plan.mapResponse.length;
|
|
129
|
+
const deps = {
|
|
130
|
+
tf: plan.transform,
|
|
131
|
+
v: plan.validation,
|
|
132
|
+
b: plan.beforeRoute,
|
|
133
|
+
a: plan.afterRoute,
|
|
134
|
+
m: plan.mapResponse,
|
|
135
|
+
e: plan.onError,
|
|
136
|
+
rv: plan.validators,
|
|
137
|
+
vc: plan.validatorConfig,
|
|
138
|
+
// Resolve the env fallback now so the hot path reads one boolean.
|
|
139
|
+
dbg: resolveDebug(debug ?? plan.debug),
|
|
140
|
+
ij: isJsonContentType,
|
|
141
|
+
};
|
|
142
|
+
const L = [];
|
|
143
|
+
L.push('"use strict";');
|
|
144
|
+
L.push('try{');
|
|
145
|
+
// ---- sync-first call emission ----
|
|
146
|
+
// The generated function is declared `async` only when a call needs await.
|
|
147
|
+
let needsAsync = false;
|
|
148
|
+
/**
|
|
149
|
+
* Emits `target = <call>` plus the await form the function demands:
|
|
150
|
+
* unconditional for an async fn, conditional (thenable guard) when it may
|
|
151
|
+
* return a promise, plain otherwise. `declare` prefixes with `let`.
|
|
152
|
+
*/
|
|
153
|
+
const emitCall = (target, call, fn, declare = false) => {
|
|
154
|
+
const assignment = declare ? `let ${target}` : target;
|
|
155
|
+
if (isAsyncFunction(fn)) {
|
|
156
|
+
L.push(`${assignment}=await ${call};`);
|
|
157
|
+
needsAsync = true;
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
if (!mayReturnPromise(fn)) {
|
|
161
|
+
L.push(`${assignment}=${call};`);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
L.push(`${assignment}=${call};${thenableGuard(target)}`);
|
|
165
|
+
needsAsync = true;
|
|
166
|
+
};
|
|
167
|
+
if (plan.transform) {
|
|
168
|
+
L.push('let _tf=TF(ctx,D.tf,D.dbg===true);');
|
|
169
|
+
if (isAsyncFunction(applyTransform)) {
|
|
170
|
+
L.push('_tf=await _tf;');
|
|
171
|
+
needsAsync = true;
|
|
172
|
+
}
|
|
173
|
+
else {
|
|
174
|
+
L.push(thenableGuard('_tf'));
|
|
175
|
+
needsAsync = true;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
if (plan.validation) {
|
|
179
|
+
emitCall('_v', 'D.v(ctx)', plan.validation, true);
|
|
180
|
+
}
|
|
181
|
+
// ---- beforeRoute chain (unrolled, mapper collection in order) ----
|
|
182
|
+
if (bLen === 0) {
|
|
183
|
+
emitCall('res', 'H(ctx)', handler, true);
|
|
184
|
+
}
|
|
185
|
+
else {
|
|
186
|
+
// A `Response` short-circuit skips the remaining beforeRoute hooks
|
|
187
|
+
// and the handler, but the mappers collected so far still apply, and
|
|
188
|
+
// the response continues through validation → afterRoute → mapResponse.
|
|
189
|
+
// A hook proven synchronous can only return `undefined`, so it never
|
|
190
|
+
// contributes a mapper; when no hook can, the collection machinery
|
|
191
|
+
// disappears entirely.
|
|
192
|
+
const canReturnMapper = [];
|
|
193
|
+
let anyMapper = false;
|
|
194
|
+
for (let i = 0; i < bLen; i++) {
|
|
195
|
+
const hook = plan.beforeRoute[i];
|
|
196
|
+
const may = isAsyncFunction(hook) || mayReturnPromise(hook);
|
|
197
|
+
canReturnMapper.push(may);
|
|
198
|
+
if (may)
|
|
199
|
+
anyMapper = true;
|
|
200
|
+
}
|
|
201
|
+
L.push(anyMapper
|
|
202
|
+
? `const M=new Array(${bLen});let mc=0;let res;`
|
|
203
|
+
: 'let res;');
|
|
204
|
+
L.push('sc:{');
|
|
205
|
+
for (let i = 0; i < bLen; i++) {
|
|
206
|
+
emitCall(`h${i}`, `D.b[${i}](ctx)`, plan.beforeRoute[i], true);
|
|
207
|
+
L.push(`if(h${i} instanceof Response){res=h${i};break sc;}`);
|
|
208
|
+
if (canReturnMapper[i]) {
|
|
209
|
+
L.push(`if(typeof h${i}==='function'){M[mc++]=h${i};}`);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
emitCall('res', 'H(ctx)', handler);
|
|
213
|
+
L.push('}');
|
|
214
|
+
if (anyMapper) {
|
|
215
|
+
L.push(`for(let i=mc-1;i>=0;i--){res=M[i](res);` +
|
|
216
|
+
`if(res!=null&&typeof res.then==='function'){res=await res;}}`);
|
|
217
|
+
needsAsync = true;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
// ---- response validation (post-handler, pre-afterRoute; JSON only) ----
|
|
221
|
+
if (plan.validators?.response) {
|
|
222
|
+
L.push('try{const ct=res.headers.get("content-type")??"";' +
|
|
223
|
+
'if(D.ij(ct)){' +
|
|
224
|
+
'const body=await res.clone().json();' +
|
|
225
|
+
// The method is lowercased before schema lookup — an
|
|
226
|
+
// uppercase key silently misses and skips enforcement.
|
|
227
|
+
'const out=VR(D.rv,METHOD.toLowerCase(),res.status,body,' +
|
|
228
|
+
'D.vc||{},D.dbg);' +
|
|
229
|
+
'if(!out.ok&&out.errorResponse){res=out.errorResponse;} } }catch(_sv){}');
|
|
230
|
+
needsAsync = true;
|
|
231
|
+
}
|
|
232
|
+
// ---- afterRoute / mapResponse chains (unrolled) ----
|
|
233
|
+
const emitChain = (key, len) => {
|
|
234
|
+
for (let i = 0; i < len; i++) {
|
|
235
|
+
const v = `c_${key}${i}`;
|
|
236
|
+
const hooks = key === 'a' ? plan.afterRoute : plan.mapResponse;
|
|
237
|
+
const hook = hooks[i];
|
|
238
|
+
const may = isAsyncFunction(hook) || mayReturnPromise(hook);
|
|
239
|
+
emitCall(v, `D.${key}[${i}](ctx)`, hook, true);
|
|
240
|
+
if (may) {
|
|
241
|
+
L.push(`if(${v} instanceof Response){res=${v};}` +
|
|
242
|
+
`else if(typeof ${v}==='function'){res=${v}(res);` +
|
|
243
|
+
`if(res!=null&&typeof res.then==='function'){res=await res;}}`);
|
|
244
|
+
needsAsync = true;
|
|
245
|
+
}
|
|
246
|
+
else {
|
|
247
|
+
// Proven synchronous: only a Response replacement is possible.
|
|
248
|
+
L.push(`if(${v} instanceof Response){res=${v};}`);
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
};
|
|
252
|
+
emitChain('a', aLen);
|
|
253
|
+
emitChain('m', mLen);
|
|
254
|
+
L.push('return res;');
|
|
255
|
+
L.push('}catch(e){return GR(DE(e,D.e,ctx,D.dbg,D.vc),ctx);}');
|
|
256
|
+
const factory = new Function('D', 'TF', 'VR', 'DE', 'GR', `return ${needsAsync ? 'async ' : ''}function(ctx,H,METHOD){${L.join('\n')}}`);
|
|
257
|
+
return factory(deps, applyTransform, validateResponse, dispatchOnError, globalErrorFinisher(plan.globalResponse));
|
|
258
|
+
}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { BurgerContext } from '../context/context.js';
|
|
2
|
+
import type { TransformMap } from './types.js';
|
|
3
|
+
/**
|
|
4
|
+
* Keys a `transform` factory may never claim — built-ins plus prototype
|
|
5
|
+
* hazards. Exported so the JIT compiler shares the exact same guard.
|
|
6
|
+
*/
|
|
7
|
+
export declare const TRANSFORM_RESERVED: Set<string>;
|
|
8
|
+
/**
|
|
9
|
+
* Validates transform keys at compile time. A reserved key would shadow a
|
|
10
|
+
* context member, so it fails startup loud with the offending key instead of
|
|
11
|
+
* corrupting `ctx` at request time.
|
|
12
|
+
*/
|
|
13
|
+
export declare function assertTransformKeys(transformMap: TransformMap | undefined, source: string): void;
|
|
14
|
+
/**
|
|
15
|
+
* Applies `transform` factories onto a context instance: each factory is
|
|
16
|
+
* called with the context and its result shallow-assigned. Reserved keys
|
|
17
|
+
* (built-ins plus prototype hazards) are dropped with a `console.warn` in
|
|
18
|
+
* debug mode.
|
|
19
|
+
*
|
|
20
|
+
* Runs once per request, before validation and `beforeRoute`. Global entries
|
|
21
|
+
* apply first, then route-level ones (so a route can override globals).
|
|
22
|
+
*
|
|
23
|
+
* Sync-first: a plain value is assigned without an `await`; only a thenable
|
|
24
|
+
* result switches to the async continuation.
|
|
25
|
+
*/
|
|
26
|
+
export declare function applyTransform(ctx: BurgerContext, transformMap: TransformMap, debug?: boolean): void | Promise<void>;
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { BurgerContext } from '../context/context.js';
|
|
2
|
+
import { isThenable } from '../utils/thenable.js';
|
|
3
|
+
const RESERVED = new Set([
|
|
4
|
+
// Reserved for a future release (like `ctx.set.cookies`).
|
|
5
|
+
'cache',
|
|
6
|
+
'params',
|
|
7
|
+
'wildcardParams',
|
|
8
|
+
'query',
|
|
9
|
+
'cookies',
|
|
10
|
+
'headers',
|
|
11
|
+
'method',
|
|
12
|
+
'url',
|
|
13
|
+
'signal',
|
|
14
|
+
'body',
|
|
15
|
+
'bodyUsed',
|
|
16
|
+
'validated',
|
|
17
|
+
'set',
|
|
18
|
+
'route',
|
|
19
|
+
'request',
|
|
20
|
+
'services',
|
|
21
|
+
'config',
|
|
22
|
+
'ip',
|
|
23
|
+
'env',
|
|
24
|
+
'executionCtx',
|
|
25
|
+
'_raw',
|
|
26
|
+
'_ctxInit',
|
|
27
|
+
'_query',
|
|
28
|
+
'_cookies',
|
|
29
|
+
// Never allow prototype-corrupting keys through to the context.
|
|
30
|
+
'__proto__',
|
|
31
|
+
'constructor',
|
|
32
|
+
'prototype',
|
|
33
|
+
]);
|
|
34
|
+
/**
|
|
35
|
+
* Keys a `transform` factory may never claim — built-ins plus prototype
|
|
36
|
+
* hazards. Exported so the JIT compiler shares the exact same guard.
|
|
37
|
+
*/
|
|
38
|
+
export const TRANSFORM_RESERVED = RESERVED;
|
|
39
|
+
/**
|
|
40
|
+
* Every name a transform may never claim: the full `BurgerContext` prototype
|
|
41
|
+
* (getters, methods, delegated `Request` members) plus the reserved names
|
|
42
|
+
* above. Built once at module load.
|
|
43
|
+
*/
|
|
44
|
+
const RESERVED_TRANSFORM_KEYS = new Set([
|
|
45
|
+
...Object.getOwnPropertyNames(BurgerContext.prototype),
|
|
46
|
+
...RESERVED,
|
|
47
|
+
]);
|
|
48
|
+
/**
|
|
49
|
+
* Validates transform keys at compile time. A reserved key would shadow a
|
|
50
|
+
* context member, so it fails startup loud with the offending key instead of
|
|
51
|
+
* corrupting `ctx` at request time.
|
|
52
|
+
*/
|
|
53
|
+
export function assertTransformKeys(transformMap, source) {
|
|
54
|
+
if (!transformMap)
|
|
55
|
+
return;
|
|
56
|
+
for (const key of Object.keys(transformMap)) {
|
|
57
|
+
if (RESERVED_TRANSFORM_KEYS.has(key)) {
|
|
58
|
+
throw new Error(`[burger-api] transform key "${key}" (${source}) is reserved ` +
|
|
59
|
+
'by BurgerContext and would shadow a context member — rename it.');
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Applies `transform` factories onto a context instance: each factory is
|
|
65
|
+
* called with the context and its result shallow-assigned. Reserved keys
|
|
66
|
+
* (built-ins plus prototype hazards) are dropped with a `console.warn` in
|
|
67
|
+
* debug mode.
|
|
68
|
+
*
|
|
69
|
+
* Runs once per request, before validation and `beforeRoute`. Global entries
|
|
70
|
+
* apply first, then route-level ones (so a route can override globals).
|
|
71
|
+
*
|
|
72
|
+
* Sync-first: a plain value is assigned without an `await`; only a thenable
|
|
73
|
+
* result switches to the async continuation.
|
|
74
|
+
*/
|
|
75
|
+
export function applyTransform(ctx, transformMap, debug = false) {
|
|
76
|
+
return runTransformFrom(ctx, transformMap, Object.keys(transformMap), 0, debug);
|
|
77
|
+
}
|
|
78
|
+
/** Continues {@link applyTransform} from the factory at `start`. */
|
|
79
|
+
function runTransformFrom(ctx, transformMap, keys, start, debug) {
|
|
80
|
+
for (let i = start; i < keys.length; i++) {
|
|
81
|
+
const key = keys[i];
|
|
82
|
+
if (RESERVED.has(key)) {
|
|
83
|
+
if (debug) {
|
|
84
|
+
console.warn(`[burger-api] transform key "${key}" is reserved — dropped`);
|
|
85
|
+
}
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const value = transformMap[key](ctx);
|
|
89
|
+
if (isThenable(value)) {
|
|
90
|
+
// Only the async path allocates a continuation.
|
|
91
|
+
return Promise.resolve(value).then((resolved) => {
|
|
92
|
+
ctx[key] = resolved;
|
|
93
|
+
return runTransformFrom(ctx, transformMap, keys, i + 1, debug);
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
ctx[key] = value;
|
|
97
|
+
}
|
|
98
|
+
return undefined;
|
|
99
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import type { BurgerContext } from '../context/context.js';
|
|
2
|
+
import type { CompiledRouteValidators, ValidatorConfig } from '../validation/types.js';
|
|
3
|
+
import type { GlobalResponsePlan } from './executor.js';
|
|
4
|
+
/**
|
|
5
|
+
* The forward hook points that run inside the single request pipeline.
|
|
6
|
+
* `onError` is a separate error-path interceptor.
|
|
7
|
+
*
|
|
8
|
+
* The fixed forward order is:
|
|
9
|
+
* onRequest → Routing → transform → Validation → beforeRoute
|
|
10
|
+
* → Handler → afterRoute → mapResponse → applySet
|
|
11
|
+
*/
|
|
12
|
+
export type HookStage = 'validation' | 'beforeRoute' | 'afterRoute' | 'mapResponse';
|
|
13
|
+
/**
|
|
14
|
+
* The return contract of a forward (pre-handler) hook:
|
|
15
|
+
* `Response` short-circuits the pipeline; `(response) => Response` registers
|
|
16
|
+
* an after-mapper applied in reverse collection order once the handler runs;
|
|
17
|
+
* `undefined` / `void` continues. Promise variants cover async hooks.
|
|
18
|
+
*
|
|
19
|
+
* The mapper branch lets one hook (e.g. `cors()`) short-circuit a request and
|
|
20
|
+
* still transform the eventual response; keep in sync with
|
|
21
|
+
* `ResponseHookResult`.
|
|
22
|
+
*/
|
|
23
|
+
export type ForwardHookResult = Response | ((response: Response) => Response | Promise<Response>) | void | undefined;
|
|
24
|
+
/**
|
|
25
|
+
* The return contract of a response hook (`afterRoute` / `mapResponse`):
|
|
26
|
+
* `Response` replaces the response; `(response) => Response` transforms it;
|
|
27
|
+
* `undefined` / `void` continues. The `Promise` variants cover async hooks.
|
|
28
|
+
*/
|
|
29
|
+
export type ResponseHookResult = Response | ((response: Response) => Response | Promise<Response>) | void | undefined;
|
|
30
|
+
/**
|
|
31
|
+
* A forward (pre-handler) lifecycle hook — `onRequest`, `validation`,
|
|
32
|
+
* `beforeRoute`. May return an after-mapper function (see
|
|
33
|
+
* {@link ForwardHookResult}) to transform the response once the handler runs.
|
|
34
|
+
* Distinct from the `transform` hook point, which injects values onto the
|
|
35
|
+
* context before the handler.
|
|
36
|
+
*/
|
|
37
|
+
export type ForwardHook = (ctx: BurgerContext) => ForwardHookResult | Promise<ForwardHookResult>;
|
|
38
|
+
/**
|
|
39
|
+
* A response lifecycle hook — `afterRoute`, `mapResponse`.
|
|
40
|
+
*/
|
|
41
|
+
export type ResponseHook = (ctx: BurgerContext) => ResponseHookResult | Promise<ResponseHookResult>;
|
|
42
|
+
/**
|
|
43
|
+
* A lifecycle hook function — the union of the stage-precise contracts.
|
|
44
|
+
* Kept for backward compatibility; prefer `ForwardHook` / `ResponseHook`
|
|
45
|
+
* when a stage is known.
|
|
46
|
+
*/
|
|
47
|
+
export type Hook = ForwardHook | ResponseHook;
|
|
48
|
+
/**
|
|
49
|
+
* An error-path interceptor hook. Runs when the pipeline throws (validation,
|
|
50
|
+
* beforeRoute, handler, afterRoute, mapResponse), dispatched nearest-first
|
|
51
|
+
* (route → global) so a route-level onError can handle its own errors before
|
|
52
|
+
* a global fallback.
|
|
53
|
+
*
|
|
54
|
+
* Returns a `Response` to handle the error, or `undefined`/`void` to let the
|
|
55
|
+
* next onError try. If none handles it, the framework renders an RFC 9457
|
|
56
|
+
* response (and logs 5xx errors server-side). May be async.
|
|
57
|
+
*/
|
|
58
|
+
export type ErrorHook = (error: Error, ctx: BurgerContext) => Response | void | undefined | Promise<Response | void | undefined>;
|
|
59
|
+
/**
|
|
60
|
+
* The frozen, per-route hook plan. Composed once at compile time and executed
|
|
61
|
+
* inside the single pipeline.
|
|
62
|
+
*
|
|
63
|
+
* `validation` runs after `transform` and before `beforeRoute`. It is a single
|
|
64
|
+
* hook (not an array) — a framework-owned stage, not a user-extensible hook
|
|
65
|
+
* point. `onError` is a separate array consulted only when the forward
|
|
66
|
+
* pipeline throws.
|
|
67
|
+
*/
|
|
68
|
+
export interface HookPlan {
|
|
69
|
+
/** Framework-owned validation stage; runs after transform, before beforeRoute. */
|
|
70
|
+
validation?: ForwardHook;
|
|
71
|
+
/** Runs global → route. */
|
|
72
|
+
beforeRoute: ForwardHook[];
|
|
73
|
+
/** Response-transform hooks; run route → global. */
|
|
74
|
+
afterRoute: ResponseHook[];
|
|
75
|
+
/** Final response hooks; may touch `ctx.set`; run route → global. */
|
|
76
|
+
mapResponse: ResponseHook[];
|
|
77
|
+
/** Error interceptor; runs nearest-first (route → global). */
|
|
78
|
+
onError: ErrorHook[];
|
|
79
|
+
/**
|
|
80
|
+
* Transform factories that compute values to inject onto the context.
|
|
81
|
+
* Runs after routing, before validation and `beforeRoute`. Never mutated
|
|
82
|
+
* at runtime.
|
|
83
|
+
*/
|
|
84
|
+
transform?: TransformMap;
|
|
85
|
+
/** Compiled route validators; used for response validation post-handler. */
|
|
86
|
+
validators?: CompiledRouteValidators;
|
|
87
|
+
/** Whether the server is in dev mode (debug or non-production). Controls error rendering detail. */
|
|
88
|
+
debug?: boolean;
|
|
89
|
+
/** Global validation config (coerce, responseValidation, errorFormat, etc.). */
|
|
90
|
+
validatorConfig?: ValidatorConfig;
|
|
91
|
+
/**
|
|
92
|
+
* Global/plugin response hooks (same shared plan on every route), so the
|
|
93
|
+
* error path can run them on onError-rendered responses too. Set only
|
|
94
|
+
* when the plan has hooks.
|
|
95
|
+
*/
|
|
96
|
+
globalResponse?: GlobalResponsePlan;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Factory functions keyed by the context field to inject. Each factory
|
|
100
|
+
* receives the {@link BurgerContext} and its result is shallow-assigned onto
|
|
101
|
+
* the context instance.
|
|
102
|
+
*
|
|
103
|
+
* ```ts
|
|
104
|
+
* export const transform = {
|
|
105
|
+
* user: (ctx) => loadUser(ctx),
|
|
106
|
+
* tenant: (ctx) => ctx.headers.get('X-Tenant'),
|
|
107
|
+
* };
|
|
108
|
+
* ```
|
|
109
|
+
*/
|
|
110
|
+
export type TransformMap = Record<string, (ctx: BurgerContext) => unknown>;
|
|
111
|
+
/**
|
|
112
|
+
* The raw, uncompiled hook object from a route's `hooks.ts` (or inline
|
|
113
|
+
* `route.ts` export). Values are normalized to arrays when the plan is built.
|
|
114
|
+
*
|
|
115
|
+
* Route scope only — there is no `onRequest` here: it runs pre-routing,
|
|
116
|
+
* before a route is matched, so declaring it in a route's `hooks.ts` is a
|
|
117
|
+
* no-op. Use {@link GlobalHooks} (the app's `src/hooks.ts`) or a plugin's
|
|
118
|
+
* `hooks` instead.
|
|
119
|
+
*/
|
|
120
|
+
export interface RouteHooks {
|
|
121
|
+
beforeRoute?: ForwardHook | ForwardHook[];
|
|
122
|
+
afterRoute?: ResponseHook | ResponseHook[];
|
|
123
|
+
mapResponse?: ResponseHook | ResponseHook[];
|
|
124
|
+
onError?: ErrorHook | ErrorHook[];
|
|
125
|
+
transform?: TransformMap;
|
|
126
|
+
}
|
|
127
|
+
/**
|
|
128
|
+
* Hook object for scopes that run before routing: the app's `src/hooks.ts` and
|
|
129
|
+
* plugin `hooks`. Adds `onRequest` (pre-routing, so app-wide or plugin-wide
|
|
130
|
+
* only) on top of {@link RouteHooks}.
|
|
131
|
+
*/
|
|
132
|
+
export interface GlobalHooks extends RouteHooks {
|
|
133
|
+
/** Pre-routing hook — runs before the route is matched. */
|
|
134
|
+
onRequest?: ForwardHook | ForwardHook[];
|
|
135
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { HookChain } from '../chain/chain.js';
|
|
2
|
+
export function composePluginHooks(chain, plugins, _routePath) {
|
|
3
|
+
for (const plugin of plugins) {
|
|
4
|
+
const hooks = plugin.hooks;
|
|
5
|
+
const scope = plugin.scope;
|
|
6
|
+
if (hooks.beforeRoute) {
|
|
7
|
+
chain.addStage('beforeRoute', toHookArray(hooks.beforeRoute), scope, plugin.name);
|
|
8
|
+
}
|
|
9
|
+
if (hooks.afterRoute) {
|
|
10
|
+
chain.addStage('afterRoute', toHookArray(hooks.afterRoute), scope, plugin.name);
|
|
11
|
+
}
|
|
12
|
+
if (hooks.mapResponse) {
|
|
13
|
+
chain.addStage('mapResponse', toHookArray(hooks.mapResponse), scope, plugin.name);
|
|
14
|
+
}
|
|
15
|
+
if (hooks.onError) {
|
|
16
|
+
chain.addStage('onError', toHookArray(hooks.onError), scope, plugin.name);
|
|
17
|
+
}
|
|
18
|
+
if (hooks.transform) {
|
|
19
|
+
// Plugin transform keys are accumulated at the plan level, not as chain
|
|
20
|
+
// nodes. The caller must merge transform records after flattening.
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
function toHookArray(h) {
|
|
25
|
+
if (h === undefined)
|
|
26
|
+
return [];
|
|
27
|
+
return Array.isArray(h) ? h : [h];
|
|
28
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { Plugin, PluginFactory, ResolvedPlugin } from './types.js';
|
|
2
|
+
import type { Scope } from '../chain/node.js';
|
|
3
|
+
/**
|
|
4
|
+
* Holds registered plugins and resolves them (factories are called once).
|
|
5
|
+
*
|
|
6
|
+
* Identity is the resolved `name` (+ optional `seed`). A plugin object is
|
|
7
|
+
* keyed immediately; a factory only after it resolves, since keying by
|
|
8
|
+
* function name would collapse every anonymous arrow factory into one.
|
|
9
|
+
* Duplicate registrations warn instead of being dropped silently.
|
|
10
|
+
*/
|
|
11
|
+
export declare class PluginRegistry {
|
|
12
|
+
private entries;
|
|
13
|
+
private resolved;
|
|
14
|
+
/** Unique key counter for not-yet-resolved factory entries. */
|
|
15
|
+
private factoryCount;
|
|
16
|
+
private key;
|
|
17
|
+
register(plugin: Plugin | PluginFactory, scope?: Scope, seed?: string): boolean;
|
|
18
|
+
has(name: string, seed?: string): boolean;
|
|
19
|
+
resolve(name: string, seed?: string): Promise<ResolvedPlugin | undefined>;
|
|
20
|
+
/** Resolves one entry (calling its factory at most once). */
|
|
21
|
+
private resolveEntry;
|
|
22
|
+
resolveAll(): Promise<ResolvedPlugin[]>;
|
|
23
|
+
clear(): void;
|
|
24
|
+
size(): number;
|
|
25
|
+
}
|