burger-api 0.9.7 → 1.0.0-beta.1

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.
Files changed (175) hide show
  1. package/README.md +84 -241
  2. package/dist/src/adapter/bun/index.d.ts +14 -0
  3. package/dist/src/adapter/bun/index.js +73 -0
  4. package/dist/src/adapter/bun/types.d.ts +15 -0
  5. package/dist/src/adapter/bun/types.js +1 -0
  6. package/dist/src/adapter/index.d.ts +1 -0
  7. package/dist/src/adapter/index.js +1 -0
  8. package/dist/src/adapter/types.d.ts +49 -0
  9. package/dist/src/adapter/types.js +1 -0
  10. package/dist/src/adapter/web-standard/fetch-handler.d.ts +39 -0
  11. package/dist/src/adapter/web-standard/fetch-handler.js +54 -0
  12. package/dist/src/adapter/web-standard/index.d.ts +8 -0
  13. package/dist/src/adapter/web-standard/index.js +7 -0
  14. package/dist/src/analysis/route-access-analyzer.d.ts +10 -0
  15. package/dist/src/analysis/route-access-analyzer.js +287 -0
  16. package/dist/src/chain/chain.d.ts +16 -0
  17. package/dist/src/chain/chain.js +17 -0
  18. package/dist/src/chain/flattener.d.ts +3 -0
  19. package/dist/src/chain/flattener.js +78 -0
  20. package/dist/src/chain/node.d.ts +25 -0
  21. package/dist/src/chain/node.js +1 -0
  22. package/dist/src/compiler/conventions.d.ts +67 -0
  23. package/dist/src/compiler/conventions.js +129 -0
  24. package/dist/src/compiler/index.d.ts +13 -0
  25. package/dist/src/compiler/index.js +11 -0
  26. package/dist/src/compiler/module-loader.d.ts +75 -0
  27. package/dist/src/compiler/module-loader.js +276 -0
  28. package/dist/src/compiler/route-module.d.ts +97 -0
  29. package/dist/src/compiler/route-module.js +1 -0
  30. package/dist/src/compiler/route-tree.d.ts +19 -0
  31. package/dist/src/compiler/route-tree.js +28 -0
  32. package/dist/src/compiler/scanner.d.ts +42 -0
  33. package/dist/src/compiler/scanner.js +240 -0
  34. package/dist/src/context/context-set.d.ts +26 -0
  35. package/dist/src/context/context-set.js +45 -0
  36. package/dist/src/context/context.d.ts +357 -0
  37. package/dist/src/context/context.js +401 -0
  38. package/dist/src/context/query-parser.d.ts +23 -0
  39. package/dist/src/context/query-parser.js +132 -0
  40. package/dist/src/context/route-access.d.ts +7 -0
  41. package/dist/src/context/route-access.js +18 -0
  42. package/dist/src/context/types.d.ts +62 -0
  43. package/dist/src/context/types.js +5 -0
  44. package/dist/src/core/asset-mime.d.ts +9 -0
  45. package/dist/src/core/asset-mime.js +35 -0
  46. package/dist/src/core/assets.d.ts +30 -0
  47. package/dist/src/core/assets.js +67 -0
  48. package/dist/src/core/docs-providers.d.ts +13 -0
  49. package/dist/src/core/docs-providers.js +89 -0
  50. package/dist/src/core/embedded-assets.d.ts +18 -0
  51. package/dist/src/core/embedded-assets.js +13 -0
  52. package/dist/src/core/openapi.d.ts +9 -10
  53. package/dist/src/core/openapi.js +333 -127
  54. package/dist/src/core/page-router.d.ts +13 -17
  55. package/dist/src/core/page-router.js +86 -55
  56. package/dist/src/core/server.d.ts +20 -11
  57. package/dist/src/core/server.js +41 -45
  58. package/dist/src/errors/forbidden.d.ts +14 -0
  59. package/dist/src/errors/forbidden.js +16 -0
  60. package/dist/src/errors/http-error.d.ts +49 -0
  61. package/dist/src/errors/http-error.js +155 -0
  62. package/dist/src/errors/method-not-allowed.d.ts +13 -0
  63. package/dist/src/errors/method-not-allowed.js +15 -0
  64. package/dist/src/errors/not-found.d.ts +14 -0
  65. package/dist/src/errors/not-found.js +16 -0
  66. package/dist/src/errors/unauthorized.d.ts +14 -0
  67. package/dist/src/errors/unauthorized.js +16 -0
  68. package/dist/src/index.d.ts +275 -50
  69. package/dist/src/index.js +974 -333
  70. package/dist/src/lifecycle/executor.d.ts +64 -0
  71. package/dist/src/lifecycle/executor.js +201 -0
  72. package/dist/src/lifecycle/hook-runner.d.ts +11 -0
  73. package/dist/src/lifecycle/hook-runner.js +156 -0
  74. package/dist/src/lifecycle/jit.d.ts +50 -0
  75. package/dist/src/lifecycle/jit.js +258 -0
  76. package/dist/src/lifecycle/transform.d.ts +26 -0
  77. package/dist/src/lifecycle/transform.js +99 -0
  78. package/dist/src/lifecycle/types.d.ts +135 -0
  79. package/dist/src/lifecycle/types.js +1 -0
  80. package/dist/src/plugin/composer.d.ts +3 -0
  81. package/dist/src/plugin/composer.js +28 -0
  82. package/dist/src/plugin/registry.d.ts +25 -0
  83. package/dist/src/plugin/registry.js +107 -0
  84. package/dist/src/plugin/types.d.ts +20 -0
  85. package/dist/src/plugin/types.js +1 -0
  86. package/dist/src/router/allow-cache.d.ts +20 -0
  87. package/dist/src/router/allow-cache.js +26 -0
  88. package/dist/src/router/compiler.d.ts +39 -0
  89. package/dist/src/router/compiler.js +867 -0
  90. package/dist/src/router/define.d.ts +67 -0
  91. package/dist/src/router/define.js +34 -0
  92. package/dist/src/router/index.d.ts +6 -0
  93. package/dist/src/router/index.js +5 -0
  94. package/dist/src/router/param-extract.d.ts +33 -0
  95. package/dist/src/router/param-extract.js +87 -0
  96. package/dist/src/router/regex-matcher.d.ts +42 -0
  97. package/dist/src/router/regex-matcher.js +216 -0
  98. package/dist/src/router/router.d.ts +214 -0
  99. package/dist/src/router/router.js +670 -0
  100. package/dist/src/router/static-map.d.ts +39 -0
  101. package/dist/src/router/static-map.js +48 -0
  102. package/dist/src/router/trie.d.ts +69 -0
  103. package/dist/src/router/trie.js +572 -0
  104. package/dist/src/router/types.d.ts +104 -0
  105. package/dist/src/router/types.js +1 -0
  106. package/dist/src/runtime/capabilities.d.ts +29 -0
  107. package/dist/src/runtime/capabilities.js +48 -0
  108. package/dist/src/types/index.d.ts +260 -109
  109. package/dist/src/types/index.js +1 -1
  110. package/dist/src/types/inference.d.ts +78 -0
  111. package/dist/src/types/inference.js +20 -0
  112. package/dist/src/types/openapi-config.d.ts +164 -0
  113. package/dist/src/types/openapi-config.js +8 -0
  114. package/dist/src/utils/env.d.ts +13 -0
  115. package/dist/src/utils/env.js +24 -0
  116. package/dist/src/utils/fs.d.ts +29 -0
  117. package/dist/src/utils/fs.js +75 -0
  118. package/dist/src/utils/index.d.ts +1 -1
  119. package/dist/src/utils/index.js +2 -2
  120. package/dist/src/utils/pathConversion.js +13 -7
  121. package/dist/src/utils/response.d.ts +42 -6
  122. package/dist/src/utils/response.js +189 -7
  123. package/dist/src/utils/routing.d.ts +32 -13
  124. package/dist/src/utils/routing.js +41 -18
  125. package/dist/src/utils/thenable.d.ts +8 -0
  126. package/dist/src/utils/thenable.js +12 -0
  127. package/dist/src/utils/timing-safe.d.ts +9 -0
  128. package/dist/src/utils/timing-safe.js +20 -0
  129. package/dist/src/utils/wildcard.d.ts +6 -7
  130. package/dist/src/utils/wildcard.js +38 -55
  131. package/dist/src/validation/adapter.d.ts +54 -0
  132. package/dist/src/validation/adapter.js +75 -0
  133. package/dist/src/validation/adapters/standard.d.ts +11 -0
  134. package/dist/src/validation/adapters/standard.js +110 -0
  135. package/dist/src/validation/adapters/zod.d.ts +9 -0
  136. package/dist/src/validation/adapters/zod.js +128 -0
  137. package/dist/src/validation/cache.d.ts +26 -0
  138. package/dist/src/validation/cache.js +35 -0
  139. package/dist/src/validation/coerce.d.ts +28 -0
  140. package/dist/src/validation/coerce.js +176 -0
  141. package/dist/src/validation/compiler.d.ts +27 -0
  142. package/dist/src/validation/compiler.js +191 -0
  143. package/dist/src/validation/error.d.ts +69 -0
  144. package/dist/src/validation/error.js +137 -0
  145. package/dist/src/validation/index.d.ts +16 -0
  146. package/dist/src/validation/index.js +12 -0
  147. package/dist/src/validation/response.d.ts +25 -0
  148. package/dist/src/validation/response.js +85 -0
  149. package/dist/src/validation/types.d.ts +148 -0
  150. package/dist/src/validation/types.js +6 -0
  151. package/dist/src/validation/validator.d.ts +39 -0
  152. package/dist/src/validation/validator.js +441 -0
  153. package/dist/src/ws/adapter.d.ts +230 -0
  154. package/dist/src/ws/adapter.js +660 -0
  155. package/dist/src/ws/compiler.d.ts +37 -0
  156. package/dist/src/ws/compiler.js +178 -0
  157. package/dist/src/ws/index.d.ts +11 -0
  158. package/dist/src/ws/index.js +8 -0
  159. package/dist/src/ws/platform.d.ts +82 -0
  160. package/dist/src/ws/platform.js +122 -0
  161. package/dist/src/ws/router.d.ts +47 -0
  162. package/dist/src/ws/router.js +183 -0
  163. package/dist/src/ws/scanner.d.ts +97 -0
  164. package/dist/src/ws/scanner.js +253 -0
  165. package/dist/src/ws/types.d.ts +381 -0
  166. package/dist/src/ws/types.js +213 -0
  167. package/package.json +72 -60
  168. package/dist/src/core/api-router.d.ts +0 -65
  169. package/dist/src/core/api-router.js +0 -264
  170. package/dist/src/core/swagger-ui.d.ts +0 -1
  171. package/dist/src/core/swagger-ui.js +0 -33
  172. package/dist/src/middleware/validator.d.ts +0 -14
  173. package/dist/src/middleware/validator.js +0 -133
  174. package/dist/src/utils/error.d.ts +0 -17
  175. package/dist/src/utils/error.js +0 -63
