@torpor/build 1.9.0 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{MiddlewareFunction-BZilnEei.d.mts → MiddlewareFunction-7rIvFkjl.d.mts} +7 -1
- package/dist/MiddlewareFunction-7rIvFkjl.d.mts.map +1 -0
- package/dist/{Router-By9Nlg39.d.mts → Router-Bxm7K20d.d.mts} +4 -4
- package/dist/Router-Bxm7K20d.d.mts.map +1 -0
- package/dist/{Server-dcRbdPXf.mjs → Server-Djd9-NkU.mjs} +2 -2
- package/dist/{Server-dcRbdPXf.mjs.map → Server-Djd9-NkU.mjs.map} +1 -1
- package/dist/{Server-qn5Ws_d0.d.mts → Server-hwbZ7P2g.d.mts} +2 -2
- package/dist/{Server-qn5Ws_d0.d.mts.map → Server-hwbZ7P2g.d.mts.map} +1 -1
- package/dist/{ServerEvent-BY4f3RVF.mjs → ServerEvent-L0rT_mBJ.mjs} +10 -1
- package/dist/{ServerEvent-BY4f3RVF.mjs.map → ServerEvent-L0rT_mBJ.mjs.map} +1 -1
- package/dist/{ServerHook-W111nEhe.d.mts → ServerHook-CyVEr5OL.d.mts} +2 -2
- package/dist/{ServerHook-W111nEhe.d.mts.map → ServerHook-CyVEr5OL.d.mts.map} +1 -1
- package/dist/{ServerLoadEvent-BH6oG1o6.d.mts → ServerLoadEvent-F60w1TZt.d.mts} +14 -4
- package/dist/ServerLoadEvent-F60w1TZt.d.mts.map +1 -0
- package/dist/{Site-DGZJB7Do.d.mts → Site-CAeAqjkk.d.mts} +192 -7
- package/dist/Site-CAeAqjkk.d.mts.map +1 -0
- package/dist/bin/index.js +37 -2
- package/dist/bin/index.js.map +1 -1
- package/dist/dev.d.mts +2 -2
- package/dist/dev.mjs +2 -2
- package/dist/{devPlugin-lLzauETn.mjs → devPlugin-D9b5uhzm.mjs} +2 -2
- package/dist/{devPlugin-lLzauETn.mjs.map → devPlugin-D9b5uhzm.mjs.map} +1 -1
- package/dist/discovery.d.mts +1 -1
- package/dist/index.d.mts +5 -5
- package/dist/nav.d.mts +28 -2
- package/dist/nav.d.mts.map +1 -1
- package/dist/nav.mjs +37 -9
- package/dist/nav.mjs.map +1 -1
- package/dist/nodeDev.d.mts +1 -1
- package/dist/nodeDev.mjs +1 -1
- package/dist/openapi.d.mts +24 -80
- package/dist/openapi.d.mts.map +1 -1
- package/dist/openapi.mjs +36 -1
- package/dist/openapi.mjs.map +1 -0
- package/dist/{plugin-D8Www11B.mjs → plugin-BQsMnkTj.mjs} +42 -3
- package/dist/plugin-BQsMnkTj.mjs.map +1 -0
- package/dist/run.d.mts +1 -1
- package/dist/run.mjs +1 -1
- package/dist/{runOpenApi-C5yMpQU1.mjs → runOpenApi-BZ314IiI.mjs} +44 -21
- package/dist/runOpenApi-BZ314IiI.mjs.map +1 -0
- package/dist/server/Server.d.mts +1 -1
- package/dist/server/Server.mjs +1 -1
- package/dist/server.d.mts +4 -4
- package/dist/server.mjs +2 -2
- package/dist/{serverEntry-D1hE-Jzt.mjs → serverEntry-8YnfpKTj.mjs} +2 -2
- package/dist/{serverEntry-D1hE-Jzt.mjs.map → serverEntry-8YnfpKTj.mjs.map} +1 -1
- package/dist/{serverEntry-BGii8bB6.d.mts → serverEntry-Da1PFlIU.d.mts} +3 -3
- package/dist/{serverEntry-BGii8bB6.d.mts.map → serverEntry-Da1PFlIU.d.mts.map} +1 -1
- package/dist/serverEntry.d.mts +1 -1
- package/dist/serverEntry.mjs +1 -1
- package/dist/{serverHandlers-CSBUEgJt.mjs → serverHandlers-Ba_35jpO.mjs} +38 -12
- package/dist/serverHandlers-Ba_35jpO.mjs.map +1 -0
- package/dist/{sitemap-xmE0zfme.d.mts → sitemap-CnIYTLhu.d.mts} +2 -2
- package/dist/{sitemap-xmE0zfme.d.mts.map → sitemap-CnIYTLhu.d.mts.map} +1 -1
- package/dist/test.d.mts +2 -2
- package/dist/test.mjs +2 -2
- package/package.json +10 -7
- package/dist/MiddlewareFunction-BZilnEei.d.mts.map +0 -1
- package/dist/Router-By9Nlg39.d.mts.map +0 -1
- package/dist/ServerLoadEvent-BH6oG1o6.d.mts.map +0 -1
- package/dist/Site-DGZJB7Do.d.mts.map +0 -1
- package/dist/plugin-D8Www11B.mjs.map +0 -1
- package/dist/runOpenApi-C5yMpQU1.mjs.map +0 -1
- package/dist/serverHandlers-CSBUEgJt.mjs.map +0 -1
|
@@ -242,7 +242,7 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
|
242
242
|
const handler = route.handler;
|
|
243
243
|
const params = route.params || {};
|
|
244
244
|
const routeMiddleware = [];
|
|
245
|
-
const endPointModule = handler.serverEndPoint ? (await handler
|
|
245
|
+
const endPointModule = handler.serverEndPoint ? (await resolveServerModule(handler))?.default : handler.type === 1 || handler.type === 3 ? (await resolveModule(handler))?.default : void 0;
|
|
246
246
|
if (Array.isArray(endPointModule?.middleware)) routeMiddleware.push(...endPointModule.middleware);
|
|
247
247
|
const { response: routeResponse, error } = await runHooks([{
|
|
248
248
|
hooks: routeMiddleware,
|
|
@@ -253,7 +253,7 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
|
253
253
|
case 4:
|
|
254
254
|
if (ev.request.method === "GET") return handleResponse(ev, url, template, await loadView(ev, url, handler, params, template));
|
|
255
255
|
else if (ev.request.method === "POST") {
|
|
256
|
-
const serverEndPoint = handler.serverEndPoint && (await handler
|
|
256
|
+
const serverEndPoint = handler.serverEndPoint && (await resolveServerModule(handler)).default;
|
|
257
257
|
return handleResponse(ev, url, template, await runAction(ev, url, handler, serverEndPoint, params, query, template), true);
|
|
258
258
|
}
|
|
259
259
|
break;
|
|
@@ -301,15 +301,40 @@ function createServerLoad(router, basePath = "", middleware = [], dev = false) {
|
|
|
301
301
|
};
|
|
302
302
|
}
|
|
303
303
|
/**
|
|
304
|
-
* Resolves the route's endpoint module, caching
|
|
305
|
-
* requests don't pay for the loader promise
|
|
304
|
+
* Resolves the route's endpoint module, caching the module on the handler so
|
|
305
|
+
* warm requests don't pay for the loader. The loader promise itself is never
|
|
306
|
+
* cached: a request that ends before it settles leaves it permanently
|
|
307
|
+
* unsettled on workerd (promises can't resolve across requests), and every
|
|
308
|
+
* later request for the route would fail on it. Two cold requests may each
|
|
309
|
+
* call the loader; `import()` is module-cached, so that costs an extra
|
|
310
|
+
* promise at most.
|
|
306
311
|
*/
|
|
307
312
|
async function resolveModule(handler) {
|
|
308
|
-
|
|
313
|
+
if (devMode) return await handler.endPoint();
|
|
314
|
+
if (handler.resolvedModule === void 0) handler.resolvedModule = await handler.endPoint();
|
|
315
|
+
return handler.resolvedModule;
|
|
309
316
|
}
|
|
317
|
+
/**
|
|
318
|
+
* Resolves the route's sibling server endpoint module (`+page.server.ts`),
|
|
319
|
+
* caching the module value like `resolveModule` does. The direct
|
|
320
|
+
* `serverEndPoint()` calls (route middleware, page actions, data requests,
|
|
321
|
+
* view loads) go through here so a warm route doesn't re-import per request.
|
|
322
|
+
*/
|
|
323
|
+
async function resolveServerModule(handler) {
|
|
324
|
+
if (!handler.serverEndPoint) return void 0;
|
|
325
|
+
if (devMode) return await handler.serverEndPoint();
|
|
326
|
+
if (handler.resolvedServerModule === void 0) handler.resolvedServerModule = await handler.serverEndPoint();
|
|
327
|
+
return handler.resolvedServerModule;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Resolves the route's folder hooks, caching the hook list on the handler as
|
|
331
|
+
* a value (never the promise -- see `resolveModule`).
|
|
332
|
+
*/
|
|
310
333
|
async function loadServerHooks(handler) {
|
|
311
334
|
if (!handler.serverHooks) return [];
|
|
312
|
-
return
|
|
335
|
+
if (devMode) return await Promise.all(handler.serverHooks.map(async (load) => (await load()).default));
|
|
336
|
+
if (handler.resolvedHooks === void 0) handler.resolvedHooks = await Promise.all(handler.serverHooks.map(async (load) => (await load()).default));
|
|
337
|
+
return handler.resolvedHooks;
|
|
313
338
|
}
|
|
314
339
|
/**
|
|
315
340
|
* Renders the site's nearest error page for a url, with the given status
|
|
@@ -338,7 +363,7 @@ async function renderErrorPage(ev, url, template, router, status, message) {
|
|
|
338
363
|
}
|
|
339
364
|
}
|
|
340
365
|
async function loadData(ev, url, handler, functionName, params) {
|
|
341
|
-
const serverEndPoint = (
|
|
366
|
+
const serverEndPoint = (await resolveModule(handler))?.default;
|
|
342
367
|
const handlerFn = serverEndPoint?.[functionName];
|
|
343
368
|
if (!serverEndPoint || !handlerFn) return notFound();
|
|
344
369
|
const paramsSchema = endpointSchema(serverEndPoint, "params");
|
|
@@ -379,7 +404,7 @@ async function loadData(ev, url, handler, functionName, params) {
|
|
|
379
404
|
* page (failure), exactly as it would with a single page load.
|
|
380
405
|
*/
|
|
381
406
|
async function loadPageData(ev, pageUrl, handler, params, reusedLayouts) {
|
|
382
|
-
const serverEndPoint = handler.serverEndPoint && (await handler
|
|
407
|
+
const serverEndPoint = handler.serverEndPoint && (await resolveServerModule(handler))?.default;
|
|
383
408
|
let query;
|
|
384
409
|
if (serverEndPoint) {
|
|
385
410
|
try {
|
|
@@ -525,7 +550,7 @@ async function loadView(ev, url, handler, params, template, status, form, fromFo
|
|
|
525
550
|
if (!clientEndPoint?.component) return notFound();
|
|
526
551
|
$page.flash = ev.flash.get();
|
|
527
552
|
if (!template) throw new Error("Page routes require a src/site.html file, which was not found; add it, or remove page/layout routes to serve endpoints only");
|
|
528
|
-
const serverEndPoint = handler.serverEndPoint && (await handler
|
|
553
|
+
const serverEndPoint = handler.serverEndPoint && (await resolveServerModule(handler))?.default;
|
|
529
554
|
let query;
|
|
530
555
|
if (serverEndPoint) {
|
|
531
556
|
try {
|
|
@@ -721,7 +746,7 @@ async function runAction(ev, url, handler, serverEndPoint, params, query, templa
|
|
|
721
746
|
let serverParams = void 0;
|
|
722
747
|
try {
|
|
723
748
|
const schema = endpointSchema(serverEndPoint, actionName);
|
|
724
|
-
const form = schema ? await validate(schema, await formDataToRecord(ev.
|
|
749
|
+
const form = schema ? await validate(schema, await formDataToRecord(await ev.formData())) : void 0;
|
|
725
750
|
serverParams = buildServerParams(ev, url, params, form ? { form } : {});
|
|
726
751
|
const serverHooks = await loadServerHooks(handler);
|
|
727
752
|
const actionParams = serverParams;
|
|
@@ -839,7 +864,8 @@ function buildServerParams(ev, url, params, values = {}, appData = {}) {
|
|
|
839
864
|
appData,
|
|
840
865
|
request: ev.request,
|
|
841
866
|
json: () => values.json !== void 0 ? Promise.resolve(values.json) : ev.json(),
|
|
842
|
-
form: () => values.form !== void 0 ? Promise.resolve(values.form) : formDataToRecord(ev.
|
|
867
|
+
form: async () => values.form !== void 0 ? Promise.resolve(values.form) : formDataToRecord(await ev.formData()),
|
|
868
|
+
formData: () => ev.formData(),
|
|
843
869
|
query: () => values.query !== void 0 ? Promise.resolve(values.query) : Promise.resolve(searchParamsToRecord(logicalUrl.searchParams)),
|
|
844
870
|
cookies: ev.cookies,
|
|
845
871
|
headers: ev.headers,
|
|
@@ -863,4 +889,4 @@ function escapeHtml(value) {
|
|
|
863
889
|
//#endregion
|
|
864
890
|
export { createServerLoad as t };
|
|
865
891
|
|
|
866
|
-
//# sourceMappingURL=serverHandlers-
|
|
892
|
+
//# sourceMappingURL=serverHandlers-Ba_35jpO.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"serverHandlers-Ba_35jpO.mjs","names":[],"sources":["../src/form/formDataToRecord.ts","../src/state/$serverPage.ts","../src/utils/searchParamsToRecord.ts","../src/validation/endpoint.ts","../src/site/layoutSlots.ts","../src/site/mergeHead.ts","../src/site/serverHandlers.ts"],"sourcesContent":["import type { FormDataRecord } from \"../types/ServerLoadEvent\";\n\n/**\n * Converts the submitted fields of a form request into a plain record: one\n * value per field, or an array when a field was submitted with multiple\n * values (e.g. a multi select). File inputs pass through as `File` values;\n * coercing them is left to the schema or the action.\n *\n * @param request The request (or FormData directly)\n * @returns The field values\n */\nexport default async function formDataToRecord(\n\trequest: Request | FormData,\n): Promise<FormDataRecord> {\n\tconst formData = request instanceof FormData ? request : await request.formData();\n\tconst result: FormDataRecord = {};\n\tfor (const key of formData.keys()) {\n\t\tif (key in result) continue;\n\t\tconst values = formData.getAll(key);\n\t\tresult[key] = values.length > 1 ? values : values[0];\n\t}\n\treturn result;\n}\n","import { $watch } from \"@torpor/view/ssr\";\nimport type PageState from \"../types/PageState\";\n\nconst PAGE_SYMBOL: unique symbol = Symbol.for(\"torp.Page\");\n\n// The server request path has no reactive subscribers, so the state is\n// stored plainly ($watch from `@torpor/view/ssr` is a no-op that returns\n// the object itself) instead of through a reactive proxy. Shares the same\n// `globalThis` slot as the client `$page`, so both variants always see the\n// same state object whichever loads first.\nconst $page: PageState =\n\t// @ts-ignore\n\t(globalThis[PAGE_SYMBOL] ??= $watch({\n\t\tstatus: 404,\n\t\turl: new URL(\"http://localhost\"),\n\t\tform: undefined,\n\t\tflash: undefined,\n\t\terror: {\n\t\t\tmessage: \"\",\n\t\t},\n\t}));\n\nexport default $page;\n","import type { QueryRecord } from \"../types/ServerLoadEvent\";\n\n/**\n * Converts a URL's query string into a plain record: one string per param,\n * or an array when a param was repeated.\n *\n * @param searchParams The URL's search params\n * @returns The param values\n */\nexport default function searchParamsToRecord(searchParams: URLSearchParams): QueryRecord {\n\tconst result: QueryRecord = {};\n\tfor (const key of searchParams.keys()) {\n\t\tif (key in result) continue;\n\t\tconst values = searchParams.getAll(key);\n\t\tresult[key] = values.length > 1 ? values : values[0];\n\t}\n\treturn result;\n}\n","import type PageServerEndPoint from \"../types/PageServerEndPoint\";\nimport type ServerEndPoint from \"../types/ServerEndPoint\";\nimport type { StandardSchemaV1 } from \"../types/StandardSchema\";\nimport type ServerEvent from \"../server/ServerEvent\";\nimport searchParamsToRecord from \"../utils/searchParamsToRecord\";\nimport unprocessable from \"../response/unprocessable\";\nimport ValidationError from \"./ValidationError\";\nimport validate from \"./validate\";\n\n/**\n * Loose views of an endpoint's schema map, keyed by handler/action name (plus\n * the reserved `params` key). The type-level constraint differs per endpoint\n * type, but the runtime treats them the same.\n */\ntype Schemas = Record<string, StandardSchemaV1 | undefined>;\n\ntype EndPoint = ServerEndPoint | PageServerEndPoint;\n\n/**\n * Gets the standard schema declared for a handler or action, if any. The\n * schemas map is keyed by name; the runtime treats it as a loose record.\n */\nexport function endpointSchema(endPoint: EndPoint, name: string): StandardSchemaV1 | undefined {\n\treturn (endPoint.schema as Schemas | undefined)?.[name];\n}\n\n/**\n * Validates the route params against the endpoint's `params` schema, if it\n * declares one, returning the coerced params. Throws a ValidationError when\n * they don't match, which callers turn into a 404 (params come from the URL,\n * so a failed validation means the resource doesn't exist).\n *\n * @param endPoint The endpoint declaring the (optional) `params` schema\n * @param params The route params from the matched route\n * @returns The validated params\n */\nexport async function validateEndpointParams(\n\tendPoint: EndPoint,\n\tparams: Record<string, any>,\n): Promise<Record<string, any>> {\n\tconst schema = endpointSchema(endPoint, \"params\");\n\treturn schema ? ((await validate(schema, params)) as Record<string, any>) : params;\n}\n\n/**\n * Validates a handler's input against its schema: get/head handlers and load\n * functions validate the URL's query string, other handlers validate the JSON\n * request body. Returns the validated values (an empty object when no schema\n * is declared), which callers pass through to the handler's event.\n *\n * @param schema The handler's (optional) schema\n * @param functionName The handler name (`get`, `post`, `load`, etc)\n * @param url The request URL, for the query string\n * @param ev The server event, for the request body\n * @returns The validated values\n */\nexport async function validateHandlerInput(\n\tschema: StandardSchemaV1 | undefined,\n\tfunctionName: string,\n\turl: URL,\n\tev: ServerEvent,\n): Promise<{ json?: unknown; form?: unknown; query?: unknown }> {\n\tif (!schema) return {};\n\tif (functionName === \"get\" || functionName === \"head\" || functionName === \"load\") {\n\t\treturn { query: await validate(schema, searchParamsToRecord(url.searchParams)) };\n\t}\n\treturn { json: await validate(schema, await ev.json()) };\n}\n\n/**\n * Turns a ValidationError thrown during endpoint validation into a 422\n * response with the schema's issues. Returns undefined for any other error,\n * which callers should rethrow.\n *\n * @param error The error thrown by a handler or validation\n * @returns A 422 response, or undefined when the error isn't a validation failure\n */\nexport function validationErrorResponse(error: unknown): Response | undefined {\n\tif (error instanceof ValidationError) {\n\t\treturn unprocessable({ message: error.message, issues: error.issues });\n\t}\n\treturn undefined;\n}\n","/**\n * Layouts are composed by the layout engine passing each layout (and finally\n * the page) as the default slot of its parent — so every `_layout` component\n * must render `<slot />`, or pass the default slot down to a child component\n * it renders. A layout that doesn't drops its entire content: the server\n * renders the layout's own markup with an empty content area (no error), and\n * the first client-side navigation that reuses the layout crashes on a null\n * slot region.\n *\n * The static `checkLayoutSlots` check catches this at build/dev time; these\n * helpers report it at request time for the cases static analysis can't see\n * (e.g. a `<slot />` rendered conditionally inside `@if`). They are\n * server-side only — nothing here is imported into the client bundle.\n */\n\n/**\n * Returns the path of the outermost layout that never rendered its\n * `<slot />`, or undefined when every level rendered.\n *\n * Slot level j (1-based) is the slot render that layout j - 1 receives: the\n * root layout (layouts[0]) renders level 1, layout i renders level i + 1,\n * and level layouts.length renders the page. A broken level makes every\n * deeper level unreachable, so the first level that never ran identifies\n * the offending layout.\n */\nexport function findMissingSlotLayout(\n\tlayouts: readonly { path: string }[],\n\tinvokedLevels: ReadonlySet<number>,\n): string | undefined {\n\tfor (let level = 1; level <= layouts.length; level++) {\n\t\tif (!invokedLevels.has(level)) {\n\t\t\treturn layouts[level - 1].path;\n\t\t}\n\t}\n\treturn undefined;\n}\n\nconst warnedLayouts = new Set<string>();\n\n/**\n * Reports a layout that dropped its slot content. The condition is a genuine\n * rendering bug (the page content is missing from the output), so it is not\n * dev-gated — but it warns only once per layout path to avoid per-request\n * noise.\n */ export function warnMissingSlotContent(layoutPath: string): void {\n\tif (warnedLayouts.has(layoutPath)) return;\n\twarnedLayouts.add(layoutPath);\n\tconsole.warn(\n\t\t`[torpor] The layout at \"${layoutPath}\" never rendered <slot />, so the page content ` +\n\t\t\t`was not included in the render. Every _layout component must render <slot /> (or ` +\n\t\t\t`pass the default slot down to a child component it renders).`,\n\t);\n}\n","const TITLE_REGEX = /<title(?:\\s[^>]*)?>[\\s\\S]*?<\\/title>/g;\nconst FIRST_TITLE_REGEX = /<title(?:\\s[^>]*)?>[\\s\\S]*?<\\/title>/;\n\n/**\n * Merges the head string rendered by a page (and its layouts) into the site\n * template. The first <title> in the head string -- the page's, since pages\n * render before the layouts around them -- wins, overriding both any later\n * component title (e.g. from a child component) and a static <title> in the\n * template itself. All other head content (styles, meta elements, etc) is\n * appended where %COMPONENT_HEAD% sits in the template, before </head>.\n */\nexport default function mergeHead(template: string, head: string): string {\n\tconst titles = head.match(TITLE_REGEX);\n\tlet html = template;\n\tlet headHtml = head;\n\tif (titles?.length) {\n\t\theadHtml = head.replace(TITLE_REGEX, \"\");\n\t\thtml = html.replace(FIRST_TITLE_REGEX, \"\");\n\t\theadHtml = titles[0] + headHtml;\n\t}\n\treturn html.replace(\"%COMPONENT_HEAD%\", headHtml);\n}\n","import { type ServerComponent, type ServerSlotRender } from \"@torpor/view/ssr\";\nimport { DATA_REUSE_HEADER, DATA_REQUEST_HEADER } from \"../dataRequest.ts\";\nimport { type DeferredMeta, jsonForScript, splitDeferred } from \"../deferred.ts\";\nimport formDataToRecord from \"../form/formDataToRecord.ts\";\nimport notFound from \"../response/notFound.ts\";\nimport ok from \"../response/ok.ts\";\nimport { readResponseBody } from \"../response/read.ts\";\nimport ServerEvent from \"../server/ServerEvent.ts\";\nimport runHooks from \"../server/runHooks.ts\";\nimport type MiddlewareFunction from \"../server/types/MiddlewareFunction\";\nimport $page from \"../state/$serverPage.ts\";\nimport type PageEndPoint from \"../types/PageEndPoint.ts\";\nimport type { HeadElement } from \"../types/PageEndPoint.ts\";\nimport type PageLoadEvent from \"../types/PageLoadEvent.ts\";\nimport type PageServerEndPoint from \"../types/PageServerEndPoint.ts\";\nimport type RouteHandler from \"../types/RouteHandler.ts\";\nimport type ServerRequest from \"../types/ServerRequest.ts\";\nimport {\n\tERROR_ROUTE,\n\tHOOK_ROUTE,\n\tHOOK_SERVER_ROUTE,\n\tLAYOUT_ROUTE,\n\tLAYOUT_SERVER_ROUTE,\n\tPAGE_ROUTE,\n\tPAGE_SERVER_ROUTE,\n\tSERVER_ROUTE,\n} from \"../types/RouteType\";\nimport type ServerEndPoint from \"../types/ServerEndPoint.ts\";\nimport type ServerHook from \"../types/ServerHook.ts\";\nimport type ServerLoadEvent from \"../types/ServerLoadEvent.ts\";\nimport searchParamsToRecord from \"../utils/searchParamsToRecord.ts\";\nimport validate from \"../validation/validate.ts\";\nimport ValidationError from \"../validation/ValidationError.ts\";\nimport {\n\tendpointSchema,\n\tvalidateEndpointParams,\n\tvalidationErrorResponse,\n} from \"../validation/endpoint.ts\";\nimport { findMissingSlotLayout, warnMissingSlotContent } from \"./layoutSlots.ts\";\nimport { getBasePath, rewriteBaseInHtml, setBasePath, stripBaseFromUrl } from \"./basePath.ts\";\nimport findErrorRoute from \"./findErrorRoute.ts\";\nimport mergeHead from \"./mergeHead.ts\";\nimport type Router from \"./Router.ts\";\n\n/**\n * The site's request handler, as created by `createServerLoad`.\n */\nexport type ServerLoad = (ev: ServerEvent, template?: string) => Promise<Response>;\n\n/** Whether the site is running under `tb --dev` (set by `createServerLoad`). */\nlet devMode = false;\n\n/** Route paths already reminded about embedded-data caching, so it warns once. */\nconst warnedEmbedRoutes = new Set<string>();\n\n/**\n * Dev-only reminder for a page that embeds its server data in the HTML (so a\n * shared cache could serve one user's data to another) without an explicit\n * `Cache-Control`. Setting any `Cache-Control` — `private`/`no-store` for\n * user-specific data, `public` for pages that are safe to share — silences it.\n * Warns once per route path.\n */\nfunction warnUncachedEmbeddedData(ev: ServerEvent, path: string): void {\n\tif (!devMode || warnedEmbedRoutes.has(path)) return;\n\t// Only an explicitly-set response header counts; header names are\n\t// case-insensitive, so scan rather than a single map lookup\n\tfor (const name of ev.headers.headers.keys()) {\n\t\tif (name.toLowerCase() === \"cache-control\") return;\n\t}\n\twarnedEmbedRoutes.add(path);\n\tconsole.warn(\n\t\t`[torpor] The page at \"${path}\" embeds its server load data in the HTML but sets no ` +\n\t\t\t`Cache-Control, so a shared cache could serve one user's data to another. Set it on ` +\n\t\t\t`the response from a load or hook — \"private, no-cache\" (or \"no-store\") for ` +\n\t\t\t`user-specific data, or \"public\" if the page is safe to share.`,\n\t);\n}\n\n/**\n * Creates the site's request handler for the given router. This is kept\n * separate from serverEntry, which imports the virtual\n * `@torpor/build/manifest` module (it only exists when a site runs or\n * builds), so that tests can exercise the handlers with their own routes.\n *\n * @param router The router, built from the site's routes\n * @param basePath The site's base path, stripped from incoming URLs before\n * routing (see basePath.ts)\n * @param middleware Global middleware (from `site.middleware`), run for\n * every request before routing -- including requests that won't match a\n * route\n * @returns The request handler, which takes the site template\n */\nexport function createServerLoad(\n\trouter: Router,\n\tbasePath = \"\",\n\tmiddleware: MiddlewareFunction[] = [],\n\tdev = false,\n): ServerLoad {\n\t// The base path is shared through module state, so that everything that\n\t// generates URLs (HTML attributes, redirect locations) sees the same\n\t// value the router strips\n\tsetBasePath(basePath);\n\tdevMode = dev;\n\n\t/**\n\t * Finalizes the response of a load or action. Successful responses and\n\t * redirects pass through; an error response gets the site's error page\n\t * rendered at the requested url, with the error's status code -- the\n\t * address bar keeps the url the user asked for, so a transient failure\n\t * (a random db hiccup, say) can be refreshed, and a typo in the path can\n\t * be seen and fixed.\n\t */\n\tasync function handleResponse(\n\t\tev: ServerEvent,\n\t\turl: URL,\n\t\ttemplate: string | undefined,\n\t\tresponse: Response,\n\t\tfromForm = false,\n\t): Promise<Response> {\n\t\t// Success codes and redirect codes are acceptable\n\t\tif (response.status >= 200 && response.status <= 399) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// 4xx error codes are acceptable from form actions\n\t\tif (fromForm && response.status >= 400 && response.status <= 499) {\n\t\t\treturn response;\n\t\t}\n\n\t\t// Read a clone, not the response itself: when the error page can't\n\t\t// render (e.g. its own load redirects), the original response is\n\t\t// returned below and its body must still be readable\n\t\tlet message = await response.clone().text();\n\t\tif (response.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\ttry {\n\t\t\t\tconst data = JSON.parse(message);\n\t\t\t\tmessage = data.message ?? message;\n\t\t\t} catch {\n\t\t\t\t// Not actually json, so show the raw body\n\t\t\t}\n\t\t}\n\t\tconst rendered = await renderErrorPage(ev, url, template, router, response.status, message);\n\t\t// No error page (or rendering it failed), so the response is passed\n\t\t// through as-is\n\t\treturn rendered ?? response;\n\t}\n\n\tconst handle = async (ev: ServerEvent, template?: string): Promise<Response> => {\n\t\t// The base is stripped before routing, so that everything below (route\n\t\t// matching, params, user code reading `event.url`) is base-free.\n\t\t// Requests that don't carry the base aren't ours\n\t\tconst url = stripBaseFromUrl(ev.url, basePath);\n\t\tif (!url) {\n\t\t\t// Like any other error, the error page is rendered at the\n\t\t\t// requested url rather than redirecting into the site\n\t\t\t$page.url = ev.url;\n\t\t\tconst response = await renderErrorPage(ev, ev.url, template, router, 404, \"Not found\");\n\t\t\treturn response ?? notFound();\n\t\t}\n\t\tconst path = url.pathname;\n\t\tconst query = url.searchParams;\n\n\t\t// A client data request: one GET to `<page url>/~server` returns the\n\t\t// server data for the page and all of its layouts, with hooks running\n\t\t// once against the page url. It doesn't need a registered `~server`\n\t\t// route (a page may have no `+page.server.ts` but still have layouts\n\t\t// with server loads)\n\t\tif (\n\t\t\tev.request.method === \"GET\" &&\n\t\t\tev.request.headers.has(DATA_REQUEST_HEADER) &&\n\t\t\tpath.endsWith(\"/~server\")\n\t\t) {\n\t\t\tconst pagePath = path.slice(0, -\"/~server\".length) || \"/\";\n\t\t\tconst pageUrl = new URL(pagePath + url.search, url);\n\t\t\tconst pageRoute = router.match(pagePath, query);\n\t\t\tif (pageRoute) {\n\t\t\t\t$page.url = pageUrl;\n\t\t\t\treturn await loadPageData(\n\t\t\t\t\tev,\n\t\t\t\t\tpageUrl,\n\t\t\t\t\tpageRoute.handler,\n\t\t\t\t\tpageRoute.params ?? {},\n\t\t\t\t\treusedLayoutPaths(ev),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\n\t\t//console.log(`handling ${ev.request.method} for '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\t\t// Update $page before routing, so that a request that doesn't match\n\t\t// any route (and gets the error page) still sees this url\n\t\t$page.url = url;\n\t\tif (path.endsWith(\"/_error\")) {\n\t\t\t$page.status = parseInt(query.get(\"status\") ?? \"404\");\n\t\t\t$page.error = { message: query.get(\"message\") ?? \"\" };\n\t\t} else {\n\t\t\t$page.status = 200;\n\t\t\t$page.error = { message: \"\" };\n\t\t}\n\n\t\tlet route = router.match(path, query);\n\t\tif (!route) {\n\t\t\t// If the route wasn't found, the user may be posting a form to a\n\t\t\t// +page.server.ts route that doesn't have a corresponding +page.ts\n\t\t\t// route, which is allowed, so check for that as well\n\t\t\tif (ev.request.method === \"POST\" && !path.endsWith(\"/~server\")) {\n\t\t\t\tconst serverPath =\n\t\t\t\t\t(path.endsWith(\"/\") ? path.substring(0, path.length - 1) : path) + \"/~server\";\n\t\t\t\troute = router.match(serverPath, query);\n\t\t\t}\n\t\t}\n\t\tif (!route) {\n\t\t\treturn handleResponse(ev, url, template, notFound());\n\t\t}\n\t\tconst handler = route.handler;\n\t\tconst params = route.params || {};\n\t\t// Route middleware, declared on the route's server endpoint\n\t\t// (+page.server.ts / +server.ts). Runs after the global middleware and\n\t\t// before folder hooks, so a guard can skip data loading entirely\n\t\tconst routeMiddleware: MiddlewareFunction[] = [];\n\t\tconst endPointModule = handler.serverEndPoint\n\t\t\t? (await resolveServerModule(handler))?.default\n\t\t\t: handler.type === PAGE_SERVER_ROUTE || handler.type === SERVER_ROUTE\n\t\t\t\t? (await resolveModule(handler))?.default\n\t\t\t\t: undefined;\n\t\tif (Array.isArray(endPointModule?.middleware)) {\n\t\t\trouteMiddleware.push(...endPointModule.middleware);\n\t\t}\n\n\t\t// TODO: Hit the server hook out here\n\t\t// We could maybe set up data loading as middleware on a route??????\n\n\t\t// Run the route's middleware around the handler: enter hooks in order\n\t\t// (a Response short-circuits the request), exit hooks in reverse\n\t\tconst { response: routeResponse, error } = await runHooks(\n\t\t\t[{ hooks: routeMiddleware, arg: ev }],\n\t\t\tasync () => {\n\t\t\t\tswitch (handler.type) {\n\t\t\t\t\tcase PAGE_ROUTE:\n\t\t\t\t\tcase LAYOUT_ROUTE: {\n\t\t\t\t\t\t// It's a /+page.ts or /_layout.ts endpoint\n\t\t\t\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\t\t\t\treturn handleResponse(\n\t\t\t\t\t\t\t\tev,\n\t\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t\ttemplate,\n\t\t\t\t\t\t\t\tawait loadView(ev, url, handler, params, template),\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t} else if (ev.request.method === \"POST\") {\n\t\t\t\t\t\t\t// The server end point comes from the sibling /+page.server.ts, if applicable\n\t\t\t\t\t\t\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\t\t\t\thandler.serverEndPoint && (await resolveServerModule(handler)).default;\n\t\t\t\t\t\t\treturn handleResponse(\n\t\t\t\t\t\t\t\tev,\n\t\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t\ttemplate,\n\t\t\t\t\t\t\t\tawait runAction(ev, url, handler, serverEndPoint, params, query, template),\n\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase PAGE_SERVER_ROUTE:\n\t\t\t\t\tcase LAYOUT_SERVER_ROUTE: {\n\t\t\t\t\t\t// It's a /+page.server.ts or /_layout.server.ts endpoint\n\t\t\t\t\t\tif (ev.request.method === \"GET\") {\n\t\t\t\t\t\t\treturn await loadData(ev, url, handler, \"load\", params);\n\t\t\t\t\t\t} else if (ev.request.method === \"POST\") {\n\t\t\t\t\t\t\tconst serverEndPoint: PageServerEndPoint | undefined = (await resolveModule(handler))\n\t\t\t\t\t\t\t\t.default;\n\t\t\t\t\t\t\treturn handleResponse(\n\t\t\t\t\t\t\t\tev,\n\t\t\t\t\t\t\t\turl,\n\t\t\t\t\t\t\t\ttemplate,\n\t\t\t\t\t\t\t\tawait runAction(ev, url, handler, serverEndPoint, params, query, template),\n\t\t\t\t\t\t\t\ttrue,\n\t\t\t\t\t\t\t);\n\t\t\t\t\t\t}\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase SERVER_ROUTE: {\n\t\t\t\t\t\t// It's a /+server.ts endpoint\n\t\t\t\t\t\tconst functionName = ev.request.method.toLowerCase().replace(\"delete\", \"del\");\n\t\t\t\t\t\treturn await loadData(ev, url, handler, functionName, params);\n\t\t\t\t\t}\n\t\t\t\t\tcase HOOK_ROUTE:\n\t\t\t\t\tcase HOOK_SERVER_ROUTE: {\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t\tcase ERROR_ROUTE: {\n\t\t\t\t\t\t// A direct request for the error page (e.g. a bookmark of\n\t\t\t\t\t\t// the url it used to be redirected to, or the prerender\n\t\t\t\t\t\t// writing 404.html). It responds with the requested status\n\t\t\t\t\t\t// rather than 200\n\t\t\t\t\t\treturn await loadView(ev, url, handler, params, template, $page.status);\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\treturn undefined;\n\t\t\t},\n\t\t\t{ event: ev },\n\t\t);\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\n\t\treturn routeResponse ?? notFound();\n\t};\n\n\treturn async function load(ev: ServerEvent, template?: string): Promise<Response> {\n\t\t// Global middleware, from `site.middleware`: runs for every request\n\t\t// before routing, including ones that won't match a route\n\t\t// (maintenance mode, legacy url redirects, etc)\n\t\tconst { response, error } = await runHooks(\n\t\t\t[{ hooks: middleware, arg: ev }],\n\t\t\tasync () => {\n\t\t\t\treturn await handle(ev, template);\n\t\t\t},\n\t\t\t{\n\t\t\t\tevent: ev,\n\t\t\t\tonError: async (ev, error) => {\n\t\t\t\t\t// A thrown exception (a load or component crashing, say) gets the\n\t\t\t\t\t// error page rendered at the requested url, like an error response\n\t\t\t\t\t// would -- unless the request was for an api endpoint (json in,\n\t\t\t\t\t// json out), or there is no error page, or rendering it failed, in\n\t\t\t\t\t// which case the error is rethrown for the server adapters\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst url = stripBaseFromUrl(ev.url, basePath) ?? ev.url;\n\t\t\t\t\t\tconst match = router.match(url.pathname, url.searchParams);\n\t\t\t\t\t\tif (match?.handler.type !== SERVER_ROUTE) {\n\t\t\t\t\t\t\t$page.url = url;\n\t\t\t\t\t\t\tconst message = error instanceof Error ? error.message : String(error);\n\t\t\t\t\t\t\treturn await renderErrorPage(ev, url, template, router, 500, message);\n\t\t\t\t\t\t}\n\t\t\t\t\t} catch {\n\t\t\t\t\t\t// Fall through to the rethrow\n\t\t\t\t\t}\n\t\t\t\t\tthrow error;\n\t\t\t\t},\n\t\t\t},\n\t\t);\n\t\tif (error && !response) {\n\t\t\tthrow error;\n\t\t}\n\t\t// handle() always returns a Response (notFound() on a fall-through)\n\t\treturn response as Response;\n\t};\n}\n\n/**\n * Resolves the route's endpoint module, caching the module on the handler so\n * warm requests don't pay for the loader. The loader promise itself is never\n * cached: a request that ends before it settles leaves it permanently\n * unsettled on workerd (promises can't resolve across requests), and every\n * later request for the route would fail on it. Two cold requests may each\n * call the loader; `import()` is module-cached, so that costs an extra\n * promise at most.\n */\nasync function resolveModule(handler: RouteHandler): Promise<any> {\n\t// In dev the loaders go through Vite's module runner, which re-imports a\n\t// module when its file is edited -- caching here would serve stale code\n\t// until restart, so dev resolves fresh on every request\n\tif (devMode) return await handler.endPoint();\n\tif (handler.resolvedModule === undefined) {\n\t\thandler.resolvedModule = await handler.endPoint();\n\t}\n\treturn handler.resolvedModule;\n}\n\n/**\n * Resolves the route's sibling server endpoint module (`+page.server.ts`),\n * caching the module value like `resolveModule` does. The direct\n * `serverEndPoint()` calls (route middleware, page actions, data requests,\n * view loads) go through here so a warm route doesn't re-import per request.\n */\nasync function resolveServerModule(handler: RouteHandler): Promise<any> {\n\tif (!handler.serverEndPoint) return undefined;\n\tif (devMode) return await handler.serverEndPoint();\n\tif (handler.resolvedServerModule === undefined) {\n\t\thandler.resolvedServerModule = await handler.serverEndPoint();\n\t}\n\treturn handler.resolvedServerModule;\n}\n\n/**\n * Resolves the route's folder hooks, caching the hook list on the handler as\n * a value (never the promise -- see `resolveModule`).\n */\nasync function loadServerHooks(handler: RouteHandler): Promise<ServerHook[]> {\n\tif (!handler.serverHooks) return [];\n\tif (devMode) {\n\t\treturn await Promise.all(handler.serverHooks.map(async (load) => (await load()).default));\n\t}\n\tif (handler.resolvedHooks === undefined) {\n\t\thandler.resolvedHooks = await Promise.all(\n\t\t\thandler.serverHooks.map(async (load) => (await load()).default),\n\t\t);\n\t}\n\treturn handler.resolvedHooks;\n}\n\n/**\n * Renders the site's nearest error page for a url, with the given status\n * code and message, at the url itself. Returns undefined when the site has\n * no matching error route, or when rendering the error page failed -- the\n * caller passes the original response or error through instead.\n *\n * The error page runs through the normal view pipeline, so it is rendered\n * inside the layouts of its route (e.g. the root `/_error` gets the root\n * `_layout`).\n */\nasync function renderErrorPage(\n\tev: ServerEvent,\n\turl: URL,\n\ttemplate: string | undefined,\n\trouter: Router,\n\tstatus: number,\n\tmessage: string,\n): Promise<Response | undefined> {\n\tconst errorPath = findErrorRoute(router, url.pathname);\n\tif (!errorPath) {\n\t\treturn undefined;\n\t}\n\t// Matched (rather than picked off `router.routes`) so that the error\n\t// route's layouts, server endpoint and hooks get loaded\n\tconst errorRoute = router.match(errorPath, new URLSearchParams());\n\tif (!errorRoute) {\n\t\treturn undefined;\n\t}\n\n\t$page.status = status;\n\t$page.error = { message };\n\n\ttry {\n\t\tconst response = await loadView(ev, url, errorRoute.handler, {}, template, status);\n\t\t// A load or layout of the error page can itself fail -- loadView\n\t\t// returns its response, which (unlike a rendered error page) won't\n\t\t// be html. The caller passes the original response through instead\n\t\tif (response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\treturn response;\n\t\t}\n\t\treturn undefined;\n\t} catch (error) {\n\t\t// The error page itself blew up; the caller's original response or\n\t\t// error is the better fallback\n\t\tconsole.log(error);\n\t\treturn undefined;\n\t}\n}\n\nasync function loadData(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tfunctionName: string,\n\tparams: Record<string, any>,\n) {\n\tconst mod = await resolveModule(handler);\n\tconst serverEndPoint: ServerEndPoint | undefined = mod?.default;\n\t// `functionName` is computed from the request method, so the handlers are\n\t// accessed through a loose record\n\tconst handlerFn = (\n\t\tserverEndPoint as unknown as Record<string, ServerRequest | undefined> | undefined\n\t)?.[functionName];\n\tif (!serverEndPoint || !handlerFn) {\n\t\treturn notFound();\n\t}\n\n\t// Route params come from the URL, so a failed validation means the\n\t// resource doesn't exist. Only endpoints declaring a params schema pay\n\t// for validation\n\tconst paramsSchema = endpointSchema(serverEndPoint, \"params\");\n\tif (paramsSchema) {\n\t\ttry {\n\t\t\tparams = (await validate(paramsSchema, params)) as Record<string, any>;\n\t\t} catch (error) {\n\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\ttry {\n\t\t// If the endpoint declares a schema for this handler, validate its\n\t\t// input up front and reject with 422 if it fails. get/head/load\n\t\t// schemas validate the query string; other schemas validate the json\n\t\t// body. Endpoints without a schema skip straight to the handler\n\t\tconst schema = endpointSchema(serverEndPoint, functionName);\n\t\tconst values = schema\n\t\t\t? functionName === \"get\" || functionName === \"head\" || functionName === \"load\"\n\t\t\t\t? { query: await validate(schema, searchParamsToRecord(url.searchParams)) }\n\t\t\t\t: { json: await validate(schema, await ev.json()) }\n\t\t\t: {};\n\n\t\tconst serverParams = buildServerParams(ev, url, params, values);\n\n\t\t// Hooks are resolved once per handler; routes without hooks don't\n\t\t// await anything here\n\t\tconst hooks = handler.serverHooks ? await loadServerHooks(handler) : [];\n\n\t\tconst { response, error } = await runHooks([{ hooks, arg: serverParams }], async () => {\n\t\t\treturn (await handlerFn(serverParams)) || undefined;\n\t\t});\n\t\tif (error) {\n\t\t\tthrow error;\n\t\t}\n\n\t\t// A hook's enter response short-circuits the request; otherwise, if\n\t\t// there was no response returned from load (such as errors or a\n\t\t// redirect), send an ok response\n\t\treturn response || ok();\n\t} catch (error) {\n\t\tconst response = validationErrorResponse(error);\n\t\tif (response) return response;\n\t\tthrow error;\n\t}\n}\n\n/**\n * Handles a client data request (see `DATA_REQUEST_HEADER`). Runs the folder\n * hooks once against the page url, then loads the server data for each layout\n * (root to leaf) and the page, returning `{ loads: [...] }` -- one entry per\n * layout plus the page, in the same order as `handler.layouts`. The client\n * runs its own load functions and merges the server entries in.\n *\n * A load that redirects or fails short-circuits the whole request, so the\n * client can fall back to a full page load (redirect) or render the error\n * page (failure), exactly as it would with a single page load.\n */\nasync function loadPageData(\n\tev: ServerEvent,\n\tpageUrl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, any>,\n\treusedLayouts: Set<string>,\n): Promise<Response> {\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await resolveServerModule(handler))?.default;\n\n\t// Validate params and the load query against the page's server endpoint\n\t// schemas, mirroring a normal page render. Params come from the url, so a\n\t// failed params validation means the resource doesn't exist\n\tlet query: unknown;\n\tif (serverEndPoint) {\n\t\ttry {\n\t\t\tparams = await validateEndpointParams(serverEndPoint, params);\n\t\t} catch (error) {\n\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\tthrow error;\n\t\t}\n\t\tconst loadSchema = endpointSchema(serverEndPoint, \"load\");\n\t\tif (loadSchema) {\n\t\t\ttry {\n\t\t\t\tquery = await validate(loadSchema, searchParamsToRecord(pageUrl.searchParams));\n\t\t\t} catch (error) {\n\t\t\t\tconst response = validationErrorResponse(error);\n\t\t\t\tif (response) return response;\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t}\n\t}\n\n\tconst serverParams = buildServerParams(ev, pageUrl, params, query ? { query } : {});\n\tconst serverHooks = await loadServerHooks(handler);\n\t// Route middleware, declared on the page's server endpoint. Runs before\n\t// the folder hooks, like it does for a normal request\n\tconst routeMiddleware = Array.isArray(serverEndPoint?.middleware)\n\t\t? serverEndPoint.middleware\n\t\t: [];\n\n\t// One entry per layout (root to leaf) followed by the page itself\n\tconst loads: (Record<string, any> | null)[] = [];\n\n\tconst { response, error } = await runHooks(\n\t\t[\n\t\t\t// Route middleware, declared on the page's server endpoint. Runs\n\t\t\t// before the folder hooks, like it does for a normal request\n\t\t\t{ hooks: routeMiddleware, arg: ev },\n\t\t\t// Hooks run from the root down; a hook's enter can return a Response\n\t\t\t// to short-circuit the request (e.g. an auth redirect)\n\t\t\t{ hooks: serverHooks, arg: serverParams },\n\t\t],\n\t\tasync () => {\n\t\t\tfor (const layout of handler.layouts ?? []) {\n\t\t\t\t// A reused layout keeps its cached data on the client, so skip its\n\t\t\t\t// load (and any side effects) but keep the slot aligned\n\t\t\t\tif (reusedLayouts.has(layout.path)) {\n\t\t\t\t\tloads.push(null);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\t\tconst result = await loadRouteServerData(layoutServerEndPoint, serverParams);\n\t\t\t\tif (result instanceof Response) return result;\n\t\t\t\tloads.push(result);\n\t\t\t}\n\n\t\t\tconst pageResult = await loadRouteServerData(serverEndPoint, serverParams);\n\t\t\tif (pageResult instanceof Response) return pageResult;\n\t\t\tloads.push(pageResult);\n\n\t\t\treturn serverDataResponse(loads);\n\t\t},\n\t\t{ event: ev },\n\t);\n\tif (error) {\n\t\tthrow error;\n\t}\n\treturn response as Response;\n}\n\ntype LoadDeferredEntry = {\n\tid: string;\n\tmeta: DeferredMeta;\n\tpromise: PromiseLike<unknown>;\n};\n\n/**\n * Splits each route's server data into critical values and deferred entries,\n * assigning ids in response order. Both the streaming data response and the\n * SSR-embedded payload use this so their ids/paths line up.\n */\nfunction splitLoads(loads: (Record<string, any> | null)[]): {\n\tcriticalLoads: (Record<string, any> | null)[];\n\tentries: LoadDeferredEntry[];\n} {\n\tconst entries: LoadDeferredEntry[] = [];\n\tconst criticalLoads = loads.map((load, index) => {\n\t\tif (load === null) return null;\n\t\tconst { critical, entries: splitEntries } = splitDeferred(load);\n\t\tfor (const entry of splitEntries) {\n\t\t\tconst id = `d${entries.length}`;\n\t\t\tentries.push({\n\t\t\t\tid,\n\t\t\t\tmeta: { id, index, path: entry.path },\n\t\t\t\tpromise: entry.promise,\n\t\t\t});\n\t\t}\n\t\treturn critical as Record<string, any>;\n\t});\n\treturn { criticalLoads, entries };\n}\n\n/**\n * Serializes a data request's loads. Critical (non-promise) values go in the\n * first frame as one JSON object per route; promise-valued properties are\n * announced in the same frame and then streamed as NDJSON frames, so a\n * navigation can mount as soon as the critical data arrives.\n */\nfunction serverDataResponse(loads: (Record<string, any> | null)[]): Response {\n\tconst { criticalLoads, entries } = splitLoads(loads);\n\n\tif (entries.length === 0) {\n\t\treturn new Response(JSON.stringify({ loads: criticalLoads }), {\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t});\n\t}\n\n\tconst first = {\n\t\ttype: \"data\",\n\t\tloads: criticalLoads,\n\t\tdeferred: entries.map((entry) => entry.meta),\n\t};\n\tconst encoder = new TextEncoder();\n\tlet cancelled = false;\n\tconst stream = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst write = (frame: object) => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(JSON.stringify(frame) + \"\\n\"));\n\t\t\t\t} catch {\n\t\t\t\t\t// The client went away; the promise handlers below finish\n\t\t\t\t\t// without anything left to write to\n\t\t\t\t}\n\t\t\t};\n\t\t\twrite(first);\n\t\t\tvoid Promise.all(\n\t\t\t\tentries.map(async (entry) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\twrite({ type: \"value\", id: entry.id, value: await entry.promise });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\twrite({ type: \"error\", id: entry.id, message: errorMessage(error) });\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t).finally(() => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Already closed by an aborted stream\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tcancelled = true;\n\t\t},\n\t});\n\treturn new Response(stream, {\n\t\theaders: { \"Content-Type\": \"application/x-ndjson\" },\n\t});\n}\n\nfunction errorMessage(error: unknown): string {\n\treturn error instanceof Error ? error.message : String(error);\n}\n\n/**\n * Runs a single route's server load (if any) as part of a data request.\n * Returns the loaded data, `null` when the route has no load, or the raw\n * Response when the load redirected or failed.\n */\nasync function loadRouteServerData(\n\tserverEndPoint: PageServerEndPoint | undefined,\n\tserverParams: ServerLoadEvent,\n): Promise<Record<string, any> | null | Response> {\n\tif (!serverEndPoint?.load) return null;\n\tconst response = await serverEndPoint.load(serverParams);\n\tif (!response) return null;\n\tif (!response.ok) return response;\n\treturn (await readResponseBody(response)) ?? null;\n}\n\nasync function loadView(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tparams: Record<string, any>,\n\ttemplate: string | undefined,\n\t// The status to respond with: a form action's result status, or an\n\t// error page's status (404, 500, ...). Defaults to 200\n\tstatus?: number,\n\tform?: Record<string, string | number>,\n\tfromForm?: boolean,\n\t// The appData that the server hooks populated around the form action,\n\t// passed through so the re-render's loads see the same data\n\tappData?: Record<string, any>,\n) {\n\t// There must be a client endpoint with a component\n\tconst clientEndPoint: PageEndPoint | undefined = (await resolveModule(handler)).default;\n\tif (!clientEndPoint?.component) {\n\t\treturn notFound();\n\t}\n\n\t// Consume the flash message when a page is rendered (but not for API\n\t// requests), so that the following page -- and only that page -- can show\n\t// it. For a form action that re-renders instead of redirecting, the\n\t// message is set and read within this request\n\t$page.flash = ev.flash.get();\n\n\t// The template comes from site.html, which endpoints-only sites don't have\n\tif (!template) {\n\t\tthrow new Error(\n\t\t\t\"Page routes require a src/site.html file, which was not found; add it, or remove page/layout routes to serve endpoints only\",\n\t\t);\n\t}\n\n\t// There may be a server endpoint\n\tconst serverEndPoint: PageServerEndPoint | undefined =\n\t\thandler.serverEndPoint && (await resolveServerModule(handler))?.default;\n\n\t// Validate the route params and the load query against the server\n\t// endpoint's schemas, if it declares any. Params come from the URL, so a\n\t// failed validation means the resource doesn't exist; a failed query goes\n\t// to the error page like any other load failure\n\tlet query: unknown;\n\tif (serverEndPoint) {\n\t\ttry {\n\t\t\tparams = await validateEndpointParams(serverEndPoint, params);\n\t\t} catch (error) {\n\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\tthrow error;\n\t\t}\n\t\tconst loadSchema = endpointSchema(serverEndPoint, \"load\");\n\t\tif (loadSchema) {\n\t\t\tconst queryRecord = searchParamsToRecord(url.searchParams);\n\t\t\ttry {\n\t\t\t\tquery = await validate(loadSchema, queryRecord);\n\t\t\t} catch (error) {\n\t\t\t\t// A form re-render's url is the POST's, and a form action can\n\t\t\t\t// drop query params that the load schema requires, so failing\n\t\t\t\t// validation here would lose the form errors. Fall back to the\n\t\t\t\t// raw query values instead and let the load make of them what\n\t\t\t\t// it can\n\t\t\t\tif (fromForm) {\n\t\t\t\t\tquery = queryRecord;\n\t\t\t\t} else {\n\t\t\t\t\tconst response = validationErrorResponse(error);\n\t\t\t\t\tif (response) return response;\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// Maybe hit the server hooks -- unless they already ran for this request,\n\t// which is the case when the view is re-rendered after a form action. In\n\t// that case the hooks' appData is passed through, so that the loads below\n\t// see the same data (e.g. the user set by an auth hook) as the action did\n\tconst serverParams = buildServerParams(ev, url, params, query ? { query } : {}, appData);\n\tconst serverHooks = fromForm ? [] : await loadServerHooks(handler);\n\t// Promise-valued server data, streamed to the client after the critical\n\t// data (see the embedding block below)\n\tlet deferredEntries: LoadDeferredEntry[] = [];\n\n\t// Hooks run around the view render: enter hooks in order (a Response\n\t// short-circuits the render), exit hooks in reverse\n\tconst { response, error } = await runHooks(\n\t\t[{ hooks: serverHooks, arg: serverParams }],\n\t\tasync () => {\n\t\t\t// Pass the data into $props\n\t\t\t// TODO: Promise.all\n\t\t\t// NOTE: We're loading data from top to bottom, overriding as we go, and I'm\n\t\t\t// not sure if this is the best way to go\n\t\t\tlet data = {};\n\t\t\t// Each route's server-only data (root layout to page), embedded into\n\t\t\t// the HTML so the first hydration doesn't refetch it (nav/loadData.ts)\n\t\t\tconst loads: (Record<string, any> | null)[] = [];\n\t\t\tif (handler.layouts) {\n\t\t\t\tfor (let layout of handler.layouts) {\n\t\t\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\t\t\tconst layoutServerEndPoint: PageServerEndPoint | undefined =\n\t\t\t\t\t\tlayout.serverEndPoint && (await layout.serverEndPoint())?.default;\n\t\t\t\t\tconst layoutResponse = await loadClientAndServerData(\n\t\t\t\t\t\turl,\n\t\t\t\t\t\tparams,\n\t\t\t\t\t\tserverParams,\n\t\t\t\t\t\tdata,\n\t\t\t\t\t\tlayoutEndPoint,\n\t\t\t\t\t\tlayoutServerEndPoint,\n\t\t\t\t\t\tloads,\n\t\t\t\t\t);\n\t\t\t\t\tif (layoutResponse?.ok === false) {\n\t\t\t\t\t\treturn layoutResponse;\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t\tlet endPointResponse = await loadClientAndServerData(\n\t\t\t\turl,\n\t\t\t\tparams,\n\t\t\t\tserverParams,\n\t\t\t\tdata,\n\t\t\t\tclientEndPoint,\n\t\t\t\tserverEndPoint,\n\t\t\t\tloads,\n\t\t\t);\n\t\t\tif (endPointResponse?.ok === false) {\n\t\t\t\treturn endPointResponse;\n\t\t\t}\n\t\t\tlet $props: Record<string, any> = { data, form };\n\n\t\t\tlet styles = \"\";\n\n\t\t\t// If there are layouts, work our way upwards, pushing each component into\n\t\t\t// the default slot of its parent\n\t\t\t// TODO: Also handle layout server data\n\t\t\t// TODO: There's probably a nicer way to do this with reducers or something\n\t\t\tlet component = clientEndPoint.component as ServerComponent;\n\t\t\tlet slots: Record<string, ServerSlotRender> | undefined = undefined;\n\t\t\t// Which slot levels actually ran during the render below, so a layout\n\t\t\t// that never rendered its <slot /> (silently dropping the page\n\t\t\t// content) can be reported (see findMissingSlotLayout)\n\t\t\tconst invokedLevels = new Set<number>();\n\t\t\tconst trackSlot = (level: number, slot: ServerSlotRender): ServerSlotRender => {\n\t\t\t\treturn ($slot, $context) => {\n\t\t\t\t\tinvokedLevels.add(level);\n\t\t\t\t\treturn slot($slot, $context);\n\t\t\t\t};\n\t\t\t};\n\t\t\tif (handler.layouts) {\n\t\t\t\tlet slotFunctions: ServerSlotRender[] = [];\n\t\t\t\t// The last slot function will render the client component\n\t\t\t\tslotFunctions[handler.layouts.length] = trackSlot(\n\t\t\t\t\thandler.layouts.length,\n\t\t\t\t\tasync (_, $context) => {\n\t\t\t\t\t\tlet { body, head } = await (clientEndPoint.component as ServerComponent)(\n\t\t\t\t\t\t\t$props,\n\t\t\t\t\t\t\t$context,\n\t\t\t\t\t\t);\n\t\t\t\t\t\tstyles += head;\n\t\t\t\t\t\treturn body;\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t\t\t?.default;\n\t\t\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\t\t\tif (i === 0) {\n\t\t\t\t\t\t\tcomponent = layoutEndPoint.component as ServerComponent;\n\t\t\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t\t\t} else {\n\t\t\t\t\t\t\tslotFunctions[i] = trackSlot(i, async (_, $context) => {\n\t\t\t\t\t\t\t\tlet { body, head } = await (layoutEndPoint.component as ServerComponent)(\n\t\t\t\t\t\t\t\t\t$props,\n\t\t\t\t\t\t\t\t\t$context,\n\t\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\t_: slotFunctions[i + 1],\n\t\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tstyles += head;\n\t\t\t\t\t\t\t\treturn body;\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tlet html;\n\t\t\ttry {\n\t\t\t\tlet { body, head } = await component($props, undefined, slots);\n\n\t\t\t\t// Render the page's (and its layouts') head element data, if the\n\t\t\t\t// endpoint declared any. Layouts lose to the page (the nearest\n\t\t\t\t// endpoint wins, as with @head content), and everything loses to\n\t\t\t\t// the first title in the compiled head -- which mergeHead keeps\n\t\t\t\tlet headData = \"\";\n\t\t\t\tconst event = { url, params, data } as PageLoadEvent;\n\t\t\t\tconst layoutEndPoints = await Promise.all(\n\t\t\t\t\t(handler.layouts ?? []).map(async (layout) => await layout.endPoint()),\n\t\t\t\t);\n\t\t\t\tconst headPoints = [clientEndPoint, ...layoutEndPoints].reverse();\n\t\t\t\tfor (const endPoint of headPoints) {\n\t\t\t\t\tconst headElements =\n\t\t\t\t\t\ttypeof endPoint.head === \"function\" ? await endPoint.head(event) : endPoint.head;\n\t\t\t\t\tif (headElements) {\n\t\t\t\t\t\theadData += headElements.map((element: HeadElement) => markupOf(element)).join(\"\");\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\t// Put the form info in a hidden input so that it can be accessed on the client\n\t\t\t\tif (form) {\n\t\t\t\t\tbody += `\\n<input type=\"hidden\" id=\"t-form-data\" value='${JSON.stringify(form).replaceAll(\"'\", \"\\\\'\")}' />`;\n\t\t\t\t}\n\n\t\t\t\t// Embed the routes' server-only data as json so the client's first\n\t\t\t\t// hydration reads it instead of making a `/~server` round trip\n\t\t\t\t// (nav/loadData.ts consumes it once and removes it). The condition\n\t\t\t\t// mirrors the client's `hasServerData`, so a route with only hooks or\n\t\t\t\t// actions still ships an all-null array that saves the refetch.\n\t\t\t\t// Promise values are left out and streamed as small scripts after\n\t\t\t\t// the page, so the render doesn't wait for them.\n\t\t\t\tif (routeHasServerData(handler)) {\n\t\t\t\t\tconst { criticalLoads, entries } = splitLoads(loads);\n\t\t\t\t\tdeferredEntries = entries;\n\t\t\t\t\tconst payload: {\n\t\t\t\t\t\tloads: (Record<string, any> | null)[];\n\t\t\t\t\t\tdeferred?: DeferredMeta[];\n\t\t\t\t\t} = { loads: criticalLoads };\n\t\t\t\t\tif (entries.length > 0) {\n\t\t\t\t\t\tpayload.deferred = entries.map((entry) => entry.meta);\n\t\t\t\t\t}\n\t\t\t\t\tconst json = JSON.stringify(payload).replaceAll(\"<\", \"\\\\u003c\");\n\t\t\t\t\tbody += `\\n<script type=\"application/json\" id=\"t-server-data\">${json}</script>`;\n\t\t\t\t\t// Nudge towards an explicit cache policy only when real data\n\t\t\t\t\t// was embedded (a payload of only nulls carries nothing)\n\t\t\t\t\tif (loads.some((load) => load !== null)) {\n\t\t\t\t\t\twarnUncachedEmbeddedData(ev, handler.path);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tstyles += head;\n\t\t\t\thtml = rewriteBaseInHtml(\n\t\t\t\t\tmergeHead(template, styles + headData).replace(\"%COMPONENT_BODY%\", body),\n\t\t\t\t\tgetBasePath(),\n\t\t\t\t);\n\t\t\t} catch (error) {\n\t\t\t\t// TODO: Show a proper Error component\n\t\t\t\thtml = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\t\t\tdeferredEntries = [];\n\t\t\t\tconsole.log(error);\n\t\t\t}\n\n\t\t\t// A layout that never rendered <slot /> silently drops the whole page\n\t\t\t// content from the output; find and report the outermost one\n\t\t\tif (handler.layouts) {\n\t\t\t\tconst missingLayout = findMissingSlotLayout(handler.layouts, invokedLevels);\n\t\t\t\tif (missingLayout !== undefined) {\n\t\t\t\t\twarnMissingSlotContent(missingLayout);\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tif (deferredEntries.length > 0) {\n\t\t\t\treturn streamHtmlResponse(html, status ?? 200, deferredEntries);\n\t\t\t}\n\n\t\t\treturn new Response(html, {\n\t\t\t\tstatus: status ?? 200,\n\t\t\t\theaders: {\n\t\t\t\t\t\"Content-Type\": \"text/html\",\n\t\t\t\t},\n\t\t\t});\n\t\t},\n\t);\n\tif (error) {\n\t\tthrow error;\n\t}\n\treturn response as Response;\n}\n\n/**\n * Streams a rendered page whose server data contained deferred values. The\n * page HTML (with skeletons/`with` branches) is sent immediately, then each\n * deferred value arrives as a tiny script that resolves its promise in the\n * client's hydration store. This is not component streaming: the SSR markup\n * for deferred values comes from the client's `$async`/`@await` boundaries.\n */\nfunction streamHtmlResponse(html: string, status: number, entries: LoadDeferredEntry[]): Response {\n\tconst encoder = new TextEncoder();\n\tconst bodyEnd = html.lastIndexOf(\"</body>\");\n\tconst before = bodyEnd === -1 ? html : html.slice(0, bodyEnd);\n\tconst after = bodyEnd === -1 ? \"\" : html.slice(bodyEnd);\n\tlet cancelled = false;\n\tconst stream = new ReadableStream<Uint8Array>({\n\t\tstart(controller) {\n\t\t\tconst write = (text: string) => {\n\t\t\t\tif (cancelled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.enqueue(encoder.encode(text));\n\t\t\t\t} catch {\n\t\t\t\t\t// Client disconnected\n\t\t\t\t}\n\t\t\t};\n\t\t\twrite(before + deferredBootstrapScript());\n\t\t\tvoid Promise.all(\n\t\t\t\tentries.map(async (entry) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\twrite(deferredScript(entry.id, await entry.promise, false));\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\twrite(deferredScript(entry.id, errorMessage(error), true));\n\t\t\t\t\t}\n\t\t\t\t}),\n\t\t\t).finally(() => {\n\t\t\t\twrite(after);\n\t\t\t\tif (cancelled) return;\n\t\t\t\ttry {\n\t\t\t\t\tcontroller.close();\n\t\t\t\t} catch {\n\t\t\t\t\t// Already closed\n\t\t\t\t}\n\t\t\t});\n\t\t},\n\t\tcancel() {\n\t\t\tcancelled = true;\n\t\t},\n\t});\n\treturn new Response(stream, {\n\t\tstatus,\n\t\theaders: { \"Content-Type\": \"text/html\" },\n\t});\n}\n\n/**\n * Creates the client-side deferred store before the inline resolve scripts\n * run. Guarded so a page with multiple deferred payloads doesn't replace a\n * store that still holds pending promises.\n */\nfunction deferredBootstrapScript(): string {\n\treturn (\n\t\t\"<script>(()=>{const g=globalThis;if(g.__torporDeferred)return;\" +\n\t\t\"const e=new Map();const get=id=>{let x=e.get(id);if(!x){let resolve,reject;\" +\n\t\t\"const promise=new Promise((res,rej)=>{resolve=res;reject=rej});promise.catch(()=>{});\" +\n\t\t\"x={promise,resolve,reject};e.set(id,x)}return x};\" +\n\t\t\"g.__torporDeferred={get,resolve:(id,v)=>get(id).resolve(v),\" +\n\t\t\"reject:(id,m)=>get(id).reject(m instanceof Error?m:new Error(String(m)))}})()</script>\"\n\t);\n}\n\n/** A script that settles one deferred entry in the hydration store. */\nfunction deferredScript(id: string, value: unknown, rejected: boolean): string {\n\tconst payload = rejected ? JSON.stringify(String(value)) : jsonForScript(value);\n\treturn `<script>__torporDeferred.${rejected ? \"reject\" : \"resolve\"}(${JSON.stringify(id)},${payload})</script>`;\n}\n\nasync function runAction(\n\tev: ServerEvent,\n\turl: URL,\n\thandler: RouteHandler,\n\tserverEndPoint: PageServerEndPoint | undefined,\n\tparams: Record<string, any>,\n\tquery: URLSearchParams,\n\ttemplate: string | undefined,\n) {\n\t// The action name rides in the query, so look for a `?/name` key rather\n\t// than taking the first key -- the url may carry ordinary load query\n\t// params as well (e.g. `?page=3&/like`, or a default action posted to a\n\t// url that already has a query). A key that names a declared action also\n\t// matches (e.g. `?set`), and a form without an action attribute calls the\n\t// `default` action\n\tconst queryKeys = Array.from(query.keys());\n\tconst actionKey =\n\t\tqueryKeys.find((key) => key.startsWith(\"/\")) ??\n\t\tqueryKeys.find((key) => !!serverEndPoint?.actions?.[key.replace(/^\\//, \"\")]);\n\tconst actionName = (actionKey ?? \"default\").replace(/^\\//, \"\");\n\tif (serverEndPoint?.actions) {\n\t\tconst action = serverEndPoint.actions[actionName];\n\t\tif (action) {\n\t\t\tif (actionName === \"load\" || actionName === \"params\") {\n\t\t\t\t// These names are reserved in the endpoint's schema map: `load`\n\t\t\t\t// validates the query string and `params` the route params, so\n\t\t\t\t// an action with one of these names would get the wrong schema\n\t\t\t\t// applied to its form data\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The action name \"${actionName}\" is reserved. ` +\n\t\t\t\t\t\t`Rename the action (and its schema key, if any), e.g. to \"save\".`,\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Route params come from the URL, so a failed validation means the\n\t\t\t// resource doesn't exist\n\t\t\ttry {\n\t\t\t\tparams = await validateEndpointParams(serverEndPoint, params);\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof ValidationError) return notFound();\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tlet result: Response | undefined | void;\n\t\t\t// The event that the hooks and action run with. It's kept around so\n\t\t\t// that the view re-render below can pass its appData (populated by\n\t\t\t// the hooks' enter functions) through to the loads\n\t\t\tlet serverParams: ServerLoadEvent | undefined = undefined;\n\t\t\ttry {\n\t\t\t\t// If the endpoint declares a schema for this action, validate the\n\t\t\t\t// submitted form data up front and reject with 422 if it fails.\n\t\t\t\t// The form data is parsed on the event, so the action's\n\t\t\t\t// `event.form()` / `event.formData()` share this read of the body\n\t\t\t\tconst schema = endpointSchema(serverEndPoint, actionName);\n\t\t\t\tconst form = schema\n\t\t\t\t\t? await validate(schema, await formDataToRecord(await ev.formData()))\n\t\t\t\t\t: undefined;\n\n\t\t\t\tserverParams = buildServerParams(ev, url, params, form ? { form } : {});\n\n\t\t\t\tconst serverHooks = await loadServerHooks(handler);\n\t\t\t\t// Hooks run from the root down; a hook's enter can return a\n\t\t\t\t// Response to short-circuit the action\n\t\t\t\tconst actionParams = serverParams;\n\t\t\t\tconst { response: hookResponse, error: hookError } = await runHooks(\n\t\t\t\t\t[{ hooks: serverHooks, arg: actionParams }],\n\t\t\t\t\tasync () => {\n\t\t\t\t\t\treturn (await action(actionParams)) || undefined;\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t\tif (hookError) {\n\t\t\t\t\tthrow hookError;\n\t\t\t\t}\n\t\t\t\tresult = hookResponse;\n\t\t\t} catch (error) {\n\t\t\t\tconst response = validationErrorResponse(error);\n\t\t\t\tif (response) return response;\n\t\t\t\tthrow error;\n\t\t\t}\n\n\t\t\tif (ev.request.headers.has(\"X-Torpor-Form-Submit\")) {\n\t\t\t\t// If the form was submitted from javascript, just return the\n\t\t\t\t// response and it will be handled on the client\n\t\t\t\t// TODO: Should we make the user return a response??\n\t\t\t\tresult ??= ok();\n\n\t\t\t\t// If it's a redirect, we need to stop the browser handling it\n\t\t\t\tif (result.status >= 300 && result.status <= 399) {\n\t\t\t\t\tconst location = result.headers.get(\"Location\") ?? \"\";\n\t\t\t\t\tresult = ok();\n\t\t\t\t\tresult.headers.set(\"X-Torpor-Form-Redirect\", \"\");\n\t\t\t\t\tresult.headers.set(\"Location\", location);\n\t\t\t\t}\n\n\t\t\t\treturn result;\n\t\t\t} else if (\n\t\t\t\t!result ||\n\t\t\t\t(result.status >= 200 && result.status <= 299) ||\n\t\t\t\t(result.status >= 400 && result.status <= 499)\n\t\t\t) {\n\t\t\t\t// If the form was submitted without javascript, and there was\n\t\t\t\t// no result, an ok result, or a 4xx error, re-render the view\n\t\t\t\t// with the form result. The server hooks already ran around the\n\t\t\t\t// action, so they are not run again here -- but their appData\n\t\t\t\t// is passed through, so that loads guarding on it (e.g. an\n\t\t\t\t// auth hook's user) re-render the page instead of erroring\n\t\t\t\t// Keep the query string, so that loads validating the query see\n\t\t\t\t// the same values as the original GET. If the form action\n\t\t\t\t// dropped params that the load schema requires, loadView falls\n\t\t\t\t// back to the raw query instead of failing validation\n\t\t\t\tconst newUrl = new URL(url.pathname + url.search, url);\n\t\t\t\tconst formStatus = result?.status;\n\t\t\t\tlet formMessage = await result?.text();\n\t\t\t\tif (formMessage && result?.headers.get(\"Content-Type\")?.includes(\"application/json\")) {\n\t\t\t\t\t$page.form = JSON.parse(formMessage);\n\t\t\t\t\tformMessage = undefined;\n\t\t\t\t} else {\n\t\t\t\t\t$page.form = {};\n\t\t\t\t}\n\t\t\t\t// Set status and message if they haven't already been set,\n\t\t\t\t// which means that you can just return e.g. forbidden() or\n\t\t\t\t// forbidden(\"no!\") and there will be something you can work\n\t\t\t\t// with in your component, or you can set a completely custom\n\t\t\t\t// object with whatever info you need\n\t\t\t\t$page.form!.status ??= formStatus ?? 0;\n\t\t\t\t$page.form!.message ??= formMessage ?? \"\";\n\t\t\t\treturn await loadView(\n\t\t\t\t\tev,\n\t\t\t\t\tnewUrl,\n\t\t\t\t\thandler,\n\t\t\t\t\tparams,\n\t\t\t\t\ttemplate,\n\t\t\t\t\tformStatus,\n\t\t\t\t\t$page.form,\n\t\t\t\t\ttrue,\n\t\t\t\t\tserverParams?.appData,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\t// If the form was submitted without javascript and there was a\n\t\t\t\t// redirect or server error, just return the result to handle it\n\t\t\t\t// as normal\n\t\t\t\treturn result;\n\t\t\t}\n\t\t}\n\t}\n\n\treturn notFound();\n}\n\n/**\n * Whether the route has any server-side code to run (a page or layout server\n * endpoint, or a folder hook) — the same condition the client uses to decide\n * whether to make a `/~server` request (nav/loadData.ts's `hasServerData`).\n * When it holds, the render embeds a server-data payload so the first\n * hydration skips that request.\n */\nfunction routeHasServerData(handler: RouteHandler): boolean {\n\tif (handler.serverHooks && handler.serverHooks.length > 0) return true;\n\tif (handler.serverEndPoint) return true;\n\treturn (handler.layouts ?? []).some((layout) => !!layout.serverEndPoint);\n}\n\nasync function loadClientAndServerData(\n\turl: URL,\n\tparams: Record<string, any>,\n\tserverParams: ServerLoadEvent,\n\tdata: Record<string, any>,\n\tclientEndPoint?: PageEndPoint,\n\tserverEndPoint?: PageServerEndPoint,\n\tloads?: (Record<string, any> | null)[],\n) {\n\tif (clientEndPoint?.load) {\n\t\tconst clientParams = buildClientParams(url, params, data);\n\t\tconst clientResponse = await clientEndPoint.load(clientParams);\n\t\tif (clientResponse) {\n\t\t\tif (clientResponse.ok) {\n\t\t\t\tconst clientData = await readResponseBody(clientResponse);\n\t\t\t\tif (clientData) Object.assign(data, clientData);\n\t\t\t} else {\n\t\t\t\treturn clientResponse;\n\t\t\t}\n\t\t}\n\t}\n\tlet serverData: Record<string, any> | null = null;\n\tif (serverEndPoint?.load) {\n\t\tconst serverResponse = await serverEndPoint.load(serverParams);\n\t\tif (serverResponse) {\n\t\t\tif (serverResponse.ok) {\n\t\t\t\tserverData = (await readResponseBody(serverResponse)) ?? null;\n\t\t\t\tif (serverData) Object.assign(data, serverData);\n\t\t\t} else {\n\t\t\t\treturn serverResponse;\n\t\t\t}\n\t\t}\n\t}\n\t// Record this route's server-only data, aligned with the page and its\n\t// layouts (root to leaf), so the render can embed it for hydration\n\tloads?.push(serverData);\n}\n\nfunction buildClientParams(url: URL, params: Record<string, any>, data: Record<string, any>) {\n\treturn {\n\t\turl,\n\t\tparams,\n\t\tdata,\n\t};\n}\n\n/**\n * The layout paths a data request asked to reuse, from the `X-Torpor-Reuse`\n * header (a JSON array). A malformed header is ignored rather than failing the\n * request -- the client just gets the layouts loaded again.\n */\nfunction reusedLayoutPaths(ev: ServerEvent): Set<string> {\n\tconst header = ev.request.headers.get(DATA_REUSE_HEADER);\n\tif (!header) return new Set();\n\ttry {\n\t\tconst paths = JSON.parse(header) as unknown;\n\t\tif (Array.isArray(paths)) {\n\t\t\treturn new Set(paths.filter((p): p is string => typeof p === \"string\"));\n\t\t}\n\t} catch {\n\t\t// Not valid json\n\t}\n\treturn new Set();\n}\n\n/**\n * The url user code (hooks, loads, actions, `@head`) should see. Client-side\n * data fetches append `/~server` to the page url, but that suffix is an\n * internal detail: without stripping it, `event.url.pathname` would differ\n * between the server-rendered page and its `~server` request, so a hook\n * guarding on the path (e.g. `path !== \"/setup\"`) would misfire.\n */\nfunction requestUrl(url: URL): URL {\n\tif (!url.pathname.endsWith(\"/~server\")) return url;\n\tconst path = url.pathname.slice(0, -\"/~server\".length) || \"/\";\n\treturn new URL(path + url.search, url);\n}\n\nfunction buildServerParams(\n\tev: ServerEvent,\n\turl: URL,\n\tparams: Record<string, any>,\n\tvalues: { json?: unknown; form?: unknown; query?: unknown } = {},\n\tappData: Record<string, any> = {},\n): ServerLoadEvent {\n\tconst logicalUrl = requestUrl(url);\n\treturn {\n\t\turl: logicalUrl,\n\t\tparams,\n\t\tappData,\n\t\trequest: ev.request,\n\t\t// The inputs may have been validated already, in which case the request\n\t\t// body has been consumed and the parsed values are returned instead.\n\t\t// Their types come from the endpoint's schemas, so they are loosely\n\t\t// typed here\n\t\tjson: (): Promise<any> =>\n\t\t\tvalues.json !== undefined ? Promise.resolve(values.json) : ev.json(),\n\t\tform: async (): Promise<any> =>\n\t\t\tvalues.form !== undefined\n\t\t\t\t? Promise.resolve(values.form)\n\t\t\t\t: formDataToRecord(await ev.formData()),\n\t\tformData: (): Promise<FormData> => ev.formData(),\n\t\tquery: (): Promise<any> =>\n\t\t\tvalues.query !== undefined\n\t\t\t\t? Promise.resolve(values.query)\n\t\t\t\t: Promise.resolve(searchParamsToRecord(logicalUrl.searchParams)),\n\t\tcookies: ev.cookies,\n\t\theaders: ev.headers,\n\t\tsession: ev.session,\n\t\tflash: ev.flash,\n\t\tadapter: ev.adapter,\n\t};\n}\n\n/**\n * Renders a head element as markup. Attribute values are escaped, since\n * they can come from user data (e.g. a post title passed to `seo()`).\n */\nfunction markupOf(element: HeadElement): string {\n\tif (\"title\" in element) {\n\t\treturn `<title>${escapeHtml(element.title)}</title>`;\n\t}\n\tif (\"name\" in element) {\n\t\treturn `<meta name=\"${escapeHtml(element.name)}\" content=\"${escapeHtml(element.content)}\" />`;\n\t}\n\treturn `<meta property=\"${escapeHtml(element.property)}\" content=\"${escapeHtml(element.content)}\" />`;\n}\n\nfunction escapeHtml(value: string): string {\n\treturn value\n\t\t.replaceAll(\"&\", \"&\")\n\t\t.replaceAll(\"<\", \"<\")\n\t\t.replaceAll(\">\", \">\")\n\t\t.replaceAll('\"', \""\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAWA,eAA8B,iBAC7B,SAC0B;CAC1B,MAAM,WAAW,mBAAmB,WAAW,UAAU,MAAM,QAAQ,SAAS;CAChF,MAAM,SAAyB,CAAC;CAChC,KAAK,MAAM,OAAO,SAAS,KAAK,GAAG;EAClC,IAAI,OAAO,QAAQ;EACnB,MAAM,SAAS,SAAS,OAAO,GAAG;EAClC,OAAO,OAAO,OAAO,SAAS,IAAI,SAAS,OAAO;CACnD;CACA,OAAO;AACR;;;ACnBA,MAAM,cAA6B,OAAO,IAAI,WAAW;AAOzD,MAAM,QAEJ,WAAW,iBAAiB,OAAO;CACnC,QAAQ;CACR,KAAK,IAAI,IAAI,kBAAkB;CAC/B,MAAM,KAAA;CACN,OAAO,KAAA;CACP,OAAO,EACN,SAAS,GACV;AACD,CAAC;;;;;;;;;;ACXF,SAAwB,qBAAqB,cAA4C;CACxF,MAAM,SAAsB,CAAC;CAC7B,KAAK,MAAM,OAAO,aAAa,KAAK,GAAG;EACtC,IAAI,OAAO,QAAQ;EACnB,MAAM,SAAS,aAAa,OAAO,GAAG;EACtC,OAAO,OAAO,OAAO,SAAS,IAAI,SAAS,OAAO;CACnD;CACA,OAAO;AACR;;;;;;;ACKA,SAAgB,eAAe,UAAoB,MAA4C;CAC9F,OAAQ,SAAS,SAAiC;AACnD;;;;;;;;;;;AAYA,eAAsB,uBACrB,UACA,QAC+B;CAC/B,MAAM,SAAS,eAAe,UAAU,QAAQ;CAChD,OAAO,SAAW,MAAM,SAAS,QAAQ,MAAM,IAA6B;AAC7E;;;;;;;;;AAmCA,SAAgB,wBAAwB,OAAsC;CAC7E,IAAI,iBAAiB,iBACpB,OAAO,cAAc;EAAE,SAAS,MAAM;EAA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AAO,CAAC,CACxB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,MAAK,QAAQ;AAC3B"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { a as RouteParamsOf, n as ParseRouteParams, t as ExactRouteParams } from "./ParseRouteParams-BtC0eH3z.mjs";
|
|
2
|
-
import { r as ServerLoadEvent } from "./ServerLoadEvent-
|
|
2
|
+
import { r as ServerLoadEvent } from "./ServerLoadEvent-F60w1TZt.mjs";
|
|
3
3
|
import { n as UntypedResponse, t as TypedResponse } from "./TypedResponse-6lznqN4U.mjs";
|
|
4
4
|
import { Component } from "@torpor/view";
|
|
5
5
|
//#region src/types/PageLoadEvent.d.ts
|
|
@@ -121,4 +121,4 @@ type SitemapOptions = {
|
|
|
121
121
|
declare function sitemapResponse(options: SitemapOptions, basePath: string, event: ServerLoadEvent): Promise<Response>;
|
|
122
122
|
//#endregion
|
|
123
123
|
export { PageLoadReturn as a, PageEndPoint as i, sitemapResponse as n, PageLoadEvent as o, HeadElement as r, SitemapOptions as t };
|
|
124
|
-
//# sourceMappingURL=sitemap-
|
|
124
|
+
//# sourceMappingURL=sitemap-CnIYTLhu.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sitemap-
|
|
1
|
+
{"version":3,"file":"sitemap-CnIYTLhu.d.mts","names":[],"sources":["../src/types/PageLoadEvent.ts","../src/types/PageLoadReturn.ts","../src/types/PageEndPoint.ts","../src/discovery/sitemap.ts"],"mappings":";;;;;;;;;;;UAQyB,cACxB,8CACA,OAAO;;;;EAKP,KAAK;;;;EAIL,QAAQ,cAAc;;;;;EAKtB,MAAM;;;;;;;;;;;;;;KCXK,eAAe,QACxB,cAAc,QAAQ,SACtB;;;;;;;;UCLsB,aACxB,8CACA,OAAO;;;;;;;;EASP,SAAS,eAAe,cAAc,WAClC,MAAM,sCACS,SACb,SAAS,gCACJ,iBAAiB,6BAErB,QAAQ,SAAS,iBAAiB,QAAQ,iBAAiB,YAC7D,SAAS;;;;;;;EAQd;;;;EAIA,QAAQ,OAAO,cAAc,WAAW,eAAe,QAAQ,QAAQ,eAAe;;;;;;;;EAQtF;IAAwB,QAAQ;;;;;EAIhC,YAAY;;;;EAKZ,OAAO,kBAAkB,OAAO,cAAc,WAAW;;KAGrD,cAAc,eAAe,cAAc;UAEtC;EACT;;UAGS;EACT;EACA;;;;;;UAOS;EACT;EACA;;;;;;;;KCtEW;;EAEX;;EAEA;;EAEA,MAAM,OAAO,+BAA+B;;;;;;;iBAQvB,gBACrB,SAAS,gBACT,kBACA,OAAO,kBACL,QAAQ"}
|
package/dist/test.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { n as ServerEvent } from "./MiddlewareFunction-
|
|
2
|
-
import { t as Site } from "./Site-
|
|
1
|
+
import { n as ServerEvent } from "./MiddlewareFunction-7rIvFkjl.mjs";
|
|
2
|
+
import { t as Site } from "./Site-CAeAqjkk.mjs";
|
|
3
3
|
//#region src/test/runTest.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* Runs a site route in test mode
|
package/dist/test.mjs
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as Router } from "./Router-C4ADUfhv.mjs";
|
|
2
|
-
import { t as ServerEvent } from "./ServerEvent-
|
|
3
|
-
import { t as createServerLoad } from "./serverHandlers-
|
|
2
|
+
import { t as ServerEvent } from "./ServerEvent-L0rT_mBJ.mjs";
|
|
3
|
+
import { t as createServerLoad } from "./serverHandlers-Ba_35jpO.mjs";
|
|
4
4
|
import fpath from "node:path";
|
|
5
5
|
//#region src/test/runTest.ts
|
|
6
6
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@torpor/build",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.10.0",
|
|
4
4
|
"description": "A framework for building sites and apps with Torpor",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"exports": {
|
|
@@ -80,17 +80,20 @@
|
|
|
80
80
|
"author": "",
|
|
81
81
|
"license": "ISC",
|
|
82
82
|
"dependencies": {
|
|
83
|
-
"@torpor/unplugin": "^1.2.
|
|
84
|
-
"@torpor/view": "^1.3.
|
|
83
|
+
"@torpor/unplugin": "^1.2.13",
|
|
84
|
+
"@torpor/view": "^1.3.3",
|
|
85
85
|
"cookie": "^2.0.1",
|
|
86
|
-
"dotenv": "^18.0.8"
|
|
87
|
-
|
|
88
|
-
|
|
86
|
+
"dotenv": "^18.0.8"
|
|
87
|
+
},
|
|
88
|
+
"peerDependencies": {
|
|
89
|
+
"vite": ">=1.2.0"
|
|
89
90
|
},
|
|
90
91
|
"devDependencies": {
|
|
91
92
|
"@typescript/native-preview": "7.0.0-dev.20260707.2",
|
|
92
93
|
"esno": "^4.8.0",
|
|
93
|
-
"typescript": "^7.0.2"
|
|
94
|
+
"typescript": "^7.0.2",
|
|
95
|
+
"vite": "npm:@voidzero-dev/vite-plus-core@1.2.0",
|
|
96
|
+
"vite-plus": "1.2.0"
|
|
94
97
|
},
|
|
95
98
|
"scripts": {
|
|
96
99
|
"check": "tsgo --noEmit && pnpm dlx oxlint --type-aware",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"MiddlewareFunction-BZilnEei.d.mts","names":[],"sources":["../src/server/ServerEvent.ts","../src/server/types/MiddlewareFunction.ts"],"mappings":";;cAMqB;;EACpB,SAAS;EACT,UAAU;;;;;;EAMV;EAEA,SAAS;EAET;EAEA,SAAS;EACT,SAAS;EACT,SAAS;EACT,OAAO;;MAOH,OAAO;EAIX,YAAY,SAAS,SAAS,SAAS,wBAAwB,MAAM;EAcrE;;;;EA4CA,QAAQ;;;;KC1FJ;;;;;;EAMJ,SAAS,IAAI,gBAAgB,kBAAkB,QAAQ;;;;;;;;;;EAUvD,QAAQ,IAAI,gBAAgB,kBAAkB,QAAQ"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Router-By9Nlg39.d.mts","names":[],"sources":["../src/types/ManifestRoute.ts","../src/types/RouteLayoutHandler.ts","../src/types/RouteHandler.ts","../src/site/Router.ts"],"mappings":";;UAAyB;EACxB;EACA;EACA,gBAAgB;EAChB;;;;UCJwB;EACxB;EACA,gBAAgB;EAChB,uBAAuB;;;;;;;UCGC;EACxB;EACA;EACA,gBAAgB;EAChB;EAEA;EACA,UAAU;EACV,uBAAuB;EACvB,qBAAqB;EAIrB,gBAAgB;EAChB;EACA,gBAAgB,QAAQ;;;;;;;cCbJ;;EACpB,QAAQ;EAMR;EAOA,SAAS,QAAQ;EAQjB,QAAQ,cAAc,cAAc,gBAAgB,cAAc;EAuBlE,MAAM,cAAc,OAAO,kBAAkB;;cA2GxC;EACL;EACA,SAAS;EAET,YAAY,cAAc,SAAS;;UAM1B;EACT,SAAS;EACT,SAAS;EACT,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"ServerLoadEvent-BH6oG1o6.d.mts","names":[],"sources":["../src/types/ServerLoadEvent.ts"],"mappings":";;;;;;;KAUY,iBAAiB,eAAe,qBAAqB;;;;;KAMrD,cAAc;;;;;;;;UASD,gBACxB,8CACA,gBACA,WAAW,gBACX,YAAY,aACZ,SAAS,cAAc;;;;EAKvB,KAAK;;;;;;EAML,QAAQ;;;;;EAOR,SAAS;;;;EAIT,SAAS;;;;EAKT,YAAY,QAAQ;;;;;;EAMpB,YAAY,QAAQ;;;;;;;EAOpB,aAAa,QAAQ;;;;EAIrB,SAAS;;;;;EAKT,SAAS;;;;;EAKT,OAAO;;;;EAIP,SAAS;;;;EAIT,SAAS,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"Site-DGZJB7Do.d.mts","names":[],"sources":["../src/types/Adapter.ts","../src/types/SitePlugin.ts","../src/types/PageServerAction.ts","../src/types/PageServerLoad.ts","../src/types/PageServerEndPoint.ts","../src/types/ServerRequest.ts","../src/types/Server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;EACA,QAAQ;;;;;;EAMR;IAAgB;IAAgB;;;;;;;;EAOhC,SAAS;;;;EAIT,aAAa;;;;;;;;;;EAUb,SAAS;;;;;;EAMT;;;;;;;EAOA,aAAa;;;;;EAKb;;;;;;;;;;;;;;;;EAgBA,aAAa,IAAI;;;;;;;EAOjB;;;;;;;EAOA;;;;;;;;;EASA,sBAAsB;;;;;;EAMtB;;;;;;;;;;;;EAYA,YAAY;;;;;;;;;;;EAWZ,UAAU;;;;;;;;;EASV,MAAM,0BAA0B;;;;;EAKhC,iBAAiB,eAAe;EAEhC;;MAKI;;;;;;;;;EAYJ,eAAqB,gBAAgB,qBAAqB;;;;;;;;;;;;EA0C1D,gBAAgB,OAAO;;;;;;;;EAwBvB,aACC,cACA,cACA,kHASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+HD,SACC,cACA;IACC;IACA,sBAAsB;IACtB,kBAAkB;IAClB;IACA,wBAAwB;IACxB,sBAAsB;IACtB;KAED"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"plugin-D8Www11B.mjs","names":[],"sources":["../src/openapi/document.ts","../src/openapi/docsHtml.ts","../src/openapi/plugin.ts"],"sourcesContent":["import type { StandardSchemaV1 } from \"../types/StandardSchema\";\nimport type { OpenApiPluginOptions, OpenApiRouteEntry, JsonSchema } from \"./types\";\n\n// The endpoint handler names, in the order they appear in docs\nconst METHODS = [\"get\", \"post\", \"patch\", \"put\", \"del\", \"options\", \"head\"] as const;\ntype Method = (typeof METHODS)[number];\n\n// Handlers whose schema validates the query string; all others validate the\n// json request body\nconst QUERY_METHODS: readonly string[] = [\"get\", \"head\"];\nconst BODY_METHODS: readonly string[] = [\"post\", \"patch\", \"put\", \"del\", \"options\"];\n\n/**\n * Builds an OpenAPI 3.1 document from a list of +server endpoints.\n *\n * Each endpoint's route path (`/api/posts/[id]`) is converted to OpenAPI\n * syntax (`/api/posts/{id}`); its `params` schema becomes path parameters,\n * its `get`/`head` schema becomes query parameters, and its `post`/`patch`/\n * `put`/`del`/`options` schema becomes a json request body. Responses are\n * stubbed: a `200` for every handler, plus a `422` when the handler declares\n * an input schema (validation errors are returned automatically).\n *\n * Throws if any endpoint declares a schema but the options have no\n * `toJsonSchema` converter.\n */\nexport default function buildOpenApiDocument(\n\tentries: OpenApiRouteEntry[],\n\toptions: OpenApiPluginOptions,\n): Record<string, unknown> {\n\tif (!options.toJsonSchema) {\n\t\tconst withSchema = entries.find(hasSchemas);\n\t\tif (withSchema) {\n\t\t\tthrow new Error(\n\t\t\t\t`The endpoint at ${withSchema.path} declares schema(s), but the openApi() plugin ` +\n\t\t\t\t\t`was not given a \"toJsonSchema\" converter. Pass one, e.g. ` +\n\t\t\t\t\t`openApi({ toJsonSchema: (s) => z.toJSONSchema(s) })`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst paths: Record<string, Record<string, unknown>> = {};\n\tfor (const entry of entries) {\n\t\tconst pathItem = buildPathItem(entry, options);\n\t\tif (pathItem) {\n\t\t\tpaths[openApiPath(entry.path)] = pathItem;\n\t\t}\n\t}\n\n\treturn {\n\t\topenapi: \"3.1.0\",\n\t\tinfo: {\n\t\t\ttitle: options.title ?? \"API\",\n\t\t\tversion: options.version ?? \"1.0.0\",\n\t\t},\n\t\tpaths,\n\t};\n}\n\nfunction hasSchemas(entry: OpenApiRouteEntry): boolean {\n\tconst schema = entry.endPoint?.schema;\n\tif (!schema) return false;\n\treturn METHODS.some((method) => schema[method]) || !!schema.params;\n}\n\nfunction buildPathItem(\n\tentry: OpenApiRouteEntry,\n\toptions: OpenApiPluginOptions,\n): Record<string, unknown> | undefined {\n\tconst endPoint = entry.endPoint;\n\tconst pathItem: Record<string, unknown> = {};\n\tlet count = 0;\n\n\tfor (const method of METHODS) {\n\t\tif (typeof endPoint[method] !== \"function\") {\n\t\t\tcontinue;\n\t\t}\n\t\tcount++;\n\n\t\tconst schema = endPoint.schema?.[method];\n\t\tconst paramsSchema = endPoint.schema?.params;\n\n\t\tconst parameters: Record<string, unknown>[] = [];\n\t\tif (paramsSchema) {\n\t\t\tparameters.push(...flattenObject(convert(paramsSchema, options), \"path\"));\n\t\t}\n\t\tif (schema && QUERY_METHODS.includes(method)) {\n\t\t\tparameters.push(...flattenObject(convert(schema, options), \"query\"));\n\t\t}\n\n\t\tconst responses: Record<string, unknown> = { \"200\": { description: \"OK\" } };\n\t\tif (schema) {\n\t\t\tresponses[\"422\"] = { description: \"Validation failed\" };\n\t\t}\n\n\t\tpathItem[method === \"del\" ? \"delete\" : method] = {\n\t\t\toperationId: operationId(method, entry.path),\n\t\t\t...(parameters.length ? { parameters } : {}),\n\t\t\t...(schema && BODY_METHODS.includes(method)\n\t\t\t\t? {\n\t\t\t\t\t\trequestBody: {\n\t\t\t\t\t\t\trequired: true,\n\t\t\t\t\t\t\tcontent: { \"application/json\": { schema: convert(schema, options) } },\n\t\t\t\t\t\t},\n\t\t\t\t\t}\n\t\t\t\t: {}),\n\t\t\tresponses,\n\t\t};\n\t}\n\n\treturn count > 0 ? pathItem : undefined;\n}\n\nfunction convert(schema: StandardSchemaV1, options: OpenApiPluginOptions): JsonSchema {\n\treturn options.toJsonSchema!(schema);\n}\n\n/**\n * Flattens a converted object schema into OpenAPI parameters. Path\n * parameters are always required; query parameters take their `required`\n * flag from the schema's `required` array.\n */\nfunction flattenObject(\n\tjsonSchema: JsonSchema,\n\tlocation: \"path\" | \"query\",\n): Record<string, unknown>[] {\n\tconst properties = jsonSchema.properties;\n\tif (!properties || typeof properties !== \"object\") {\n\t\treturn [];\n\t}\n\tconst required = Array.isArray(jsonSchema.required) ? jsonSchema.required : [];\n\treturn Object.entries(properties as Record<string, JsonSchema>).map(([name, propSchema]) => ({\n\t\tname,\n\t\tin: location,\n\t\trequired: location === \"path\" ? true : required.includes(name),\n\t\tschema: propSchema,\n\t}));\n}\n\n/**\n * Converts a route path to OpenAPI syntax: `/api/posts/[id]` becomes\n * `/api/posts/{id}`.\n */\nfunction openApiPath(routePath: string): string {\n\treturn routePath.replace(/\\[\\.\\.\\.([^\\]]+)\\]/g, \"{$1}\").replace(/\\[([^\\]]+)\\]/g, \"{$1}\");\n}\n\nfunction operationId(method: Method, routePath: string): string {\n\tconst segments = openApiPath(routePath)\n\t\t.split(/[^a-zA-Z0-9]+/)\n\t\t.filter((s) => s.length > 0)\n\t\t.map((s) => s.charAt(0).toUpperCase() + s.slice(1));\n\tconst verb = method === \"del\" ? \"delete\" : method;\n\treturn verb + (segments.join(\"\") || \"Root\");\n}\n","/**\n * A standalone HTML page loading Swagger UI from a CDN, pointed at the\n * OpenAPI document endpoint.\n */\nexport default function openApiDocsHtml(docPath: string): string {\n\treturn `<!doctype html>\n<html lang=\"en\">\n<head>\n\t<meta charset=\"utf-8\" />\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n\t<title>API Docs</title>\n\t<link rel=\"stylesheet\" href=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui.css\" />\n</head>\n<body>\n\t<div id=\"swagger-ui\"></div>\n\t<script src=\"https://unpkg.com/swagger-ui-dist@5/swagger-ui-bundle.js\" crossorigin></script>\n\t<script>\n\t\twindow.addEventListener(\"DOMContentLoaded\", () => {\n\t\t\tSwaggerUIBundle({ url: ${JSON.stringify(docPath)}, dom_id: \"#swagger-ui\" });\n\t\t});\n\t</script>\n</body>\n</html>\n`;\n}\n","import type SitePlugin from \"../types/SitePlugin\";\nimport openApiDocsHtml from \"./docsHtml\";\nimport type { OpenApiPluginOptions, ResolvedOpenApiOptions } from \"./types\";\n\n/**\n * The `site.pluginState` key the openApi plugin stores its resolved options\n * under. A registry symbol (`Symbol.for`), so that the user's config, the\n * manifest plugin and the generated runtime code all resolve to the same\n * key even when they are loaded as separate module instances.\n */\nexport const OPEN_API_STATE_KEY: symbol = Symbol.for(\"@torpor/build/openapi\");\n\n/**\n * Serves an OpenAPI 3.1 document for the site's `+server` endpoints, plus an\n * optional interactive docs page.\n *\n * ```ts\n * import { Site } from \"@torpor/build\";\n * import { openApi } from \"@torpor/build/openapi\";\n * import { z } from \"zod\";\n *\n * const site = new Site();\n * site.addRouteFolder(\"src/routes\");\n * site.plugins = [\n * \topenApi({\n * \t\ttitle: \"My API\",\n * \t\ttoJsonSchema: (s) => z.toJSONSchema(s as z.ZodType, { io: \"input\" }),\n * \t}),\n * ];\n * export default site;\n * ```\n *\n * The document is served at `/openapi.json` (configurable with `path`) and\n * the docs page at `/docs` (set `docs: false` to disable). Endpoints are\n * picked up from every `+server.ts` route: its `params` schema becomes path\n * parameters, `get`/`head` schemas become query parameters, and\n * `post`/`patch`/`put`/`del`/`options` schemas become request bodies.\n *\n * The resolved options are stored in `site.pluginState` under\n * `OPEN_API_STATE_KEY`, which the manifest plugin reads at build time to\n * generate the document endpoint.\n */\nexport function openApi(options: OpenApiPluginOptions = {}): SitePlugin {\n\treturn (site) => {\n\t\tconst docPath = withLeadingSlash(options.path ?? \"/openapi.json\");\n\t\tif (site.routes.some((route) => route.path === docPath)) {\n\t\t\tthrow new Error(\n\t\t\t\t`There is already a route registered at ${docPath}, so the OpenAPI document can't be ` +\n\t\t\t\t\t`served there. Pass a different \"path\" to the openApi() plugin`,\n\t\t\t);\n\t\t}\n\n\t\tconst resolved: ResolvedOpenApiOptions = {\n\t\t\tpath: docPath,\n\t\t\tdocs: options.docs === false ? undefined : withLeadingSlash(options.docs ?? \"/docs\"),\n\t\t\ttitle: options.title ?? \"API\",\n\t\t\tversion: options.version ?? \"1.0.0\",\n\t\t\ttoJsonSchema: options.toJsonSchema,\n\t\t};\n\t\tsite.pluginState.set(OPEN_API_STATE_KEY, resolved);\n\n\t\tif (resolved.docs) {\n\t\t\tconst html = openApiDocsHtml(docPath);\n\t\t\tsite.addRoute(resolved.docs, {\n\t\t\t\tserver: {\n\t\t\t\t\tget: () =>\n\t\t\t\t\t\tnew Response(html, {\n\t\t\t\t\t\t\theaders: { \"Content-Type\": \"text/html; charset=utf-8\" },\n\t\t\t\t\t\t}),\n\t\t\t\t},\n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