@stacksjs/router 0.70.294 → 0.70.296

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/dist/index.d.ts CHANGED
@@ -22,7 +22,8 @@ export type {
22
22
  // Re-export everything from bun-router (includes response factory)
23
23
  export * from '@stacksjs/bun-router';
24
24
  // Export Stacks-specific action resolver and URL helper
25
- export { assertRouteMiddlewareResolvable, clearMiddlewareCache, createStacksRouter, findUnresolvableRouteMiddleware, installMiddlewareHotReload, route, serve, serverResponse, url, warnOnMultipleRouterInstances } from './stacks-router';
25
+ export { assertRouteMiddlewareResolvable,
26
+ configureViewDirectories, clearMiddlewareCache, createStacksRouter, findUnresolvableRouteMiddleware, installMiddlewareHotReload, route, serve, serverResponse, url, warnOnMultipleRouterInstances } from './stacks-router';
26
27
  // Export request context helpers
27
28
  export { cacheRequestQuery, getCurrentRequest, getTraceId, request, runWithRequest, setCurrentRequest, withTraceId } from './request-context';
28
29
  // Export Middleware class for defining route middleware
@@ -41,6 +42,19 @@ export {
41
42
  } from './error-handler';
42
43
  // Export route introspection helpers
43
44
  export { listRegisteredRoutes, routeParams } from './stacks-router';
45
+ // Route-model binding (stacksjs/stacks#2231): what lets `can:view,site`
46
+ // reach `SitePolicy.view(user, site)` instead of handing the policy layer a
47
+ // raw path string it can never match a policy against.
48
+ export {
49
+ clearRouteModelBindings,
50
+ defineRouteModelBinding,
51
+ resolveRouteModel,
52
+ routeModelBindings,
53
+ setRouteModelFallback,
54
+ type RouteModelContext,
55
+ type RouteModelResolution,
56
+ type RouteModelResolver,
57
+ } from './route-model-binding';
44
58
  // Export JSON-vs-HTML negotiation predicate so userland can short-circuit
45
59
  // the same decision the framework makes in formatResult / error-handler.
46
60
  export { isApiRequest, JSON_CONTENT_TYPE } from './api-shape';
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- var {require}=import.meta;import"./request-augmentation";export*from"@stacksjs/bun-router";export{assertRouteMiddlewareResolvable,clearMiddlewareCache,createStacksRouter,findUnresolvableRouteMiddleware,installMiddlewareHotReload,route,serve,serverResponse,url,warnOnMultipleRouterInstances}from"./stacks-router";export{cacheRequestQuery,getCurrentRequest,getTraceId,request,runWithRequest,setCurrentRequest,withTraceId}from"./request-context";export{Middleware}from"./middleware";export{loadRoutes}from"./route-loader";export{clearTrackedQueries,createErrorResponse,createMiddlewareErrorResponse,createNotFoundResponse,createValidationErrorResponse,getQueryShapeCounts,trackQuery}from"./error-handler";export{listRegisteredRoutes,routeParams}from"./stacks-router";export{isApiRequest,JSON_CONTENT_TYPE}from"./api-shape";export{rateLimit,rateLimitStatus,clearRateLimit}from"./rate-limit";export{PathParamError,safePathParam,sanitizePathParam}from"./path-sanitize";export{checkApplicationHealth,runHealthProbes}from"./health";export{stream}from"./stacks-router";export{signedUrl,signUrl,verifySignedUrl,verifySignedUrlMiddleware}from"./signed-url";export{EncryptedSessionStore}from"./encrypted-session-store";export{createSessionStore,createStacksSessionStore,DatabaseSessionStore,FileSessionStore,MemorySessionStore,RedisSessionStore}from"./session-factory";import("@stacksjs/database").then(({setQueryTracker})=>{if(typeof setQueryTracker==="function"){const{trackQuery}=require("./error-handler");setQueryTracker(trackQuery)}}).catch(()=>{});
1
+ var {require}=import.meta;import"./request-augmentation";export*from"@stacksjs/bun-router";export{assertRouteMiddlewareResolvable,configureViewDirectories,clearMiddlewareCache,createStacksRouter,findUnresolvableRouteMiddleware,installMiddlewareHotReload,route,serve,serverResponse,url,warnOnMultipleRouterInstances}from"./stacks-router";export{cacheRequestQuery,getCurrentRequest,getTraceId,request,runWithRequest,setCurrentRequest,withTraceId}from"./request-context";export{Middleware}from"./middleware";export{loadRoutes}from"./route-loader";export{clearTrackedQueries,createErrorResponse,createMiddlewareErrorResponse,createNotFoundResponse,createValidationErrorResponse,getQueryShapeCounts,trackQuery}from"./error-handler";export{listRegisteredRoutes,routeParams}from"./stacks-router";export{clearRouteModelBindings,defineRouteModelBinding,resolveRouteModel,routeModelBindings,setRouteModelFallback}from"./route-model-binding";export{isApiRequest,JSON_CONTENT_TYPE}from"./api-shape";export{rateLimit,rateLimitStatus,clearRateLimit}from"./rate-limit";export{PathParamError,safePathParam,sanitizePathParam}from"./path-sanitize";export{checkApplicationHealth,runHealthProbes}from"./health";export{stream}from"./stacks-router";export{signedUrl,signUrl,verifySignedUrl,verifySignedUrlMiddleware}from"./signed-url";export{EncryptedSessionStore}from"./encrypted-session-store";export{createSessionStore,createStacksSessionStore,DatabaseSessionStore,FileSessionStore,MemorySessionStore,RedisSessionStore}from"./session-factory";import("@stacksjs/database").then(({setQueryTracker})=>{if(typeof setQueryTracker==="function"){const{trackQuery}=require("./error-handler");setQueryTracker(trackQuery)}}).catch(()=>{});
@@ -3,3 +3,100 @@ import type { RouteRegistry } from './route-types';
3
3
  * Load all routes from the registry
4
4
  */
5
5
  export declare function loadRoutes(registry: RouteRegistry): Promise<void>;
6
+ /**
7
+ * Which framework default route bundles this app mounts.
8
+ *
9
+ * `STACKS_SKIP_DEFAULT_ROUTES=1` was a single boolean over a 724-line
10
+ * `dashboard.ts` that bundled auth, password reset, 2FA, storefront
11
+ * cart/checkout, reviews, sitemap, AI and voice together. An app wanting
12
+ * `/login` and 2FA without shipping `Product` or `Coupon` had exactly two
13
+ * options: mount the commerce demo surface, or turn everything off and
14
+ * re-declare the auth routes by hand with the rate limits copied out of
15
+ * framework source. One reporting app took the second and permanently gave up
16
+ * 2FA, sign-out-everywhere and API token management (stacksjs/stacks#2229).
17
+ *
18
+ * `STACKS_DEFAULT_ROUTES=auth` now names the bundles directly.
19
+ *
20
+ * ## Why bundles are not gated on `feature()`
21
+ *
22
+ * The issue asks for `feature('auth')` to mount the auth bundle. It cannot:
23
+ * `feature()` treats a present config object as enabled, and `config/auth.ts`
24
+ * ships in every scaffolded app with `enabled: true`. Gating on it would mount
25
+ * `/login`, `/register`, `/generate-two-factor-secret`, `/logout-all` and
26
+ * `/auth/tokens` in every app that currently runs with `dashboard` off -
27
+ * silently widening the public surface of existing apps on upgrade. An opt-in
28
+ * that is on by default is not an opt-in. So selection is explicit, and the
29
+ * default is exactly what the app got before.
30
+ *
31
+ * Precedence: `STACKS_DEFAULT_ROUTES` wins; then the legacy
32
+ * `STACKS_SKIP_DEFAULT_ROUTES`; then everything.
33
+ *
34
+ * Accepted spellings, so the two variables cannot contradict each other in a
35
+ * surprising way:
36
+ * - `STACKS_DEFAULT_ROUTES=auth,email` - exactly those bundles
37
+ * - `STACKS_DEFAULT_ROUTES=none` (or empty) - none, same as the old `=1`
38
+ * - `STACKS_DEFAULT_ROUTES=all` - everything, same as the old unset
39
+ * - `STACKS_SKIP_DEFAULT_ROUTES=1` - none. Still supported, still documented.
40
+ *
41
+ * An unknown name is ignored rather than fatal: a typo should cost you the
42
+ * bundle you misspelled, not the whole boot. `unknown` reports them so the
43
+ * caller can warn.
44
+ *
45
+ * ## Actions still resolve when routes do not
46
+ *
47
+ * Worth knowing because it is what made the original failure confusing to
48
+ * diagnose. Turning bundles off stops the framework's ROUTES from being
49
+ * registered; it does not stop its ACTIONS from resolving. A handler
50
+ * referenced by string - `route.post('/login', 'Actions/Auth/LoginAction')` -
51
+ * is still found in `@stacksjs/defaults`, so an app can re-declare a route in
52
+ * `routes/api.ts` and point it at a framework action it never copied into
53
+ * `app/Actions/`. The reporting app's nine hand-written auth routes work
54
+ * exactly this way, which is why they have no files behind them.
55
+ */
56
+ export declare function resolveDefaultRouteBundles(env?: NodeJS.ProcessEnv): Set<DefaultRouteBundle>;
57
+ /**
58
+ * {@link resolveDefaultRouteBundles} plus the names it did not recognise, and
59
+ * whether the app named bundles at all.
60
+ *
61
+ * `explicit` matters because it decides who wins against the feature flags. An
62
+ * app that wrote `STACKS_DEFAULT_ROUTES=auth` has said what it wants; the
63
+ * `feature('dashboard')` gate must not then withhold it, or the whole point -
64
+ * mounting auth WITHOUT the dashboard surface - is lost. When nothing is
65
+ * named, the flags gate exactly as they did before.
66
+ */
67
+ export declare function resolveDefaultRouteBundlesWithDiagnostics(env?: NodeJS.ProcessEnv): { bundles: Set<DefaultRouteBundle>, unknown: string[], explicit: boolean };
68
+ /**
69
+ * Load framework default routes via `storage/framework/defaults/bootstrap.ts`.
70
+ *
71
+ * The bootstrap file is the single source of truth for which framework
72
+ * packages participate in route registration. It either imports each
73
+ * package (whose own entry calls `route.register(...)` on import — the
74
+ * service-provider pattern competing frameworks use to let packages
75
+ * self-wire at boot) or registers routes files directly via
76
+ * `route.register(...)`. Adding a new framework package = add a line
77
+ * to bootstrap.ts; the loader stays untouched.
78
+ *
79
+ * Resolved through @stacksjs/path so the same import works whether this
80
+ * package runs from the workspace or from `node_modules/@stacksjs/router/`.
81
+ */
82
+ /**
83
+ * The framework's default route files, as selectable bundles.
84
+ *
85
+ * `core` is not listed because it is not optional: it carries the locale
86
+ * cookie and the `/locale/{code}` redirect, and bootstrap registers it
87
+ * unconditionally.
88
+ */
89
+ export declare const DEFAULT_ROUTE_BUNDLES: readonly ['auth', 'dashboard', 'email'];
90
+ /**
91
+ * Bundles an app must ask for. Excluded from the implicit default AND from
92
+ * `all`, because both are what an app that said nothing gets: `social` mounts
93
+ * OAuth callback URLs, which are surface for nothing in an app that never
94
+ * configured a provider (stacksjs/stacks#2276). Naming one in
95
+ * `STACKS_DEFAULT_ROUTES` mounts it like any other; bootstrap additionally
96
+ * mounts `social` on its own when a provider is actually configured, so the
97
+ * env var is only needed to force it on or off.
98
+ */
99
+ export declare const OPT_IN_ROUTE_BUNDLES: readonly ['social'];
100
+ /** Where {@link loadFrameworkRoutes} leaves the selection for bootstrap.ts. */
101
+ export declare const DEFAULT_ROUTE_BUNDLES_KEY: '__stacksDefaultRouteBundles';
102
+ export type DefaultRouteBundle = typeof DEFAULT_ROUTE_BUNDLES[number] | typeof OPT_IN_ROUTE_BUNDLES[number];
@@ -1 +1 @@
1
- import{log}from"@stacksjs/logging";import{route}from"./stacks-router";const NO_PREFIX_KEYS=["web"];export async function loadRoutes(registry){for(const[key,definition]of Object.entries(registry)){const config=normalizeDefinition(definition),prefix=config.prefix!==void 0?config.prefix?config.prefix.startsWith("/")?config.prefix:`/${config.prefix}`:void 0:NO_PREFIX_KEYS.includes(key)?void 0:`/${key}`,middleware=normalizeMiddleware(config.middleware);log.debug(`[route-loader] Loading: ${config.path} prefix=${prefix||"/"} middleware=[${middleware.join(", ")}]`);try{if(prefix||middleware.length>0)await route.group({prefix,middleware:middleware.length>0?middleware:void 0},async()=>{await importRouteFile(config.path)});else await importRouteFile(config.path)}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[Routes] Failed to load route file '${config.path}': ${message}`);throw Error(`Route loading failed for '${config.path}': ${message}`)}}await loadFrameworkRoutes()}async function loadFrameworkRoutes(){if(process.env.STACKS_SKIP_DEFAULT_ROUTES==="1")return;try{const{frameworkPath}=await import("@stacksjs/path"),bootstrapPath=frameworkPath("defaults/bootstrap.ts");if(await Bun.file(bootstrapPath).exists())await import(bootstrapPath)}catch(error){const message=error instanceof Error?error.message:String(error);if(!message.includes("Cannot find module")&&!message.includes("MODULE_NOT_FOUND"))console.error(`[Routes] Failed to load framework bootstrap: ${message}`)}}function assertSafeRouteName(routeName){if(typeof routeName!=="string"||routeName.length===0)throw Error("[route-loader] Invalid route path: empty or non-string");if(routeName.includes("\x00"))throw Error("[route-loader] Invalid route path: null byte");let decoded;try{decoded=decodeURIComponent(routeName)}catch{throw Error("[route-loader] Invalid route path: malformed URL encoding")}const cleanPath=decoded.replace(/\.ts$/,"");if(cleanPath.startsWith("/")||/^[A-Za-z]:[\\/]/.test(cleanPath))throw Error(`[route-loader] Invalid route path: absolute paths not allowed (${cleanPath})`);if(cleanPath.split(/[/\\]/).some((s)=>s===".."))throw Error(`[route-loader] Invalid route path: '..' segment not allowed (${cleanPath})`);return cleanPath}async function importRouteFile(routeName){const cleanPath=assertSafeRouteName(routeName),{projectPath}=await import("@stacksjs/path");await import(projectPath(`routes/${cleanPath}`))}function normalizeDefinition(def){if(typeof def==="string")return{path:def};return def}function normalizeMiddleware(middleware){if(!middleware)return[];if(typeof middleware==="string")return[middleware];return middleware}
1
+ import{log}from"@stacksjs/logging";import{route}from"./stacks-router";const NO_PREFIX_KEYS=["web"];export async function loadRoutes(registry){for(const[key,definition]of Object.entries(registry)){const config=normalizeDefinition(definition),prefix=config.prefix!==void 0?config.prefix?config.prefix.startsWith("/")?config.prefix:`/${config.prefix}`:void 0:NO_PREFIX_KEYS.includes(key)?void 0:`/${key}`,middleware=normalizeMiddleware(config.middleware);log.debug(`[route-loader] Loading: ${config.path} prefix=${prefix||"/"} middleware=[${middleware.join(", ")}]`);try{if(prefix||middleware.length>0)await route.group({prefix,middleware:middleware.length>0?middleware:void 0},async()=>{await importRouteFile(config.path)});else await importRouteFile(config.path)}catch(error){const message=error instanceof Error?error.message:String(error);console.error(`[Routes] Failed to load route file '${config.path}': ${message}`);throw Error(`Route loading failed for '${config.path}': ${message}`)}}await loadFrameworkRoutes()}export const DEFAULT_ROUTE_BUNDLES=["auth","dashboard","email"],OPT_IN_ROUTE_BUNDLES=["social"],DEFAULT_ROUTE_BUNDLES_KEY="__stacksDefaultRouteBundles";export function resolveDefaultRouteBundles(env=process.env){return resolveDefaultRouteBundlesWithDiagnostics(env).bundles}export function resolveDefaultRouteBundlesWithDiagnostics(env=process.env){const all=()=>new Set(DEFAULT_ROUTE_BUNDLES),raw=env.STACKS_DEFAULT_ROUTES;if(raw!==void 0){const names=raw.split(",").map((name)=>name.trim().toLowerCase()).filter(Boolean);if(names.length===0||names.includes("none"))return{bundles:new Set,unknown:[],explicit:!0};if(names.includes("all"))return{bundles:all(),unknown:[],explicit:!0};const bundles=new Set,unknown=[];for(const name of names)if(DEFAULT_ROUTE_BUNDLES.includes(name)||OPT_IN_ROUTE_BUNDLES.includes(name))bundles.add(name);else unknown.push(name);return{bundles,unknown,explicit:!0}}if(env.STACKS_SKIP_DEFAULT_ROUTES==="1")return{bundles:new Set,unknown:[],explicit:!0};return{bundles:all(),unknown:[],explicit:!1}}async function loadFrameworkRoutes(){const{bundles,unknown,explicit}=resolveDefaultRouteBundlesWithDiagnostics();for(const name of unknown)log.warn(`[Routes] STACKS_DEFAULT_ROUTES lists unknown bundle "${name}" \u2014 known bundles are ${DEFAULT_ROUTE_BUNDLES.join(", ")}.`);if(bundles.size===0)return;globalThis[DEFAULT_ROUTE_BUNDLES_KEY]={bundles,explicit};try{try{const{overridesReady}=await import("@stacksjs/config");await overridesReady}catch{}const{frameworkPath}=await import("@stacksjs/path"),bootstrapPath=frameworkPath("defaults/bootstrap.ts");if(await Bun.file(bootstrapPath).exists())await import(bootstrapPath)}catch(error){const message=error instanceof Error?error.message:String(error);if(!message.includes("Cannot find module")&&!message.includes("MODULE_NOT_FOUND"))console.error(`[Routes] Failed to load framework bootstrap: ${message}`)}}function assertSafeRouteName(routeName){if(typeof routeName!=="string"||routeName.length===0)throw Error("[route-loader] Invalid route path: empty or non-string");if(routeName.includes("\x00"))throw Error("[route-loader] Invalid route path: null byte");let decoded;try{decoded=decodeURIComponent(routeName)}catch{throw Error("[route-loader] Invalid route path: malformed URL encoding")}const cleanPath=decoded.replace(/\.ts$/,"");if(cleanPath.startsWith("/")||/^[A-Za-z]:[\\/]/.test(cleanPath))throw Error(`[route-loader] Invalid route path: absolute paths not allowed (${cleanPath})`);if(cleanPath.split(/[/\\]/).some((s)=>s===".."))throw Error(`[route-loader] Invalid route path: '..' segment not allowed (${cleanPath})`);return cleanPath}async function importRouteFile(routeName){const cleanPath=assertSafeRouteName(routeName),{projectPath}=await import("@stacksjs/path");await import(projectPath(`routes/${cleanPath}`))}function normalizeDefinition(def){if(typeof def==="string")return{path:def};return def}function normalizeMiddleware(middleware){if(!middleware)return[];if(typeof middleware==="string")return[middleware];return middleware}
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Bind a route parameter to a model.
3
+ *
4
+ * ```ts
5
+ * defineRouteModelBinding('site', id => Site.find(Number(id)))
6
+ * ```
7
+ *
8
+ * The last registration for a name wins, so an app can override a convention
9
+ * binding without having to unregister one.
10
+ */
11
+ export declare function defineRouteModelBinding(param: string, resolver: RouteModelResolver): void;
12
+ /**
13
+ * A resolver consulted for any parameter with no explicit binding.
14
+ *
15
+ * This is how a convention — parameter `site` resolves through the `Site`
16
+ * model — is supplied without the router having to import the ORM, which would
17
+ * be a dependency cycle. Pass `null` to remove it.
18
+ */
19
+ export declare function setRouteModelFallback(resolver: RouteModelResolver | null): void;
20
+ /** Registered parameter names, for diagnostics and tests. */
21
+ export declare function routeModelBindings(): string[];
22
+ export declare function clearRouteModelBindings(): void;
23
+ /**
24
+ * Resolve one route parameter to a model instance.
25
+ *
26
+ * A resolver that throws is treated as "no model" rather than allowed to
27
+ * propagate: a lookup failure must not turn an authorization check into a 500,
28
+ * and falling through to the unresolved path denies, which is the safe
29
+ * direction.
30
+ */
31
+ export declare function resolveRouteModel(param: string, value: string, request?: unknown): Promise<RouteModelResolution>;
32
+ /**
33
+ * Route-model binding (stacksjs/stacks#2231).
34
+ *
35
+ * The framework ships a full Policy system and a `can:` middleware, and they
36
+ * could not be connected. `Can` read the route parameter and handed the RAW
37
+ * STRING to `authorize()`, while `resolveAbility()` only reaches for a policy
38
+ * when the first argument is an object with a matching `constructor.name`. A
39
+ * string's is `String`, so `can:view,site` could never dispatch to
40
+ * `SitePolicy.view(user, site)` — every ownership check had to be written
41
+ * imperatively inside the handler instead.
42
+ *
43
+ * A gate that is opt-in per handler rather than declarative on the route means
44
+ * a new endpoint that forgets the three-line prologue is readable by anyone.
45
+ * One real app carries that prologue at 18 call sites and wrote a source-grep
46
+ * test purely to stop a copy being deleted.
47
+ *
48
+ * Resolution order: an explicit binding, then the fallback, then nothing. The
49
+ * "nothing" case matters most — it is what keeps this from changing behaviour
50
+ * for a parameter no one has bound.
51
+ */
52
+ export declare interface RouteModelContext {
53
+ param: string
54
+ request?: unknown
55
+ }
56
+ /**
57
+ * Outcome of a resolution attempt.
58
+ *
59
+ * `bound` distinguishes "nobody claims this parameter" from "someone claims it
60
+ * and there is no such row". They must not collapse: the first has to keep
61
+ * passing the raw string through, exactly as before, or every existing
62
+ * `can:ability,param` route changes meaning at once.
63
+ */
64
+ export declare interface RouteModelResolution {
65
+ bound: boolean
66
+ model?: unknown
67
+ }
68
+ /**
69
+ * Resolves a parameter's raw path value to a model.
70
+ *
71
+ * `context.param` is supplied so ONE resolver can serve every parameter — which
72
+ * is what the convention fallback needs, since it derives the model name from
73
+ * the parameter name.
74
+ */
75
+ export type RouteModelResolver = (value: string, context: RouteModelContext) => unknown | Promise<unknown>;
@@ -0,0 +1 @@
1
+ const bindings=new Map;let fallbackResolver=null;export function defineRouteModelBinding(param,resolver){bindings.set(param,resolver)}export function setRouteModelFallback(resolver){fallbackResolver=resolver}export function routeModelBindings(){return[...bindings.keys()].sort()}export function clearRouteModelBindings(){bindings.clear();fallbackResolver=null}export async function resolveRouteModel(param,value,request){const resolver=bindings.get(param)??fallbackResolver;if(!resolver)return{bound:!1};try{const model=await resolver(value,{param,request});if(model===void 0)return{bound:!1};return{bound:!0,model:model??void 0}}catch{return{bound:!0,model:void 0}}}
@@ -100,6 +100,35 @@ export declare function findUnresolvableRouteMiddleware(): Promise<Array<{ alias
100
100
  * request-time guard in createMiddlewareHandler 500s as a backstop).
101
101
  */
102
102
  export declare function assertRouteMiddlewareResolvable(): Promise<void>;
103
+ /**
104
+ * Whether this request is asking "would this be accepted?" rather than
105
+ * "do this" (stacksjs/stacks#2226).
106
+ *
107
+ * An Action's `validations:` block was a server-only artifact: nothing could
108
+ * read it from a template or a client script, so every form in every app
109
+ * retyped the rules in the browser and the two copies drifted. The framework's
110
+ * own defaults demonstrated it — the browser refused a 7-character password
111
+ * that `POST /register` would have accepted.
112
+ *
113
+ * Rather than serialise the rules (a `schema.*` chain is a live object with
114
+ * no faithful JSON projection), the client asks the real endpoint to run the
115
+ * real rules and stops short of the side effect. Same shape as Laravel
116
+ * Precognition, and deliberately header-compatible with it.
117
+ *
118
+ * `?_validate=1` is accepted too: a header cannot be set on a plain form
119
+ * submission or a `<script client>` block using a bare fetch shorthand, and
120
+ * requiring one would have put this out of reach of the simplest caller.
121
+ */
122
+ export declare function precognitionRequest(req: EnhancedRequest): { only: string[] } | null;
123
+ /**
124
+ * The "nothing to report" answer to a precognition request. 204 rather than an
125
+ * empty 200 so a client cannot mistake it for the action's real result.
126
+ *
127
+ * `Vary` because the same URL and method now has two different answers
128
+ * depending on a request header — without it a shared cache is entitled to
129
+ * serve this 204 to a caller that meant to submit.
130
+ */
131
+ export declare function precognitionSuccess(): Response;
103
132
  /**
104
133
  * Run an action's declarative `validations:` against the request.
105
134
  *
@@ -114,6 +143,34 @@ export declare function enhanceRequest(req: EnhancedRequest): EnhancedRequest;
114
143
  * Create a Stacks-enhanced router
115
144
  */
116
145
  export declare function createStacksRouter(config?: StacksRouterConfig): StacksRouterInstance;
146
+ /**
147
+ * Tell the file-based view renderer where this application keeps its templates.
148
+ *
149
+ * Two different programs render `.stx` in a Stacks app and they were not
150
+ * agreeing. `buddy dev` and the production server go through
151
+ * `bun-plugin-stx`'s own `serve()`, which is handed the components, layouts and
152
+ * partials directories explicitly. `route.serve()` goes through bun-router's
153
+ * file routing, which was handed nothing - so its components directory fell
154
+ * back to `<viewsDir>/components`, and `resources/components`, where every
155
+ * Stacks app actually keeps them, was never looked in.
156
+ *
157
+ * The failure is silent in the direction that hides bugs. The page still
158
+ * answers 200; the component is replaced inline with
159
+ * `[Error loading component: ENOENT ...]`. So a test that boots the router and
160
+ * asserts on rendered HTML cannot see any component at all, and reads as though
161
+ * the feature under test were missing rather than the harness.
162
+ *
163
+ * Only fills in what has not been set: an application that called
164
+ * `route.bunRouter.views(...)` itself has said something more specific, and
165
+ * this must not overwrite it.
166
+ *
167
+ * **It deliberately does not set `viewsPath`.** Naming one switches on
168
+ * file-based route discovery, which walks the whole views tree - so an
169
+ * application that never asked for file routing would start doing it because a
170
+ * directory happened to exist. Where the views are is already decided
171
+ * elsewhere; the only thing missing was where the *components* are.
172
+ */
173
+ export declare function configureViewDirectories(bunRouter: Router): void;
117
174
  /**
118
175
  * Handle a server request through the router
119
176
  * This is the main entry point for the Stacks server
@@ -1,5 +1,5 @@
1
- import{Middleware}from"./middleware";import"./request-augmentation";import process from"node:process";import{Buffer}from"node:buffer";import{existsSync}from"node:fs";import{timingSafeEqual}from"node:crypto";import{collect}from"@stacksjs/collections";import{log,report}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{UploadedFile}from"@stacksjs/storage";import{applyRequestEnhancements,Router}from"@stacksjs/bun-router";import{checkApplicationHealth}from"./health";const ROUTER_INSTANCES_KEY=Symbol.for("@stacksjs/router:loaded-instances"),loadedRouterInstances=globalThis[ROUTER_INSTANCES_KEY]??=new Set;loadedRouterInstances.add(import.meta.path);const MULTI_INSTANCE_WARNED_KEY=Symbol.for("@stacksjs/router:multi-instance-warned");export function warnOnMultipleRouterInstances(){if(loadedRouterInstances.size<=1)return!1;const g=globalThis;if(!g[MULTI_INSTANCE_WARNED_KEY]){g[MULTI_INSTANCE_WARNED_KEY]=!0;const paths=[...loadedRouterInstances].map((p)=>` - ${p}`).join(`
1
+ import{response}from"@stacksjs/bun-router";import{Middleware}from"./middleware";import"./request-augmentation";import process from"node:process";import{Buffer}from"node:buffer";import{existsSync}from"node:fs";import{timingSafeEqual}from"node:crypto";import{collect}from"@stacksjs/collections";import{log,report}from"@stacksjs/logging";import{path as p}from"@stacksjs/path";import{UploadedFile}from"@stacksjs/storage";import{applyRequestEnhancements,Router}from"@stacksjs/bun-router";import{checkApplicationHealth}from"./health";const ROUTER_INSTANCES_KEY=Symbol.for("@stacksjs/router:loaded-instances"),loadedRouterInstances=globalThis[ROUTER_INSTANCES_KEY]??=new Set;loadedRouterInstances.add(import.meta.path);const MULTI_INSTANCE_WARNED_KEY=Symbol.for("@stacksjs/router:multi-instance-warned");export function warnOnMultipleRouterInstances(){if(loadedRouterInstances.size<=1)return!1;const g=globalThis;if(!g[MULTI_INSTANCE_WARNED_KEY]){g[MULTI_INSTANCE_WARNED_KEY]=!0;const paths=[...loadedRouterInstances].map((p)=>` - ${p}`).join(`
2
2
  `);log.warn(`${loadedRouterInstances.size} distinct @stacksjs/router modules loaded in one process; they now share one route table (stacksjs/stacks#1982) so routing still works, but this is a duplicated install worth fixing. It usually means an app vendors storage/framework/core AND installs the published @stacksjs/* dist, and a tsconfig \`paths\` mapping (\`@stacksjs/* -> ./*/src\`) splits module resolution between core files and root files. See stacksjs/stacks#1975.
3
3
  Loaded instances:
4
- ${paths}`)}return!0}let __defaultsPkgRoot;function resolveDefaultsPath(rel){const vendored=p.storagePath(`framework/defaults/${rel}`);if(existsSync(vendored))return vendored;if(__defaultsPkgRoot===void 0)try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());__defaultsPkgRoot=pkgJson.slice(0,pkgJson.lastIndexOf("/"))}catch{__defaultsPkgRoot=null}return __defaultsPkgRoot?`${__defaultsPkgRoot}/${rel}`:vendored}import{runWithRequest}from"./request-context";import{isApiRequest,JSON_CONTENT_TYPE}from"./api-shape";import{clearTrackedQueries,createErrorResponse,createMiddlewareErrorResponse}from"./error-handler";import{rateLimit as enforceRateLimit}from"./rate-limit";import{applySecurityHeaders}from"./security-headers";import{isCursorPaginator,isPaginator,isSimplePaginator}from"@stacksjs/orm";const csrfSkipRegistry=new Set,csrfRequireRegistry=new Set,routeRateLimitRegistry=new Map;function rateLimitWindowToSeconds(window){if(typeof window==="number"){if(!Number.isFinite(window)||window<=0)throw Error(`[Router] .rateLimit(): window must be a positive number of seconds, got ${window}`);return Math.floor(window)}switch(window){case"second":return 1;case"minute":return 60;case"hour":return 3600;case"day":return 86400;default:throw Error(`[Router] .rateLimit(): unknown period '${String(window)}'`)}}class BoundedMap{max;map=new Map;constructor(max){this.max=max}get(key){return this.map.get(key)}has(key){return this.map.has(key)}set(key,value){if(this.map.has(key))this.map.delete(key);this.map.set(key,value);if(this.map.size>this.max){const oldest=this.map.keys().next().value;if(oldest!==void 0)this.map.delete(oldest)}return this}delete(key){return this.map.delete(key)}clear(){this.map.clear()}get size(){return this.map.size}}function isExposeRoutesAuthorized(req){const flag=process.env.STACKS_EXPOSE_ROUTES??"";if(!flag)return!((process.env.APP_ENV??"").toLowerCase()==="production"||process.env.NODE_ENV==="production");if(flag==="1")return!((process.env.APP_ENV??"").toLowerCase()==="production"||process.env.NODE_ENV==="production");const url=new URL(req.url),submitted=req.headers.get("x-stacks-routes-token")||req.headers.get("X-Stacks-Routes-Token")||url.searchParams.get("token")||"";if(typeof submitted!=="string"||submitted.length===0||submitted.length!==flag.length)return!1;try{return timingSafeEqual(Buffer.from(submitted),Buffer.from(flag))}catch{return!1}}async function applyCorsIfConfigured(req,response){if(!req._corsConfig||!response)return response;try{const{applyCorsHeaders}=await import(resolveDefaultsPath("app/Middleware/Cors.ts"));return applyCorsHeaders(req,response,req._corsConfig)}catch(err){log.warn("[router] CORS header injection failed",{error:err});return response}}const ACTION_CACHE_MAX=5000,actionSkipsCsrfCache=new BoundedMap(ACTION_CACHE_MAX),routeHandlerKeyRegistry=new BoundedMap(ACTION_CACHE_MAX),CSRF_PROTECTED_METHODS=new Set(["POST","PUT","PATCH","DELETE"]),namedRouteRegistry=new Map;function compileNamedRoute(path){const paramNames=extractRouteParamNames(path),colonRegex=new Map;for(const name of paramNames)colonRegex.set(name,new RegExp(`(^|/):${name}(?=$|/)`,"g"));return{path,paramNames,colonRegex}}function extractRouteParamNames(routePath){const names=new Set;for(const m of routePath.matchAll(/\{(\w+)\}/g))if(m[1])names.add(m[1]);for(const m of routePath.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(m[1])names.add(m[1]);return[...names]}export function url(routeName,params={}){const named=namedRouteRegistry.get(routeName);if(!named)throw Error(`Route '${routeName}' is not defined. Available routes: ${[...namedRouteRegistry.keys()].join(", ")}`);const missing=named.paramNames.filter((name)=>!(name in params)||params[name]===void 0);if(missing.length>0)throw Error(`url('${routeName}'): missing required path param${missing.length>1?"s":""} [${missing.join(", ")}] for path '${named.path}'. Pass them as the second argument: url('${routeName}', { ${named.paramNames.join(", ")} })`);let appUrl;try{appUrl=process.env.APP_URL||"https://localhost"}catch{appUrl="https://localhost"}appUrl=appUrl.replace(/\/$/,"");if(!appUrl.startsWith("http"))appUrl=`https://${appUrl}`;let resolvedPath=named.path;const queryParams={};for(const[key,value]of Object.entries(params)){const curly=`{${key}}`;if(resolvedPath.includes(curly))resolvedPath=resolvedPath.replaceAll(curly,encodeURIComponent(String(value)));else{const re=named.colonRegex.get(key);if(re&&re.test(resolvedPath)){re.lastIndex=0;resolvedPath=resolvedPath.replace(re,`$1${encodeURIComponent(String(value))}`)}else queryParams[key]=String(value)}}const queryString=Object.keys(queryParams).length>0?`?${new URLSearchParams(queryParams).toString()}`:"";return`${appUrl}${resolvedPath}${queryString}`}export function routeParams(routeName){const named=namedRouteRegistry.get(routeName);return named?[...named.paramNames]:[]}export function listRegisteredRoutes(){const out=[],seen=new Set;for(const key of routeMiddlewareRegistry.keys()){if(seen.has(key))continue;seen.add(key);const idx=key.indexOf(":");if(idx===-1)continue;const method=key.slice(0,idx),path=key.slice(idx+1);let routeName;for(const[n,named]of namedRouteRegistry.entries())if(named.path===path){routeName=n;break}out.push({method,path,name:routeName})}return out.sort((a,b)=>a.path.localeCompare(b.path))}const DEFAULT_MIDDLEWARE_PRIORITY=10,_warnedInvalidPriorities=new Set;function warnInvalidMiddlewarePriority(name,raw){const key=`${name}:${String(raw)}`;if(_warnedInvalidPriorities.has(key))return;_warnedInvalidPriorities.add(key);log.warn(`[Router] Middleware '${name}' declared an invalid priority (${String(raw)}). Priorities must be a finite non-negative number; falling back to default ${DEFAULT_MIDDLEWARE_PRIORITY}.`)}function adaptMiddlewareForBunRouter(middleware){if(middleware instanceof Middleware)return middleware.toRouterHandler();if(middleware&&typeof middleware==="object"&&typeof middleware.handle==="function"&&typeof middleware!=="function"){const handle=middleware.handle.bind(middleware);return async(req,next)=>{try{await handle(req)}catch(thrown){if(thrown instanceof Response)return thrown;throw thrown}return next()}}return middleware}const middlewareCache=new Map;let middlewareAliasesPromise=null;async function getMiddlewareAliases(){if(middlewareAliasesPromise)return middlewareAliasesPromise;middlewareAliasesPromise=(async()=>{try{return(await import(p.appPath("Middleware.ts"))).default||{}}catch{try{return(await import(resolveDefaultsPath("app/Middleware.ts"))).default||{}}catch{return{}}}})();return middlewareAliasesPromise}const PASCAL_SPLIT_REGEX=/[-_\s]+/,pascalCaseCache=new Map;function toPascalCase(input){if(!input)return input;const cached=pascalCaseCache.get(input);if(cached!==void 0)return cached;const out=input.split(PASCAL_SPLIT_REGEX).filter(Boolean).map((part)=>part.charAt(0).toUpperCase()+part.slice(1)).join("");pascalCaseCache.set(input,out);return out}async function resolveMiddlewareName(name){const resolved=(await getMiddlewareAliases())[name]||toPascalCase(name);log.debug(`[middleware] Resolved: ${name} \u2192 ${resolved}`);return resolved}async function loadMiddleware(name){if(middlewareCache.has(name))return middlewareCache.get(name)??null;const className=await resolveMiddlewareName(name);let userPathError;try{const userPath=p.appPath(`Middleware/${className}.ts`),handler=(await import(userPath)).default??null;if(!handler||typeof handler.handle!=="function"){log.error(`[Router] Middleware '${name}' resolved to ${userPath}, but the file has no default export with a handle() method`);middlewareCache.set(name,null);return null}middlewareCache.set(name,handler);return handler}catch(err){userPathError=err}try{const defaultPath=resolveDefaultsPath(`app/Middleware/${className}.ts`),handler=(await import(defaultPath)).default??null;if(!handler||typeof handler.handle!=="function"){log.error(`[Router] Middleware '${name}' resolved to ${defaultPath}, but the file has no default export with a handle() method`);middlewareCache.set(name,null);return null}middlewareCache.set(name,handler);return handler}catch(err){const userMsg=userPathError instanceof Error?userPathError.message:String(userPathError);log.error(`[Router] Failed to load middleware '${name}' (resolved to '${className}'). app/Middleware: ${userMsg}; defaults:`,err);return null}}export function clearMiddlewareCache(){middlewareCache.clear();middlewareAliasesPromise=null;actionSkipsCsrfCache.clear();routeHandlerKeyRegistry.clear()}export function installMiddlewareHotReload(){if(process.env.APP_ENV==="production"||process.env.NODE_ENV==="production")return()=>{};let fsWatchers=[];(async()=>{try{const fs=await import("node:fs"),targets=[p.appPath("Middleware"),p.appPath("Middleware.ts")];for(const target of targets)try{if(!fs.existsSync(target))continue;const w=fs.watch(target,{recursive:!0},()=>{log.debug("[middleware] hot-reload: clearing cache");clearMiddlewareCache()});fsWatchers.push(w)}catch{}}catch{}})();return()=>{for(const w of fsWatchers)try{w.close()}catch{}fsWatchers=[]}}const routeMiddlewareRegistry=new Map;export function clearRouteMiddlewareRegistry(){routeMiddlewareRegistry.clear()}const routeApiResponseRegistry=new Set;function parseMiddlewareName(middleware){const colonIndex=middleware.indexOf(":");if(colonIndex===-1)return{name:middleware};return{name:middleware.substring(0,colonIndex),params:middleware.substring(colonIndex+1)}}export async function findUnresolvableRouteMiddleware(){const usage=new Map;for(const[routeKey,entries]of routeMiddlewareRegistry)for(const entry of entries){const{name}=parseMiddlewareName(entry),routes=usage.get(name)??[];routes.push(routeKey);usage.set(name,routes)}if(!usage.has("csrf"))usage.set("csrf",["(auto-injected on POST/PUT/PATCH/DELETE)"]);const unresolvable=[];for(const[alias,routes]of usage){const handler=await loadMiddleware(alias);if(!handler||typeof handler.handle!=="function")unresolvable.push({alias,routes})}return unresolvable}export async function assertRouteMiddlewareResolvable(){const unresolvable=await findUnresolvableRouteMiddleware();if(unresolvable.length===0)return;const detail=unresolvable.map((u)=>`"${u.alias}" (used by ${u.routes.join(", ")})`).join("; ");throw Error(`[Router] Unresolvable middleware alias(es): ${detail}. Check the alias map in app/Middleware.ts or add app/Middleware/<Class>.ts.`)}function createMiddlewareHandler(routeKey,handler){const wrappedBase=wrapHandler(handler,!0);let actionPrefetch=null;if(typeof handler==="string"){const method=routeKey.slice(0,routeKey.indexOf(":")).toUpperCase();if(CSRF_PROTECTED_METHODS.has(method))actionPrefetch=resolveStringHandler(handler).then(()=>{return}).catch(()=>{return})}return async(req)=>{try{await parseRequestBody(req)}catch(err){const error=err instanceof Error?err:Error(String(err));return createMiddlewareErrorResponse(error,req)}const enhancedReq=enhanceRequest(req);await seedCsrfTokenForRender(enhancedReq);if(actionPrefetch)await actionPrefetch;if(routeApiResponseRegistry.has(routeKey))req._forceJson=!0;return runWithRequest(enhancedReq,async()=>{const rl=routeRateLimitRegistry.get(routeKey);if(rl)try{await enforceRateLimit(routeKey,rl.max).over(rl.windowSeconds)}catch(err){return createMiddlewareErrorResponse(err,req)}const userMiddleware=routeMiddlewareRegistry.get(routeKey)||[],method=req.method.toUpperCase(),middlewareEntries=[...userMiddleware],alreadyHasCsrf=userMiddleware.some((m)=>m==="csrf"||m.startsWith("csrf:")),routeSkipped=csrfSkipRegistry.has(routeKey),routeRequired=csrfRequireRegistry.has(routeKey),handlerKey=routeHandlerKeyRegistry.get(routeKey),actionSkipped=handlerKey?actionSkipsCsrfCache.get(handlerKey)===!0:!1;if(CSRF_PROTECTED_METHODS.has(method)&&!alreadyHasCsrf&&(routeRequired||!routeSkipped&&!actionSkipped))middlewareEntries.unshift("csrf");if(middlewareEntries.length>0){const lvl=(process.env.LOG_LEVEL||"info").toLowerCase();if(lvl!=="info"&&lvl!=="warn"&&lvl!=="error"){const schemeEnd=req.url.indexOf("://"),pathStart=schemeEnd===-1?0:req.url.indexOf("/",schemeEnd+3),q=req.url.indexOf("?",pathStart<0?0:pathStart),urlPath=pathStart<0?"/":req.url.slice(pathStart,q===-1?void 0:q);log.debug(`[middleware] Executing chain: [${middlewareEntries.join(", ")}] for ${method} ${urlPath}`)}}const resolved=[];for(const middlewareEntry of middlewareEntries){const{name:middlewareName,params}=parseMiddlewareName(middlewareEntry);if(params){enhancedReq._middlewareParams=enhancedReq._middlewareParams||{};enhancedReq._middlewareParams[middlewareName]=params}const middleware=await loadMiddleware(middlewareName);if(!middleware||typeof middleware.handle!=="function"){log.error(`[Router] Middleware '${middlewareName}' on ${routeKey} could not be resolved \u2014 failing closed`);const failClosedError=Error(`Middleware '${middlewareName}' could not be resolved`),failClosedResponse=await createErrorResponse(failClosedError,enhancedReq,{status:500});return await applyCorsIfConfigured(enhancedReq,failClosedResponse)}const rawPriority=middleware.priority;let priority=DEFAULT_MIDDLEWARE_PRIORITY;if(typeof rawPriority==="number"&&Number.isFinite(rawPriority)&&rawPriority>=0)priority=rawPriority;else if(rawPriority!==void 0)warnInvalidMiddlewarePriority(middlewareName,rawPriority);resolved.push({name:middlewareName,handler:middleware,priority})}resolved.sort((a,b)=>a.priority-b.priority);const middlewareTimings=[];for(const{name:middlewareName,handler:middleware}of resolved){const mwStart=process.hrtime.bigint();let mwTimer;try{const MIDDLEWARE_TIMEOUT_MS=30000,timeoutPromise=new Promise((_,reject)=>{mwTimer=setTimeout(()=>reject(Error(`Middleware '${middlewareName}' exceeded ${MIDDLEWARE_TIMEOUT_MS}ms`)),MIDDLEWARE_TIMEOUT_MS)});await Promise.race([middleware.handle(enhancedReq),timeoutPromise]);const elapsedMs=Number(process.hrtime.bigint()-mwStart)/1e6;middlewareTimings.push({name:middlewareName,ms:elapsedMs})}catch(error){const elapsedMs=Number(process.hrtime.bigint()-mwStart)/1e6;middlewareTimings.push({name:middlewareName,ms:elapsedMs});log.debug(`[middleware] Blocked by: ${middlewareName}`);if(error instanceof Response){try{const{_requestId:reqId,_startNs:startNs}=enhancedReq,total=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,parts=total!=null?[`total;dur=${total.toFixed(1)}`]:[];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}if(parts.length>0)error.headers.set("Server-Timing",parts.join(", "));if(reqId)error.headers.set("X-Request-ID",reqId)}catch{}return await applyCorsIfConfigured(enhancedReq,error)}const err=error instanceof Error?error:Error(String(error)),errorResponse="statusCode"in err||"status"in err?await createMiddlewareErrorResponse(err,enhancedReq):await(()=>{log.error(`[Router] Middleware '${middlewareName}' threw an unexpected error:`,err);return createErrorResponse(err,enhancedReq,{status:500})})();try{const{_requestId:reqId,_startNs:startNs}=enhancedReq,total=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,parts=total!=null?[`total;dur=${total.toFixed(1)}`]:[];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}if(parts.length>0)errorResponse.headers.set("Server-Timing",parts.join(", "));if(reqId)errorResponse.headers.set("X-Request-ID",reqId)}catch{}return await applyCorsIfConfigured(enhancedReq,errorResponse)}finally{clearTimeout(mwTimer)}}let response=await wrappedBase(enhancedReq);clearTrackedQueries();if(response){if(req.method==="GET"||req.method==="HEAD"||req.method==="OPTIONS")try{const{seedCsrfCookieIfMissing}=await import(resolveDefaultsPath("app/Middleware/Csrf.ts"));response=seedCsrfCookieIfMissing(enhancedReq,response,enhancedReq._csrfToken)}catch(err){log.warn("[router] CSRF cookie seeding failed",{error:err})}}if(response)response=await applyCorsIfConfigured(enhancedReq,response);const{_requestId:reqId,_startNs:startNs}=enhancedReq,durMs=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,setHeaders=(h)=>{if(reqId)h.set("X-Request-ID",reqId);if(durMs!=null){const parts=[`total;dur=${durMs.toFixed(1)}`];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}h.set("Server-Timing",parts.join(", "))}applySecurityHeaders(h)};if(response&&typeof response.headers?.set==="function"){if(response.status>=400&&(response.headers.get("content-type")||"").includes("json")&&reqId)try{const text=await response.clone().text(),parsed=JSON.parse(text);if(parsed&&typeof parsed==="object"){const newHeaders=new Headers(response.headers);setHeaders(newHeaders);return new Response(JSON.stringify({...parsed,request_id:reqId}),{status:response.status,statusText:response.statusText,headers:newHeaders})}}catch{}try{setHeaders(response.headers)}catch{try{const cloned=response.clone(),newHeaders=new Headers(response.headers);setHeaders(newHeaders);return new Response(cloned.body,{status:response.status,statusText:response.statusText,headers:newHeaders})}catch{}}}if(enhancedReq._compress===!0&&response)try{const{applyCompression}=await import(resolveDefaultsPath("app/Middleware/Compress.ts"));return await applyCompression(enhancedReq,response)}catch(err){log.warn(`[router] Compression failed; sending uncompressed response: ${err instanceof Error?err.message:String(err)}`)}return response})}}function createChainableRoute(routeKey){if(!routeMiddlewareRegistry.has(routeKey))routeMiddlewareRegistry.set(routeKey,[]);const routePath=routeKey.includes(":")?routeKey.substring(routeKey.indexOf(":")+1):routeKey,chain={middleware(name){const middlewareList=routeMiddlewareRegistry.get(routeKey);if(middlewareList)middlewareList.push(name);return chain},name(routeName){namedRouteRegistry.set(routeName,compileNamedRoute(routePath));return chain},skipCsrf(){csrfSkipRegistry.add(routeKey);csrfRequireRegistry.delete(routeKey);return chain},requireCsrf(){csrfRequireRegistry.add(routeKey);csrfSkipRegistry.delete(routeKey);return chain},rateLimit(max,window){if(!Number.isFinite(max)||max<=0)throw Error(`[Router] .rateLimit(): max must be a positive number, got ${String(max)}`);const windowSeconds=rateLimitWindowToSeconds(window);routeRateLimitRegistry.set(routeKey,{max:Math.floor(max),windowSeconds});return chain}};return chain}async function fileExists(path){try{return await Bun.file(path).exists()}catch{return!1}}function assertSafeHandlerPath(handlerPath){if(typeof handlerPath!=="string"||handlerPath.length===0)throw Error(`[Router] Refusing to resolve handler '${String(handlerPath)}': empty or non-string`);if(handlerPath.includes("\x00"))throw Error("[Router] Refusing to resolve handler with null byte");if(handlerPath.startsWith("/")||/^[A-Za-z]:[\\/]/.test(handlerPath))throw Error(`[Router] Refusing to resolve absolute handler path '${handlerPath}'`);if(handlerPath.split(/[/\\]/).some((s)=>s===".."))throw Error(`[Router] Refusing to resolve handler path '${handlerPath}' (contains '..' segment)`)}const _moduleImportCache=new Map;function cachedImport(fullPath){let p=_moduleImportCache.get(fullPath);if(!p){p=import(fullPath);_moduleImportCache.set(fullPath,p)}return p}const _resolvedHandlerCache=new Map;function resolveStringHandler(handlerPath){let resolved=_resolvedHandlerCache.get(handlerPath);if(!resolved){resolved=resolveStringHandlerUncached(handlerPath);_resolvedHandlerCache.set(handlerPath,resolved);resolved.catch(()=>_resolvedHandlerCache.delete(handlerPath))}return resolved}async function resolveStringHandlerUncached(handlerPath){assertSafeHandlerPath(handlerPath);let modulePath=handlerPath;modulePath=modulePath.endsWith(".ts")?modulePath.slice(0,-3):modulePath;if(modulePath.includes("Controller")){const[controllerPath,methodName="index"]=modulePath.split("@"),userPath=p.appPath(`${controllerPath}.ts`),defaultPath=resolveDefaultsPath(`app/${controllerPath}.ts`),fullPath=await fileExists(userPath)?userPath:defaultPath;try{const controller=await cachedImport(fullPath);if(!controller.default||typeof controller.default!=="function")throw Error(`Controller ${controllerPath} does not export a default class`);const instance=new controller.default;if(typeof instance[methodName]!=="function")throw Error(`Method ${methodName} not found in controller ${controllerPath}`);return async(req)=>{const result=await instance[methodName](req);return formatResult(result,req)}}catch(error){log.error(`[Router] Failed to load controller '${fullPath}':`,error);throw error}}let fullPath;if(modulePath.includes("storage/framework/orm"))fullPath=modulePath;else if(modulePath.includes("OrmAction"))fullPath=p.storagePath(`framework/actions/src/${modulePath}.ts`);else if(modulePath.includes("Actions")){const userPath=p.projectPath(`app/${modulePath}.ts`),defaultPath=resolveDefaultsPath(`app/${modulePath}.ts`);fullPath=await fileExists(userPath)?userPath:defaultPath}else{const userPath=p.appPath(`${modulePath}.ts`),defaultPath=resolveDefaultsPath(`app/${modulePath}.ts`);fullPath=await fileExists(userPath)?userPath:defaultPath}try{const action=(await cachedImport(fullPath)).default;if(!action)throw Error(`Action '${handlerPath}' has no default export`);if(typeof action.handle!=="function"){log.error(`[Router] Action '${handlerPath}' structure:`,Object.keys(action));throw Error(`Action '${handlerPath}' has no handle() method. Got: ${typeof action.handle}`)}const actionSkipsCsrf=action.skipCsrf===!0||action.csrf===!1;actionSkipsCsrfCache.set(handlerPath,actionSkipsCsrf);const actionForcesJson=action.apiResponse===!0;return async(req)=>{if(actionSkipsCsrf)req._skipCsrf=!0;if(actionForcesJson)req._forceJson=!0;req._requestValidationRules=action.validations??modelValidationRules(action.modelDefinition??action.model);try{if(action.validations){const validationResult=await validateActionInput(req,action.validations);if(!validationResult.valid)return Response.json({error:"Validation failed",errors:validationResult.errors},{status:422})}if(typeof action.authorize==="function"){const auth=await action.authorize(req);if(auth instanceof Response)return auth;if(auth===!1)return Response.json({error:"Forbidden"},{status:403})}if(typeof action.before==="function"){const pre=await action.before(req);if(pre instanceof Response)return pre}const result=await action.handle(req);return formatResult(result,req)}catch(handleError){report(handleError,{label:`[Router] action.handle() for '${handlerPath}'`});throw handleError}}}catch(importError){log.error(`[Router] Failed to import action '${fullPath}':`,importError);throw importError}}export async function validateActionInput(req,validations){const errors={},input=await getRequestInput(req,validations);for(const[field,validation]of Object.entries(validations)){const value=input[field];let result;try{result=validation.rule.validate(value)}catch{result={valid:!1,errors:[{message:`${field} validation failed`}]}}if(!result.valid){const fieldErrors=[],label=field.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,(c)=>c.toUpperCase()),decorate=(msg)=>msg.toLowerCase().startsWith(field.toLowerCase())||msg.includes(label)?msg:`${label} ${msg}`;if(result.errors&&result.errors.length>0)if(validation.message){const firstMessage=result.errors[0]?.message??"";fieldErrors.push(typeof validation.message==="string"?validation.message:validation.message[field]||decorate(firstMessage))}else result.errors.forEach((err)=>fieldErrors.push(decorate(err.message)));else fieldErrors.push(validation.message?typeof validation.message==="string"?validation.message:`${label} is invalid`:`${label} is invalid`);errors[field]=fieldErrors}}return{valid:Object.keys(errors).length===0,errors}}function modelValidationRules(model){if(!model?.attributes||typeof model.attributes!=="object")return;const rules={};for(const[field,attribute]of Object.entries(model.attributes)){const validation=attribute?.validation;if(validation?.rule)rules[field]=validation}return Object.keys(rules).length>0?rules:void 0}async function getRequestInput(req,validations){const input={},q=req.query;if(q)for(const key in q)input[key]=q[key];else new URL(req.url).searchParams.forEach((value,key)=>{input[key]=value});if(req.params)Object.assign(input,req.params);if(req.jsonBody&&typeof req.jsonBody==="object")Object.assign(input,req.jsonBody);else if(req.formBody&&typeof req.formBody==="object")Object.assign(input,req.formBody);if(typeof req.allFiles==="function")try{const files=req.allFiles();for(const key of Object.keys(files??{}))if(!(key in input))input[key]=files[key]}catch{}if(!validations)return input;for(const[field,validation]of Object.entries(validations)){const value=input[field];if(typeof value!=="string")continue;const validatorName=validation.rule?.name;if(validatorName==="number"){const n=Number(value);if(Number.isFinite(n))input[field]=n}else if(validatorName==="boolean"){if(value==="true"||value==="1")input[field]=!0;else if(value==="false"||value==="0")input[field]=!1}}return input}function formatResult(result,req){if(result instanceof Response)return result;if(result instanceof ReadableStream)return new Response(result,{headers:{"Content-Type":"application/octet-stream"}});const apiShaped=req._forceJson===!0||isApiRequest(req);if(result===null||result===void 0)return apiShaped?new Response(null,{status:204}):new Response("",{status:200});if(typeof result==="object"){const linkHeader=buildPaginatorLinkHeader(result);if(linkHeader)return Response.json(result,{headers:{Link:linkHeader}});return Response.json(result)}if(apiShaped)return Response.json(result);return new Response(String(result),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}function buildPaginatorLinkHeader(value){if(!isPaginator(value)&&!isSimplePaginator(value)&&!isCursorPaginator(value))return null;const v=value,parts=[];if(v.prev_page_url)parts.push(`<${v.prev_page_url}>; rel="prev"`);if(v.next_page_url)parts.push(`<${v.next_page_url}>; rel="next"`);if(v.first_page_url)parts.push(`<${v.first_page_url}>; rel="first"`);if(v.last_page_url)parts.push(`<${v.last_page_url}>; rel="last"`);return parts.length>0?parts.join(", "):null}export function stream(source,options={}){const baseHeaders={};if(options.type==="sse"){baseHeaders["Content-Type"]="text/event-stream; charset=utf-8";baseHeaders["Cache-Control"]="no-cache";baseHeaders.Connection="keep-alive"}else if(options.type==="ndjson")baseHeaders["Content-Type"]="application/x-ndjson; charset=utf-8";else baseHeaders["Content-Type"]=options.contentType??"application/octet-stream";const body=source instanceof ReadableStream?source:new ReadableStream({async start(controller){try{for await(const chunk of source)controller.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):chunk);controller.close()}catch(err){controller.error(err)}}}),merged=new Headers(baseHeaders);if(options.headers)new Headers(options.headers).forEach((value,key)=>merged.set(key,value));return new Response(body,{status:options.status??200,headers:merged})}function getAllInputFor(req){const cached=req._allInputCache;if(cached)return cached;const input={},query=req.query;if(query)for(const key in query)input[key]=query[key];if(req.jsonBody&&typeof req.jsonBody==="object")Object.assign(input,req.jsonBody);if(req.formBody&&typeof req.formBody==="object")Object.assign(input,req.formBody);if(req.params&&typeof req.params==="object")Object.assign(input,req.params);req._allInputCache=input;return input}function flashInputFor(req,keys){const input=getAllInputFor(req);req._oldInput=keys?Object.fromEntries(keys.filter((key)=>(key in input)).map((key)=>[key,input[key]])):{...input}}const REQUEST_METHODS={get(key,defaultValue){const value=getAllInputFor(this)[key];return value!==void 0?value:defaultValue},input(key,defaultValue){const value=getAllInputFor(this)[key];return value!==void 0?value:defaultValue},all(){return getAllInputFor(this)},only(keys){const input=getAllInputFor(this),result={};for(const key of keys)if(key in input)result[key]=input[key];return result},except(keys){const result={...getAllInputFor(this)};for(const key of keys)delete result[key];return result},has(key){const input=getAllInputFor(this);if(Array.isArray(key))return key.every((k)=>(k in input)&&input[k]!==void 0);return key in input&&input[key]!==void 0},hasAny(keys){const input=getAllInputFor(this);return keys.some((k)=>(k in input)&&input[k]!==void 0)},filled(key){const input=getAllInputFor(this),isFilled=(k)=>{const value=input[k];return value!==void 0&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0)};if(Array.isArray(key))return key.every(isFilled);return isFilled(key)},missing(key){const input=getAllInputFor(this);if(Array.isArray(key))return key.every((k)=>!(k in input)||input[k]===void 0);return!(key in input)||input[key]===void 0},merge(data){Object.assign(getAllInputFor(this),data)},keys(){return Object.keys(getAllInputFor(this))},string(key,defaultValue=""){const value=getAllInputFor(this)[key];return value!==void 0&&value!==null?String(value):defaultValue},integer(key,defaultValue=0){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return defaultValue;if(typeof value==="number")return Number.isFinite(value)?Math.trunc(value):defaultValue;const str=String(value).trim();if(!/^-?\d+$/.test(str))return defaultValue;const parsed=Number.parseInt(str,10);return Number.isFinite(parsed)?parsed:defaultValue},float(key,defaultValue=0){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return defaultValue;if(typeof value==="number")return Number.isFinite(value)?value:defaultValue;const str=String(value).trim();if(!/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(str))return defaultValue;const parsed=Number.parseFloat(str);return Number.isFinite(parsed)?parsed:defaultValue},boolean(key,defaultValue=!1){const value=getAllInputFor(this)[key];if(value===void 0||value===null)return defaultValue;if(typeof value==="boolean")return value;if(value==="true"||value==="1"||value===1)return!0;if(value==="false"||value==="0"||value===0)return!1;return defaultValue},array(key){const value=getAllInputFor(this)[key];if(Array.isArray(value))return value;return value!==void 0&&value!==null?[value]:[]},date(key){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return null;const parsed=new Date(value);return Number.isNaN(parsed.getTime())?null:parsed},enum(key,enumType){const value=getAllInputFor(this)[key];if(value===void 0||value===null)return null;if(Object.values(enumType).includes(value))return value;const enumKey=String(value);return enumKey in enumType?enumType[enumKey]:null},collect(key){const value=getAllInputFor(this)[key];if(Array.isArray(value))return collect(value);return collect(value===void 0||value===null?[]:[value])},whenHas(key,callback,defaultCallback){const input=getAllInputFor(this);if(key in input&&input[key]!==void 0)callback(input[key]);else defaultCallback?.()},whenFilled(key,callback,defaultCallback){const value=getAllInputFor(this)[key];if(value!==void 0&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0))callback(value);else defaultCallback?.()},isValue(key,value){return getAllInputFor(this)[key]===value},async validate(rules,messages={}){const selectedRules=rules??this._requestValidationRules;if(!selectedRules||Object.keys(selectedRules).length===0){const input=getAllInputFor(this);this._validatedInput=input;return input}const normalized={};for(const[field,definition]of Object.entries(selectedRules)){if(typeof definition==="string")throw TypeError(`String validation rules are not supported for "${field}". Use schema validators.`);if(definition&&typeof definition==="object"&&"rule"in definition){const message=messages[field];normalized[field]=message?{...definition,message}:definition}else normalized[field]=definition}const{validate}=await import("@stacksjs/validation"),validated=await validate(this,normalized);this._validatedInput=validated;return validated},getValidated(){return this._validatedInput??{}},safe(){const data=this._validatedInput??{};return{all:()=>({...data}),get:(key,defaultValue)=>(key in data)?data[key]:defaultValue,only:(keys)=>Object.fromEntries(keys.filter((key)=>(key in data)).map((key)=>[key,data[key]])),except:(keys)=>Object.fromEntries(Object.entries(data).filter(([key])=>!keys.includes(key)))}},old(key,defaultValue){return this._oldInput?.[key]??defaultValue},flashInput(keys){flashInputFor(this,keys)},flashInputOnly(keys){flashInputFor(this,keys)},flashInputExcept(keys){const input=getAllInputFor(this);this._oldInput=Object.fromEntries(Object.entries(input).filter(([key])=>!keys.includes(key)))},file(key){const file=(this.files||{})[key];if(!file)return null;const rawFile=Array.isArray(file)?file[0]:file;return rawFile?new UploadedFile(rawFile):null},getFiles(key){const file=(this.files||{})[key];if(!file)return[];return(Array.isArray(file)?file:[file]).map((f)=>new UploadedFile(f))},hasFile(key){const files=this.files||{};return key in files&&files[key]!==void 0},allFiles(){const files=this.files||{},result={};for(const[key,value]of Object.entries(files))if(Array.isArray(value))result[key]=value.map((f)=>new UploadedFile(f));else result[key]=new UploadedFile(value);return result},getParams(){return{...this.params}},isEmpty(){return Object.keys(getAllInputFor(this)).length===0},browser(){return this.headers.get("sec-ch-ua")||this.headers.get("user-agent")},ipForRateLimit(){const ip=this.ip;if(typeof ip==="function")return ip.call(this)||null;return typeof ip==="string"&&ip?ip:null},getMethod(){return this.method.toUpperCase()},async user(){return this._authenticatedUser},async userToken(){return this._currentAccessToken},async tokenCan(ability){if(typeof ability!=="string"||ability.length===0)return!1;const token=this._currentAccessToken;if(!token||typeof token!=="object")return!1;if(!Array.isArray(token.abilities))return!1;if(token.abilities.includes("*"))return!0;return token.abilities.includes(ability)},async tokenCant(ability){return!await this.tokenCan(ability)},async can(ability,...args){if(typeof ability!=="string"||ability.length===0)return!1;const{Gate}=await import("@stacksjs/auth"),user=this._authenticatedUser??null;return Gate.allows(ability,user,...args)},async cannot(ability,...args){return!await this.can(ability,...args)},async authorize(ability,...args){const{Gate}=await import("@stacksjs/auth"),user=this._authenticatedUser??null;await Gate.authorize(ability,user,...args)}};async function seedCsrfTokenForRender(req){const method=req.method?.toUpperCase?.()??"GET";if(method!=="GET"&&method!=="HEAD")return;const cookieHeader=req.headers?.get?.("cookie")??"";if(cookieHeader.includes("X-CSRF-Token=")||cookieHeader.includes("csrf-token="))return;try{const{generateCsrfToken,CSRF_COOKIE_NAME}=await import(resolveDefaultsPath("app/Middleware/Csrf.ts")),token=generateCsrfToken();req._csrfToken=token;try{const merged=cookieHeader?`${cookieHeader}; ${CSRF_COOKIE_NAME}=${token}`:`${CSRF_COOKIE_NAME}=${token}`;req.headers.set("cookie",merged)}catch{}}catch{}}export function enhanceRequest(req){applyRequestEnhancements(req,req.params||{});let query=req.query;if(!query){const url=new URL(req.url);query={};url.searchParams.forEach((value,key)=>{query[key]=value});req.query=query}Object.assign(req,REQUEST_METHODS);return req}function wrapHandler(handler,skipParsing=!1){if(typeof handler==="string"){const handlerPath=handler;return async(req)=>{try{if(!skipParsing){await parseRequestBody(req);req=enhanceRequest(req)}return await(await resolveStringHandler(handlerPath))(req)}catch(error){report(error,{label:`[Router] ${handlerPath}`});const rawStatus=error?.statusCode??error?.status,status=typeof rawStatus==="number"&&Number.isInteger(rawStatus)&&rawStatus>=400&&rawStatus<600?rawStatus:void 0;return await createErrorResponse(error instanceof Error?error:Error(String(error)),req,{handlerPath,status})}}}const fn=handler;return async(req)=>{const result=await fn(req);return formatResult(result,req)}}async function parseRequestBody(req){if(req._bodyParsed)return;req._bodyParsed=!0;const contentType=req.headers.get("content-type")||"";try{if(JSON_CONTENT_TYPE.test(contentType)){const raw=await req.clone().text();req._rawBody=raw;if(raw.length===0)req.jsonBody={};else try{const body=JSON.parse(raw);req.jsonBody=body&&typeof body==="object"?body:{}}catch(parseErr){const message=parseErr instanceof Error?parseErr.message:"Invalid JSON",{HttpError}=await import("@stacksjs/error-handling");throw new HttpError(400,`Invalid JSON body: ${message}`)}}else if(contentType.includes("application/x-www-form-urlencoded")){const text=await req.clone().text(),params=new URLSearchParams(text),formBody={};params.forEach((value,key)=>{formBody[key]=value});req.formBody=formBody}else if(contentType.includes("multipart/form-data")){const formData=await req.clone().formData(),formBody={},files={};formData.forEach((value,key)=>{if(value instanceof File)if(files[key])if(Array.isArray(files[key]))files[key].push(value);else files[key]=[files[key],value];else files[key]=value;else formBody[key]=value});Reflect.set(req,"formBody",formBody);Reflect.set(req,"files",files)}}catch(e){if(typeof(e?.status??e?.statusCode)==="number")throw e;log.debug("[stacks-router] Body parsing failed:",e)}}export function createStacksRouter(config={}){const bunRouter=new Router({verbose:config.verbose??!1});let currentPrefix="",currentGroupMiddleware=[],currentGroupApiResponse=!1;function registerRoute(method,path,_handler){const fullPath=currentPrefix+path,routeKey=`${method}:${fullPath}`;log.debug(`[router] ${method} ${fullPath} \u2192 ${typeof _handler==="string"?_handler:"function"}`);if(currentGroupMiddleware.length>0)routeMiddlewareRegistry.set(routeKey,[...currentGroupMiddleware]);if(currentGroupApiResponse)routeApiResponseRegistry.add(routeKey);if(typeof _handler==="string")routeHandlerKeyRegistry.set(routeKey,_handler);return{fullPath,routeKey}}const stacksRouter={bunRouter,get routes(){return bunRouter.routes},get(path,handler){const{fullPath,routeKey}=registerRoute("GET",path,handler);bunRouter.get(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},post(path,handler){const{fullPath,routeKey}=registerRoute("POST",path,handler);bunRouter.post(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},put(path,handler){const{fullPath,routeKey}=registerRoute("PUT",path,handler);bunRouter.put(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},patch(path,handler){const{fullPath,routeKey}=registerRoute("PATCH",path,handler);bunRouter.patch(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},delete(path,handler){const{fullPath,routeKey}=registerRoute("DELETE",path,handler);bunRouter.delete(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},options(path,handler){const{fullPath,routeKey}=registerRoute("OPTIONS",path,handler);bunRouter.options(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},group(options,callback){const previousPrefix=currentPrefix,previousMiddleware=[...currentGroupMiddleware],previousApiResponse=currentGroupApiResponse;if(options.prefix)currentPrefix=previousPrefix+options.prefix;const middlewareList=options.middleware?Array.isArray(options.middleware)?options.middleware:[options.middleware]:void 0;if(middlewareList)currentGroupMiddleware=[...currentGroupMiddleware,...middlewareList];if(options.apiResponse===!0)currentGroupApiResponse=!0;log.debug(`[router] Entering group: prefix=${options.prefix||"/"} middleware=[${middlewareList?.join(", ")||""}]${currentGroupApiResponse?" apiResponse=true":""}`);const result=callback();if(result instanceof Promise)return result.then(()=>{currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;return stacksRouter}).catch((err)=>{currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;throw err});currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;return stacksRouter},resource(name,handler,options){const actions=["index","store","show","update","destroy"],activeActions=options?.only?actions.filter((a)=>options.only.includes(a)):options?.except?actions.filter((a)=>!options.except.includes(a)):actions,handlerBase=handler.replace(/Action$/,"");log.debug(`[router] Resource: /${name} \u2192 ${handler} [${activeActions.join(", ")}]`);const registerResourceRoutes=()=>{for(const action of activeActions)switch(action){case"index":stacksRouter.get(`/${name}`,`${handlerBase}IndexAction`);break;case"store":stacksRouter.post(`/${name}`,`${handlerBase}StoreAction`);break;case"show":stacksRouter.get(`/${name}/:id`,`${handlerBase}ShowAction`);break;case"update":stacksRouter.put(`/${name}/:id`,`${handlerBase}UpdateAction`);break;case"destroy":stacksRouter.delete(`/${name}/:id`,`${handlerBase}DestroyAction`);break}};if(options?.middleware)stacksRouter.group({middleware:options.middleware},registerResourceRoutes);else registerResourceRoutes();return stacksRouter},match(methods,path,handler){log.debug(`[router] Match: [${methods.join(", ")}] ${path} \u2192 ${typeof handler==="string"?handler:"function"}`);for(const method of methods){const m=method.toUpperCase(),{fullPath,routeKey}=registerRoute(m,path,handler),wrappedHandler=createMiddlewareHandler(routeKey,handler);switch(m){case"GET":bunRouter.get(fullPath,wrappedHandler);break;case"POST":bunRouter.post(fullPath,wrappedHandler);break;case"PUT":bunRouter.put(fullPath,wrappedHandler);break;case"PATCH":bunRouter.patch(fullPath,wrappedHandler);break;case"DELETE":bunRouter.delete(fullPath,wrappedHandler);break;case"OPTIONS":bunRouter.options(fullPath,wrappedHandler);break}}return createChainableRoute(`${methods[0]}:${currentPrefix}${path}`)},health(){bunRouter.get("/api/health",async()=>{const health=await checkApplicationHealth();return Response.json(health,{status:health.status==="healthy"?200:503})});bunRouter.get("/__routes",(req)=>{if(!isExposeRoutesAuthorized(req))return Response.json({error:"disabled"},{status:404});return Response.json(listRegisteredRoutes())});bunRouter.get("/__storage/:path",async(req)=>{const url=new URL(req.url),token=url.searchParams.get("token"),params=req.params,rawPath=params?.path?decodeURIComponent(params.path):decodeURIComponent(url.pathname.replace(/^\/__storage\//,""));if(!token||typeof rawPath!=="string"||rawPath.length===0)return new Response("Forbidden",{status:403});const{verifySignedStorageToken,Storage}=await import("@stacksjs/storage");if(!verifySignedStorageToken(token,rawPath).valid)return new Response("Forbidden",{status:403});try{const adapter=Storage.disk();if(!await adapter.fileExists(rawPath))return new Response("Not Found",{status:404});const buf=await adapter.readToBuffer(rawPath),mime=await adapter.mimeType(rawPath).catch(()=>"application/octet-stream");return new Response(buf,{status:200,headers:{"Content-Type":mime,"Cache-Control":"private, max-age=60","X-Content-Type-Options":"nosniff"}})}catch(err){log.error("[storage] signed-url fetch failed:",err);return new Response("Internal Error",{status:500})}});bunRouter.get("/__openapi.json",async(req)=>{if(!isExposeRoutesAuthorized(req))return Response.json({error:"disabled"},{status:404});try{const{generateOpenApi}=await import("@stacksjs/api"),spec=await generateOpenApi({write:!1,portable:!1});return Response.json(spec)}catch(err){return Response.json({error:"OpenAPI generation failed",message:err instanceof Error?err.message:String(err)},{status:500})}});return stacksRouter},use(middleware){const adapted=adaptMiddlewareForBunRouter(middleware);bunRouter.globalMiddleware.push(adapted);return stacksRouter},async serve(options={}){warnOnMultipleRouterInstances();return bunRouter.serve(options)},async handleRequest(req){return bunRouter.handleRequest(req)},getAllowedMethods(pathname,domain){return bunRouter.getAllowedMethods(pathname,domain)},async register(routePath,options){log.debug(`[router] Register: ${routePath} prefix=${options?.prefix||"none"}`);const callback=async()=>{await import(routePath)};if(options?.prefix||options?.middleware)await stacksRouter.group({prefix:options.prefix,middleware:options.middleware},callback);else await callback();return stacksRouter},async importRoutes(){log.debug("[router] Loading user routes from registry...");try{const{loadRoutes}=await import("./route-loader"),{appPath}=await import("@stacksjs/path"),routeRegistry=(await import(appPath("Routes.ts"))).default;await loadRoutes(routeRegistry)}catch(error){log.error("Failed to load route registry:",error);throw error}log.debug("[router] Loading ORM routes...");const ormRoutesCandidates=[p.frameworkPath("orm/routes.ts"),p.frameworkPath("core/orm/routes.ts")];let ormRoutesLoaded=!1;for(const candidate of ormRoutesCandidates)try{if(await Bun.file(candidate).exists()){await import(candidate);ormRoutesLoaded=!0;break}}catch(error){log.warn(`[router] ORM routes candidate failed to load, falling back to next: ${candidate}
5
- `,error)}if(!ormRoutesLoaded)log.warn("[router] No ORM routes candidate loaded \u2014 model useApi endpoints are unavailable.");log.debug("[router] Loading discovered package routes...");try{await stacksRouter.loadDiscoveredRoutes()}catch(error){log.debug("Package route discovery skipped:",error)}await assertRouteMiddlewareResolvable()},async loadDiscoveredRoutes(){try{const manifestPath=p.storagePath("framework/discovered-packages.json"),file=Bun.file(manifestPath);if(!await file.exists())return;const packages=(await file.json())?.packages;if(!packages)return;const pantryDir=p.projectPath("pantry");for(const[pkgName,meta]of Object.entries(packages)){const routes=meta?.routes;if(!routes)continue;const routeList=Array.isArray(routes)?routes:[routes],pkgDir=`${pantryDir}/${pkgName}`;for(const routeFile of routeList){log.debug(`[router] Discovered route: ${pkgName} \u2192 ${routeFile}`);const fullPath=routeFile.startsWith("/")?routeFile:`${pkgDir}/${routeFile}`,prefix=meta?.routePrefix,middleware=meta?.routeMiddleware;try{await stacksRouter.register(fullPath,{prefix,middleware})}catch(err){log.warn(`Failed to load routes from package '${pkgName}': ${err}`)}}}}catch{}}};return stacksRouter}const ROUTE_SINGLETON_KEY=Symbol.for("@stacksjs/router:route-singleton");export const route=globalThis[ROUTE_SINGLETON_KEY]??=createStacksRouter();let routesLoadPromise=null,routingContextRunner=null;async function getRoutingContextRunner(){if(!routingContextRunner)try{const{withRoutingContext}=await import("@stacksjs/database");routingContextRunner=typeof withRoutingContext==="function"?withRoutingContext:(fn)=>fn()}catch{routingContextRunner=(fn)=>fn()}return routingContextRunner}export async function serverResponse(request,_body){return(await getRoutingContextRunner())(()=>handleServerRequest(request))}async function handleServerRequest(request){if(!routesLoadPromise){log.debug("[router] Loading routes for first time...");routesLoadPromise=route.importRoutes().catch((err)=>{routesLoadPromise=null;throw err})}await routesLoadPromise;const response=await route.handleRequest(request);if(response.status===404&&response.headers.get("content-type")?.includes("json"))try{const body=await response.clone().json();if(body?.message==="Not Found"||body?.error==="Not Found"){const url=new URL(request.url),enriched={...body,path:url.pathname,method:request.method};return new Response(JSON.stringify(enriched),{status:404,headers:response.headers})}}catch{}return response}export async function serve(options={}){return route.serve(options)}
4
+ ${paths}`)}return!0}let __defaultsPkgRoot;function resolveDefaultsPath(rel){const vendored=p.storagePath(`framework/defaults/${rel}`);if(existsSync(vendored))return vendored;if(__defaultsPkgRoot===void 0)try{const pkgJson=Bun.resolveSync("@stacksjs/defaults/package.json",process.cwd());__defaultsPkgRoot=pkgJson.slice(0,pkgJson.lastIndexOf("/"))}catch{__defaultsPkgRoot=null}return __defaultsPkgRoot?`${__defaultsPkgRoot}/${rel}`:vendored}import{runWithRequest}from"./request-context";import{isApiRequest,JSON_CONTENT_TYPE}from"./api-shape";import{clearTrackedQueries,createErrorResponse,createMiddlewareErrorResponse}from"./error-handler";import{rateLimit as enforceRateLimit}from"./rate-limit";import{applySecurityHeaders}from"./security-headers";import{isCursorPaginator,isPaginator,isSimplePaginator}from"@stacksjs/orm";const csrfSkipRegistry=new Set,csrfRequireRegistry=new Set,routeRateLimitRegistry=new Map;function rateLimitWindowToSeconds(window){if(typeof window==="number"){if(!Number.isFinite(window)||window<=0)throw Error(`[Router] .rateLimit(): window must be a positive number of seconds, got ${window}`);return Math.floor(window)}switch(window){case"second":return 1;case"minute":return 60;case"hour":return 3600;case"day":return 86400;default:throw Error(`[Router] .rateLimit(): unknown period '${String(window)}'`)}}class BoundedMap{max;map=new Map;constructor(max){this.max=max}get(key){return this.map.get(key)}has(key){return this.map.has(key)}set(key,value){if(this.map.has(key))this.map.delete(key);this.map.set(key,value);if(this.map.size>this.max){const oldest=this.map.keys().next().value;if(oldest!==void 0)this.map.delete(oldest)}return this}delete(key){return this.map.delete(key)}clear(){this.map.clear()}get size(){return this.map.size}}function isExposeRoutesAuthorized(req){const flag=process.env.STACKS_EXPOSE_ROUTES??"";if(!flag)return!((process.env.APP_ENV??"").toLowerCase()==="production"||process.env.NODE_ENV==="production");if(flag==="1")return!((process.env.APP_ENV??"").toLowerCase()==="production"||process.env.NODE_ENV==="production");const url=new URL(req.url),submitted=req.headers.get("x-stacks-routes-token")||req.headers.get("X-Stacks-Routes-Token")||url.searchParams.get("token")||"";if(typeof submitted!=="string"||submitted.length===0||submitted.length!==flag.length)return!1;try{return timingSafeEqual(Buffer.from(submitted),Buffer.from(flag))}catch{return!1}}async function applyCorsIfConfigured(req,response){if(!req._corsConfig||!response)return response;try{const{applyCorsHeaders}=await import(resolveDefaultsPath("app/Middleware/Cors.ts"));return applyCorsHeaders(req,response,req._corsConfig)}catch(err){log.warn("[router] CORS header injection failed",{error:err});return response}}const ACTION_CACHE_MAX=5000,actionSkipsCsrfCache=new BoundedMap(ACTION_CACHE_MAX),routeHandlerKeyRegistry=new BoundedMap(ACTION_CACHE_MAX),CSRF_PROTECTED_METHODS=new Set(["POST","PUT","PATCH","DELETE"]),namedRouteRegistry=new Map;function compileNamedRoute(path){const paramNames=extractRouteParamNames(path),colonRegex=new Map;for(const name of paramNames)colonRegex.set(name,new RegExp(`(^|/):${name}(?=$|/)`,"g"));return{path,paramNames,colonRegex}}function extractRouteParamNames(routePath){const names=new Set;for(const m of routePath.matchAll(/\{(\w+)\}/g))if(m[1])names.add(m[1]);for(const m of routePath.matchAll(/(?:^|\/):(\w+)(?=$|\/)/g))if(m[1])names.add(m[1]);return[...names]}export function url(routeName,params={}){const named=namedRouteRegistry.get(routeName);if(!named)throw Error(`Route '${routeName}' is not defined. Available routes: ${[...namedRouteRegistry.keys()].join(", ")}`);const missing=named.paramNames.filter((name)=>!(name in params)||params[name]===void 0);if(missing.length>0)throw Error(`url('${routeName}'): missing required path param${missing.length>1?"s":""} [${missing.join(", ")}] for path '${named.path}'. Pass them as the second argument: url('${routeName}', { ${named.paramNames.join(", ")} })`);let appUrl;try{appUrl=process.env.APP_URL||"https://localhost"}catch{appUrl="https://localhost"}appUrl=appUrl.replace(/\/$/,"");if(!appUrl.startsWith("http"))appUrl=`https://${appUrl}`;let resolvedPath=named.path;const queryParams={};for(const[key,value]of Object.entries(params)){const curly=`{${key}}`;if(resolvedPath.includes(curly))resolvedPath=resolvedPath.replaceAll(curly,encodeURIComponent(String(value)));else{const re=named.colonRegex.get(key);if(re&&re.test(resolvedPath)){re.lastIndex=0;resolvedPath=resolvedPath.replace(re,`$1${encodeURIComponent(String(value))}`)}else queryParams[key]=String(value)}}const queryString=Object.keys(queryParams).length>0?`?${new URLSearchParams(queryParams).toString()}`:"";return`${appUrl}${resolvedPath}${queryString}`}export function routeParams(routeName){const named=namedRouteRegistry.get(routeName);return named?[...named.paramNames]:[]}export function listRegisteredRoutes(){const out=[],seen=new Set;for(const key of routeMiddlewareRegistry.keys()){if(seen.has(key))continue;seen.add(key);const idx=key.indexOf(":");if(idx===-1)continue;const method=key.slice(0,idx),path=key.slice(idx+1);let routeName;for(const[n,named]of namedRouteRegistry.entries())if(named.path===path){routeName=n;break}out.push({method,path,name:routeName})}return out.sort((a,b)=>a.path.localeCompare(b.path))}const DEFAULT_MIDDLEWARE_PRIORITY=10,_warnedInvalidPriorities=new Set;function warnInvalidMiddlewarePriority(name,raw){const key=`${name}:${String(raw)}`;if(_warnedInvalidPriorities.has(key))return;_warnedInvalidPriorities.add(key);log.warn(`[Router] Middleware '${name}' declared an invalid priority (${String(raw)}). Priorities must be a finite non-negative number; falling back to default ${DEFAULT_MIDDLEWARE_PRIORITY}.`)}function adaptMiddlewareForBunRouter(middleware){if(middleware instanceof Middleware)return middleware.toRouterHandler();if(middleware&&typeof middleware==="object"&&typeof middleware.handle==="function"&&typeof middleware!=="function"){const handle=middleware.handle.bind(middleware);return async(req,next)=>{try{await handle(req)}catch(thrown){if(thrown instanceof Response)return thrown;throw thrown}return next()}}return middleware}const middlewareCache=new Map;let middlewareAliasesPromise=null;async function getMiddlewareAliases(){if(middlewareAliasesPromise)return middlewareAliasesPromise;middlewareAliasesPromise=(async()=>{try{return(await import(p.appPath("Middleware.ts"))).default||{}}catch{try{return(await import(resolveDefaultsPath("app/Middleware.ts"))).default||{}}catch{return{}}}})();return middlewareAliasesPromise}const PASCAL_SPLIT_REGEX=/[-_\s]+/,pascalCaseCache=new Map;function toPascalCase(input){if(!input)return input;const cached=pascalCaseCache.get(input);if(cached!==void 0)return cached;const out=input.split(PASCAL_SPLIT_REGEX).filter(Boolean).map((part)=>part.charAt(0).toUpperCase()+part.slice(1)).join("");pascalCaseCache.set(input,out);return out}async function resolveMiddlewareName(name){const resolved=(await getMiddlewareAliases())[name]||toPascalCase(name);log.debug(`[middleware] Resolved: ${name} \u2192 ${resolved}`);return resolved}async function loadMiddleware(name){if(middlewareCache.has(name))return middlewareCache.get(name)??null;const className=await resolveMiddlewareName(name);let userPathError;try{const userPath=p.appPath(`Middleware/${className}.ts`),handler=(await import(userPath)).default??null;if(!handler||typeof handler.handle!=="function"){log.error(`[Router] Middleware '${name}' resolved to ${userPath}, but the file has no default export with a handle() method`);middlewareCache.set(name,null);return null}middlewareCache.set(name,handler);return handler}catch(err){userPathError=err}try{const defaultPath=resolveDefaultsPath(`app/Middleware/${className}.ts`),handler=(await import(defaultPath)).default??null;if(!handler||typeof handler.handle!=="function"){log.error(`[Router] Middleware '${name}' resolved to ${defaultPath}, but the file has no default export with a handle() method`);middlewareCache.set(name,null);return null}middlewareCache.set(name,handler);return handler}catch(err){const userMsg=userPathError instanceof Error?userPathError.message:String(userPathError);log.error(`[Router] Failed to load middleware '${name}' (resolved to '${className}'). app/Middleware: ${userMsg}; defaults:`,err);return null}}export function clearMiddlewareCache(){middlewareCache.clear();middlewareAliasesPromise=null;actionSkipsCsrfCache.clear();routeHandlerKeyRegistry.clear()}export function installMiddlewareHotReload(){if(process.env.APP_ENV==="production"||process.env.NODE_ENV==="production")return()=>{};let fsWatchers=[];(async()=>{try{const fs=await import("node:fs"),targets=[p.appPath("Middleware"),p.appPath("Middleware.ts")];for(const target of targets)try{if(!fs.existsSync(target))continue;const w=fs.watch(target,{recursive:!0},()=>{log.debug("[middleware] hot-reload: clearing cache");clearMiddlewareCache()});fsWatchers.push(w)}catch{}}catch{}})();return()=>{for(const w of fsWatchers)try{w.close()}catch{}fsWatchers=[]}}const routeMiddlewareRegistry=new Map;export function clearRouteMiddlewareRegistry(){routeMiddlewareRegistry.clear()}const routeApiResponseRegistry=new Set;function parseMiddlewareName(middleware){const colonIndex=middleware.indexOf(":");if(colonIndex===-1)return{name:middleware};return{name:middleware.substring(0,colonIndex),params:middleware.substring(colonIndex+1)}}export async function findUnresolvableRouteMiddleware(){const usage=new Map;for(const[routeKey,entries]of routeMiddlewareRegistry)for(const entry of entries){const{name}=parseMiddlewareName(entry),routes=usage.get(name)??[];routes.push(routeKey);usage.set(name,routes)}if(!usage.has("csrf"))usage.set("csrf",["(auto-injected on POST/PUT/PATCH/DELETE)"]);const unresolvable=[];for(const[alias,routes]of usage){const handler=await loadMiddleware(alias);if(!handler||typeof handler.handle!=="function")unresolvable.push({alias,routes})}return unresolvable}export async function assertRouteMiddlewareResolvable(){const unresolvable=await findUnresolvableRouteMiddleware();if(unresolvable.length===0)return;const detail=unresolvable.map((u)=>`"${u.alias}" (used by ${u.routes.join(", ")})`).join("; ");throw Error(`[Router] Unresolvable middleware alias(es): ${detail}. Check the alias map in app/Middleware.ts or add app/Middleware/<Class>.ts.`)}function createMiddlewareHandler(routeKey,handler){const wrappedBase=wrapHandler(handler,!0);let actionPrefetch=null;if(typeof handler==="string"){const method=routeKey.slice(0,routeKey.indexOf(":")).toUpperCase();if(CSRF_PROTECTED_METHODS.has(method))actionPrefetch=resolveStringHandler(handler).then(()=>{return}).catch(()=>{return})}return async(req)=>{try{await parseRequestBody(req)}catch(err){const error=err instanceof Error?err:Error(String(err));return createMiddlewareErrorResponse(error,req)}const enhancedReq=enhanceRequest(req);await seedCsrfTokenForRender(enhancedReq);if(actionPrefetch)await actionPrefetch;if(routeApiResponseRegistry.has(routeKey))req._forceJson=!0;return runWithRequest(enhancedReq,async()=>{const rl=routeRateLimitRegistry.get(routeKey);if(rl)try{await enforceRateLimit(routeKey,rl.max).over(rl.windowSeconds)}catch(err){return createMiddlewareErrorResponse(err,req)}const userMiddleware=routeMiddlewareRegistry.get(routeKey)||[],method=req.method.toUpperCase(),middlewareEntries=[...userMiddleware],alreadyHasCsrf=userMiddleware.some((m)=>m==="csrf"||m.startsWith("csrf:")),routeSkipped=csrfSkipRegistry.has(routeKey),routeRequired=csrfRequireRegistry.has(routeKey),handlerKey=routeHandlerKeyRegistry.get(routeKey),actionSkipped=handlerKey?actionSkipsCsrfCache.get(handlerKey)===!0:!1;if(CSRF_PROTECTED_METHODS.has(method)&&!alreadyHasCsrf&&(routeRequired||!routeSkipped&&!actionSkipped))middlewareEntries.unshift("csrf");if(middlewareEntries.length>0){const lvl=(process.env.LOG_LEVEL||"info").toLowerCase();if(lvl!=="info"&&lvl!=="warn"&&lvl!=="error"){const schemeEnd=req.url.indexOf("://"),pathStart=schemeEnd===-1?0:req.url.indexOf("/",schemeEnd+3),q=req.url.indexOf("?",pathStart<0?0:pathStart),urlPath=pathStart<0?"/":req.url.slice(pathStart,q===-1?void 0:q);log.debug(`[middleware] Executing chain: [${middlewareEntries.join(", ")}] for ${method} ${urlPath}`)}}const resolved=[];for(const middlewareEntry of middlewareEntries){const{name:middlewareName,params}=parseMiddlewareName(middlewareEntry);if(params){enhancedReq._middlewareParams=enhancedReq._middlewareParams||{};enhancedReq._middlewareParams[middlewareName]=params}const middleware=await loadMiddleware(middlewareName);if(!middleware||typeof middleware.handle!=="function"){log.error(`[Router] Middleware '${middlewareName}' on ${routeKey} could not be resolved \u2014 failing closed`);const failClosedError=Error(`Middleware '${middlewareName}' could not be resolved`),failClosedResponse=await createErrorResponse(failClosedError,enhancedReq,{status:500});return await applyCorsIfConfigured(enhancedReq,failClosedResponse)}const rawPriority=middleware.priority;let priority=DEFAULT_MIDDLEWARE_PRIORITY;if(typeof rawPriority==="number"&&Number.isFinite(rawPriority)&&rawPriority>=0)priority=rawPriority;else if(rawPriority!==void 0)warnInvalidMiddlewarePriority(middlewareName,rawPriority);resolved.push({name:middlewareName,handler:middleware,priority})}resolved.sort((a,b)=>a.priority-b.priority);const middlewareTimings=[];for(const{name:middlewareName,handler:middleware}of resolved){const mwStart=process.hrtime.bigint();let mwTimer;try{const MIDDLEWARE_TIMEOUT_MS=30000,timeoutPromise=new Promise((_,reject)=>{mwTimer=setTimeout(()=>reject(Error(`Middleware '${middlewareName}' exceeded ${MIDDLEWARE_TIMEOUT_MS}ms`)),MIDDLEWARE_TIMEOUT_MS)});await Promise.race([middleware.handle(enhancedReq),timeoutPromise]);const elapsedMs=Number(process.hrtime.bigint()-mwStart)/1e6;middlewareTimings.push({name:middlewareName,ms:elapsedMs})}catch(error){const elapsedMs=Number(process.hrtime.bigint()-mwStart)/1e6;middlewareTimings.push({name:middlewareName,ms:elapsedMs});log.debug(`[middleware] Blocked by: ${middlewareName}`);if(error instanceof Response){try{const{_requestId:reqId,_startNs:startNs}=enhancedReq,total=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,parts=total!=null?[`total;dur=${total.toFixed(1)}`]:[];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}if(parts.length>0)error.headers.set("Server-Timing",parts.join(", "));if(reqId)error.headers.set("X-Request-ID",reqId)}catch{}return await applyCorsIfConfigured(enhancedReq,error)}const err=error instanceof Error?error:Error(String(error)),errorResponse="statusCode"in err||"status"in err?await createMiddlewareErrorResponse(err,enhancedReq):await(()=>{log.error(`[Router] Middleware '${middlewareName}' threw an unexpected error:`,err);return createErrorResponse(err,enhancedReq,{status:500})})();try{const{_requestId:reqId,_startNs:startNs}=enhancedReq,total=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,parts=total!=null?[`total;dur=${total.toFixed(1)}`]:[];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}if(parts.length>0)errorResponse.headers.set("Server-Timing",parts.join(", "));if(reqId)errorResponse.headers.set("X-Request-ID",reqId)}catch{}return await applyCorsIfConfigured(enhancedReq,errorResponse)}finally{clearTimeout(mwTimer)}}let response=await wrappedBase(enhancedReq);clearTrackedQueries();if(response){if(req.method==="GET"||req.method==="HEAD"||req.method==="OPTIONS")try{const{seedCsrfCookieIfMissing}=await import(resolveDefaultsPath("app/Middleware/Csrf.ts"));response=seedCsrfCookieIfMissing(enhancedReq,response,enhancedReq._csrfToken)}catch(err){log.warn("[router] CSRF cookie seeding failed",{error:err})}}if(response)response=await applyCorsIfConfigured(enhancedReq,response);const{_requestId:reqId,_startNs:startNs}=enhancedReq,durMs=startNs!=null?Number(process.hrtime.bigint()-startNs)/1e6:null,setHeaders=(h)=>{if(reqId)h.set("X-Request-ID",reqId);if(durMs!=null){const parts=[`total;dur=${durMs.toFixed(1)}`];for(const t of middlewareTimings){const safeName=t.name.replace(/[^A-Za-z0-9_-]/g,"_").slice(0,32);parts.push(`mw_${safeName};dur=${t.ms.toFixed(1)}`)}h.set("Server-Timing",parts.join(", "))}applySecurityHeaders(h)};if(response&&typeof response.headers?.set==="function"){if(response.status>=400&&(response.headers.get("content-type")||"").includes("json")&&reqId)try{const text=await response.clone().text(),parsed=JSON.parse(text);if(parsed&&typeof parsed==="object"){const newHeaders=new Headers(response.headers);setHeaders(newHeaders);return new Response(JSON.stringify({...parsed,request_id:reqId}),{status:response.status,statusText:response.statusText,headers:newHeaders})}}catch{}try{setHeaders(response.headers)}catch{try{const cloned=response.clone(),newHeaders=new Headers(response.headers);setHeaders(newHeaders);return new Response(cloned.body,{status:response.status,statusText:response.statusText,headers:newHeaders})}catch{}}}if(enhancedReq._compress===!0&&response)try{const{applyCompression}=await import(resolveDefaultsPath("app/Middleware/Compress.ts"));return await applyCompression(enhancedReq,response)}catch(err){log.warn(`[router] Compression failed; sending uncompressed response: ${err instanceof Error?err.message:String(err)}`)}return response})}}function createChainableRoute(routeKey){if(!routeMiddlewareRegistry.has(routeKey))routeMiddlewareRegistry.set(routeKey,[]);const routePath=routeKey.includes(":")?routeKey.substring(routeKey.indexOf(":")+1):routeKey,chain={middleware(name){const middlewareList=routeMiddlewareRegistry.get(routeKey);if(middlewareList)middlewareList.push(name);return chain},name(routeName){namedRouteRegistry.set(routeName,compileNamedRoute(routePath));return chain},skipCsrf(){csrfSkipRegistry.add(routeKey);csrfRequireRegistry.delete(routeKey);return chain},requireCsrf(){csrfRequireRegistry.add(routeKey);csrfSkipRegistry.delete(routeKey);return chain},rateLimit(max,window){if(!Number.isFinite(max)||max<=0)throw Error(`[Router] .rateLimit(): max must be a positive number, got ${String(max)}`);const windowSeconds=rateLimitWindowToSeconds(window);routeRateLimitRegistry.set(routeKey,{max:Math.floor(max),windowSeconds});return chain}};return chain}async function fileExists(path){try{return await Bun.file(path).exists()}catch{return!1}}function assertSafeHandlerPath(handlerPath){if(typeof handlerPath!=="string"||handlerPath.length===0)throw Error(`[Router] Refusing to resolve handler '${String(handlerPath)}': empty or non-string`);if(handlerPath.includes("\x00"))throw Error("[Router] Refusing to resolve handler with null byte");if(handlerPath.startsWith("/")||/^[A-Za-z]:[\\/]/.test(handlerPath))throw Error(`[Router] Refusing to resolve absolute handler path '${handlerPath}'`);if(handlerPath.split(/[/\\]/).some((s)=>s===".."))throw Error(`[Router] Refusing to resolve handler path '${handlerPath}' (contains '..' segment)`)}const _moduleImportCache=new Map;function cachedImport(fullPath){let p=_moduleImportCache.get(fullPath);if(!p){p=import(fullPath);_moduleImportCache.set(fullPath,p)}return p}const _resolvedHandlerCache=new Map;function resolveStringHandler(handlerPath){let resolved=_resolvedHandlerCache.get(handlerPath);if(!resolved){resolved=resolveStringHandlerUncached(handlerPath);_resolvedHandlerCache.set(handlerPath,resolved);resolved.catch(()=>_resolvedHandlerCache.delete(handlerPath))}return resolved}function validationFailureResponse(errors){return response.validationError(errors)}export function precognitionRequest(req){const header=req.headers?.get?.("Precognition"),viaHeader=typeof header==="string"&&header.toLowerCase()==="true";let viaQuery=!1;try{viaQuery=new URL(req.url).searchParams.get("_validate")==="1"}catch{viaQuery=!1}if(!viaHeader&&!viaQuery)return null;return{only:(req.headers?.get?.("Precognition-Validate-Only")??"").split(",").map((field)=>field.trim()).filter(Boolean)}}export function precognitionSuccess(){return new Response(null,{status:204,headers:{Precognition:"true","Precognition-Success":"true",Vary:"Precognition, Precognition-Validate-Only"}})}async function resolveStringHandlerUncached(handlerPath){assertSafeHandlerPath(handlerPath);let modulePath=handlerPath;modulePath=modulePath.endsWith(".ts")?modulePath.slice(0,-3):modulePath;if(modulePath.includes("Controller")){const[controllerPath,methodName="index"]=modulePath.split("@"),userPath=p.appPath(`${controllerPath}.ts`),defaultPath=resolveDefaultsPath(`app/${controllerPath}.ts`),fullPath=await fileExists(userPath)?userPath:defaultPath;try{const controller=await cachedImport(fullPath);if(!controller.default||typeof controller.default!=="function")throw Error(`Controller ${controllerPath} does not export a default class`);const instance=new controller.default;if(typeof instance[methodName]!=="function")throw Error(`Method ${methodName} not found in controller ${controllerPath}`);return async(req)=>{const result=await instance[methodName](req);return formatResult(result,req)}}catch(error){log.error(`[Router] Failed to load controller '${fullPath}':`,error);throw error}}let fullPath;if(modulePath.includes("storage/framework/orm"))fullPath=modulePath;else if(modulePath.includes("OrmAction"))fullPath=p.storagePath(`framework/actions/src/${modulePath}.ts`);else if(modulePath.includes("Actions")){const userPath=p.projectPath(`app/${modulePath}.ts`),defaultPath=resolveDefaultsPath(`app/${modulePath}.ts`);fullPath=await fileExists(userPath)?userPath:defaultPath}else{const userPath=p.appPath(`${modulePath}.ts`),defaultPath=resolveDefaultsPath(`app/${modulePath}.ts`);fullPath=await fileExists(userPath)?userPath:defaultPath}try{const action=(await cachedImport(fullPath)).default;if(!action)throw Error(`Action '${handlerPath}' has no default export`);if(typeof action.handle!=="function"){log.error(`[Router] Action '${handlerPath}' structure:`,Object.keys(action));throw Error(`Action '${handlerPath}' has no handle() method. Got: ${typeof action.handle}`)}const actionSkipsCsrf=action.skipCsrf===!0||action.csrf===!1;actionSkipsCsrfCache.set(handlerPath,actionSkipsCsrf);const actionForcesJson=action.apiResponse===!0;return async(req)=>{if(actionSkipsCsrf)req._skipCsrf=!0;if(actionForcesJson)req._forceJson=!0;req._requestValidationRules=action.validations??modelValidationRules(action.modelDefinition??action.model);try{const precognition=precognitionRequest(req);if(precognition){if(!action.validations)return precognitionSuccess();const rules=precognition.only.length>0?Object.fromEntries(Object.entries(action.validations).filter(([field])=>precognition.only.includes(field))):action.validations,precognitionResult=await validateActionInput(req,rules);return precognitionResult.valid?precognitionSuccess():validationFailureResponse(precognitionResult.errors)}if(action.validations){const validationResult=await validateActionInput(req,action.validations);if(!validationResult.valid)return validationFailureResponse(validationResult.errors)}if(typeof action.authorize==="function"){const auth=await action.authorize(req);if(auth instanceof Response)return auth;if(auth===!1)return Response.json({error:"Forbidden"},{status:403})}if(typeof action.before==="function"){const pre=await action.before(req);if(pre instanceof Response)return pre}const result=await action.handle(req);return formatResult(result,req)}catch(handleError){report(handleError,{label:`[Router] action.handle() for '${handlerPath}'`});throw handleError}}}catch(importError){log.error(`[Router] Failed to import action '${fullPath}':`,importError);throw importError}}export async function validateActionInput(req,validations){const errors={},input=await getRequestInput(req,validations);for(const[field,validation]of Object.entries(validations)){const value=input[field];let result;try{result=validation.rule.validate(value)}catch{result={valid:!1,errors:[{message:`${field} validation failed`}]}}if(!result.valid){const fieldErrors=[],label=field.replace(/[-_]+/g," ").replace(/([a-z])([A-Z])/g,"$1 $2").replace(/^./,(c)=>c.toUpperCase()),decorate=(msg)=>msg.toLowerCase().startsWith(field.toLowerCase())||msg.includes(label)?msg:`${label} ${msg}`;if(result.errors&&result.errors.length>0)if(validation.message){const firstMessage=result.errors[0]?.message??"";fieldErrors.push(typeof validation.message==="string"?validation.message:validation.message[field]||decorate(firstMessage))}else result.errors.forEach((err)=>fieldErrors.push(decorate(err.message)));else fieldErrors.push(validation.message?typeof validation.message==="string"?validation.message:`${label} is invalid`:`${label} is invalid`);errors[field]=fieldErrors}}return{valid:Object.keys(errors).length===0,errors}}function modelValidationRules(model){if(!model?.attributes||typeof model.attributes!=="object")return;const rules={};for(const[field,attribute]of Object.entries(model.attributes)){const validation=attribute?.validation;if(validation?.rule)rules[field]=validation}return Object.keys(rules).length>0?rules:void 0}async function getRequestInput(req,validations){const input={},q=req.query;if(q)for(const key in q)input[key]=q[key];else new URL(req.url).searchParams.forEach((value,key)=>{input[key]=value});if(req.params)Object.assign(input,req.params);if(req.jsonBody&&typeof req.jsonBody==="object")Object.assign(input,req.jsonBody);else if(req.formBody&&typeof req.formBody==="object")Object.assign(input,req.formBody);if(typeof req.allFiles==="function")try{const files=req.allFiles();for(const key of Object.keys(files??{}))if(!(key in input))input[key]=files[key]}catch{}if(!validations)return input;for(const[field,validation]of Object.entries(validations)){const value=input[field];if(typeof value!=="string")continue;const validatorName=validation.rule?.name;if(validatorName==="number"){const n=Number(value);if(Number.isFinite(n))input[field]=n}else if(validatorName==="boolean"){if(value==="true"||value==="1")input[field]=!0;else if(value==="false"||value==="0")input[field]=!1}}return input}function formatResult(result,req){if(result instanceof Response)return result;if(result instanceof ReadableStream)return new Response(result,{headers:{"Content-Type":"application/octet-stream"}});const apiShaped=req._forceJson===!0||isApiRequest(req);if(result===null||result===void 0)return apiShaped?new Response(null,{status:204}):new Response("",{status:200});if(typeof result==="object"){const linkHeader=buildPaginatorLinkHeader(result);if(linkHeader)return Response.json(result,{headers:{Link:linkHeader}});return Response.json(result)}if(apiShaped)return Response.json(result);return new Response(String(result),{headers:{"Content-Type":"text/plain; charset=utf-8"}})}function buildPaginatorLinkHeader(value){if(!isPaginator(value)&&!isSimplePaginator(value)&&!isCursorPaginator(value))return null;const v=value,parts=[];if(v.prev_page_url)parts.push(`<${v.prev_page_url}>; rel="prev"`);if(v.next_page_url)parts.push(`<${v.next_page_url}>; rel="next"`);if(v.first_page_url)parts.push(`<${v.first_page_url}>; rel="first"`);if(v.last_page_url)parts.push(`<${v.last_page_url}>; rel="last"`);return parts.length>0?parts.join(", "):null}export function stream(source,options={}){const baseHeaders={};if(options.type==="sse"){baseHeaders["Content-Type"]="text/event-stream; charset=utf-8";baseHeaders["Cache-Control"]="no-cache";baseHeaders.Connection="keep-alive"}else if(options.type==="ndjson")baseHeaders["Content-Type"]="application/x-ndjson; charset=utf-8";else baseHeaders["Content-Type"]=options.contentType??"application/octet-stream";const body=source instanceof ReadableStream?source:new ReadableStream({async start(controller){try{for await(const chunk of source)controller.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):chunk);controller.close()}catch(err){controller.error(err)}}}),merged=new Headers(baseHeaders);if(options.headers)new Headers(options.headers).forEach((value,key)=>merged.set(key,value));return new Response(body,{status:options.status??200,headers:merged})}function getAllInputFor(req){const cached=req._allInputCache;if(cached)return cached;const input={},query=req.query;if(query)for(const key in query)input[key]=query[key];if(req.jsonBody&&typeof req.jsonBody==="object")Object.assign(input,req.jsonBody);if(req.formBody&&typeof req.formBody==="object")Object.assign(input,req.formBody);if(req.params&&typeof req.params==="object")Object.assign(input,req.params);req._allInputCache=input;return input}function flashInputFor(req,keys){const input=getAllInputFor(req);req._oldInput=keys?Object.fromEntries(keys.filter((key)=>(key in input)).map((key)=>[key,input[key]])):{...input}}const REQUEST_METHODS={get(key,defaultValue){const value=getAllInputFor(this)[key];return value!==void 0?value:defaultValue},input(key,defaultValue){const value=getAllInputFor(this)[key];return value!==void 0?value:defaultValue},all(){return getAllInputFor(this)},only(keys){const input=getAllInputFor(this),result={};for(const key of keys)if(key in input)result[key]=input[key];return result},except(keys){const result={...getAllInputFor(this)};for(const key of keys)delete result[key];return result},has(key){const input=getAllInputFor(this);if(Array.isArray(key))return key.every((k)=>(k in input)&&input[k]!==void 0);return key in input&&input[key]!==void 0},hasAny(keys){const input=getAllInputFor(this);return keys.some((k)=>(k in input)&&input[k]!==void 0)},filled(key){const input=getAllInputFor(this),isFilled=(k)=>{const value=input[k];return value!==void 0&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0)};if(Array.isArray(key))return key.every(isFilled);return isFilled(key)},missing(key){const input=getAllInputFor(this);if(Array.isArray(key))return key.every((k)=>!(k in input)||input[k]===void 0);return!(key in input)||input[key]===void 0},merge(data){Object.assign(getAllInputFor(this),data)},keys(){return Object.keys(getAllInputFor(this))},string(key,defaultValue=""){const value=getAllInputFor(this)[key];return value!==void 0&&value!==null?String(value):defaultValue},integer(key,defaultValue=0){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return defaultValue;if(typeof value==="number")return Number.isFinite(value)?Math.trunc(value):defaultValue;const str=String(value).trim();if(!/^-?\d+$/.test(str))return defaultValue;const parsed=Number.parseInt(str,10);return Number.isFinite(parsed)?parsed:defaultValue},float(key,defaultValue=0){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return defaultValue;if(typeof value==="number")return Number.isFinite(value)?value:defaultValue;const str=String(value).trim();if(!/^-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?$/.test(str))return defaultValue;const parsed=Number.parseFloat(str);return Number.isFinite(parsed)?parsed:defaultValue},boolean(key,defaultValue=!1){const value=getAllInputFor(this)[key];if(value===void 0||value===null)return defaultValue;if(typeof value==="boolean")return value;if(value==="true"||value==="1"||value===1)return!0;if(value==="false"||value==="0"||value===0)return!1;return defaultValue},array(key){const value=getAllInputFor(this)[key];if(Array.isArray(value))return value;return value!==void 0&&value!==null?[value]:[]},date(key){const value=getAllInputFor(this)[key];if(value===void 0||value===null||value==="")return null;const parsed=new Date(value);return Number.isNaN(parsed.getTime())?null:parsed},enum(key,enumType){const value=getAllInputFor(this)[key];if(value===void 0||value===null)return null;if(Object.values(enumType).includes(value))return value;const enumKey=String(value);return enumKey in enumType?enumType[enumKey]:null},collect(key){const value=getAllInputFor(this)[key];if(Array.isArray(value))return collect(value);return collect(value===void 0||value===null?[]:[value])},whenHas(key,callback,defaultCallback){const input=getAllInputFor(this);if(key in input&&input[key]!==void 0)callback(input[key]);else defaultCallback?.()},whenFilled(key,callback,defaultCallback){const value=getAllInputFor(this)[key];if(value!==void 0&&value!==null&&value!==""&&!(Array.isArray(value)&&value.length===0))callback(value);else defaultCallback?.()},isValue(key,value){return getAllInputFor(this)[key]===value},async validate(rules,messages={}){const selectedRules=rules??this._requestValidationRules;if(!selectedRules||Object.keys(selectedRules).length===0){const input=getAllInputFor(this);this._validatedInput=input;return input}const normalized={};for(const[field,definition]of Object.entries(selectedRules)){if(typeof definition==="string")throw TypeError(`String validation rules are not supported for "${field}". Use schema validators.`);if(definition&&typeof definition==="object"&&"rule"in definition){const message=messages[field];normalized[field]=message?{...definition,message}:definition}else normalized[field]=definition}const{validate}=await import("@stacksjs/validation"),validated=await validate(this,normalized);this._validatedInput=validated;return validated},getValidated(){return this._validatedInput??{}},safe(){const data=this._validatedInput??{};return{all:()=>({...data}),get:(key,defaultValue)=>(key in data)?data[key]:defaultValue,only:(keys)=>Object.fromEntries(keys.filter((key)=>(key in data)).map((key)=>[key,data[key]])),except:(keys)=>Object.fromEntries(Object.entries(data).filter(([key])=>!keys.includes(key)))}},old(key,defaultValue){return this._oldInput?.[key]??defaultValue},flashInput(keys){flashInputFor(this,keys)},flashInputOnly(keys){flashInputFor(this,keys)},flashInputExcept(keys){const input=getAllInputFor(this);this._oldInput=Object.fromEntries(Object.entries(input).filter(([key])=>!keys.includes(key)))},file(key){const file=(this.files||{})[key];if(!file)return null;const rawFile=Array.isArray(file)?file[0]:file;return rawFile?new UploadedFile(rawFile):null},getFiles(key){const file=(this.files||{})[key];if(!file)return[];return(Array.isArray(file)?file:[file]).map((f)=>new UploadedFile(f))},hasFile(key){const files=this.files||{};return key in files&&files[key]!==void 0},allFiles(){const files=this.files||{},result={};for(const[key,value]of Object.entries(files))if(Array.isArray(value))result[key]=value.map((f)=>new UploadedFile(f));else result[key]=new UploadedFile(value);return result},getParams(){return{...this.params}},isEmpty(){return Object.keys(getAllInputFor(this)).length===0},browser(){return this.headers.get("sec-ch-ua")||this.headers.get("user-agent")},ipForRateLimit(){const ip=this.ip;if(typeof ip==="function")return ip.call(this)||null;return typeof ip==="string"&&ip?ip:null},getMethod(){return this.method.toUpperCase()},async user(){return this._authenticatedUser},async userToken(){return this._currentAccessToken},async tokenCan(ability){if(typeof ability!=="string"||ability.length===0)return!1;const token=this._currentAccessToken;if(!token||typeof token!=="object")return!1;if(!Array.isArray(token.abilities))return!1;if(token.abilities.includes("*"))return!0;return token.abilities.includes(ability)},async tokenCant(ability){return!await this.tokenCan(ability)},async can(ability,...args){if(typeof ability!=="string"||ability.length===0)return!1;const{Gate}=await import("@stacksjs/auth"),user=this._authenticatedUser??null;return Gate.allows(ability,user,...args)},async cannot(ability,...args){return!await this.can(ability,...args)},async authorize(ability,...args){const{Gate}=await import("@stacksjs/auth"),user=this._authenticatedUser??null;await Gate.authorize(ability,user,...args)}};async function seedCsrfTokenForRender(req){const method=req.method?.toUpperCase?.()??"GET";if(method!=="GET"&&method!=="HEAD")return;const cookieHeader=req.headers?.get?.("cookie")??"";if(cookieHeader.includes("X-CSRF-Token=")||cookieHeader.includes("csrf-token="))return;try{const{generateCsrfToken,CSRF_COOKIE_NAME}=await import(resolveDefaultsPath("app/Middleware/Csrf.ts")),token=generateCsrfToken();req._csrfToken=token;try{const merged=cookieHeader?`${cookieHeader}; ${CSRF_COOKIE_NAME}=${token}`:`${CSRF_COOKIE_NAME}=${token}`;req.headers.set("cookie",merged)}catch{}}catch{}}export function enhanceRequest(req){applyRequestEnhancements(req,req.params||{});let query=req.query;if(!query){const url=new URL(req.url);query={};url.searchParams.forEach((value,key)=>{query[key]=value});req.query=query}Object.assign(req,REQUEST_METHODS);return req}function wrapHandler(handler,skipParsing=!1){if(typeof handler==="string"){const handlerPath=handler;return async(req)=>{try{if(!skipParsing){await parseRequestBody(req);req=enhanceRequest(req)}return await(await resolveStringHandler(handlerPath))(req)}catch(error){report(error,{label:`[Router] ${handlerPath}`});const rawStatus=error?.statusCode??error?.status,status=typeof rawStatus==="number"&&Number.isInteger(rawStatus)&&rawStatus>=400&&rawStatus<600?rawStatus:void 0;return await createErrorResponse(error instanceof Error?error:Error(String(error)),req,{handlerPath,status})}}}const fn=handler;return async(req)=>{const result=await fn(req);return formatResult(result,req)}}async function parseRequestBody(req){if(req._bodyParsed)return;req._bodyParsed=!0;const contentType=req.headers.get("content-type")||"";try{if(JSON_CONTENT_TYPE.test(contentType)){const raw=await req.clone().text();req._rawBody=raw;if(raw.length===0)req.jsonBody={};else try{const body=JSON.parse(raw);req.jsonBody=body&&typeof body==="object"?body:{}}catch(parseErr){const message=parseErr instanceof Error?parseErr.message:"Invalid JSON",{HttpError}=await import("@stacksjs/error-handling");throw new HttpError(400,`Invalid JSON body: ${message}`)}}else if(contentType.includes("application/x-www-form-urlencoded")){const text=await req.clone().text(),params=new URLSearchParams(text),formBody={};params.forEach((value,key)=>{formBody[key]=value});req.formBody=formBody}else if(contentType.includes("multipart/form-data")){const formData=await req.clone().formData(),formBody={},files={};formData.forEach((value,key)=>{if(value instanceof File)if(files[key])if(Array.isArray(files[key]))files[key].push(value);else files[key]=[files[key],value];else files[key]=value;else formBody[key]=value});Reflect.set(req,"formBody",formBody);Reflect.set(req,"files",files)}}catch(e){if(typeof(e?.status??e?.statusCode)==="number")throw e;log.debug("[stacks-router] Body parsing failed:",e)}}export function createStacksRouter(config={}){const bunRouter=new Router({verbose:config.verbose??!1});let currentPrefix="",currentGroupMiddleware=[],currentGroupApiResponse=!1;function registerRoute(method,path,_handler){const fullPath=currentPrefix+path,routeKey=`${method}:${fullPath}`;log.debug(`[router] ${method} ${fullPath} \u2192 ${typeof _handler==="string"?_handler:"function"}`);if(currentGroupMiddleware.length>0)routeMiddlewareRegistry.set(routeKey,[...currentGroupMiddleware]);if(currentGroupApiResponse)routeApiResponseRegistry.add(routeKey);if(typeof _handler==="string")routeHandlerKeyRegistry.set(routeKey,_handler);return{fullPath,routeKey}}const stacksRouter={bunRouter,get routes(){return bunRouter.routes},get(path,handler){const{fullPath,routeKey}=registerRoute("GET",path,handler);bunRouter.get(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},post(path,handler){const{fullPath,routeKey}=registerRoute("POST",path,handler);bunRouter.post(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},put(path,handler){const{fullPath,routeKey}=registerRoute("PUT",path,handler);bunRouter.put(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},patch(path,handler){const{fullPath,routeKey}=registerRoute("PATCH",path,handler);bunRouter.patch(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},delete(path,handler){const{fullPath,routeKey}=registerRoute("DELETE",path,handler);bunRouter.delete(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},options(path,handler){const{fullPath,routeKey}=registerRoute("OPTIONS",path,handler);bunRouter.options(fullPath,createMiddlewareHandler(routeKey,handler));return createChainableRoute(routeKey)},group(options,callback){const previousPrefix=currentPrefix,previousMiddleware=[...currentGroupMiddleware],previousApiResponse=currentGroupApiResponse;if(options.prefix)currentPrefix=previousPrefix+options.prefix;const middlewareList=options.middleware?Array.isArray(options.middleware)?options.middleware:[options.middleware]:void 0;if(middlewareList)currentGroupMiddleware=[...currentGroupMiddleware,...middlewareList];if(options.apiResponse===!0)currentGroupApiResponse=!0;log.debug(`[router] Entering group: prefix=${options.prefix||"/"} middleware=[${middlewareList?.join(", ")||""}]${currentGroupApiResponse?" apiResponse=true":""}`);const result=callback();if(result instanceof Promise)return result.then(()=>{currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;return stacksRouter}).catch((err)=>{currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;throw err});currentPrefix=previousPrefix;currentGroupMiddleware=previousMiddleware;currentGroupApiResponse=previousApiResponse;return stacksRouter},resource(name,handler,options){const actions=["index","store","show","update","destroy"],activeActions=options?.only?actions.filter((a)=>options.only.includes(a)):options?.except?actions.filter((a)=>!options.except.includes(a)):actions,handlerBase=handler.replace(/Action$/,"");log.debug(`[router] Resource: /${name} \u2192 ${handler} [${activeActions.join(", ")}]`);const registerResourceRoutes=()=>{for(const action of activeActions)switch(action){case"index":stacksRouter.get(`/${name}`,`${handlerBase}IndexAction`);break;case"store":stacksRouter.post(`/${name}`,`${handlerBase}StoreAction`);break;case"show":stacksRouter.get(`/${name}/:id`,`${handlerBase}ShowAction`);break;case"update":stacksRouter.put(`/${name}/:id`,`${handlerBase}UpdateAction`);break;case"destroy":stacksRouter.delete(`/${name}/:id`,`${handlerBase}DestroyAction`);break}};if(options?.middleware)stacksRouter.group({middleware:options.middleware},registerResourceRoutes);else registerResourceRoutes();return stacksRouter},match(methods,path,handler){log.debug(`[router] Match: [${methods.join(", ")}] ${path} \u2192 ${typeof handler==="string"?handler:"function"}`);for(const method of methods){const m=method.toUpperCase(),{fullPath,routeKey}=registerRoute(m,path,handler),wrappedHandler=createMiddlewareHandler(routeKey,handler);switch(m){case"GET":bunRouter.get(fullPath,wrappedHandler);break;case"POST":bunRouter.post(fullPath,wrappedHandler);break;case"PUT":bunRouter.put(fullPath,wrappedHandler);break;case"PATCH":bunRouter.patch(fullPath,wrappedHandler);break;case"DELETE":bunRouter.delete(fullPath,wrappedHandler);break;case"OPTIONS":bunRouter.options(fullPath,wrappedHandler);break}}return createChainableRoute(`${methods[0]}:${currentPrefix}${path}`)},health(){bunRouter.get("/api/health",async()=>{const health=await checkApplicationHealth();return Response.json(health,{status:health.status==="healthy"?200:503})});bunRouter.get("/__routes",(req)=>{if(!isExposeRoutesAuthorized(req))return Response.json({error:"disabled"},{status:404});return Response.json(listRegisteredRoutes())});bunRouter.get("/__storage/:path",async(req)=>{const url=new URL(req.url),token=url.searchParams.get("token"),params=req.params,rawPath=params?.path?decodeURIComponent(params.path):decodeURIComponent(url.pathname.replace(/^\/__storage\//,""));if(!token||typeof rawPath!=="string"||rawPath.length===0)return new Response("Forbidden",{status:403});const{verifySignedStorageToken,Storage}=await import("@stacksjs/storage");if(!verifySignedStorageToken(token,rawPath).valid)return new Response("Forbidden",{status:403});try{const adapter=Storage.disk();if(!await adapter.fileExists(rawPath))return new Response("Not Found",{status:404});const buf=await adapter.readToBuffer(rawPath),mime=await adapter.mimeType(rawPath).catch(()=>"application/octet-stream");return new Response(buf,{status:200,headers:{"Content-Type":mime,"Cache-Control":"private, max-age=60","X-Content-Type-Options":"nosniff"}})}catch(err){log.error("[storage] signed-url fetch failed:",err);return new Response("Internal Error",{status:500})}});bunRouter.get("/__openapi.json",async(req)=>{if(!isExposeRoutesAuthorized(req))return Response.json({error:"disabled"},{status:404});try{const{generateOpenApi}=await import("@stacksjs/api"),spec=await generateOpenApi({write:!1,portable:!1});return Response.json(spec)}catch(err){return Response.json({error:"OpenAPI generation failed",message:err instanceof Error?err.message:String(err)},{status:500})}});return stacksRouter},use(middleware){const adapted=adaptMiddlewareForBunRouter(middleware);bunRouter.globalMiddleware.push(adapted);return stacksRouter},async serve(options={}){warnOnMultipleRouterInstances();configureViewDirectories(bunRouter);return bunRouter.serve(options)},async handleRequest(req){return bunRouter.handleRequest(req)},getAllowedMethods(pathname,domain){return bunRouter.getAllowedMethods(pathname,domain)},async register(routePath,options){log.debug(`[router] Register: ${routePath} prefix=${options?.prefix||"none"}`);const callback=async()=>{await import(routePath)};if(options?.prefix||options?.middleware)await stacksRouter.group({prefix:options.prefix,middleware:options.middleware},callback);else await callback();return stacksRouter},async importRoutes(){log.debug("[router] Loading user routes from registry...");try{const{loadRoutes}=await import("./route-loader"),{appPath}=await import("@stacksjs/path"),routeRegistry=(await import(appPath("Routes.ts"))).default;await loadRoutes(routeRegistry)}catch(error){log.error("Failed to load route registry:",error);throw error}log.debug("[router] Loading ORM routes...");const ormRoutesCandidates=[p.frameworkPath("orm/routes.ts"),p.frameworkPath("core/orm/routes.ts")];let ormRoutesLoaded=!1;for(const candidate of ormRoutesCandidates)try{if(await Bun.file(candidate).exists()){await import(candidate);ormRoutesLoaded=!0;break}}catch(error){log.warn(`[router] ORM routes candidate failed to load, falling back to next: ${candidate}
5
+ `,error)}if(!ormRoutesLoaded)log.warn("[router] No ORM routes candidate loaded \u2014 model useApi endpoints are unavailable.");log.debug("[router] Loading discovered package routes...");try{await stacksRouter.loadDiscoveredRoutes()}catch(error){log.debug("Package route discovery skipped:",error)}await assertRouteMiddlewareResolvable()},async loadDiscoveredRoutes(){try{const manifestPath=p.storagePath("framework/discovered-packages.json"),file=Bun.file(manifestPath);if(!await file.exists())return;const packages=(await file.json())?.packages;if(!packages)return;const pantryDir=p.projectPath("pantry");for(const[pkgName,meta]of Object.entries(packages)){const routes=meta?.routes;if(!routes)continue;const routeList=Array.isArray(routes)?routes:[routes],pkgDir=`${pantryDir}/${pkgName}`;for(const routeFile of routeList){log.debug(`[router] Discovered route: ${pkgName} \u2192 ${routeFile}`);const fullPath=routeFile.startsWith("/")?routeFile:`${pkgDir}/${routeFile}`,prefix=meta?.routePrefix,middleware=meta?.routeMiddleware;try{await stacksRouter.register(fullPath,{prefix,middleware})}catch(err){log.warn(`Failed to load routes from package '${pkgName}': ${err}`)}}}}catch{}}};return stacksRouter}export function configureViewDirectories(bunRouter){const router=bunRouter;if(typeof router.views!=="function")return;const existing=router._fileRoutingConfig;if(existing&&Object.keys(existing).length>0)return;if(!existsSync(p.projectPath("resources/views")))return;const layouts=[p.projectPath("resources/views/layouts"),p.projectPath("resources/layouts")].find(existsSync),partials=[p.projectPath("resources/views/partials"),p.projectPath("resources/partials")].find(existsSync),components=[p.projectPath("resources/components"),p.projectPath("resources/views/components")].find(existsSync);router.views({...components?{componentsDir:components}:{},...layouts?{layoutsDir:layouts}:{},...partials?{partialsDir:partials}:{}})}const ROUTE_SINGLETON_KEY=Symbol.for("@stacksjs/router:route-singleton");export const route=globalThis[ROUTE_SINGLETON_KEY]??=createStacksRouter();let routesLoadPromise=null,routingContextRunner=null;async function getRoutingContextRunner(){if(!routingContextRunner)try{const{withRoutingContext}=await import("@stacksjs/database");routingContextRunner=typeof withRoutingContext==="function"?withRoutingContext:(fn)=>fn()}catch{routingContextRunner=(fn)=>fn()}return routingContextRunner}export async function serverResponse(request,_body){return(await getRoutingContextRunner())(()=>handleServerRequest(request))}async function handleServerRequest(request){if(!routesLoadPromise){log.debug("[router] Loading routes for first time...");routesLoadPromise=route.importRoutes().catch((err)=>{routesLoadPromise=null;throw err})}await routesLoadPromise;const response=await route.handleRequest(request);if(response.status===404&&response.headers.get("content-type")?.includes("json"))try{const body=await response.clone().json();if(body?.message==="Not Found"||body?.error==="Not Found"){const url=new URL(request.url),enriched={...body,path:url.pathname,method:request.method};return new Response(JSON.stringify(enriched),{status:404,headers:response.headers})}}catch{}return response}export async function serve(options={}){return route.serve(options)}
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/router",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.70.294",
5
+ "version": "0.70.296",
6
6
  "description": "The Stacks framework router.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -60,19 +60,19 @@
60
60
  },
61
61
  "dependencies": {
62
62
  "@stacksjs/bun-router": "^0.0.21",
63
- "@stacksjs/collections": "0.70.294",
63
+ "@stacksjs/collections": "0.70.296",
64
64
  "ts-rate-limiter": "^0.4.2"
65
65
  },
66
66
  "devDependencies": {
67
- "@stacksjs/actions": "0.70.294",
68
- "@stacksjs/config": "0.70.294",
67
+ "@stacksjs/actions": "0.70.296",
68
+ "@stacksjs/config": "0.70.296",
69
69
  "better-dx": "^0.2.17",
70
- "@stacksjs/error-handling": "0.70.294",
71
- "@stacksjs/logging": "0.70.294",
72
- "@stacksjs/orm": "0.70.294",
73
- "@stacksjs/path": "0.70.294",
74
- "@stacksjs/storage": "0.70.294",
75
- "@stacksjs/types": "0.70.294",
76
- "@stacksjs/validation": "0.70.294"
70
+ "@stacksjs/error-handling": "0.70.296",
71
+ "@stacksjs/logging": "0.70.296",
72
+ "@stacksjs/orm": "0.70.296",
73
+ "@stacksjs/path": "0.70.296",
74
+ "@stacksjs/storage": "0.70.296",
75
+ "@stacksjs/types": "0.70.296",
76
+ "@stacksjs/validation": "0.70.296"
77
77
  }
78
78
  }