@@ -0,0 +1,670 @@
1
+ import { renderUncaught } from '../errors/http-error.js';
2
+ import { dispatchOnError } from '../lifecycle/executor.js';
3
+ import { applySet, notFound, methodNotAllowed, } from '../utils/response.js';
4
+ import { extractPathnameFromUrl, urlPathnameEndsWithSlash, } from '../utils/wildcard.js';
5
+ import { isThenable } from '../utils/thenable.js';
6
+ import { RouterCompiler, buildGlobalResponsePlan } from './compiler.js';
7
+ import { hasGlobalResponseHooks, runGlobalResponseHooks, } from '../lifecycle/executor.js';
8
+ import { resolveDebug } from '../utils/env.js';
9
+ import { AllowCache } from './allow-cache.js';
10
+ import { StaticMap } from './static-map.js';
11
+ import { Trie } from './trie.js';
12
+ import { buildRegexMatcher, } from './regex-matcher.js';
13
+ import { BurgerContext, EMPTY_SERVICES, createServices, isRequestIPSource, } from '../context/context.js';
14
+ import { HTTP_METHODS } from '../utils/routing.js';
15
+ /**
16
+ * Public router: owns the compiled dispatch state and orchestrates lookup
17
+ * and execution.
18
+ *
19
+ * Static, dynamic (`:param`), and wildcard (`*`) routes are all registered
20
+ * on Bun's native `routes` map; compiled handlers self-extract `params` /
21
+ * `wildcardParams`. The `fetch` fallback still runs for unmatched and
22
+ * trailing-slash requests (`/foo/` ≡ `/foo`), consulting the internal trie.
23
+ *
24
+ * Both paths execute the same compiled handler, so method dispatch,
25
+ * 405+Allow, auto-HEAD, and lifecycle behavior are identical. Non-Bun
26
+ * (WinterCG) adapters dispatch every route through `fetch` + trie.
27
+ */
28
+ export class Router {
29
+ staticMap = new StaticMap();
30
+ trie = new Trie();
31
+ allowCache = new AllowCache();
32
+ compiler;
33
+ /** Dev mode: controls error-rendering detail (stack/cause in problem bodies). */
34
+ debug;
35
+ /** Dynamic-dispatch engine preference ('auto' default). */
36
+ engine;
37
+ /** Native dispatch table for `:param` / `*` routes (Bun `routes` map keys). */
38
+ nativeRoutesMap = new Map();
39
+ /** Per-path per-method specialized executors (fed to Bun method objects). */
40
+ methodCores = new Map();
41
+ /** Retained compiled-route metadata (RouteAccessInfo + RouteMeta). */
42
+ compiledRoutes;
43
+ /** Memoized `staticRoutes()` result; rebuilt on `compile()`. */
44
+ cachedStaticRoutes;
45
+ /** Memoized `nativeRoutes()` result; rebuilt on `compile()`. */
46
+ cachedNativeRoutes;
47
+ /** Pre-routing hooks (Plugin + Global scope). Run before routing in `fetch()`. */
48
+ onRequestHooks = [];
49
+ /** True when pre-routing `onRequest` hooks exist (hot-path flag). */
50
+ hasOnRequest = false;
51
+ /**
52
+ * Error hooks available before a route is matched (Global → Plugin →
53
+ * Framework, nearest-first). Let pre-routing `onRequest` throws go
54
+ * through the same `onError` pipeline as request errors.
55
+ */
56
+ onErrorHooks = [];
57
+ /**
58
+ * Global/plugin response hooks (afterRoute + mapResponse) for responses
59
+ * with no matched route plan: 404/405/auto-OPTIONS, pages/assets/docs,
60
+ * and onError-rendered errors. Compiled once at startup.
61
+ */
62
+ globalResponsePlan = {
63
+ afterRoute: [],
64
+ mapResponse: [],
65
+ };
66
+ /** Hot-path flag: true when the global response plan has hooks. */
67
+ globalResponseActive = false;
68
+ /** App services resolved ONCE; shared (frozen) by every request context. */
69
+ appServices = EMPTY_SERVICES;
70
+ /** Per-app server reference for lazy `ctx.ip` (written once at startup). */
71
+ ipHolder = {};
72
+ /**
73
+ * RegExp matcher for dynamic/wildcard routes (WinterCG fast path).
74
+ * Built when the engine setting allows and compilation succeeds;
75
+ * `null` means dispatch stays on the trie.
76
+ */
77
+ regexMatcher = null;
78
+ constructor(config = {}) {
79
+ // Resolve once: `debug: true` or NODE_ENV=development. The compiler
80
+ // (hook plans) and renderUnhandled share this exact value, so
81
+ // onRequest errors and handler errors render the same.
82
+ this.debug = resolveDebug(config.debug);
83
+ this.engine = config.engine;
84
+ this.compiler = new RouterCompiler(this.debug, config.validation ?? {}, config.jit !== false);
85
+ }
86
+ /**
87
+ * Compiles a `RouteDefinition[]` into the dispatch structures.
88
+ * Replaces all tables wholesale (no incremental merge) so hot reload
89
+ * cannot leak stale routes.
90
+ */
91
+ compile(defs, plugins, providers, onRequestHooks, globalHooks) {
92
+ // Services are resolved once here (shared with the compiled handlers,
93
+ // which receive the already-built object).
94
+ this.appServices = createServices(providers);
95
+ const result = this.compiler.compile(defs, plugins, this.appServices, onRequestHooks, globalHooks, this.ipHolder);
96
+ this.staticMap = result.staticMap;
97
+ this.trie = result.trie;
98
+ this.allowCache = result.allowCache;
99
+ this.nativeRoutesMap = result.nativeRoutes;
100
+ this.methodCores = result.methodCores;
101
+ this.compiledRoutes = result.routes;
102
+ this.cachedStaticRoutes = undefined;
103
+ this.cachedNativeRoutes = undefined;
104
+ this.onRequestHooks = onRequestHooks ?? [];
105
+ this.hasOnRequest = this.onRequestHooks.length > 0;
106
+ this.onErrorHooks = buildPreRoutingErrorChain(plugins, globalHooks);
107
+ this.globalResponsePlan = buildGlobalResponsePlan(plugins, globalHooks);
108
+ this.globalResponseActive = hasGlobalResponseHooks(this.globalResponsePlan);
109
+ this.regexMatcher = this.buildMatcher(result);
110
+ }
111
+ /**
112
+ * Records the serving runtime's handle (Bun's `Server`) once so `ctx.ip`
113
+ * can resolve the socket peer lazily — no per-request WeakMap write.
114
+ * Adapter-facing; called at startup by the Bun serve path.
115
+ */
116
+ setRequestIPSource(server) {
117
+ if (isRequestIPSource(server)) {
118
+ this.ipHolder.server = server;
119
+ }
120
+ }
121
+ /**
122
+ * The per-app `ctx.ip` holder. Non-API contexts (dynamic pages) receive it
123
+ * so their `ctx.ip` resolves exactly like API routes.
124
+ */
125
+ getRequestIPHolder() {
126
+ return this.ipHolder;
127
+ }
128
+ /**
129
+ * The app services resolved ONCE at compile time. Non-API contexts
130
+ * (dynamic pages) receive the same shared object so `ctx.services` is
131
+ * populated there too.
132
+ */
133
+ getAppServices() {
134
+ return this.appServices;
135
+ }
136
+ /**
137
+ * Builds the RegExp dispatch matcher for dynamic/wildcard routes when
138
+ * the configured engine asks for it ('regex'). 'auto' stays on the trie,
139
+ * so the matcher is an explicit opt-in.
140
+ */
141
+ buildMatcher(result) {
142
+ if (this.engine !== 'regex')
143
+ return null;
144
+ if (!result.routes || result.routes.size === 0)
145
+ return null;
146
+ const entries = [];
147
+ for (const [path, compiled] of result.routes) {
148
+ if (!isDynamicPath(path))
149
+ continue;
150
+ entries.push({
151
+ path,
152
+ handler: compiled.handler,
153
+ methods: new Set(Object.keys(compiled.def.handlers).map((m) => m.toUpperCase())),
154
+ isWildcard: compiled.def.isWildcard === true || path.includes('*'),
155
+ });
156
+ }
157
+ // The trie is compiled in the same pass — its DFS order is the
158
+ // authoritative alternative order.
159
+ const built = buildRegexMatcher(entries, result.trie.orderedPatterns());
160
+ if (!built)
161
+ return null; // trie fallback applies
162
+ return built;
163
+ }
164
+ /**
165
+ * Read-only access to the retained compiled-route metadata
166
+ * (`RouteAccessInfo` + `RouteMeta`). Populated by `compile()`; not used on
167
+ * the request hot path, so it has no runtime performance impact.
168
+ */
169
+ getCompiledRoutes() {
170
+ return this.compiledRoutes;
171
+ }
172
+ /**
173
+ * Returns the static routes as a `Bun.serve` `routes` map: one **method
174
+ * object** per path (`{ GET: fnGet, POST: fnPost, HEAD: fnHead, ... }`).
175
+ * Each method is specialized at compile time; a method the route does not
176
+ * declare answers 405 + Allow here, so Bun never falls through to a less
177
+ * specific route.
178
+ */
179
+ staticRoutes() {
180
+ if (this.cachedStaticRoutes)
181
+ return this.cachedStaticRoutes;
182
+ const out = {};
183
+ for (const [path] of this.staticMap.entries()) {
184
+ out[path] = this.buildMethods(path);
185
+ }
186
+ this.cachedStaticRoutes = out;
187
+ return out;
188
+ }
189
+ /**
190
+ * Same method-object shape for `:param` / `*` routes: Bun matches the
191
+ * pattern natively. Wildcard requests with a trailing slash are handed to
192
+ * the fetch dispatch (which strips the slash before matching); ordinary
193
+ * wildcard requests keep their native dispatch. Every HTTP method key is
194
+ * present, matching the fetch path's 405 + Allow instead of falling
195
+ * through.
196
+ */
197
+ nativeRoutes() {
198
+ if (this.cachedNativeRoutes)
199
+ return this.cachedNativeRoutes;
200
+ const out = {};
201
+ for (const pattern of this.nativeRoutesMap.keys()) {
202
+ const methods = this.buildMethods(pattern);
203
+ // Bun matches a native wildcard before the fetch fallback, so a
204
+ // trailing slash arrives here instead of `dispatchMatched`. Hand
205
+ // it to the fetch path, which removes the slash before matching.
206
+ if (pattern.includes('*')) {
207
+ for (const key of HTTP_METHODS) {
208
+ const inner = methods[key];
209
+ methods[key] = (request) => {
210
+ // Newer Bun versions expose the wildcard remainder;
211
+ // older ones leave `request.params` empty, so fall
212
+ // back to the URL pathname (still allocation-free).
213
+ const wildcard = request.params?.['*'];
214
+ const trailing = wildcard !== undefined
215
+ ? wildcard.endsWith('/')
216
+ : urlPathnameEndsWithSlash(request.url);
217
+ if (trailing) {
218
+ return this.fetchWithPath(request, extractPathnameFromUrl(request.url));
219
+ }
220
+ return inner(request);
221
+ };
222
+ }
223
+ }
224
+ out[pattern] = methods;
225
+ }
226
+ this.cachedNativeRoutes = out;
227
+ return out;
228
+ }
229
+ /**
230
+ * Exact static API paths as direct dispatchers, keyed by path.
231
+ * `fetchHandler()` merges these into its page/asset lookup so a static
232
+ * API request resolves in one `Map.get` instead of a page-map miss plus
233
+ * a `StaticMap` hit. Each dispatcher mirrors the `fetch` fallback for its
234
+ * own path: known method → specialized core, otherwise the compiled
235
+ * method-dispatch handler (405 + Allow), with global response hooks and
236
+ * the `onRequest` pipeline applied exactly as `fetchWithPath` does.
237
+ */
238
+ staticDispatchMap() {
239
+ const out = new Map();
240
+ for (const path of this.staticMap.keys()) {
241
+ out.set(path, this.buildStaticDispatch(path));
242
+ }
243
+ return out;
244
+ }
245
+ buildStaticDispatch(path) {
246
+ // Hook path: reuse the router's own pre-routing pipeline. The path is
247
+ // exact, so no slash handling is skipped.
248
+ if (this.hasOnRequest) {
249
+ return (request, _ctxInit, _prebuilt, env, executionCtx) => this.dispatchWithOnRequest(request, env, executionCtx, path);
250
+ }
251
+ const entry = this.staticMap.getEntry(path);
252
+ // A known method runs its core — the core already carries the global
253
+ // response plan. Only the method-dispatch fallback (405 + Allow) is a
254
+ // non-route response, so only it gets `finishNonRouteResponse` —
255
+ // exactly the split `dispatchMatched` uses.
256
+ const finishFallback = this.globalResponseActive;
257
+ return (request, _ctxInit, _prebuilt, env, executionCtx) => {
258
+ const core = entry.cores?.[request.method];
259
+ if (core) {
260
+ return core(request, undefined, undefined, env, executionCtx);
261
+ }
262
+ const response = entry.handler(request, undefined, undefined, env, executionCtx);
263
+ return finishFallback
264
+ ? this.finishNonRouteResponse(response, request, undefined, env, executionCtx)
265
+ : response;
266
+ };
267
+ }
268
+ /**
269
+ * Builds the Bun method object for one compiled path. Every HTTP method
270
+ * key is present: a declared method runs its compiled core (wrapped by
271
+ * onRequest when hooks exist), an undeclared one answers the same
272
+ * 405 + Allow as the fetch path.
273
+ */
274
+ buildMethods(path) {
275
+ const cores = this.methodCores.get(path);
276
+ const out = {};
277
+ const allow = this.allowCache.get(path) ?? '';
278
+ if (!this.hasOnRequest) {
279
+ // Every method key must exist on a matched path: Bun falls
280
+ // through to a less specific route when the key is missing.
281
+ const missing = this.globalResponseActive
282
+ ? (request) => this.finishNonRouteResponse(methodNotAllowed(allow), request, undefined)
283
+ : () => methodNotAllowed(allow);
284
+ for (const key of HTTP_METHODS) {
285
+ const core = cores[key];
286
+ out[key] = core
287
+ ? (request) => core(request)
288
+ : missing;
289
+ }
290
+ return out;
291
+ }
292
+ // Missing methods still run onRequest once and the global response
293
+ // hooks, exactly like the fetch path's 405.
294
+ const missing = async (request) => {
295
+ const outcome = await this.runOnRequest(request);
296
+ if (outcome.shortCircuit)
297
+ return outcome.shortCircuit;
298
+ const finished = await this.finishNonRouteResponse(methodNotAllowed(allow), request, outcome.ctx);
299
+ return outcome.mappers.length > 0
300
+ ? this.applyMappers(finished, outcome.mappers)
301
+ : finished;
302
+ };
303
+ for (const key of HTTP_METHODS) {
304
+ const core = cores[key];
305
+ if (!core) {
306
+ out[key] = missing;
307
+ continue;
308
+ }
309
+ const wrapped = async (request) => {
310
+ const outcome = await this.runOnRequest(request);
311
+ if (outcome.shortCircuit)
312
+ return outcome.shortCircuit;
313
+ try {
314
+ // The onRequest context is bound by the route, so state
315
+ // seeded pre-routing survives (one context per request).
316
+ const result = await core(request, undefined, outcome.ctx);
317
+ return outcome.mappers.length > 0
318
+ ? this.applyMappers(result, outcome.mappers)
319
+ : result;
320
+ }
321
+ catch (error) {
322
+ return this.renderUnhandled(request, error);
323
+ }
324
+ };
325
+ out[key] = wrapped;
326
+ }
327
+ return out;
328
+ }
329
+ /**
330
+ * Wraps a non-API handler registered on the native routes map (pages,
331
+ * static assets, `/openapi.json`, `/docs`) so global/plugin `onRequest`
332
+ * hooks (CORS, logging, auth, rate limiting) apply to it exactly like
333
+ * API routes. Also catches its errors for the global/plugin `onError`
334
+ * chain. Returned unchanged when no hooks exist.
335
+ */
336
+ wrapWithOnRequest(handler) {
337
+ if (this.onRequestHooks.length === 0 &&
338
+ !this.globalResponseActive &&
339
+ this.onErrorHooks.length === 0) {
340
+ return handler;
341
+ }
342
+ const inner = handler;
343
+ const wrapped = async (request, _serverOrCtxInit, prebuilt, env, executionCtx) => {
344
+ const outcome = await this.runOnRequest(request, env, executionCtx);
345
+ if (outcome.shortCircuit)
346
+ return outcome.shortCircuit;
347
+ // The onRequest context is handed to the handler so pages bind
348
+ // it (one context per request) and ctx.set survives.
349
+ const ctx = prebuilt ?? outcome.ctx;
350
+ try {
351
+ const result = (await inner(request, undefined, ctx, env, executionCtx));
352
+ const finished = await this.finishNonRouteResponse(result, request, ctx, env, executionCtx);
353
+ return outcome.mappers.length > 0
354
+ ? this.applyMappers(finished, outcome.mappers)
355
+ : finished;
356
+ }
357
+ catch (error) {
358
+ // Page/asset/docs errors use the same onError chain as API
359
+ // routes, then the global response hooks.
360
+ const rendered = await this.renderNonRouteError(error, request, ctx, env, executionCtx);
361
+ return outcome.mappers.length > 0
362
+ ? this.applyMappers(rendered, outcome.mappers)
363
+ : rendered;
364
+ }
365
+ };
366
+ return wrapped;
367
+ }
368
+ /**
369
+ * Runs the pre-routing `onError` chain (plugin + global) for a response
370
+ * source that has no matched route plan (page, asset, docs), then the
371
+ * global response hooks and `ctx.set` — the non-route equivalent of a
372
+ * route's error exit.
373
+ */
374
+ async renderNonRouteError(error, request, prebuilt, env, executionCtx) {
375
+ const ctx = prebuilt ??
376
+ BurgerContext.create(request, undefined, undefined, this.appServices, undefined, env, executionCtx, this.ipHolder);
377
+ const rendered = await dispatchOnError(error, this.onErrorHooks, ctx, this.debug);
378
+ return this.finishNonRouteResponse(rendered, request, ctx, env, executionCtx);
379
+ }
380
+ /** Renders an error that escaped the pipeline; logs it when 5xx. */
381
+ renderUnhandled(request, error) {
382
+ return renderUncaught(error, request, this.debug);
383
+ }
384
+ /**
385
+ * Applies the global/plugin response plan and `ctx.set` to a response
386
+ * that did not run a route plan (404/405/OPTIONS, pages/assets/docs,
387
+ * onError renders). Returns the response unchanged — zero cost — when
388
+ * neither applies.
389
+ */
390
+ finishNonRouteResponse(response, request, prebuilt, env, executionCtx) {
391
+ if (!this.globalResponseActive && prebuilt?.hasSet() !== true) {
392
+ return response;
393
+ }
394
+ return isThenable(response)
395
+ ? response.then((res) => this.applyGlobalResponseHooks(res, request, prebuilt, env, executionCtx))
396
+ : this.applyGlobalResponseHooks(response, request, prebuilt, env, executionCtx);
397
+ }
398
+ /** Runs the global response plan, then `ctx.set`, for one response. */
399
+ async applyGlobalResponseHooks(response, request, prebuilt, env, executionCtx) {
400
+ const ctx = prebuilt ??
401
+ BurgerContext.create(request, undefined, undefined, this.appServices, undefined, env, executionCtx, this.ipHolder);
402
+ let res = response;
403
+ if (this.globalResponseActive) {
404
+ try {
405
+ res = await runGlobalResponseHooks(this.globalResponsePlan, ctx, res);
406
+ }
407
+ catch (error) {
408
+ // A failing response hook renders through the same onError
409
+ // chain as request errors instead of rejecting.
410
+ res = await dispatchOnError(error, this.onErrorHooks, ctx, this.debug);
411
+ }
412
+ }
413
+ return ctx.hasSet() ? applySet(res, ctx.set) : res;
414
+ }
415
+ /**
416
+ * Compatibility alias for `staticRoutes()`.
417
+ */
418
+ get routes() {
419
+ return this.staticRoutes();
420
+ }
421
+ /**
422
+ * Executes pre-routing `onRequest` hooks on a minimal BurgerContext.
423
+ * Returns a Response if any hook short-circuits, or undefined to continue.
424
+ * Platform `env` / `executionCtx` are bound onto the context here so they
425
+ * survive into the dispatched handler via re-binding.
426
+ */
427
+ async runOnRequest(request, env, executionCtx) {
428
+ // ONE context per request: created here (before routing) so
429
+ // onRequest hooks can seed state that survives into the handler.
430
+ // The dispatched route binds this instance to its matched route.
431
+ const ctx = BurgerContext.create(request, undefined, undefined, this.appServices, undefined, env, executionCtx, this.ipHolder);
432
+ const outcome = {
433
+ shortCircuit: undefined,
434
+ mappers: [],
435
+ ctx,
436
+ };
437
+ if (this.onRequestHooks.length === 0)
438
+ return outcome;
439
+ for (const hook of this.onRequestHooks) {
440
+ try {
441
+ const result = await hook(ctx);
442
+ if (result instanceof Response) {
443
+ // Global/plugin response hooks and ctx.set apply to the
444
+ // short-circuit too; mappers from earlier hooks still
445
+ // wrap it (e.g. cors() then rateLimit(): the 429 keeps
446
+ // CORS headers) — same contract as beforeRoute.
447
+ outcome.shortCircuit = await this.applyMappers(await this.finishNonRouteResponse(result, request, ctx, env, executionCtx), outcome.mappers);
448
+ return outcome;
449
+ }
450
+ if (typeof result === 'function') {
451
+ outcome.mappers.push(result);
452
+ }
453
+ }
454
+ catch (error) {
455
+ // Same onError chain as request errors (nearest-first:
456
+ // Global → Plugin → Framework) — never a bare render. The
457
+ // rendered error also gets the global response hooks.
458
+ outcome.shortCircuit = await this.applyMappers(await this.finishNonRouteResponse(await dispatchOnError(error, this.onErrorHooks, ctx, this.debug), request, ctx, env, executionCtx), outcome.mappers);
459
+ return outcome;
460
+ }
461
+ }
462
+ return outcome;
463
+ }
464
+ /**
465
+ * Dynamic / wildcard lookup: the RegExp matcher first (when compiled),
466
+ * then the radix trie. Both produce identical match shapes. A match that
467
+ * binds a `:param` to an empty segment is rejected. Apps with no dynamic
468
+ * routes skip both matchers.
469
+ */
470
+ matchDynamic(path) {
471
+ if (!this.regexMatcher && this.nativeRoutesMap.size === 0)
472
+ return null;
473
+ let match = null;
474
+ if (this.regexMatcher)
475
+ match = this.regexMatcher(path);
476
+ if (!match)
477
+ match = this.trie.match(path);
478
+ if (match && hasEmptyParam(match.params))
479
+ return null;
480
+ return match;
481
+ }
482
+ /**
483
+ * Applies collected after-mappers in onion order (last registered runs
484
+ * first, the first hook's mapper wraps outermost) — identical to
485
+ * `runHooks` and the JIT for beforeRoute.
486
+ */
487
+ async applyMappers(response, mappers) {
488
+ let res = response;
489
+ for (let i = mappers.length - 1; i >= 0; i--) {
490
+ res = await mappers[i](res);
491
+ }
492
+ return res;
493
+ }
494
+ /**
495
+ * The `fetch` fallback handed to `Bun.serve`: dynamic/wildcard routes
496
+ * via the trie, plus loose-trailing-slash static variants Bun did not
497
+ * match directly.
498
+ *
499
+ * `env` / `executionCtx` are optional platform bindings (WinterCG
500
+ * `fetch(request, env, ctx)`). The signature is its own shape — NOT the
501
+ * server-oriented `FetchHandler` — so the platform slots stay unambiguous.
502
+ * Sync-first: a synchronously resolved executor returns a `Response`
503
+ * directly; only hook plans and async handlers produce a Promise.
504
+ */
505
+ fetch = (request, env, executionCtx) => this.hasOnRequest
506
+ ? this.dispatchWithOnRequest(request, env, executionCtx, undefined)
507
+ : this.dispatchMatched(request, extractPathnameFromUrl(request.url), undefined, undefined, env, executionCtx);
508
+ /**
509
+ * `fetch` with a pathname the caller already extracted (e.g.
510
+ * `fetchHandler()` resolved page/asset routes first), avoiding a second
511
+ * URL parse per request. The pathname must come from
512
+ * `extractPathnameFromUrl`.
513
+ */
514
+ fetchWithPath = (request, pathname, env, executionCtx) => this.hasOnRequest
515
+ ? this.dispatchWithOnRequest(request, env, executionCtx, pathname)
516
+ : this.dispatchMatched(request, pathname, undefined, undefined, env, executionCtx);
517
+ /** Pre-routing hook path: context + mappers wrap the matched dispatch. */
518
+ async dispatchWithOnRequest(request, env, executionCtx, precomputedPath) {
519
+ // Pre-routing: create the one context and run onRequest hooks. A hook
520
+ // returning a Response short-circuits the pipeline; mapper functions
521
+ // are collected and applied to the eventual response.
522
+ const outcome = await this.runOnRequest(request, env, executionCtx);
523
+ if (outcome.shortCircuit)
524
+ return outcome.shortCircuit;
525
+ const mappers = outcome.mappers;
526
+ const apply = mappers.length > 0
527
+ ? (res) => this.applyMappers(res, mappers)
528
+ : undefined;
529
+ const path = precomputedPath ?? extractPathnameFromUrl(request.url);
530
+ return this.dispatchMatched(request, path, outcome.ctx, apply, env, executionCtx);
531
+ }
532
+ /**
533
+ * Routing + execution against the compiled tables. `prebuilt` is the
534
+ * pre-routing context (onRequest path) or `undefined`; `apply` wraps the
535
+ * response in collected onRequest mappers when any exist.
536
+ */
537
+ dispatchMatched(request, raw, prebuilt, apply, env, executionCtx) {
538
+ // Collapse repeated slashes but PRESERVE a single trailing slash (an
539
+ // explicitly registered static slash form is tried first; otherwise
540
+ // the slash is removed before dynamic matching). The regex runs only
541
+ // when the path actually carries `//`.
542
+ const path = raw.indexOf('//') === -1 ? raw : raw.replace(/\/+/g, '/');
543
+ // 1. Exact static route (slash-preserving — Bun already serves the exact
544
+ // form natively; this catches the trailing-slash variants it missed).
545
+ const staticEntry = this.staticMap.getEntry(path);
546
+ if (staticEntry) {
547
+ // No ctxInit: the compiled executor seeds the route identity from
548
+ // its own frozen static route meta (no per-request allocation).
549
+ // A known method dispatches straight to its specialized core
550
+ // (skips the method-dispatch wrapper); an unknown method falls
551
+ // through to the wrapper's 405 + Allow.
552
+ const core = staticEntry.cores?.[request.method];
553
+ const response = core
554
+ ? core(request, undefined, prebuilt, env, executionCtx)
555
+ : this.finishNonRouteResponse(staticEntry.handler(request, undefined, prebuilt, env, executionCtx), request, prebuilt, env, executionCtx);
556
+ return apply === undefined
557
+ ? response
558
+ : applyToResponse(response, apply);
559
+ }
560
+ // 2. Loose trailing slash: remove it BEFORE matching so a sibling
561
+ // wildcard cannot steal a `:param` match (`/users/1/` ≡ `/users/1`,
562
+ // not the wildcard with `['1', '']`). The exact slash form of a
563
+ // static route was already tried above; `/` is never stripped.
564
+ let routePath = path;
565
+ let match = null;
566
+ if (path.length > 1 && path.endsWith('/')) {
567
+ const normalized = path.slice(0, -1);
568
+ const loose = this.staticMap.getEntry(normalized);
569
+ if (loose) {
570
+ const ctxInit = {
571
+ route: { path: normalized, pattern: normalized },
572
+ };
573
+ const core = loose.cores?.[request.method];
574
+ const response = core
575
+ ? core(request, ctxInit, prebuilt, env, executionCtx)
576
+ : this.finishNonRouteResponse(loose.handler(request, ctxInit, prebuilt, env, executionCtx), request, prebuilt, env, executionCtx);
577
+ return apply === undefined
578
+ ? response
579
+ : applyToResponse(response, apply);
580
+ }
581
+ match = this.matchDynamic(normalized);
582
+ if (match)
583
+ routePath = normalized;
584
+ }
585
+ // 3. Dynamic / wildcard routes in their exact form (see
586
+ // matchDynamic). A `:param` never matches an empty segment
587
+ // (`/users/` is not `/users/:id` with id "").
588
+ if (!match)
589
+ match = this.matchDynamic(path);
590
+ if (match) {
591
+ // Auto-HEAD: a GET route implies HEAD is allowed.
592
+ const method = request.method;
593
+ const headAllowed = method === 'HEAD' && match.methods.has('GET');
594
+ if (!match.methods.has(method) && !headAllowed) {
595
+ const allow = this.allowCache.get(match.pattern) ??
596
+ [...match.methods].join(', ');
597
+ const notAllowed = this.finishNonRouteResponse(methodNotAllowed(allow), request, prebuilt, env, executionCtx);
598
+ return apply === undefined
599
+ ? notAllowed
600
+ : applyToResponse(notAllowed, apply);
601
+ }
602
+ // Seed `ctxInit`: `route` is always present; `params` /
603
+ // `wildcardParams` are added only when the route has them.
604
+ const ctxInit = {
605
+ route: { path: routePath, pattern: match.pattern },
606
+ params: match.params,
607
+ wildcardParams: match.wildcardParams,
608
+ };
609
+ const response = match.handler(request, ctxInit, prebuilt, env, executionCtx);
610
+ return apply === undefined
611
+ ? response
612
+ : applyToResponse(response, apply);
613
+ }
614
+ const notFoundResponse = this.finishNonRouteResponse(notFound(), request, prebuilt, env, executionCtx);
615
+ return apply === undefined
616
+ ? notFoundResponse
617
+ : applyToResponse(notFoundResponse, apply);
618
+ }
619
+ }
620
+ /** Applies collected onRequest mappers to a sync or async response. */
621
+ function applyToResponse(response, apply) {
622
+ return isThenable(response) ? response.then(apply) : apply(response);
623
+ }
624
+ /**
625
+ * Builds the pre-routing `onError` chain: the hooks available before a route
626
+ * is matched, in the same nearest-first order a route plan uses (Global →
627
+ * Plugin → Framework).
628
+ */
629
+ function buildPreRoutingErrorChain(plugins, globalHooks) {
630
+ const buckets = {
631
+ local: [],
632
+ global: [],
633
+ plugin: [],
634
+ framework: [],
635
+ };
636
+ const push = (value, to) => {
637
+ if (value === undefined)
638
+ return;
639
+ if (Array.isArray(value))
640
+ for (const h of value)
641
+ to.push(h);
642
+ else
643
+ to.push(value);
644
+ };
645
+ push(globalHooks?.onError, buckets.global);
646
+ for (const plugin of plugins ?? []) {
647
+ push(plugin.hooks.onError, buckets[plugin.scope]);
648
+ }
649
+ return [
650
+ ...buckets.global,
651
+ ...buckets.plugin,
652
+ ...buckets.framework,
653
+ ];
654
+ }
655
+ /** True when any matched `:param` captured an empty segment. */
656
+ function hasEmptyParam(params) {
657
+ if (!params)
658
+ return false;
659
+ for (const k in params)
660
+ if (params[k] === '')
661
+ return true;
662
+ return false;
663
+ }
664
+ /**
665
+ * A route path is dynamic when it carries a `:param` or `*` segment —
666
+ * the set dispatched through the trie / RegExp matcher.
667
+ */
668
+ function isDynamicPath(path) {
669
+ return path.includes(':') || path.includes('*');
670
+ }