@torpor/build 1.8.4 → 1.8.6
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/{Server-C0PGzSQO.mjs → Server-dcRbdPXf.mjs} +9 -27
- package/dist/Server-dcRbdPXf.mjs.map +1 -0
- package/dist/Server-qn5Ws_d0.d.mts.map +1 -1
- package/dist/bin/index.js +1 -1
- package/dist/clientEntry.mjs +1 -1
- package/dist/dev.mjs +2 -2
- package/dist/{devPlugin-CL0eu77n.mjs → devPlugin-lLzauETn.mjs} +2 -2
- package/dist/{devPlugin-CL0eu77n.mjs.map → devPlugin-lLzauETn.mjs.map} +1 -1
- package/dist/{load-Clec6rli.mjs → load-G-4A435s.mjs} +15 -5
- package/dist/{load-Clec6rli.mjs.map → load-G-4A435s.mjs.map} +1 -1
- package/dist/nav.mjs +1 -1
- package/dist/nodeDev.mjs +1 -1
- package/dist/run.mjs +1 -1
- package/dist/runHooks-D5p1Rh7i.mjs +61 -0
- package/dist/runHooks-D5p1Rh7i.mjs.map +1 -0
- package/dist/{runOpenApi-AEDhan_-.mjs → runOpenApi-C5yMpQU1.mjs} +3 -3
- package/dist/{runOpenApi-AEDhan_-.mjs.map → runOpenApi-C5yMpQU1.mjs.map} +1 -1
- package/dist/server/Server.mjs +1 -1
- package/dist/server.mjs +1 -1
- package/dist/serverEntry-BGii8bB6.d.mts.map +1 -1
- package/dist/{serverEntry-DdNjmynd.mjs → serverEntry-D1hE-Jzt.mjs} +2 -2
- package/dist/{serverEntry-DdNjmynd.mjs.map → serverEntry-D1hE-Jzt.mjs.map} +1 -1
- package/dist/serverEntry.mjs +1 -1
- package/dist/{serverHandlers-BpKfaFsD.mjs → serverHandlers-CSBUEgJt.mjs} +71 -108
- package/dist/serverHandlers-CSBUEgJt.mjs.map +1 -0
- package/dist/test.mjs +1 -1
- package/package.json +3 -3
- package/dist/Server-C0PGzSQO.mjs.map +0 -1
- package/dist/serverHandlers-BpKfaFsD.mjs.map +0 -1
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { t as PathTrie } from "./pathTrie-D4Ax2Mu9.mjs";
|
|
2
2
|
import { t as ServerEvent } from "./ServerEvent-BY4f3RVF.mjs";
|
|
3
|
+
import { t as runHooks } from "./runHooks-D5p1Rh7i.mjs";
|
|
3
4
|
//#region src/server/Server.ts
|
|
4
5
|
/**
|
|
5
6
|
* A Fetch API Request/Response server.
|
|
@@ -23,32 +24,13 @@ var Server = class {
|
|
|
23
24
|
const match = this.match(url.pathname);
|
|
24
25
|
let ev = new ServerEvent(request, match?.params, url);
|
|
25
26
|
if (this.middleware.length) {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
}
|
|
34
|
-
if (!response && match) {
|
|
35
|
-
const result = await match.fn(ev);
|
|
36
|
-
if (result) response = result;
|
|
37
|
-
}
|
|
38
|
-
} catch (e) {
|
|
39
|
-
error = e;
|
|
40
|
-
ev.error = e;
|
|
41
|
-
} finally {
|
|
42
|
-
if (response) ev.response = response;
|
|
43
|
-
while (entered > 0) {
|
|
44
|
-
entered--;
|
|
45
|
-
const result = await this.middleware[entered].exit?.(ev);
|
|
46
|
-
if (result) {
|
|
47
|
-
response = result;
|
|
48
|
-
ev.response = result;
|
|
49
|
-
}
|
|
50
|
-
}
|
|
51
|
-
}
|
|
27
|
+
const { response, error } = await runHooks([{
|
|
28
|
+
hooks: this.middleware,
|
|
29
|
+
arg: ev
|
|
30
|
+
}], async () => {
|
|
31
|
+
if (!match) return void 0;
|
|
32
|
+
return await match.fn(ev) || void 0;
|
|
33
|
+
}, { event: ev });
|
|
52
34
|
if (error && !response) throw error;
|
|
53
35
|
} else if (match) ev.response = await match.fn(ev);
|
|
54
36
|
else return new Response(null, { status: 404 });
|
|
@@ -101,4 +83,4 @@ var RouteHandler = class {
|
|
|
101
83
|
//#endregion
|
|
102
84
|
export { Server as t };
|
|
103
85
|
|
|
104
|
-
//# sourceMappingURL=Server-
|
|
86
|
+
//# sourceMappingURL=Server-dcRbdPXf.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Server-dcRbdPXf.mjs","names":[],"sources":["../src/server/Server.ts"],"sourcesContent":["import PathTrie from \"../utils/pathTrie\";\nimport ServerEvent from \"./ServerEvent\";\nimport runHooks from \"./runHooks\";\nimport type MiddlewareFunction from \"./types/MiddlewareFunction\";\nimport type ServerFunction from \"./types/ServerFunction\";\n\n/**\n * A Fetch API Request/Response server.\n */\nexport default class Server {\n\t// TODO: We don't use any of the routes, just add(\"*\") in runDev/runBuild...\n\troutes: RouteHandler[] = [];\n\t// Match index for the routes above\n\t#trie = new PathTrie<RouteHandler>();\n\t// TODO: We only use the Vite middleware here\n\tmiddleware: MiddlewareFunction[] = [];\n\n\tconstructor() {\n\t\tthis.routes = [];\n\t\tthis.middleware = [];\n\t}\n\n\t/**\n\t * The standard Fetch API method that should work in any runtime (including\n\t * Node with polyfills).\n\t * @returns\n\t */\n\tfetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {\n\t\t// Use the request as-is when we were given one, so that the adapter\n\t\t// doesn't pay for constructing it twice\n\t\tconst request = input instanceof Request && !init ? input : new Request(input, init);\n\t\tconst url = new URL(request.url);\n\t\tconst match = this.match(url.pathname);\n\t\tlet ev = new ServerEvent(request, match?.params, url);\n\n\t\tif (this.middleware.length) {\n\t\t\t// Route-scoped middleware is set on server endpoints (or globally on\n\t\t\t// `site.middleware`); this list is the low-level, per-Server primitive\n\t\t\tconst { response, error } = await runHooks(\n\t\t\t\t[{ hooks: this.middleware, arg: ev }],\n\t\t\t\tasync (): Promise<Response | undefined> => {\n\t\t\t\t\tif (!match) return undefined;\n\t\t\t\t\treturn (await match.fn(ev)) || undefined;\n\t\t\t\t},\n\t\t\t\t{ event: ev },\n\t\t\t);\n\t\t\tif (error && !response) {\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t} else if (match) {\n\t\t\tev.response = await match.fn(ev);\n\t\t} else {\n\t\t\treturn new Response(null, { status: 404 });\n\t\t}\n\n\t\t// TODO: Should I be returning 200 if there's no response? Because it's not an error??\n\t\tev.response ??= new Response(null, { status: 200 });\n\t\tev.addHeaders();\n\n\t\treturn ev.response;\n\t};\n\n\t/**\n\t * Adds a server function at a route path.\n\t * @param path The route path pattern.\n\t * @param fn The function to call when the pattern is matched.\n\t * @returns\n\t */\n\tadd(path: string, fn: ServerFunction): Server {\n\t\tlet handler = new RouteHandler(path, fn);\n\t\tthis.routes.push(handler);\n\t\tthis.#trie.insert(path, handler);\n\t\tthis.#sortRoutes();\n\t\treturn this;\n\t}\n\n\tmatch(path: string): Match | undefined {\n\t\tconst found = this.#trie.match(path);\n\t\tif (found) {\n\t\t\treturn {\n\t\t\t\tfn: found.value.fn,\n\t\t\t\tparams: found.params,\n\t\t\t};\n\t\t}\n\t\tconsole.log(`Server path not found: ${path}`);\n\t}\n\n\t// TODO:\n\t//use(path: string, ...fn: MiddlewareFunction[])\n\tuse(...fn: MiddlewareFunction[]): Server {\n\t\tthis.middleware = this.middleware.concat(fn);\n\t\treturn this;\n\t}\n\n\t#sortRoutes() {\n\t\tthis.routes = this.routes.sort((a, b) => {\n\t\t\t// Sort [param]s after paths\n\t\t\t// There might be a quicker/easier way to do this\n\t\t\tfor (let i = 0; i < Math.min(a.path.length, b.path.length); i++) {\n\t\t\t\tif (a.path[i] === \"[\" && b.path[i] !== \"[\") {\n\t\t\t\t\treturn 1;\n\t\t\t\t} else if (b.path[i] === \"[\" && a.path[i] !== \"[\") {\n\t\t\t\t\treturn -1;\n\t\t\t\t} else if (a.path[i] === b.path[i]) {\n\t\t\t\t\t// Keep going...\n\t\t\t\t} else {\n\t\t\t\t\treturn a.path[i].localeCompare(b.path[i]);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn a.path.length - b.path.length;\n\t\t});\n\t}\n}\n\nclass RouteHandler {\n\tpath: string;\n\tfn: ServerFunction;\n\n\tconstructor(path: string, fn: ServerFunction) {\n\t\tthis.path = path;\n\t\tthis.fn = fn;\n\t}\n}\n\n//class MiddlewareHandler {\n//\tpath: string;\n//\tregex: RegExp;\n//\tfn: MiddlewareFunction;\n//\n//\tconstructor(path: string, fn: MiddlewareFunction) {\n//\t\tthis.path = path;\n//\t\tthis.regex = pathToRegex(path);\n//\t\tthis.fn = fn;\n//\t}\n//}\n\ninterface Match {\n\tfn: ServerFunction;\n\tparams?: Record<string, string>;\n}\n"],"mappings":";;;;;;;AASA,IAAqB,SAArB,MAA4B;CAE3B,SAAyB,CAAC;CAE1B,QAAQ,IAAI,SAAuB;CAEnC,aAAmC,CAAC;CAEpC,cAAc;EACb,KAAK,SAAS,CAAC;EACf,KAAK,aAAa,CAAC;CACpB;;;;;;CAOA,QAAQ,OAAO,OAA0B,SAA0C;EAGlF,MAAM,UAAU,iBAAiB,WAAW,CAAC,OAAO,QAAQ,IAAI,QAAQ,OAAO,IAAI;EACnF,MAAM,MAAM,IAAI,IAAI,QAAQ,GAAG;EAC/B,MAAM,QAAQ,KAAK,MAAM,IAAI,QAAQ;EACrC,IAAI,KAAK,IAAI,YAAY,SAAS,OAAO,QAAQ,GAAG;EAEpD,IAAI,KAAK,WAAW,QAAQ;GAG3B,MAAM,EAAE,UAAU,UAAU,MAAM,SACjC,CAAC;IAAE,OAAO,KAAK;IAAY,KAAK;GAAG,CAAC,GACpC,YAA2C;IAC1C,IAAI,CAAC,OAAO,OAAO,KAAA;IACnB,OAAQ,MAAM,MAAM,GAAG,EAAE,KAAM,KAAA;GAChC,GACA,EAAE,OAAO,GAAG,CACb;GACA,IAAI,SAAS,CAAC,UACb,MAAM;EAER,OAAO,IAAI,OACV,GAAG,WAAW,MAAM,MAAM,GAAG,EAAE;OAE/B,OAAO,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;EAI1C,GAAG,aAAa,IAAI,SAAS,MAAM,EAAE,QAAQ,IAAI,CAAC;EAClD,GAAG,WAAW;EAEd,OAAO,GAAG;CACX;;;;;;;CAQA,IAAI,MAAc,IAA4B;EAC7C,IAAI,UAAU,IAAI,aAAa,MAAM,EAAE;EACvC,KAAK,OAAO,KAAK,OAAO;EACxB,KAAK,MAAM,OAAO,MAAM,OAAO;EAC/B,KAAK,YAAY;EACjB,OAAO;CACR;CAEA,MAAM,MAAiC;EACtC,MAAM,QAAQ,KAAK,MAAM,MAAM,IAAI;EACnC,IAAI,OACH,OAAO;GACN,IAAI,MAAM,MAAM;GAChB,QAAQ,MAAM;EACf;EAED,QAAQ,IAAI,0BAA0B,MAAM;CAC7C;CAIA,IAAI,GAAG,IAAkC;EACxC,KAAK,aAAa,KAAK,WAAW,OAAO,EAAE;EAC3C,OAAO;CACR;CAEA,cAAc;EACb,KAAK,SAAS,KAAK,OAAO,MAAM,GAAG,MAAM;GAGxC,KAAK,IAAI,IAAI,GAAG,IAAI,KAAK,IAAI,EAAE,KAAK,QAAQ,EAAE,KAAK,MAAM,GAAG,KAC3D,IAAI,EAAE,KAAK,OAAO,OAAO,EAAE,KAAK,OAAO,KACtC,OAAO;QACD,IAAI,EAAE,KAAK,OAAO,OAAO,EAAE,KAAK,OAAO,KAC7C,OAAO;QACD,IAAI,EAAE,KAAK,OAAO,EAAE,KAAK,IAAI,CAEpC,OACC,OAAO,EAAE,KAAK,EAAE,CAAC,cAAc,EAAE,KAAK,EAAE;GAG1C,OAAO,EAAE,KAAK,SAAS,EAAE,KAAK;EAC/B,CAAC;CACF;AACD;AAEA,IAAM,eAAN,MAAmB;CAClB;CACA;CAEA,YAAY,MAAc,IAAoB;EAC7C,KAAK,OAAO;EACZ,KAAK,KAAK;CACX;AACD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Server-qn5Ws_d0.d.mts","names":[],"sources":["../src/server/types/ServerFunction.ts","../src/server/Server.ts"],"mappings":";;KAEK,kBACJ,GAAG,gBACC,8BAA8B,QAAQ;;;;;;
|
|
1
|
+
{"version":3,"file":"Server-qn5Ws_d0.d.mts","names":[],"sources":["../src/server/types/ServerFunction.ts","../src/server/Server.ts"],"mappings":";;KAEK,kBACJ,GAAG,gBACC,8BAA8B,QAAQ;;;;;;cCKtB;;EAEpB,QAAQ;EAIR,YAAY;EAEZ;;;;;;EAUA,QAAe,OAAO,cAAc,KAAK,OAAO,gBAAc,QAAQ;;;;;;;EAyCtE,IAAI,cAAc,IAAI,iBAAiB;EAQvC,MAAM,eAAe;EAarB,OAAO,IAAI,uBAAuB;;cAyB7B;EACL;EACA,IAAI;EAEJ,YAAY,cAAc,IAAI;;UAkBrB;EACT,IAAI;EACJ,SAAS"}
|
package/dist/bin/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#! /usr/bin/env node
|
|
2
|
-
import { a as loadSite, n as run, t as runOpenApi } from "../runOpenApi-
|
|
2
|
+
import { a as loadSite, n as run, t as runOpenApi } from "../runOpenApi-C5yMpQU1.mjs";
|
|
3
3
|
//#region src/bin/index.ts
|
|
4
4
|
const workingDir = process.cwd();
|
|
5
5
|
if (process.argv.includes("--openapi")) {
|
package/dist/clientEntry.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { t as Router } from "./Router-C4ADUfhv.mjs";
|
|
2
2
|
import { o as setBasePath } from "./basePath-DQnbHc7o.mjs";
|
|
3
3
|
import { t as $page } from "./_page-CW6SLuT4.mjs";
|
|
4
|
-
import { a as client, n as navigate, r as loadData } from "./load-
|
|
4
|
+
import { a as client, n as navigate, r as loadData } from "./load-G-4A435s.mjs";
|
|
5
5
|
import manifest from "@torpor/build/manifest";
|
|
6
6
|
//#region src/site/clientEntry.ts
|
|
7
7
|
setBasePath(manifest.base);
|
package/dist/dev.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import { t as Server } from "./Server-
|
|
2
|
-
import { t as load } from "./serverEntry-
|
|
1
|
+
import { t as Server } from "./Server-dcRbdPXf.mjs";
|
|
2
|
+
import { t as load } from "./serverEntry-D1hE-Jzt.mjs";
|
|
3
3
|
export { Server, load };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { r as serverError } from "./response-C5EZsszY.mjs";
|
|
2
|
-
import { t as Server } from "./Server-
|
|
2
|
+
import { t as Server } from "./Server-dcRbdPXf.mjs";
|
|
3
3
|
import { t as flattenHeaders } from "./flattenHeaders-DM5qsSqO.mjs";
|
|
4
4
|
import { existsSync, promises, realpathSync } from "node:fs";
|
|
5
5
|
import fpath from "node:path";
|
|
@@ -141,4 +141,4 @@ async function sendResponse(response, res) {
|
|
|
141
141
|
//#endregion
|
|
142
142
|
export { siteEntryPaths as i, prepareTemplate as n, detectSourceMode as r, devPlugin as t };
|
|
143
143
|
|
|
144
|
-
//# sourceMappingURL=devPlugin-
|
|
144
|
+
//# sourceMappingURL=devPlugin-lLzauETn.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devPlugin-CL0eu77n.mjs","names":["path","path","fs"],"sources":["../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/devPlugin.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,UAA2B;CAC3D,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAOA,MAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CAD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AAO;CACpC;CACA,IAAI,IAAI,WAAW,SAAS,IAAI,WAAW,QAAQ;EAClD,KAAK,OAAO,SAAS,MAAM,GAAG;EAE9B,KAAK,SAAS;CACf;CACA,OAAO,IAAI,QAAQ,GAAG,SAAS,KAAK,OAAO,OAAO,IAAI;AACvD;AAEA,eAAe,aAAa,UAAoB,KAAoC;CACnF,IAAI,aAAa,SAAS;CAC1B,SAAS,QAAQ,SAAS,OAAO,QAAQ,IAAI,UAAU,KAAK,KAAK,CAAC;CAClE,IAAI,CAAC,SAAS,MAAM;EACnB,IAAI,IAAI;EACR;CACD;CACA,SAAS,QAAQ,SAAS,IAA2D,CAAC,CAAC,KAAK,GAAG;AAChG"}
|
|
1
|
+
{"version":3,"file":"devPlugin-lLzauETn.mjs","names":["path","path","fs"],"sources":["../src/utils/entryPaths.ts","../src/run/prepareTemplate.ts","../src/run/devPlugin.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\n\n/**\n * Paths to the site entry files that `tb` loads from the installed\n * `@torpor/build` package, in either source (linked framework) or dist\n * (registry install) mode.\n */\nexport type SiteEntryPaths = {\n\tserverEntry: string;\n\tclientEntry: string;\n\tclientDevEntry: string;\n};\n\n/**\n * Whether tb should run the framework from its TypeScript source instead of\n * its compiled dist. This is a framework-development convenience: registry\n * installs always run dist. Source mode is enabled explicitly via the\n * TORPOR_SOURCE_DEV env var, or automatically when both `@torpor/build` and\n * `@torpor/view` are symlinked into the app from outside node_modules (as\n * workspace links and `link:` overrides do). Both packages must be linked,\n * because source mode resolves their `torpor:source` export conditions, which\n * point at src files that registry installs don't ship.\n */\nexport function detectSourceMode(siteRoot: string): boolean {\n\tif (process.env.TORPOR_SOURCE_DEV) return true;\n\tconst packages = [\"@torpor/build\", \"@torpor/view\"];\n\treturn packages.every((pkg) => {\n\t\ttry {\n\t\t\tconst dist = path.resolve(siteRoot, \"node_modules\", pkg, \"dist/index.mjs\");\n\t\t\tconst real = realpathSync(dist);\n\t\t\treturn !real.includes(\"node_modules\");\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t});\n}\n\n/**\n * The site entry files for the given mode: raw TypeScript sources when the\n * framework is linked (Vite transforms them, and edits show up without a\n * rebuild), compiled `.mjs` bundles for registry installs.\n */\nexport function siteEntryPaths(siteRoot: string, sourceMode: boolean): SiteEntryPaths {\n\tconst folder = path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/site\" : \"dist\",\n\t);\n\tconst ext = sourceMode ? \".ts\" : \".mjs\";\n\treturn {\n\t\tserverEntry: path.join(folder, `serverEntry${ext}`),\n\t\tclientEntry: path.join(folder, `clientEntry${ext}`),\n\t\tclientDevEntry: path.join(folder, `clientEntryDev${ext}`),\n\t};\n}\n\n/**\n * The torpor `Server` class module that a Cloudflare `_worker.ts` imports,\n * for the given mode.\n */\nexport function serverClassPath(siteRoot: string, sourceMode: boolean): string {\n\treturn path.resolve(\n\t\tsiteRoot,\n\t\t\"node_modules/@torpor/build\",\n\t\tsourceMode ? \"src/server/Server.ts\" : \"dist/server/Server.mjs\",\n\t);\n}\n","export default function prepareTemplate(\n\ttemplate: string,\n\tclientScript: string,\n\tclientDevScript?: string,\n): string {\n\tlet result = template;\n\n\t// Put %COMPONENT_HEAD% before </head>\n\t// This is where styles will go\n\tlet headStart = result.indexOf(\"</head>\");\n\tif (headStart === -1) {\n\t\tthrow new Error(`Couldn't find <head> end tag`);\n\t}\n\tresult = result.substring(0, headStart) + \"%COMPONENT_HEAD%\" + result.substring(headStart);\n\n\t// Put %COMPONENT_BODY% inside <div id=\"app\"></div>\n\t// This is where the component's HTML will go\n\tlet divMatchStart = regexIndexOf(result, /<div\\s+id=(\"app\"|'app'|app)[\\s>]/);\n\tif (divMatchStart === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tlet bodyStart = result.indexOf(\">\", divMatchStart) + 1;\n\tlet bodyEnd = result.indexOf(\"</div>\", bodyStart);\n\tif (bodyEnd === -1) {\n\t\tthrow new Error(`Couldn't find <div id=\"app\"></div>`);\n\t}\n\tresult = result.substring(0, bodyStart) + \"%COMPONENT_BODY%\" + result.substring(bodyEnd);\n\n\t// Add the clientEntry script at the very end, for hydrating and navigating\n\tif (clientDevScript) {\n\t\tresult += `<script type=\"module\" src=\"${clientDevScript}\"></script>`;\n\t}\n\tresult += `<script type=\"module\" src=\"${clientScript}\"></script>`;\n\n\treturn result;\n}\n\n// From https://stackoverflow.com/a/274094\nfunction regexIndexOf(string: string, regex: RegExp, position?: number) {\n\tvar indexOf = string.substring(position || 0).search(regex);\n\treturn indexOf >= 0 ? indexOf + (position || 0) : indexOf;\n}\n","import { type IncomingMessage, type ServerResponse } from \"node:http\";\nimport { existsSync, promises as fs } from \"node:fs\";\nimport path from \"node:path\";\nimport { Readable } from \"node:stream\";\nimport { type Plugin, type ViteDevServer } from \"vite\";\nimport { serverError } from \"../response.ts\";\nimport Server from \"../server/Server.ts\";\nimport flattenHeaders from \"../server/connect/flattenHeaders.ts\";\nimport type Site from \"../site/Site.ts\";\nimport { siteEntryPaths } from \"../utils/entryPaths\";\nimport prepareTemplate from \"./prepareTemplate.ts\";\n\ntype ReqHandler = (req: IncomingMessage, res: ServerResponse) => Promise<void>;\n\n/**\n * The default Node-runtime dev plugin. Reads `src/site.html`, sets up a torpor\n * `Server` whose catch-all route renders via `vite.ssrLoadModule`, and registers\n * a Connect middleware (after Vite's own middlewares) that bridges Node\n * req/res to the torpor Server's fetch handler.\n *\n * Adapters that need a different runtime (e.g. workerd) provide their own\n * `dev()` plugin instead.\n */\nexport default function devPlugin(site: Site, sourceMode = false): Plugin {\n\treturn {\n\t\tname: \"torpor-dev\",\n\t\tconfigureServer(vite) {\n\t\t\t// Kick off async setup immediately; the middleware awaits it so we\n\t\t\t// don't depend on whether Vite awaits configureServer itself.\n\t\t\tconst handlerPromise = createDevHandler(vite, site, sourceMode);\n\t\t\t// Return a post-hook so our middleware runs AFTER Vite's internal\n\t\t\t// middlewares (static serving, transforms, HMR), acting as the SSR\n\t\t\t// fallback.\n\t\t\treturn () => {\n\t\t\t\tvite.middlewares.use(async (req, res, next) => {\n\t\t\t\t\ttry {\n\t\t\t\t\t\tconst handler = await handlerPromise;\n\t\t\t\t\t\tawait handler(req, res);\n\t\t\t\t\t} catch (e) {\n\t\t\t\t\t\tnext(e as Error);\n\t\t\t\t\t}\n\t\t\t\t});\n\t\t\t};\n\t\t},\n\t};\n}\n\nasync function createDevHandler(\n\tvite: ViteDevServer,\n\tsite: Site,\n\tsourceMode: boolean,\n): Promise<ReqHandler> {\n\tconst entries = siteEntryPaths(site.root, sourceMode);\n\tconst serverScript = entries.serverEntry;\n\n\t// Read site.html if present\n\t// It's called site.html because @torpor/build builds the site (html, routes\n\t// etc) while the user builds the app (components etc). An endpoints-only\n\t// site has no site.html, and no template is needed\n\tlet template: string | undefined;\n\tconst templateFile = path.resolve(site.root, \"src/site.html\");\n\tif (existsSync(templateFile)) {\n\t\ttemplate = await fs.readFile(templateFile, \"utf-8\");\n\n\t\t// Apply Vite HTML transforms. This injects the Vite HMR client, and also\n\t\t// applies HTML transforms from Vite plugins. Note that we only support a\n\t\t// universal transform, not individual transforms for each route\n\t\ttemplate = await vite.transformIndexHtml(\"\", template);\n\n\t\t// Prepare site.html so that we can just splice components into it\n\t\ttemplate = prepareTemplate(template, entries.clientEntry, entries.clientDevEntry);\n\t}\n\n\tconst server = new Server();\n\n\t// Every request (GET, POST, etc) goes through loadEndPoint\n\tserver.add(\"*\", async (ev) => {\n\t\ttry {\n\t\t\t// Load the server entry. ssrLoadModule automatically transforms ESM\n\t\t\t// source code to be usable in Node.js. No bundling is required, and\n\t\t\t// it provides efficient invalidation similar to HMR\n\t\t\tconst { load } = await vite.ssrLoadModule(serverScript);\n\n\t\t\t// Render the app HTML (or fetch server data etc) via serverEntry's\n\t\t\t// exported `load` function\n\t\t\treturn await load(ev, template);\n\t\t} catch (e: any) {\n\t\t\t// If an error is caught, let Vite fix the stack trace so it maps\n\t\t\t// back to your actual source code\n\t\t\tvite.ssrFixStacktrace(e);\n\t\t\treturn serverError(e);\n\t\t}\n\t});\n\n\t// Put adapter-specific functionality in the `adapter` property of\n\t// globalThis for now\n\t// @ts-ignore\n\tglobalThis.adapter = { env: process.env };\n\n\treturn async (req, res) => {\n\t\tconst request = await nodeReqToRequest(req);\n\t\tconst response = await server.fetch(request);\n\t\tawait sendResponse(response, res);\n\t};\n}\n\nasync function nodeReqToRequest(req: IncomingMessage): Promise<Request> {\n\tconst url = req.url ?? \"/\";\n\tconst host = req.headers.host ?? \"localhost\";\n\tconst protocol = \"encrypted\" in req.socket && req.socket.encrypted ? \"https\" : \"http\";\n\tconst init: RequestInit = {\n\t\tmethod: req.method,\n\t\theaders: flattenHeaders(req.headers),\n\t};\n\tif (req.method !== \"GET\" && req.method !== \"HEAD\") {\n\t\tinit.body = Readable.toWeb(req) as ReadableStream;\n\t\t// @ts-ignore duplex is required when streaming a body\n\t\tinit.duplex = \"half\";\n\t}\n\treturn new Request(`${protocol}://${host}${url}`, init);\n}\n\nasync function sendResponse(response: Response, res: ServerResponse): Promise<void> {\n\tres.statusCode = response.status;\n\tresponse.headers.forEach((value, key) => res.setHeader(key, value));\n\tif (!response.body) {\n\t\tres.end();\n\t\treturn;\n\t}\n\tReadable.fromWeb(response.body as unknown as import(\"node:stream/web\").ReadableStream).pipe(res);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAwBA,SAAgB,iBAAiB,UAA2B;CAC3D,IAAI,QAAQ,IAAI,mBAAmB,OAAO;CAE1C,OAAO,CADW,iBAAiB,cACrB,CAAC,CAAC,OAAO,QAAQ;EAC9B,IAAI;GACH,MAAM,OAAOA,MAAK,QAAQ,UAAU,gBAAgB,KAAK,gBAAgB;GAEzE,OAAO,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;AAOA,SAAgB,eAAe,UAAkB,Y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ACf;CACA,OAAO,IAAI,QAAQ,GAAG,SAAS,KAAK,OAAO,OAAO,IAAI;AACvD;AAEA,eAAe,aAAa,UAAoB,KAAoC;CACnF,IAAI,aAAa,SAAS;CAC1B,SAAS,QAAQ,SAAS,OAAO,QAAQ,IAAI,UAAU,KAAK,KAAK,CAAC;CAClE,IAAI,CAAC,SAAS,MAAM;EACnB,IAAI,IAAI;EACR;CACD;CACA,SAAS,QAAQ,SAAS,IAA2D,CAAC,CAAC,KAAK,GAAG;AAChG"}
|
|
@@ -494,8 +494,15 @@ async function renderNavigation(rawUrl, withHydration) {
|
|
|
494
494
|
let layoutStack = client.layoutStack;
|
|
495
495
|
let component = clientEndPoint.component;
|
|
496
496
|
let slots = void 0;
|
|
497
|
-
let reused = false;
|
|
498
497
|
let reusedIndex = -1;
|
|
498
|
+
for (let i = layoutStack.length - 1; i >= 0; i--) {
|
|
499
|
+
const stackLayout = layoutStack[i];
|
|
500
|
+
if (stackLayout.reuse && stackLayout.slotRegion?.startNode?.parentNode != null) {
|
|
501
|
+
reusedIndex = i;
|
|
502
|
+
break;
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
let reused = reusedIndex !== -1;
|
|
499
506
|
if (handler.layouts) {
|
|
500
507
|
let slotFunctions = [];
|
|
501
508
|
slotFunctions[handler.layouts.length] = function clientComponent(parent, anchor) {
|
|
@@ -505,10 +512,8 @@ async function renderNavigation(rawUrl, withHydration) {
|
|
|
505
512
|
for (let i = handler.layouts.length - 1; i >= 0; i--) {
|
|
506
513
|
const layoutEndPoint = (await handler.layouts[i].endPoint())?.default;
|
|
507
514
|
if (layoutEndPoint?.component) {
|
|
508
|
-
if (
|
|
515
|
+
if (i === reusedIndex) {
|
|
509
516
|
component = slotFunctions[i + 1];
|
|
510
|
-
reusedIndex = i;
|
|
511
|
-
reused = true;
|
|
512
517
|
break;
|
|
513
518
|
} else if (i === 0) {
|
|
514
519
|
component = layoutEndPoint.component;
|
|
@@ -524,6 +529,11 @@ async function renderNavigation(rawUrl, withHydration) {
|
|
|
524
529
|
try {
|
|
525
530
|
if (reused) {
|
|
526
531
|
const slotRegion = layoutStack[reusedIndex].slotRegion;
|
|
532
|
+
if (slotRegion === null || slotRegion.startNode === null || slotRegion.startNode.parentNode === null) {
|
|
533
|
+
console.error("The layout slot was cleared during navigation; falling back to a full page load");
|
|
534
|
+
window.location.reload();
|
|
535
|
+
return;
|
|
536
|
+
}
|
|
527
537
|
app = slotRegion.startNode.parentNode;
|
|
528
538
|
clearLayoutSlot(slotRegion);
|
|
529
539
|
component(app, null);
|
|
@@ -556,4 +566,4 @@ async function load(path) {
|
|
|
556
566
|
//#endregion
|
|
557
567
|
export { client as a, reload as i, navigate as n, loadData as r, load as t };
|
|
558
568
|
|
|
559
|
-
//# sourceMappingURL=load-
|
|
569
|
+
//# sourceMappingURL=load-G-4A435s.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"load-Clec6rli.mjs","names":[],"sources":["../src/state/client.ts","../src/nav/reload.ts","../src/nav/formSubmit.ts","../src/nav/loadData.ts","../src/nav/navigate.ts","../src/nav/load.ts"],"sourcesContent":["import type ClientState from \"../types/ClientState\";\n\nconst CLIENT_SYMBOL: unique symbol = Symbol.for(\"torp.Client\");\n\nconst client: ClientState =\n\t// @ts-ignore\n\t(globalThis[CLIENT_SYMBOL] ??= {\n\t\t// @ts-ignore This will definitely, 100% get set\n\t\trouter: null,\n\t\tlayoutStack: [],\n\t\t// TODO: Probably expire after 30 seconds or something?\n\t\tprefetchedData: {},\n\t\tprefetchedServerData: {},\n\t\tviewTransitions: false,\n\t});\n\nexport default client;\n","import navigate from \"./navigate\";\n\n/**\n * Reloads data for the currently loaded page and rerenders it.\n */\nexport default async function reload(): Promise<boolean> {\n\tconst url = new URL(document.location.href);\n\treturn await navigate(url);\n}\n","import $page from \"../state/$page\";\nimport load from \"./load\";\nimport reload from \"./reload\";\n\nexport default async function formSubmit(e: SubmitEvent): Promise<void> {\n\t// We'll take it from here\n\te.preventDefault();\n\n\t// Reset $page on submit and link navigation\n\t// TODO: Should we put data in $page.data??\n\t$page.form = undefined;\n\n\t// Perform a POST fetch to the form's action location\n\tconst form = e.target as HTMLFormElement;\n\tconst button = e.submitter as HTMLButtonElement | null;\n\t// HACK: submit buttons have their formAction set to the current page if not\n\t// set, so we can't just check whether it's empty and fallback to form action\n\t//const action = button?.formAction ?? form.action;\n\tlet action = form.action || document.URL;\n\tif (button && button.formAction && button.formAction !== document.URL) {\n\t\taction = button.formAction;\n\t}\n\tconst options = {\n\t\tbody: button ? new FormData(form, button) : new FormData(form),\n\t\tmethod: \"POST\",\n\t\tmode: \"cors\",\n\t\tcredentials: \"same-origin\",\n\t\t// Add a special header which tells the server that we want the raw\n\t\t// error response (if applicable) rather than the reloaded page that you\n\t\t// would get if submitting a page without javascript\n\t\theaders: {\n\t\t\t\"X-Torpor-Form-Submit\": \"\",\n\t\t},\n\t};\n\tconst response = await fetch(\n\t\taction,\n\t\t// @ts-ignore -- don't know what it's complaining about here\n\t\toptions,\n\t);\n\n\tif (\n\t\tresponse.status === 200 &&\n\t\tresponse.headers.has(\"Content-Disposition\") &&\n\t\t/attachment;\\s*filename=\"(.+?)\"/.test(response.headers.get(\"Content-Disposition\")!)\n\t) {\n\t\t// TODO: Is this enough to check to see if we have a file that should download?\n\t\t// Download the file by creating a dummy <a> and clicking it\n\t\tconst downloadFileName =\n\t\t\tresponse.headers.get(\"Content-Disposition\")?.match(/attachment;\\s*filename=\"(.+?)\"/)![1] ??\n\t\t\t\"file\";\n\t\tconst downloadLink = document.createElement(\"a\");\n\t\tdownloadLink.href = window.URL.createObjectURL(await response.blob());\n\t\tdownloadLink.download = downloadFileName;\n\t\tdownloadLink.click();\n\t} else if (response.status === 200 && response.headers.has(\"X-Torpor-Form-Redirect\")) {\n\t\t// TODO: Should do the correct type of redirect e.g. seeOther etc\n\t\tconst redirect = response.headers.get(\"Location\")!;\n\t\tawait load(redirect);\n\t\twindow.location.href = redirect;\n\t} else if (\n\t\t(response.status >= 200 && response.status <= 299) ||\n\t\t(response.status >= 400 && response.status <= 499)\n\t) {\n\t\t// Put the response into `$page.form`, and it will be put into `$props` in reload\n\t\tif (response.headers.get(\"Content-Type\") === \"application/json\") {\n\t\t\t$page.form = await response.json();\n\t\t}\n\t\tawait reload();\n\t} else if (response.status >= 500) {\n\t\t// A server error: like a no-javascript submit, the response is the\n\t\t// error page rendered at this url with the error status. Swap the\n\t\t// document for it -- the url stays, so a transient failure can be\n\t\t// retried with a refresh. Without an error page, reload, which will\n\t\t// show the raw error response instead\n\t\tif (response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\tconst html = await response.text();\n\t\t\tdocument.open();\n\t\t\tdocument.write(html);\n\t\t\tdocument.close();\n\t\t} else {\n\t\t\twindow.location.reload();\n\t\t}\n\t}\n}\n","import { type DeferredMeta, setAtPath } from \"../deferred.ts\";\nimport { DATA_REUSE_HEADER, DATA_REQUEST_HEADER } from \"../dataRequest.ts\";\nimport { readResponseBody } from \"../response/read.ts\";\nimport { getBasePath } from \"../site/basePath\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport type RouteHandler from \"../types/RouteHandler\";\nimport client from \"../state/client\";\n\n/**\n * The result of loading a route's data. `error` is set when a load function\n * returned an error response (redirects excluded) -- the caller renders the\n * error page instead of the route.\n */\nexport type LoadDataResult = {\n\tdata: Record<string, any>;\n\terror?: {\n\t\tstatus: number;\n\t\tmessage: string;\n\t};\n};\n\n/**\n * Loads a route's data for a client-side navigation.\n *\n * One request (`GET <page url>/~server` with the data header) returns the\n * server data for the page and all of its layouts, with hooks running once\n * against the page url. The client then runs its own load functions (layout\n * by layout, then the page), merging each route's fresh server data in the\n * same order the server render does.\n */\nexport default async function loadData(\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\tpath: string,\n\tquery: URLSearchParams,\n\tnewLayoutStack: LayoutPath[],\n\tclientEndPoint: PageEndPoint | undefined,\n\tprefetch = false,\n): Promise<LoadDataResult | void> {\n\tlet data = {};\n\n\t// Work out up front which layouts are already rendered (their data is\n\t// reused), so the data request can skip loading them. A prefetch also skips\n\t// their server loads (they're already in the client stack) but must not\n\t// adopt their live slot regions: it may never be followed by a navigation\n\tconst layoutStack = client.layoutStack;\n\tconst layouts = (handler.layouts ?? []).map((layout, index) => {\n\t\tlet layoutPath = layout.path;\n\t\tfor (let key in params) {\n\t\t\tlayoutPath = layoutPath.replace(`[${key}]`, params[key]);\n\t\t}\n\t\tconst previous = layoutStack.at(index);\n\t\tconst rendered = previous?.path === layoutPath;\n\t\tconst reuse = !prefetch && rendered;\n\t\treturn { layout, index, layoutPath, previous, rendered, reuse };\n\t});\n\n\t// A page can opt out of the data request when it has no server load of its\n\t// own and every layout is already rendered (e.g. a tab switch under a\n\t// session hook that doesn't gate access). Its client load still runs.\n\tconst skipServerData =\n\t\tclientEndPoint?.serverData === false &&\n\t\t!handler.serverEndPoint &&\n\t\tlayouts.every((layout) => layout.rendered);\n\n\t// One request for all the (non-reused) server data\n\tconst server = skipServerData\n\t\t? {}\n\t\t: await loadServerData(\n\t\t\t\thandler,\n\t\t\t\tpath,\n\t\t\t\tquery,\n\t\t\t\tlayouts.filter((l) => l.rendered).map((l) => l.layoutPath),\n\t\t\t\tprefetch,\n\t\t\t);\n\tif (server === undefined) {\n\t\t// A load redirected: the client can't follow it through fetch, so the\n\t\t// caller falls back to a full page load\n\t\treturn;\n\t}\n\tif (\"error\" in server) {\n\t\treturn { data, error: server.error };\n\t}\n\n\tfor (const { layout, index, layoutPath, previous, rendered, reuse } of layouts) {\n\t\tconst stackLayout: LayoutPath = {\n\t\t\tpath: layoutPath,\n\t\t\tdata: {},\n\t\t\treuse,\n\t\t\tslotRegion: null,\n\t\t};\n\n\t\tif (rendered && previous) {\n\t\t\t// The layout is already rendered: keep its data. Only a real\n\t\t\t// navigation reuses its slot region; a prefetch must leave it alone\n\t\t\t// (and not run its client load again)\n\t\t\tif (reuse) stackLayout.slotRegion = previous.slotRegion;\n\t\t\tObject.assign(stackLayout.data, previous.data);\n\t\t} else {\n\t\t\t// A new layout: run its client load (its server data already\n\t\t\t// arrived in the single request)\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\tconst response = await runClientLoad(\n\t\t\t\tlayoutEndPoint,\n\t\t\t\tclientLocation(layoutPath),\n\t\t\t\tquery,\n\t\t\t\tparams,\n\t\t\t\tstackLayout.data,\n\t\t\t\tprefetch,\n\t\t\t);\n\t\t\tif (response) {\n\t\t\t\tif (isRedirect(response)) return;\n\t\t\t\treturn { data, error: await errorOf(response) };\n\t\t\t}\n\t\t\tconst serverData = server.loads?.[index];\n\t\t\tif (serverData) Object.assign(stackLayout.data, serverData);\n\t\t}\n\n\t\tObject.assign(data, stackLayout.data);\n\t\tnewLayoutStack.push(stackLayout);\n\t}\n\n\t// The page's client load, then its server data\n\tconst response = await runClientLoad(\n\t\tclientEndPoint,\n\t\tclientLocation(path),\n\t\tquery,\n\t\tparams,\n\t\tdata,\n\t\tprefetch,\n\t);\n\tif (response) {\n\t\tif (isRedirect(response)) return;\n\t\treturn { data, error: await errorOf(response) };\n\t}\n\tconst pageServerData = server.loads?.[handler.layouts?.length ?? 0];\n\tif (pageServerData) Object.assign(data, pageServerData);\n\n\treturn { data };\n}\n\ntype ServerData = {\n\tloads?: (Record<string, any> | null)[];\n\t/** Promise-valued properties streamed after the critical loads. */\n\tdeferred?: DeferredMeta[];\n};\n\ntype ServerDataFrame = {\n\ttype?: string;\n\tid?: string;\n\tvalue?: unknown;\n\tmessage?: string;\n} & ServerData;\n\n/**\n * A request-local registry of deferred promises. Values arrive after the first\n * frame (client navigation) or in inline scripts (initial hydration), and\n * resolve the promises already placed in the page's `data`.\n */\nclass DeferredStore {\n\t#entries = new Map<\n\t\tstring,\n\t\t{\n\t\t\tpromise: Promise<unknown>;\n\t\t\tresolve: (value: unknown) => void;\n\t\t\treject: (error: unknown) => void;\n\t\t}\n\t>();\n\n\tget(id: string): Promise<unknown> {\n\t\tlet entry = this.#entries.get(id);\n\t\tif (!entry) {\n\t\t\tlet resolve!: (value: unknown) => void;\n\t\t\tlet reject!: (error: unknown) => void;\n\t\t\tconst promise = new Promise<unknown>((res, rej) => {\n\t\t\t\tresolve = res;\n\t\t\t\treject = rej;\n\t\t\t});\n\t\t\t// A prefetch (or a navigation the user leaves) may never read the\n\t\t\t// promise; don't let its rejection surface as unhandled\n\t\t\tpromise.catch(() => {});\n\t\t\tentry = { promise, resolve, reject };\n\t\t\tthis.#entries.set(id, entry);\n\t\t}\n\t\treturn entry.promise;\n\t}\n\n\tresolve(id: string, value: unknown): void {\n\t\tconst entry = this.#entries.get(id);\n\t\tif (!entry) return;\n\t\tthis.#entries.delete(id);\n\t\tentry.resolve(value);\n\t}\n\n\treject(id: string, error: unknown): void {\n\t\tconst entry = this.#entries.get(id);\n\t\tif (!entry) return;\n\t\tthis.#entries.delete(id);\n\t\tentry.reject(error instanceof Error ? error : new Error(String(error)));\n\t}\n\n\trejectAll(error: unknown): void {\n\t\tfor (const id of this.#entries.keys()) {\n\t\t\tthis.reject(id, error);\n\t\t}\n\t}\n\n\t/** Places a promise for each deferred entry into the load that owns it. */\n\tattach(server: ServerData, get: (id: string) => Promise<unknown>): ServerData {\n\t\tfor (const entry of server.deferred ?? []) {\n\t\t\tconst load = server.loads?.[entry.index];\n\t\t\tif (!load) continue;\n\t\t\tsetAtPath(load, entry.path, get(entry.id));\n\t\t}\n\t\treturn server;\n\t}\n}\n\n/**\n * Fetches the page's combined server data for a navigation, reusing a prefetch\n * when there is one.\n *\n * A prefetch warms this request for the navigation that follows, and a\n * navigation consumes it (once). So a hover costs one request, a click that\n * lands while the prefetch is still in flight awaits the same promise instead\n * of issuing a second one, and a prefetched response is never served to more\n * than the one navigation it was loaded for (no stale data on later visits).\n */\nasync function loadServerData(\n\thandler: RouteHandler,\n\tpath: string,\n\tquery: URLSearchParams,\n\treusedLayouts: string[],\n\tprefetch: boolean,\n): Promise<ServerData | { error: { status: number; message: string } } | undefined> {\n\t// The server embeds the first render's data in the HTML (see the render\n\t// path in site/serverHandlers.ts), so the initial hydration can read it\n\t// instead of making a round trip. The element is consumed once, so later\n\t// navigations use the fetch below\n\tconst embedded = takeEmbeddedServerData();\n\tif (embedded !== undefined) {\n\t\treturn attachEmbeddedDeferred(embedded);\n\t}\n\n\tif (!hasServerData(handler)) {\n\t\treturn {};\n\t}\n\n\tconst key = serverDataKey(path, query);\n\n\tif (prefetch) {\n\t\tconst cached = client.prefetchedServerData[key];\n\t\tif (cached) return cached;\n\n\t\tconst pending = requestServerData(path, query, reusedLayouts);\n\t\tclient.prefetchedServerData[key] = pending;\n\t\t// A failed prefetch mustn't poison the navigation that follows it\n\t\tvoid pending.catch(() => {\n\t\t\tif (client.prefetchedServerData[key] === pending) {\n\t\t\t\tdelete client.prefetchedServerData[key];\n\t\t\t}\n\t\t});\n\t\treturn pending;\n\t}\n\n\tconst prefetched = client.prefetchedServerData[key];\n\tif (prefetched) {\n\t\tdelete client.prefetchedServerData[key];\n\t\treturn prefetched;\n\t}\n\n\treturn requestServerData(path, query, reusedLayouts);\n}\n\n/** The `/~server` request cache key: the page path and its query. */\nfunction serverDataKey(path: string, query: URLSearchParams): string {\n\treturn path + (query.size > 0 ? `?${query}` : \"\");\n}\n\n/**\n * The posted data request: `GET <page url>/~server` carrying the data header,\n * which the server answers with the page's and its layouts' server data as one\n * JSON body.\n */\nasync function requestServerData(\n\tpath: string,\n\tquery: URLSearchParams,\n\treusedLayouts: string[],\n): Promise<ServerData | { error: { status: number; message: string } } | undefined> {\n\tconst url = new URL(\n\t\tdocument.location.origin + getBasePath() + path.replace(/\\/$/, \"\") + \"/~server\",\n\t);\n\tfor (let [name, value] of query) {\n\t\turl.searchParams.append(name, value);\n\t}\n\n\tconst headers: Record<string, string> = { [DATA_REQUEST_HEADER]: \"1\" };\n\tif (reusedLayouts.length > 0) {\n\t\theaders[DATA_REUSE_HEADER] = JSON.stringify(reusedLayouts);\n\t}\n\n\tconst response = await fetch(url, {\n\t\tredirect: \"manual\",\n\t\theaders,\n\t});\n\tif (isRedirect(response)) {\n\t\treturn undefined;\n\t}\n\tif (!response.ok) {\n\t\treturn { error: await errorOf(response) };\n\t}\n\t// A site without a server (e.g. a static host) responds with the page's\n\t// html rather than json; there's nothing to merge\n\tconst type = response.headers.get(\"Content-Type\");\n\tif (type?.includes(\"application/x-ndjson\")) {\n\t\treturn await readServerDataStream(response);\n\t}\n\tif (!type?.includes(\"application/json\")) {\n\t\treturn {};\n\t}\n\treturn (await response.json()) as ServerData;\n}\n\n/**\n * Reads a streamed data response: the first frame carries the critical loads\n * and the list of deferred paths, later frames resolve those promises. The\n * function returns as soon as the first frame is read, so a navigation mounts\n * before slow values arrive.\n */\nasync function readServerDataStream(response: Response): Promise<ServerData> {\n\tconst reader = response.body?.getReader();\n\tif (!reader) return {};\n\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst readFrame = async (): Promise<ServerDataFrame | undefined> => {\n\t\twhile (true) {\n\t\t\tconst newline = buffer.indexOf(\"\\n\");\n\t\t\tif (newline >= 0) {\n\t\t\t\tconst line = buffer.slice(0, newline).trim();\n\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\tif (line) return JSON.parse(line) as ServerDataFrame;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tconst line = buffer.trim();\n\t\t\t\tbuffer = \"\";\n\t\t\t\treturn line ? (JSON.parse(line) as ServerDataFrame) : undefined;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t}\n\t};\n\n\tconst first = await readFrame();\n\tif (!first) return {};\n\tif (first.loads === undefined) return {};\n\tconst store = new DeferredStore();\n\tconst server = store.attach(first, (id) => store.get(id));\n\n\t// Keep reading in the background. The view is already mounted; values\n\t// resolve their promises as the frames arrive.\n\tvoid (async () => {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst frame = await readFrame();\n\t\t\t\tif (!frame) break;\n\t\t\t\tif (frame.type === \"value\" && frame.id !== undefined) {\n\t\t\t\t\tstore.resolve(frame.id, frame.value);\n\t\t\t\t} else if (frame.type === \"error\" && frame.id !== undefined) {\n\t\t\t\t\tstore.reject(frame.id, frame.message ?? \"Deferred data failed\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tstore.rejectAll(new Error(\"The deferred data stream ended before a value arrived\"));\n\t\t} catch (error) {\n\t\t\tstore.rejectAll(error);\n\t\t}\n\t})();\n\n\treturn server;\n}\n\n/**\n * Recreates the promises for a page's embedded server data. The server emits\n * a bootstrap store before the inline resolve scripts, so by the time this\n * runs a value may already be resolved (or still be in flight).\n */\nfunction attachEmbeddedDeferred(server: ServerData): ServerData {\n\tif (!server.deferred?.length) return server;\n\tconst globalStore = (\n\t\tglobalThis as {\n\t\t\t__torporDeferred?: { get(id: string): Promise<unknown> };\n\t\t}\n\t).__torporDeferred;\n\t// The bootstrap is only emitted with a deferred payload; fall back to\n\t// never-resolving promises rather than throwing if it is missing\n\tconst store = new DeferredStore();\n\tconst get = globalStore ? (id: string) => globalStore.get(id) : (id: string) => store.get(id);\n\treturn store.attach(server, get);\n}\n\n/**\n * Reads and removes the server data the initial render embedded in the HTML\n * (a `t-server-data` script tag), or `undefined` when there is none (a later\n * navigation, or a page with no server data).\n */\nfunction takeEmbeddedServerData(): ServerData | undefined {\n\tconst element = document.getElementById(\"t-server-data\");\n\tif (element === null) {\n\t\treturn undefined;\n\t}\n\telement.remove();\n\ttry {\n\t\treturn JSON.parse(element.textContent ?? \"\") as ServerData;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Whether the route has any server-side code to run (a page or layout server\n * load, or a folder hook). Without any, there's no data request to make.\n */\nfunction hasServerData(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\n/**\n * The result of running a route's client load: the json it returned (if any),\n * or the non-ok Response the caller should turn into an error page. Cached as\n * a whole because a Response body can only be read once.\n */\ntype ClientLoadResult = {\n\tdata?: Record<string, any>;\n\tresponse?: Response;\n};\n\n/**\n * Runs a route's client-side load, merging its json data into `data`. Returns\n * a non-ok Response for the caller to turn into an error page.\n *\n * A prefetch caches the in-flight promise, not its resolved value, so a\n * navigation that lands while the load is still running continues the same\n * request instead of running it a second time. The navigation that follows\n * consumes (and clears) the entry; a failed promise is dropped so the\n * navigation retries.\n */\nasync function runClientLoad(\n\tendPoint: PageEndPoint | undefined,\n\tlocation: string,\n\tquery: URLSearchParams,\n\tparams: Record<string, string>,\n\tdata: Record<string, any>,\n\tprefetch: boolean,\n): Promise<Response | undefined> {\n\tif (!endPoint?.load) return;\n\n\tconst clientKey = location + (query.size > 0 ? `?${query}` : \"\");\n\tconst prefetchedData = client.prefetchedData;\n\tlet pending = prefetchedData[clientKey] as Promise<ClientLoadResult> | undefined;\n\n\tif (!pending) {\n\t\t// Only a prefetch warms the cache. A navigation runs its own load\n\t\t// directly, so a result is never left behind for a later visit.\n\t\tif (!prefetch) {\n\t\t\tconst result = await loadClientResponse(endPoint.load, query, params, data);\n\t\t\treturn mergeClientLoad(result, data);\n\t\t}\n\n\t\tconst promise = loadClientResponse(endPoint.load, query, params, data);\n\t\tprefetchedData[clientKey] = promise;\n\t\tpending = promise;\n\t\t// A failed prefetch mustn't poison the navigation that follows it\n\t\tvoid promise.catch(() => {\n\t\t\tif (prefetchedData[clientKey] === promise) {\n\t\t\t\tdelete prefetchedData[clientKey];\n\t\t\t}\n\t\t});\n\t} else if (!prefetch) {\n\t\t// The navigation consumes the warm entry\n\t\tdelete prefetchedData[clientKey];\n\t}\n\n\treturn mergeClientLoad(await pending, data);\n}\n\nasync function loadClientResponse(\n\tload: NonNullable<PageEndPoint[\"load\"]>,\n\tquery: URLSearchParams,\n\tparams: Record<string, string>,\n\tdata: Record<string, any>,\n): Promise<ClientLoadResult> {\n\tconst clientUrl = new URL(document.location.href);\n\tfor (let [name, value] of query) {\n\t\tclientUrl.searchParams.append(name, value);\n\t}\n\tconst response = await load({ url: clientUrl, params, data });\n\tif (!response) return {};\n\tif (!response.ok) return { response };\n\tconst body = await readResponseBody(response);\n\treturn body ? { data: body } : {};\n}\n\nfunction mergeClientLoad(\n\tresult: ClientLoadResult,\n\tdata: Record<string, any>,\n): Response | undefined {\n\tif (result.data) Object.assign(data, result.data);\n\treturn result.response;\n}\n\nfunction clientLocation(path: string): string {\n\treturn document.location.origin + getBasePath() + path;\n}\n\nfunction isRedirect(response: Response): boolean {\n\t// A `redirect: \"manual\"` fetch surfaces a cross-navigation redirect as an\n\t// opaque (\"opaqueredirect\") response in browsers, with status 0\n\treturn (response.status >= 300 && response.status < 400) || response.type === \"opaqueredirect\";\n}\n\n/**\n * The status and message of a failed load response. The body only becomes\n * the message when it's a `message`-carrying json body or plain text -- an\n * html body is a whole page (e.g. a static host's 404), not a message.\n */\nasync function errorOf(response: Response): Promise<{ status: number; message: string }> {\n\tlet message = \"\";\n\tconst type = response.headers.get(\"Content-Type\");\n\tif (type?.includes(\"application/json\")) {\n\t\ttry {\n\t\t\tconst data = await response.json();\n\t\t\tif (typeof data.message === \"string\") {\n\t\t\t\tmessage = data.message;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not actually json\n\t\t}\n\t} else if (type?.includes(\"text/plain\")) {\n\t\tmessage = await response.text();\n\t}\n\treturn { status: response.status, message: message || response.statusText };\n}\n","import { clearLayoutSlot, fillLayoutSlot, hydrate } from \"@torpor/view\";\nimport { type Component, type SlotRender } from \"@torpor/view\";\nimport { mount, unmount } from \"@torpor/view\";\nimport $page from \"../state/$page\";\nimport client from \"../state/client\";\nimport { getBasePath, stripBaseFromUrl } from \"../site/basePath\";\nimport findErrorRoute from \"../site/findErrorRoute\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport formSubmit from \"./formSubmit\";\nimport loadData from \"./loadData\";\n\n/**\n * Navigations run one at a time. Each mutates shared client state\n * (`client.layoutStack`) and the live DOM, so two in flight at once can have\n * one clear a layout's slot region that the other is about to reuse (the\n * `slotRegion.startNode!` in `render` then throws). Requests are chained, so a\n * rapid second click -- or a popstate while a form submit reloads -- waits for\n * the first to finish instead of interleaving.\n */\nlet pendingNavigation: Promise<unknown> = Promise.resolve();\n\n// @ts-ignore\nexport default function navigate(rawUrl: URL, withHydration = false): Promise<boolean> {\n\tconst result = pendingNavigation.then(() => navigateNow(rawUrl, withHydration));\n\t// Keep the chain alive even when a navigation fails, so one bad navigation\n\t// can't wedge every later one\n\tpendingNavigation = result.catch(() => {});\n\treturn result;\n}\n\nasync function navigateNow(rawUrl: URL, withHydration: boolean): Promise<boolean> {\n\t// A failed route-module import (e.g. a stale dev dep hash) or a throwing\n\t// load must not reject the click handler's promise: the caller's full-page\n\t// fallback would never run and the link would appear dead. Restore $page to\n\t// the page that is still on screen and return false so the caller reloads,\n\t// which picks up the new modules.\n\tconst previousUrl = $page.url;\n\tconst previousStatus = $page.status;\n\tconst previousError = $page.error;\n\ttry {\n\t\treturn await renderNavigation(rawUrl, withHydration);\n\t} catch (error) {\n\t\t$page.url = previousUrl;\n\t\t$page.status = previousStatus;\n\t\t$page.error = previousError;\n\t\tconsole.error(error);\n\t\treturn false;\n\t}\n}\n\nasync function renderNavigation(rawUrl: URL, withHydration: boolean): Promise<boolean> {\n\tlet parent = document.getElementById(\"app\");\n\tif (!parent) {\n\t\t// TODO: 500\n\t\tconsole.log(\"500\");\n\t\treturn false;\n\t}\n\n\t// The base path is stripped before matching (routes are base-free), but\n\t// kept in browser state: the caller pushes the original URL. When the\n\t// url doesn't carry the base there will be no matching route anyway\n\tconst url = stripBaseFromUrl(rawUrl, getBasePath()) ?? rawUrl;\n\tconst path = url.pathname;\n\tconst query = url.searchParams;\n\n\t//console.log(`navigating to '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\tlet route = client.router.match(path, query);\n\n\t// Update $page before building the components\n\t$page.url = url;\n\tif (route) {\n\t\tif (path.endsWith(\"/_error\")) {\n\t\t\t// A direct visit to the error page (e.g. a bookmark of the url it\n\t\t\t// used to be redirected to). Make it look a bit classier by\n\t\t\t// stripping the query, which carries the status and message\n\t\t\t$page.status = parseInt(query.get(\"status\") ?? \"404\");\n\t\t\t$page.error = { message: query.get(\"message\") ?? \"\" };\n\t\t\twindow.history.replaceState({}, \"\", rawUrl.toString().split(\"?\")[0]);\n\t\t} else {\n\t\t\t$page.status = 200;\n\t\t\t$page.error = { message: \"\" };\n\t\t}\n\t} else {\n\t\t// There's no page at this url -- render the nearest error page at it,\n\t\t// so the address bar keeps the url the user asked for: a transient\n\t\t// failure can be refreshed, and a typo can be seen and fixed\n\t\tconst errorPath = findErrorRoute(client.router, path);\n\t\tconst errorRoute = errorPath && client.router.match(errorPath, query);\n\t\tif (!errorRoute) {\n\t\t\t// Leave the current page alone; the caller falls back to a full\n\t\t\t// page load, and the server renders the error page (or passes the\n\t\t\t// raw response through, when it has no error page)\n\t\t\treturn false;\n\t\t}\n\t\troute = errorRoute;\n\t\t$page.status = 404;\n\t\t$page.error = { message: \"Not found\" };\n\t}\n\tlet handler = route.handler;\n\tlet params = route.params || {};\n\n\t// There must be a client endpoint with a component. Routes with no client\n\t// component (a pure `+server` route like `/logout`) can't be rendered\n\t// client-side, so return false and let the caller do a full page load\n\tlet clientEndPoint: PageEndPoint | undefined = handler.endPoint\n\t\t? (await handler.endPoint())?.default\n\t\t: undefined;\n\tif (!clientEndPoint?.component) {\n\t\treturn false;\n\t}\n\n\tlet newLayoutStack: LayoutPath[] = [];\n\n\t// Pass the data into $props\n\t// TODO: Don't load if this is the first time -- it should have been passed\n\t// to us, somehow...\n\tconst result = await loadData(handler, params, path, query, newLayoutStack, clientEndPoint);\n\tif (result === undefined) {\n\t\t// A load redirected, or (on a prerendered site with no server) the\n\t\t// ~server request couldn't be made. Leave the current page alone;\n\t\t// the caller (e.g. the client entry) falls back to a full page load,\n\t\t// which follows the redirect\n\t\treturn false;\n\t}\n\tlet data = result.data;\n\tif (result.error) {\n\t\tif (withHydration) {\n\t\t\t// The server rendered this page fine moments ago -- keep its\n\t\t\t// markup rather than hydrating an error page over it\n\t\t\treturn false;\n\t\t}\n\t\t// The load failed -- render the nearest error page at this url, so\n\t\t// the address bar keeps the url the user asked for: a transient\n\t\t// failure (a random db hiccup, say) can be retried with a refresh\n\t\tconst errorPath = findErrorRoute(client.router, path);\n\t\tconst errorRoute = errorPath && client.router.match(errorPath, query);\n\t\tif (!errorRoute) {\n\t\t\t// No error page -- the caller falls back to a full page load,\n\t\t\t// where the server passes the error response through\n\t\t\treturn false;\n\t\t}\n\t\troute = errorRoute;\n\t\thandler = errorRoute.handler;\n\t\tparams = errorRoute.params || {};\n\t\tclientEndPoint = handler.endPoint ? (await handler.endPoint())?.default : undefined;\n\t\tif (!clientEndPoint?.component) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$page.status = result.error.status;\n\t\t$page.error = { message: result.error.message };\n\n\t\t// The error page starts fresh: drop the layouts collected for the\n\t\t// route that failed (the error route's own layouts are loaded into\n\t\t// the empty stack, reusing whatever the current page shares)\n\t\tnewLayoutStack.length = 0;\n\t\tconst errorResult = await loadData(\n\t\t\thandler,\n\t\t\tparams,\n\t\t\tpath,\n\t\t\tquery,\n\t\t\tnewLayoutStack,\n\t\t\tclientEndPoint,\n\t\t);\n\t\tif (errorResult === undefined || errorResult.error) {\n\t\t\t// The error page's own load failed too -- fall back to a full\n\t\t\t// page load\n\t\t\treturn false;\n\t\t}\n\t\tdata = errorResult.data;\n\t}\n\t// We may have form data in a hidden input -- not sure if this is the best\n\t// way to do it\n\tlet formInput = document.getElementById(\"t-form-data\") as HTMLInputElement;\n\tlet form: Record<string, string> | undefined;\n\tif (formInput) {\n\t\tform = JSON.parse(formInput.value);\n\t\t$page.form = form;\n\t\tformInput.remove();\n\t}\n\tlet $props: Record<string, any> = { data };\n\n\t// We may have form data in $page.form, either from the hidden input\n\t// (above), or added via onformsubmit (below)\n\t$props.form = $page.form;\n\n\t// Add some special context for submitting Forms client-side\n\tconst $context = {\n\t\tTorporBuildContext: { onformsubmit: formSubmit },\n\t};\n\n\tclient.layoutStack.push({ path: route.handler.path, data: {}, reuse: false, slotRegion: null });\n\tclient.layoutStack = newLayoutStack;\n\tlet layoutStack = client.layoutStack;\n\n\t// If there are layouts, work our way upwards, pushing each component into\n\t// the default slot of its parent\n\t// TODO: There's probably a nicer way to do this with reducers or something\n\tlet component = clientEndPoint.component as Component;\n\tlet slots: Record<string, SlotRender> | undefined = undefined;\n\tlet reused = false;\n\t// The index of the innermost reused layout. Its slotRegion is the region\n\t// that must be cleared and refilled (it contains the next layout's or the\n\t// page's content). This is usually the last entry of the stack, but not\n\t// when an outer layout is reused while an inner one is new — e.g.\n\t// navigating between sections that share the root layout.\n\tlet reusedIndex = -1;\n\tif (handler.layouts) {\n\t\tlet slotFunctions: SlotRender[] = [];\n\t\t// The last slot function will render the client component\n\t\tslotFunctions[handler.layouts.length] = function clientComponent(parent, anchor) {\n\t\t\tlet i = layoutStack.length - 1;\n\t\t\tlayoutStack[i].slotRegion = fillLayoutSlot(\n\t\t\t\tclientEndPoint.component!,\n\t\t\t\tslotFunctions[i + 1],\n\t\t\t\tparent,\n\t\t\t\tanchor,\n\t\t\t\t$props,\n\t\t\t\t$context,\n\t\t\t);\n\t\t};\n\n\t\t// Each earlier slot function will render a layout\n\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t?.default;\n\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\tif (layoutStack[i].reuse) {\n\t\t\t\t\t// Reuse this layout — clear and refill its slot (done in\n\t\t\t\t\t// the try block below so a failure doesn't leave the slot\n\t\t\t\t\t// half-cleared)\n\t\t\t\t\tcomponent = slotFunctions[i + 1] as Component;\n\t\t\t\t\treusedIndex = i;\n\t\t\t\t\treused = true;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (i === 0) {\n\t\t\t\t\tcomponent = layoutEndPoint.component as Component;\n\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t} else {\n\t\t\t\t\tslotFunctions[i] = function layoutComponent(parent, anchor, _, $context) {\n\t\t\t\t\t\tlayoutStack[i - 1].slotRegion = fillLayoutSlot(\n\t\t\t\t\t\t\tlayoutEndPoint.component!,\n\t\t\t\t\t\t\tslotFunctions[i + 1],\n\t\t\t\t\t\t\tparent,\n\t\t\t\t\t\t\tanchor,\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};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// A definite alias, so that the render closure's type checks hold\n\tlet app: HTMLElement = parent;\n\t// The DOM update, wrapped by the view transitions API when navigating\n\t// (but not on the initial hydration)\n\tconst render = () => {\n\t\ttry {\n\t\t\tif (reused) {\n\t\t\t\t// The layout is being reused — clear the old slot content, then\n\t\t\t\t// call the slot function directly to fill it with the new page.\n\t\t\t\t// We must not go through `mount` here: the slot's container still\n\t\t\t\t// holds the layout's own children (e.g. a header), which `mount`\n\t\t\t\t// refuses to mount into. Both the clear and the fill are inside\n\t\t\t\t// the try so that a failure doesn't leave the slot half-cleared.\n\t\t\t\tconst slotRegion = layoutStack[reusedIndex].slotRegion;\n\t\t\t\tapp = slotRegion.startNode!.parentNode as HTMLElement;\n\t\t\t\tclearLayoutSlot(slotRegion);\n\t\t\t\tcomponent(app, null);\n\t\t\t} else if (withHydration) {\n\t\t\t\thydrate(app, component, $props, slots);\n\t\t\t} else {\n\t\t\t\t// The layout chain changed (or there was no previous layout to\n\t\t\t\t// reuse): tear down the previous UI entirely — disposing its\n\t\t\t\t// region tree and clearing `#app` — so `mount` starts fresh.\n\t\t\t\t// Without this, `mount` throws because `#app` still holds the\n\t\t\t\t// previous render's children, and it would reuse a stale root\n\t\t\t\t// region.\n\t\t\t\tunmount(app);\n\t\t\t\tmount(app, component, $props, slots);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// TODO: Show a proper Error component\n\t\t\tapp.innerHTML = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\t\tconsole.log(error);\n\t\t}\n\n\t\tif (!withHydration) {\n\t\t\t// Scroll back to the top when moving to a different page; keep the\n\t\t\t// scroll position for same-page navigations (query changes,\n\t\t\t// re-renders after form actions)\n\t\t\tconst current = stripBaseFromUrl(new URL(document.location.href), getBasePath())?.pathname;\n\t\t\tif (current !== path) {\n\t\t\t\twindow.scrollTo(0, 0);\n\t\t\t}\n\t\t}\n\t};\n\n\tif (\n\t\t!withHydration &&\n\t\tclient.viewTransitions &&\n\t\ttypeof document.startViewTransition === \"function\"\n\t) {\n\t\tdocument.startViewTransition(render);\n\t} else {\n\t\trender();\n\t}\n\n\t// Reset prefetched data on each navigation\n\tclient.prefetchedData = {};\n\n\treturn true;\n}\n","import navigate from \"./navigate\";\n\n/**\n * Loads and renders the page at the supplied path.\n */\nexport default async function load(path: string): Promise<boolean> {\n\tconst url = new URL(path, document.location.href);\n\treturn await navigate(url);\n}\n"],"mappings":";;;;;;AAEA,MAAM,gBAA+B,OAAO,IAAI,aAAa;AAE7D,MAAM,SAEJ,WAAW,mBAAmB;CAE9B,QAAQ;CACR,aAAa,CAAC;CAEd,gBAAgB,CAAC;CACjB,sBAAsB,CAAC;CACvB,iBAAiB;AAClB;;;;;;ACTD,eAA8B,SAA2B;CAExD,OAAO,MAAM,SAAS,IADN,IAAI,SAAS,SAAS,IAChB,CAAG;AAC1B;;;ACJA,eAA8B,WAAW,GAA+B;CAEvE,EAAE,eAAe;CAIjB,MAAM,OAAO,KAAA;CAGb,MAAM,OAAO,EAAE;CACf,MAAM,SAAS,EAAE;CAIjB,IAAI,SAAS,KAAK,UAAU,SAAS;CACrC,IAA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Y,IAAI,EAAE,CAAC,aAAa,eAC/B,eAAe,WACf,cAAc,IAAI,IAClB,QACA,QACA,QACA,QACD;IACD;GAEF;EACD;CACD;CAGA,IAAI,MAAmB;CAGvB,MAAM,eAAe;EACpB,IAAI;GACH,IAAI,QAAQ;IAOX,MAAM,aAAa,YAAY,YAAY,CAAC;IAC5C,MAAM,WAAW,UAAW;IAC5B,gBAAgB,UAAU;IAC1B,UAAU,KAAK,IAAI;GACpB,OAAO,IAAI,eACV,QAAQ,KAAK,WAAW,QAAQ,KAAK;QAC/B;IAON,QAAQ,GAAG;IACX,MAAM,KAAK,WAAW,QAAQ,KAAK;GACpC;EACD,SAAS,OAAO;GAEf,IAAI,YAAY,6DAA2D,QAAQ;GACnF,QAAQ,IAAI,KAAK;EAClB;EAEA,IAAI,CAAC,eAIY;OAAA,iBAAiB,IAAI,IAAI,SAAS,SAAS,IAAI,GAAG,YAAY,CAAC,CAAC,EAAE,aAClE,MACf,OAAO,SAAS,GAAG,CAAC;EAAA;CAGvB;CAEA,IACC,CAAC,iBACD,OAAO,mBACP,OAAO,SAAS,wBAAwB,YAExC,SAAS,oBAAoB,MAAM;MAEnC,OAAO;CAIR,OAAO,iBAAiB,CAAC;CAEzB,OAAO;AACR;;;;;;ACvTA,eAA8B,KAAK,MAAgC;CAElE,OAAO,MAAM,SAAS,IADN,IAAI,MAAM,SAAS,SAAS,IACtB,CAAG;AAC1B"}
|
|
1
|
+
{"version":3,"file":"load-G-4A435s.mjs","names":[],"sources":["../src/state/client.ts","../src/nav/reload.ts","../src/nav/formSubmit.ts","../src/nav/loadData.ts","../src/nav/navigate.ts","../src/nav/load.ts"],"sourcesContent":["import type ClientState from \"../types/ClientState\";\n\nconst CLIENT_SYMBOL: unique symbol = Symbol.for(\"torp.Client\");\n\nconst client: ClientState =\n\t// @ts-ignore\n\t(globalThis[CLIENT_SYMBOL] ??= {\n\t\t// @ts-ignore This will definitely, 100% get set\n\t\trouter: null,\n\t\tlayoutStack: [],\n\t\t// TODO: Probably expire after 30 seconds or something?\n\t\tprefetchedData: {},\n\t\tprefetchedServerData: {},\n\t\tviewTransitions: false,\n\t});\n\nexport default client;\n","import navigate from \"./navigate\";\n\n/**\n * Reloads data for the currently loaded page and rerenders it.\n */\nexport default async function reload(): Promise<boolean> {\n\tconst url = new URL(document.location.href);\n\treturn await navigate(url);\n}\n","import $page from \"../state/$page\";\nimport load from \"./load\";\nimport reload from \"./reload\";\n\nexport default async function formSubmit(e: SubmitEvent): Promise<void> {\n\t// We'll take it from here\n\te.preventDefault();\n\n\t// Reset $page on submit and link navigation\n\t// TODO: Should we put data in $page.data??\n\t$page.form = undefined;\n\n\t// Perform a POST fetch to the form's action location\n\tconst form = e.target as HTMLFormElement;\n\tconst button = e.submitter as HTMLButtonElement | null;\n\t// HACK: submit buttons have their formAction set to the current page if not\n\t// set, so we can't just check whether it's empty and fallback to form action\n\t//const action = button?.formAction ?? form.action;\n\tlet action = form.action || document.URL;\n\tif (button && button.formAction && button.formAction !== document.URL) {\n\t\taction = button.formAction;\n\t}\n\tconst options = {\n\t\tbody: button ? new FormData(form, button) : new FormData(form),\n\t\tmethod: \"POST\",\n\t\tmode: \"cors\",\n\t\tcredentials: \"same-origin\",\n\t\t// Add a special header which tells the server that we want the raw\n\t\t// error response (if applicable) rather than the reloaded page that you\n\t\t// would get if submitting a page without javascript\n\t\theaders: {\n\t\t\t\"X-Torpor-Form-Submit\": \"\",\n\t\t},\n\t};\n\tconst response = await fetch(\n\t\taction,\n\t\t// @ts-ignore -- don't know what it's complaining about here\n\t\toptions,\n\t);\n\n\tif (\n\t\tresponse.status === 200 &&\n\t\tresponse.headers.has(\"Content-Disposition\") &&\n\t\t/attachment;\\s*filename=\"(.+?)\"/.test(response.headers.get(\"Content-Disposition\")!)\n\t) {\n\t\t// TODO: Is this enough to check to see if we have a file that should download?\n\t\t// Download the file by creating a dummy <a> and clicking it\n\t\tconst downloadFileName =\n\t\t\tresponse.headers.get(\"Content-Disposition\")?.match(/attachment;\\s*filename=\"(.+?)\"/)![1] ??\n\t\t\t\"file\";\n\t\tconst downloadLink = document.createElement(\"a\");\n\t\tdownloadLink.href = window.URL.createObjectURL(await response.blob());\n\t\tdownloadLink.download = downloadFileName;\n\t\tdownloadLink.click();\n\t} else if (response.status === 200 && response.headers.has(\"X-Torpor-Form-Redirect\")) {\n\t\t// TODO: Should do the correct type of redirect e.g. seeOther etc\n\t\tconst redirect = response.headers.get(\"Location\")!;\n\t\tawait load(redirect);\n\t\twindow.location.href = redirect;\n\t} else if (\n\t\t(response.status >= 200 && response.status <= 299) ||\n\t\t(response.status >= 400 && response.status <= 499)\n\t) {\n\t\t// Put the response into `$page.form`, and it will be put into `$props` in reload\n\t\tif (response.headers.get(\"Content-Type\") === \"application/json\") {\n\t\t\t$page.form = await response.json();\n\t\t}\n\t\tawait reload();\n\t} else if (response.status >= 500) {\n\t\t// A server error: like a no-javascript submit, the response is the\n\t\t// error page rendered at this url with the error status. Swap the\n\t\t// document for it -- the url stays, so a transient failure can be\n\t\t// retried with a refresh. Without an error page, reload, which will\n\t\t// show the raw error response instead\n\t\tif (response.headers.get(\"Content-Type\")?.includes(\"text/html\")) {\n\t\t\tconst html = await response.text();\n\t\t\tdocument.open();\n\t\t\tdocument.write(html);\n\t\t\tdocument.close();\n\t\t} else {\n\t\t\twindow.location.reload();\n\t\t}\n\t}\n}\n","import { type DeferredMeta, setAtPath } from \"../deferred.ts\";\nimport { DATA_REUSE_HEADER, DATA_REQUEST_HEADER } from \"../dataRequest.ts\";\nimport { readResponseBody } from \"../response/read.ts\";\nimport { getBasePath } from \"../site/basePath\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport type RouteHandler from \"../types/RouteHandler\";\nimport client from \"../state/client\";\n\n/**\n * The result of loading a route's data. `error` is set when a load function\n * returned an error response (redirects excluded) -- the caller renders the\n * error page instead of the route.\n */\nexport type LoadDataResult = {\n\tdata: Record<string, any>;\n\terror?: {\n\t\tstatus: number;\n\t\tmessage: string;\n\t};\n};\n\n/**\n * Loads a route's data for a client-side navigation.\n *\n * One request (`GET <page url>/~server` with the data header) returns the\n * server data for the page and all of its layouts, with hooks running once\n * against the page url. The client then runs its own load functions (layout\n * by layout, then the page), merging each route's fresh server data in the\n * same order the server render does.\n */\nexport default async function loadData(\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n\tpath: string,\n\tquery: URLSearchParams,\n\tnewLayoutStack: LayoutPath[],\n\tclientEndPoint: PageEndPoint | undefined,\n\tprefetch = false,\n): Promise<LoadDataResult | void> {\n\tlet data = {};\n\n\t// Work out up front which layouts are already rendered (their data is\n\t// reused), so the data request can skip loading them. A prefetch also skips\n\t// their server loads (they're already in the client stack) but must not\n\t// adopt their live slot regions: it may never be followed by a navigation\n\tconst layoutStack = client.layoutStack;\n\tconst layouts = (handler.layouts ?? []).map((layout, index) => {\n\t\tlet layoutPath = layout.path;\n\t\tfor (let key in params) {\n\t\t\tlayoutPath = layoutPath.replace(`[${key}]`, params[key]);\n\t\t}\n\t\tconst previous = layoutStack.at(index);\n\t\tconst rendered = previous?.path === layoutPath;\n\t\tconst reuse = !prefetch && rendered;\n\t\treturn { layout, index, layoutPath, previous, rendered, reuse };\n\t});\n\n\t// A page can opt out of the data request when it has no server load of its\n\t// own and every layout is already rendered (e.g. a tab switch under a\n\t// session hook that doesn't gate access). Its client load still runs.\n\tconst skipServerData =\n\t\tclientEndPoint?.serverData === false &&\n\t\t!handler.serverEndPoint &&\n\t\tlayouts.every((layout) => layout.rendered);\n\n\t// One request for all the (non-reused) server data\n\tconst server = skipServerData\n\t\t? {}\n\t\t: await loadServerData(\n\t\t\t\thandler,\n\t\t\t\tpath,\n\t\t\t\tquery,\n\t\t\t\tlayouts.filter((l) => l.rendered).map((l) => l.layoutPath),\n\t\t\t\tprefetch,\n\t\t\t);\n\tif (server === undefined) {\n\t\t// A load redirected: the client can't follow it through fetch, so the\n\t\t// caller falls back to a full page load\n\t\treturn;\n\t}\n\tif (\"error\" in server) {\n\t\treturn { data, error: server.error };\n\t}\n\n\tfor (const { layout, index, layoutPath, previous, rendered, reuse } of layouts) {\n\t\tconst stackLayout: LayoutPath = {\n\t\t\tpath: layoutPath,\n\t\t\tdata: {},\n\t\t\treuse,\n\t\t\tslotRegion: null,\n\t\t};\n\n\t\tif (rendered && previous) {\n\t\t\t// The layout is already rendered: keep its data. Only a real\n\t\t\t// navigation reuses its slot region; a prefetch must leave it alone\n\t\t\t// (and not run its client load again)\n\t\t\tif (reuse) stackLayout.slotRegion = previous.slotRegion;\n\t\t\tObject.assign(stackLayout.data, previous.data);\n\t\t} else {\n\t\t\t// A new layout: run its client load (its server data already\n\t\t\t// arrived in the single request)\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await layout.endPoint())?.default;\n\t\t\tconst response = await runClientLoad(\n\t\t\t\tlayoutEndPoint,\n\t\t\t\tclientLocation(layoutPath),\n\t\t\t\tquery,\n\t\t\t\tparams,\n\t\t\t\tstackLayout.data,\n\t\t\t\tprefetch,\n\t\t\t);\n\t\t\tif (response) {\n\t\t\t\tif (isRedirect(response)) return;\n\t\t\t\treturn { data, error: await errorOf(response) };\n\t\t\t}\n\t\t\tconst serverData = server.loads?.[index];\n\t\t\tif (serverData) Object.assign(stackLayout.data, serverData);\n\t\t}\n\n\t\tObject.assign(data, stackLayout.data);\n\t\tnewLayoutStack.push(stackLayout);\n\t}\n\n\t// The page's client load, then its server data\n\tconst response = await runClientLoad(\n\t\tclientEndPoint,\n\t\tclientLocation(path),\n\t\tquery,\n\t\tparams,\n\t\tdata,\n\t\tprefetch,\n\t);\n\tif (response) {\n\t\tif (isRedirect(response)) return;\n\t\treturn { data, error: await errorOf(response) };\n\t}\n\tconst pageServerData = server.loads?.[handler.layouts?.length ?? 0];\n\tif (pageServerData) Object.assign(data, pageServerData);\n\n\treturn { data };\n}\n\ntype ServerData = {\n\tloads?: (Record<string, any> | null)[];\n\t/** Promise-valued properties streamed after the critical loads. */\n\tdeferred?: DeferredMeta[];\n};\n\ntype ServerDataFrame = {\n\ttype?: string;\n\tid?: string;\n\tvalue?: unknown;\n\tmessage?: string;\n} & ServerData;\n\n/**\n * A request-local registry of deferred promises. Values arrive after the first\n * frame (client navigation) or in inline scripts (initial hydration), and\n * resolve the promises already placed in the page's `data`.\n */\nclass DeferredStore {\n\t#entries = new Map<\n\t\tstring,\n\t\t{\n\t\t\tpromise: Promise<unknown>;\n\t\t\tresolve: (value: unknown) => void;\n\t\t\treject: (error: unknown) => void;\n\t\t}\n\t>();\n\n\tget(id: string): Promise<unknown> {\n\t\tlet entry = this.#entries.get(id);\n\t\tif (!entry) {\n\t\t\tlet resolve!: (value: unknown) => void;\n\t\t\tlet reject!: (error: unknown) => void;\n\t\t\tconst promise = new Promise<unknown>((res, rej) => {\n\t\t\t\tresolve = res;\n\t\t\t\treject = rej;\n\t\t\t});\n\t\t\t// A prefetch (or a navigation the user leaves) may never read the\n\t\t\t// promise; don't let its rejection surface as unhandled\n\t\t\tpromise.catch(() => {});\n\t\t\tentry = { promise, resolve, reject };\n\t\t\tthis.#entries.set(id, entry);\n\t\t}\n\t\treturn entry.promise;\n\t}\n\n\tresolve(id: string, value: unknown): void {\n\t\tconst entry = this.#entries.get(id);\n\t\tif (!entry) return;\n\t\tthis.#entries.delete(id);\n\t\tentry.resolve(value);\n\t}\n\n\treject(id: string, error: unknown): void {\n\t\tconst entry = this.#entries.get(id);\n\t\tif (!entry) return;\n\t\tthis.#entries.delete(id);\n\t\tentry.reject(error instanceof Error ? error : new Error(String(error)));\n\t}\n\n\trejectAll(error: unknown): void {\n\t\tfor (const id of this.#entries.keys()) {\n\t\t\tthis.reject(id, error);\n\t\t}\n\t}\n\n\t/** Places a promise for each deferred entry into the load that owns it. */\n\tattach(server: ServerData, get: (id: string) => Promise<unknown>): ServerData {\n\t\tfor (const entry of server.deferred ?? []) {\n\t\t\tconst load = server.loads?.[entry.index];\n\t\t\tif (!load) continue;\n\t\t\tsetAtPath(load, entry.path, get(entry.id));\n\t\t}\n\t\treturn server;\n\t}\n}\n\n/**\n * Fetches the page's combined server data for a navigation, reusing a prefetch\n * when there is one.\n *\n * A prefetch warms this request for the navigation that follows, and a\n * navigation consumes it (once). So a hover costs one request, a click that\n * lands while the prefetch is still in flight awaits the same promise instead\n * of issuing a second one, and a prefetched response is never served to more\n * than the one navigation it was loaded for (no stale data on later visits).\n */\nasync function loadServerData(\n\thandler: RouteHandler,\n\tpath: string,\n\tquery: URLSearchParams,\n\treusedLayouts: string[],\n\tprefetch: boolean,\n): Promise<ServerData | { error: { status: number; message: string } } | undefined> {\n\t// The server embeds the first render's data in the HTML (see the render\n\t// path in site/serverHandlers.ts), so the initial hydration can read it\n\t// instead of making a round trip. The element is consumed once, so later\n\t// navigations use the fetch below\n\tconst embedded = takeEmbeddedServerData();\n\tif (embedded !== undefined) {\n\t\treturn attachEmbeddedDeferred(embedded);\n\t}\n\n\tif (!hasServerData(handler)) {\n\t\treturn {};\n\t}\n\n\tconst key = serverDataKey(path, query);\n\n\tif (prefetch) {\n\t\tconst cached = client.prefetchedServerData[key];\n\t\tif (cached) return cached;\n\n\t\tconst pending = requestServerData(path, query, reusedLayouts);\n\t\tclient.prefetchedServerData[key] = pending;\n\t\t// A failed prefetch mustn't poison the navigation that follows it\n\t\tvoid pending.catch(() => {\n\t\t\tif (client.prefetchedServerData[key] === pending) {\n\t\t\t\tdelete client.prefetchedServerData[key];\n\t\t\t}\n\t\t});\n\t\treturn pending;\n\t}\n\n\tconst prefetched = client.prefetchedServerData[key];\n\tif (prefetched) {\n\t\tdelete client.prefetchedServerData[key];\n\t\treturn prefetched;\n\t}\n\n\treturn requestServerData(path, query, reusedLayouts);\n}\n\n/** The `/~server` request cache key: the page path and its query. */\nfunction serverDataKey(path: string, query: URLSearchParams): string {\n\treturn path + (query.size > 0 ? `?${query}` : \"\");\n}\n\n/**\n * The posted data request: `GET <page url>/~server` carrying the data header,\n * which the server answers with the page's and its layouts' server data as one\n * JSON body.\n */\nasync function requestServerData(\n\tpath: string,\n\tquery: URLSearchParams,\n\treusedLayouts: string[],\n): Promise<ServerData | { error: { status: number; message: string } } | undefined> {\n\tconst url = new URL(\n\t\tdocument.location.origin + getBasePath() + path.replace(/\\/$/, \"\") + \"/~server\",\n\t);\n\tfor (let [name, value] of query) {\n\t\turl.searchParams.append(name, value);\n\t}\n\n\tconst headers: Record<string, string> = { [DATA_REQUEST_HEADER]: \"1\" };\n\tif (reusedLayouts.length > 0) {\n\t\theaders[DATA_REUSE_HEADER] = JSON.stringify(reusedLayouts);\n\t}\n\n\tconst response = await fetch(url, {\n\t\tredirect: \"manual\",\n\t\theaders,\n\t});\n\tif (isRedirect(response)) {\n\t\treturn undefined;\n\t}\n\tif (!response.ok) {\n\t\treturn { error: await errorOf(response) };\n\t}\n\t// A site without a server (e.g. a static host) responds with the page's\n\t// html rather than json; there's nothing to merge\n\tconst type = response.headers.get(\"Content-Type\");\n\tif (type?.includes(\"application/x-ndjson\")) {\n\t\treturn await readServerDataStream(response);\n\t}\n\tif (!type?.includes(\"application/json\")) {\n\t\treturn {};\n\t}\n\treturn (await response.json()) as ServerData;\n}\n\n/**\n * Reads a streamed data response: the first frame carries the critical loads\n * and the list of deferred paths, later frames resolve those promises. The\n * function returns as soon as the first frame is read, so a navigation mounts\n * before slow values arrive.\n */\nasync function readServerDataStream(response: Response): Promise<ServerData> {\n\tconst reader = response.body?.getReader();\n\tif (!reader) return {};\n\n\tconst decoder = new TextDecoder();\n\tlet buffer = \"\";\n\tconst readFrame = async (): Promise<ServerDataFrame | undefined> => {\n\t\twhile (true) {\n\t\t\tconst newline = buffer.indexOf(\"\\n\");\n\t\t\tif (newline >= 0) {\n\t\t\t\tconst line = buffer.slice(0, newline).trim();\n\t\t\t\tbuffer = buffer.slice(newline + 1);\n\t\t\t\tif (line) return JSON.parse(line) as ServerDataFrame;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tconst line = buffer.trim();\n\t\t\t\tbuffer = \"\";\n\t\t\t\treturn line ? (JSON.parse(line) as ServerDataFrame) : undefined;\n\t\t\t}\n\t\t\tbuffer += decoder.decode(value, { stream: true });\n\t\t}\n\t};\n\n\tconst first = await readFrame();\n\tif (!first) return {};\n\tif (first.loads === undefined) return {};\n\tconst store = new DeferredStore();\n\tconst server = store.attach(first, (id) => store.get(id));\n\n\t// Keep reading in the background. The view is already mounted; values\n\t// resolve their promises as the frames arrive.\n\tvoid (async () => {\n\t\ttry {\n\t\t\tfor (;;) {\n\t\t\t\tconst frame = await readFrame();\n\t\t\t\tif (!frame) break;\n\t\t\t\tif (frame.type === \"value\" && frame.id !== undefined) {\n\t\t\t\t\tstore.resolve(frame.id, frame.value);\n\t\t\t\t} else if (frame.type === \"error\" && frame.id !== undefined) {\n\t\t\t\t\tstore.reject(frame.id, frame.message ?? \"Deferred data failed\");\n\t\t\t\t}\n\t\t\t}\n\t\t\tstore.rejectAll(new Error(\"The deferred data stream ended before a value arrived\"));\n\t\t} catch (error) {\n\t\t\tstore.rejectAll(error);\n\t\t}\n\t})();\n\n\treturn server;\n}\n\n/**\n * Recreates the promises for a page's embedded server data. The server emits\n * a bootstrap store before the inline resolve scripts, so by the time this\n * runs a value may already be resolved (or still be in flight).\n */\nfunction attachEmbeddedDeferred(server: ServerData): ServerData {\n\tif (!server.deferred?.length) return server;\n\tconst globalStore = (\n\t\tglobalThis as {\n\t\t\t__torporDeferred?: { get(id: string): Promise<unknown> };\n\t\t}\n\t).__torporDeferred;\n\t// The bootstrap is only emitted with a deferred payload; fall back to\n\t// never-resolving promises rather than throwing if it is missing\n\tconst store = new DeferredStore();\n\tconst get = globalStore ? (id: string) => globalStore.get(id) : (id: string) => store.get(id);\n\treturn store.attach(server, get);\n}\n\n/**\n * Reads and removes the server data the initial render embedded in the HTML\n * (a `t-server-data` script tag), or `undefined` when there is none (a later\n * navigation, or a page with no server data).\n */\nfunction takeEmbeddedServerData(): ServerData | undefined {\n\tconst element = document.getElementById(\"t-server-data\");\n\tif (element === null) {\n\t\treturn undefined;\n\t}\n\telement.remove();\n\ttry {\n\t\treturn JSON.parse(element.textContent ?? \"\") as ServerData;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n\n/**\n * Whether the route has any server-side code to run (a page or layout server\n * load, or a folder hook). Without any, there's no data request to make.\n */\nfunction hasServerData(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\n/**\n * The result of running a route's client load: the json it returned (if any),\n * or the non-ok Response the caller should turn into an error page. Cached as\n * a whole because a Response body can only be read once.\n */\ntype ClientLoadResult = {\n\tdata?: Record<string, any>;\n\tresponse?: Response;\n};\n\n/**\n * Runs a route's client-side load, merging its json data into `data`. Returns\n * a non-ok Response for the caller to turn into an error page.\n *\n * A prefetch caches the in-flight promise, not its resolved value, so a\n * navigation that lands while the load is still running continues the same\n * request instead of running it a second time. The navigation that follows\n * consumes (and clears) the entry; a failed promise is dropped so the\n * navigation retries.\n */\nasync function runClientLoad(\n\tendPoint: PageEndPoint | undefined,\n\tlocation: string,\n\tquery: URLSearchParams,\n\tparams: Record<string, string>,\n\tdata: Record<string, any>,\n\tprefetch: boolean,\n): Promise<Response | undefined> {\n\tif (!endPoint?.load) return;\n\n\tconst clientKey = location + (query.size > 0 ? `?${query}` : \"\");\n\tconst prefetchedData = client.prefetchedData;\n\tlet pending = prefetchedData[clientKey] as Promise<ClientLoadResult> | undefined;\n\n\tif (!pending) {\n\t\t// Only a prefetch warms the cache. A navigation runs its own load\n\t\t// directly, so a result is never left behind for a later visit.\n\t\tif (!prefetch) {\n\t\t\tconst result = await loadClientResponse(endPoint.load, query, params, data);\n\t\t\treturn mergeClientLoad(result, data);\n\t\t}\n\n\t\tconst promise = loadClientResponse(endPoint.load, query, params, data);\n\t\tprefetchedData[clientKey] = promise;\n\t\tpending = promise;\n\t\t// A failed prefetch mustn't poison the navigation that follows it\n\t\tvoid promise.catch(() => {\n\t\t\tif (prefetchedData[clientKey] === promise) {\n\t\t\t\tdelete prefetchedData[clientKey];\n\t\t\t}\n\t\t});\n\t} else if (!prefetch) {\n\t\t// The navigation consumes the warm entry\n\t\tdelete prefetchedData[clientKey];\n\t}\n\n\treturn mergeClientLoad(await pending, data);\n}\n\nasync function loadClientResponse(\n\tload: NonNullable<PageEndPoint[\"load\"]>,\n\tquery: URLSearchParams,\n\tparams: Record<string, string>,\n\tdata: Record<string, any>,\n): Promise<ClientLoadResult> {\n\tconst clientUrl = new URL(document.location.href);\n\tfor (let [name, value] of query) {\n\t\tclientUrl.searchParams.append(name, value);\n\t}\n\tconst response = await load({ url: clientUrl, params, data });\n\tif (!response) return {};\n\tif (!response.ok) return { response };\n\tconst body = await readResponseBody(response);\n\treturn body ? { data: body } : {};\n}\n\nfunction mergeClientLoad(\n\tresult: ClientLoadResult,\n\tdata: Record<string, any>,\n): Response | undefined {\n\tif (result.data) Object.assign(data, result.data);\n\treturn result.response;\n}\n\nfunction clientLocation(path: string): string {\n\treturn document.location.origin + getBasePath() + path;\n}\n\nfunction isRedirect(response: Response): boolean {\n\t// A `redirect: \"manual\"` fetch surfaces a cross-navigation redirect as an\n\t// opaque (\"opaqueredirect\") response in browsers, with status 0\n\treturn (response.status >= 300 && response.status < 400) || response.type === \"opaqueredirect\";\n}\n\n/**\n * The status and message of a failed load response. The body only becomes\n * the message when it's a `message`-carrying json body or plain text -- an\n * html body is a whole page (e.g. a static host's 404), not a message.\n */\nasync function errorOf(response: Response): Promise<{ status: number; message: string }> {\n\tlet message = \"\";\n\tconst type = response.headers.get(\"Content-Type\");\n\tif (type?.includes(\"application/json\")) {\n\t\ttry {\n\t\t\tconst data = await response.json();\n\t\t\tif (typeof data.message === \"string\") {\n\t\t\t\tmessage = data.message;\n\t\t\t}\n\t\t} catch {\n\t\t\t// Not actually json\n\t\t}\n\t} else if (type?.includes(\"text/plain\")) {\n\t\tmessage = await response.text();\n\t}\n\treturn { status: response.status, message: message || response.statusText };\n}\n","import { clearLayoutSlot, fillLayoutSlot, hydrate } from \"@torpor/view\";\nimport { type Component, type SlotRender } from \"@torpor/view\";\nimport { mount, unmount } from \"@torpor/view\";\nimport $page from \"../state/$page\";\nimport client from \"../state/client\";\nimport { getBasePath, stripBaseFromUrl } from \"../site/basePath\";\nimport findErrorRoute from \"../site/findErrorRoute\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport formSubmit from \"./formSubmit\";\nimport loadData from \"./loadData\";\n\n/**\n * Navigations run one at a time. Each mutates shared client state\n * (`client.layoutStack`) and the live DOM, so two in flight at once can have\n * one clear a layout's slot region that the other is about to reuse (the\n * `slotRegion.startNode!` in `render` then throws). Requests are chained, so a\n * rapid second click -- or a popstate while a form submit reloads -- waits for\n * the first to finish instead of interleaving.\n */\nlet pendingNavigation: Promise<unknown> = Promise.resolve();\n\n// @ts-ignore\nexport default function navigate(rawUrl: URL, withHydration = false): Promise<boolean> {\n\tconst result = pendingNavigation.then(() => navigateNow(rawUrl, withHydration));\n\t// Keep the chain alive even when a navigation fails, so one bad navigation\n\t// can't wedge every later one\n\tpendingNavigation = result.catch(() => {});\n\treturn result;\n}\n\nasync function navigateNow(rawUrl: URL, withHydration: boolean): Promise<boolean> {\n\t// A failed route-module import (e.g. a stale dev dep hash) or a throwing\n\t// load must not reject the click handler's promise: the caller's full-page\n\t// fallback would never run and the link would appear dead. Restore $page to\n\t// the page that is still on screen and return false so the caller reloads,\n\t// which picks up the new modules.\n\tconst previousUrl = $page.url;\n\tconst previousStatus = $page.status;\n\tconst previousError = $page.error;\n\ttry {\n\t\treturn await renderNavigation(rawUrl, withHydration);\n\t} catch (error) {\n\t\t$page.url = previousUrl;\n\t\t$page.status = previousStatus;\n\t\t$page.error = previousError;\n\t\tconsole.error(error);\n\t\treturn false;\n\t}\n}\n\nasync function renderNavigation(rawUrl: URL, withHydration: boolean): Promise<boolean> {\n\tlet parent = document.getElementById(\"app\");\n\tif (!parent) {\n\t\t// TODO: 500\n\t\tconsole.log(\"500\");\n\t\treturn false;\n\t}\n\n\t// The base path is stripped before matching (routes are base-free), but\n\t// kept in browser state: the caller pushes the original URL. When the\n\t// url doesn't carry the base there will be no matching route anyway\n\tconst url = stripBaseFromUrl(rawUrl, getBasePath()) ?? rawUrl;\n\tconst path = url.pathname;\n\tconst query = url.searchParams;\n\n\t//console.log(`navigating to '${path}'${query.size ? ` with ${query}` : \"\"}`);\n\n\tlet route = client.router.match(path, query);\n\n\t// Update $page before building the components\n\t$page.url = url;\n\tif (route) {\n\t\tif (path.endsWith(\"/_error\")) {\n\t\t\t// A direct visit to the error page (e.g. a bookmark of the url it\n\t\t\t// used to be redirected to). Make it look a bit classier by\n\t\t\t// stripping the query, which carries the status and message\n\t\t\t$page.status = parseInt(query.get(\"status\") ?? \"404\");\n\t\t\t$page.error = { message: query.get(\"message\") ?? \"\" };\n\t\t\twindow.history.replaceState({}, \"\", rawUrl.toString().split(\"?\")[0]);\n\t\t} else {\n\t\t\t$page.status = 200;\n\t\t\t$page.error = { message: \"\" };\n\t\t}\n\t} else {\n\t\t// There's no page at this url -- render the nearest error page at it,\n\t\t// so the address bar keeps the url the user asked for: a transient\n\t\t// failure can be refreshed, and a typo can be seen and fixed\n\t\tconst errorPath = findErrorRoute(client.router, path);\n\t\tconst errorRoute = errorPath && client.router.match(errorPath, query);\n\t\tif (!errorRoute) {\n\t\t\t// Leave the current page alone; the caller falls back to a full\n\t\t\t// page load, and the server renders the error page (or passes the\n\t\t\t// raw response through, when it has no error page)\n\t\t\treturn false;\n\t\t}\n\t\troute = errorRoute;\n\t\t$page.status = 404;\n\t\t$page.error = { message: \"Not found\" };\n\t}\n\tlet handler = route.handler;\n\tlet params = route.params || {};\n\n\t// There must be a client endpoint with a component. Routes with no client\n\t// component (a pure `+server` route like `/logout`) can't be rendered\n\t// client-side, so return false and let the caller do a full page load\n\tlet clientEndPoint: PageEndPoint | undefined = handler.endPoint\n\t\t? (await handler.endPoint())?.default\n\t\t: undefined;\n\tif (!clientEndPoint?.component) {\n\t\treturn false;\n\t}\n\n\tlet newLayoutStack: LayoutPath[] = [];\n\n\t// Pass the data into $props\n\t// TODO: Don't load if this is the first time -- it should have been passed\n\t// to us, somehow...\n\tconst result = await loadData(handler, params, path, query, newLayoutStack, clientEndPoint);\n\tif (result === undefined) {\n\t\t// A load redirected, or (on a prerendered site with no server) the\n\t\t// ~server request couldn't be made. Leave the current page alone;\n\t\t// the caller (e.g. the client entry) falls back to a full page load,\n\t\t// which follows the redirect\n\t\treturn false;\n\t}\n\tlet data = result.data;\n\tif (result.error) {\n\t\tif (withHydration) {\n\t\t\t// The server rendered this page fine moments ago -- keep its\n\t\t\t// markup rather than hydrating an error page over it\n\t\t\treturn false;\n\t\t}\n\t\t// The load failed -- render the nearest error page at this url, so\n\t\t// the address bar keeps the url the user asked for: a transient\n\t\t// failure (a random db hiccup, say) can be retried with a refresh\n\t\tconst errorPath = findErrorRoute(client.router, path);\n\t\tconst errorRoute = errorPath && client.router.match(errorPath, query);\n\t\tif (!errorRoute) {\n\t\t\t// No error page -- the caller falls back to a full page load,\n\t\t\t// where the server passes the error response through\n\t\t\treturn false;\n\t\t}\n\t\troute = errorRoute;\n\t\thandler = errorRoute.handler;\n\t\tparams = errorRoute.params || {};\n\t\tclientEndPoint = handler.endPoint ? (await handler.endPoint())?.default : undefined;\n\t\tif (!clientEndPoint?.component) {\n\t\t\treturn false;\n\t\t}\n\n\t\t$page.status = result.error.status;\n\t\t$page.error = { message: result.error.message };\n\n\t\t// The error page starts fresh: drop the layouts collected for the\n\t\t// route that failed (the error route's own layouts are loaded into\n\t\t// the empty stack, reusing whatever the current page shares)\n\t\tnewLayoutStack.length = 0;\n\t\tconst errorResult = await loadData(\n\t\t\thandler,\n\t\t\tparams,\n\t\t\tpath,\n\t\t\tquery,\n\t\t\tnewLayoutStack,\n\t\t\tclientEndPoint,\n\t\t);\n\t\tif (errorResult === undefined || errorResult.error) {\n\t\t\t// The error page's own load failed too -- fall back to a full\n\t\t\t// page load\n\t\t\treturn false;\n\t\t}\n\t\tdata = errorResult.data;\n\t}\n\t// We may have form data in a hidden input -- not sure if this is the best\n\t// way to do it\n\tlet formInput = document.getElementById(\"t-form-data\") as HTMLInputElement;\n\tlet form: Record<string, string> | undefined;\n\tif (formInput) {\n\t\tform = JSON.parse(formInput.value);\n\t\t$page.form = form;\n\t\tformInput.remove();\n\t}\n\tlet $props: Record<string, any> = { data };\n\n\t// We may have form data in $page.form, either from the hidden input\n\t// (above), or added via onformsubmit (below)\n\t$props.form = $page.form;\n\n\t// Add some special context for submitting Forms client-side\n\tconst $context = {\n\t\tTorporBuildContext: { onformsubmit: formSubmit },\n\t};\n\n\tclient.layoutStack.push({ path: route.handler.path, data: {}, reuse: false, slotRegion: null });\n\tclient.layoutStack = newLayoutStack;\n\tlet layoutStack = client.layoutStack;\n\n\t// If there are layouts, work our way upwards, pushing each component into\n\t// the default slot of its parent\n\t// TODO: There's probably a nicer way to do this with reducers or something\n\tlet component = clientEndPoint.component as Component;\n\tlet slots: Record<string, SlotRender> | undefined = undefined;\n\t// The index of the innermost layout that can actually be reused. It must\n\t// be on the same path (loadData marked it) *and* its slot region must still\n\t// be live: a released region has no `startNode`, and one whose window was\n\t// left pointing at a removed node has a detached `startNode`. A reactive\n\t// update inside the layout during this navigation — e.g. an @if branch\n\t// before the <slot> being cleared because $page.url changed — can cascade\n\t// through `clearRegion` and release the slot region; a post-hydration\n\t// re-render can remove the node it starts at. Reusing either throws on\n\t// `slotRegion.startNode!.parentNode`, so treat such layouts as new instead:\n\t// keep the nearest live ancestor layout, or fully re-render the chain below.\n\tlet reusedIndex = -1;\n\tfor (let i = layoutStack.length - 1; i >= 0; i--) {\n\t\tconst stackLayout = layoutStack[i];\n\t\tif (stackLayout.reuse && stackLayout.slotRegion?.startNode?.parentNode != null) {\n\t\t\treusedIndex = i;\n\t\t\tbreak;\n\t\t}\n\t}\n\tlet reused = reusedIndex !== -1;\n\tif (handler.layouts) {\n\t\tlet slotFunctions: SlotRender[] = [];\n\t\t// The last slot function will render the client component\n\t\tslotFunctions[handler.layouts.length] = function clientComponent(parent, anchor) {\n\t\t\tlet i = layoutStack.length - 1;\n\t\t\tlayoutStack[i].slotRegion = fillLayoutSlot(\n\t\t\t\tclientEndPoint.component!,\n\t\t\t\tslotFunctions[i + 1],\n\t\t\t\tparent,\n\t\t\t\tanchor,\n\t\t\t\t$props,\n\t\t\t\t$context,\n\t\t\t);\n\t\t};\n\n\t\t// Each earlier slot function will render a layout\n\t\tfor (let i = handler.layouts.length - 1; i >= 0; i--) {\n\t\t\tconst layoutEndPoint: PageEndPoint | undefined = (await handler.layouts[i].endPoint())\n\t\t\t\t?.default;\n\t\t\tif (layoutEndPoint?.component) {\n\t\t\t\tif (i === reusedIndex) {\n\t\t\t\t\t// Reuse this layout — clear and refill its slot (done in\n\t\t\t\t\t// the try block below so a failure doesn't leave the slot\n\t\t\t\t\t// half-cleared)\n\t\t\t\t\tcomponent = slotFunctions[i + 1] as Component;\n\t\t\t\t\tbreak;\n\t\t\t\t} else if (i === 0) {\n\t\t\t\t\tcomponent = layoutEndPoint.component as Component;\n\t\t\t\t\tslots = { _: slotFunctions[i + 1] };\n\t\t\t\t} else {\n\t\t\t\t\tslotFunctions[i] = function layoutComponent(parent, anchor, _, $context) {\n\t\t\t\t\t\tlayoutStack[i - 1].slotRegion = fillLayoutSlot(\n\t\t\t\t\t\t\tlayoutEndPoint.component!,\n\t\t\t\t\t\t\tslotFunctions[i + 1],\n\t\t\t\t\t\t\tparent,\n\t\t\t\t\t\t\tanchor,\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};\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\t// A definite alias, so that the render closure's type checks hold\n\tlet app: HTMLElement = parent;\n\t// The DOM update, wrapped by the view transitions API when navigating\n\t// (but not on the initial hydration)\n\tconst render = () => {\n\t\ttry {\n\t\t\tif (reused) {\n\t\t\t\t// The layout is being reused — clear the old slot content, then\n\t\t\t\t// call the slot function directly to fill it with the new page.\n\t\t\t\t// We must not go through `mount` here: the slot's container still\n\t\t\t\t// holds the layout's own children (e.g. a header), which `mount`\n\t\t\t\t// refuses to mount into. Both the clear and the fill are inside\n\t\t\t\t// the try so that a failure doesn't leave the slot half-cleared.\n\t\t\t\tconst slotRegion = layoutStack[reusedIndex].slotRegion;\n\t\t\t\tif (\n\t\t\t\t\tslotRegion === null ||\n\t\t\t\t\tslotRegion.startNode === null ||\n\t\t\t\t\tslotRegion.startNode.parentNode === null\n\t\t\t\t) {\n\t\t\t\t\t// The region died after we planned to reuse it (a layout\n\t\t\t\t\t// update ran while an endpoint was being imported). Don't\n\t\t\t\t\t// paint an error over the current page — reload so the\n\t\t\t\t\t// server renders the requested page.\n\t\t\t\t\tconsole.error(\n\t\t\t\t\t\t\"The layout slot was cleared during navigation; falling back to a full page load\",\n\t\t\t\t\t);\n\t\t\t\t\twindow.location.reload();\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tapp = slotRegion.startNode.parentNode as HTMLElement;\n\t\t\t\tclearLayoutSlot(slotRegion);\n\t\t\t\tcomponent(app, null);\n\t\t\t} else if (withHydration) {\n\t\t\t\thydrate(app, component, $props, slots);\n\t\t\t} else {\n\t\t\t\t// The layout chain changed (or there was no previous layout to\n\t\t\t\t// reuse): tear down the previous UI entirely — disposing its\n\t\t\t\t// region tree and clearing `#app` — so `mount` starts fresh.\n\t\t\t\t// Without this, `mount` throws because `#app` still holds the\n\t\t\t\t// previous render's children, and it would reuse a stale root\n\t\t\t\t// region.\n\t\t\t\tunmount(app);\n\t\t\t\tmount(app, component, $props, slots);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\t// TODO: Show a proper Error component\n\t\t\tapp.innerHTML = '<span style=\"color: red\">Script syntax error</span><p>' + error + \"</p>\";\n\t\t\tconsole.log(error);\n\t\t}\n\n\t\tif (!withHydration) {\n\t\t\t// Scroll back to the top when moving to a different page; keep the\n\t\t\t// scroll position for same-page navigations (query changes,\n\t\t\t// re-renders after form actions)\n\t\t\tconst current = stripBaseFromUrl(new URL(document.location.href), getBasePath())?.pathname;\n\t\t\tif (current !== path) {\n\t\t\t\twindow.scrollTo(0, 0);\n\t\t\t}\n\t\t}\n\t};\n\n\tif (\n\t\t!withHydration &&\n\t\tclient.viewTransitions &&\n\t\ttypeof document.startViewTransition === \"function\"\n\t) {\n\t\tdocument.startViewTransition(render);\n\t} else {\n\t\trender();\n\t}\n\n\t// Reset prefetched data on each navigation\n\tclient.prefetchedData = {};\n\n\treturn true;\n}\n","import navigate from \"./navigate\";\n\n/**\n * Loads and renders the page at the supplied path.\n */\nexport default async function load(path: string): Promise<boolean> {\n\tconst url = new URL(path, document.location.href);\n\treturn await navigate(url);\n}\n"],"mappings":";;;;;;AAEA,MAAM,gBAA+B,OAAO,IAAI,aAAa;AAE7D,MAAM,SAEJ,WAAW,mBAAmB;CAE9B,QAAQ;CACR,aAAa,CAAC;CAEd,gBAAgB,CAAC;CACjB,sBAAsB,CAAC;CACvB,iBAAiB;AAClB;;;;;;ACTD,eAA8B,SAA2B;CAExD,OAAO,MAAM,SAAS,IADN,IAAI,SAAS,SAAS,IAChB,CAAG;AAC1B;;;ACJA,eAA8B,WAAW,GAA+B;CAEvE,EAAE,eAAe;CAIjB,MAAM,OAAO,KAAA;CAGb,MAAM,OAAO,EAAE;CACf,MAAM,SAAS,EAAE;CAIjB,IAAI,SAAS,KAAK,UAAU,SAAS;CACrC,IAAI,UAAU,OAAO,cAAc,OAAO,eAAe,SAAS,KACjE,SAAS,OAAO;CAEjB,MAAM,UAAU;EACf,MAAM,SAAS,IAAI,SAAS,MAAM,MAAM,IAAI,IAAI,SAAS,IAAI;EAC7D,QAAQ;EACR,MAAM;EACN,aAAa;EAIb,SAAS,EACR,wBAAwB,GACzB;CACD;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QACA,QACD;IACD;GAEF;EACD;CACD;CAGA,IAAI,MAAmB;CAGvB,MAAM,eAAe;EACpB,IAAI;GACH,IAAI,QAAQ;IAOX,MAAM,aAAa,YAAY,YAAY,CAAC;IAC5C,IACC,eAAe,QACf,WAAW,cAAc,QACzB,WAAW,UAAU,eAAe,MACnC;KAKD,QAAQ,MACP,iFACD;KACA,OAAO,SAAS,OAAO;KACvB;IACD;IACA,MAAM,WAAW,UAAU;IAC3B,gBAAgB,UAAU;IAC1B,UAAU,KAAK,IAAI;GACpB,OAAO,IAAI,eACV,QAAQ,KAAK,WAAW,QAAQ,KAAK;QAC/B;IAON,QAAQ,GAAG;IACX,MAAM,KAAK,WAAW,QAAQ,KAAK;GACpC;EACD,SAAS,OAAO;GAEf,IAAI,YAAY,6DAA2D,QAAQ;GACnF,QAAQ,IAAI,KAAK;EAClB;EAEA,IAAI,CAAC,eAIY;OAAA,iBAAiB,IAAI,IAAI,SAAS,SAAS,IAAI,GAAG,YAAY,CAAC,CAAC,EAAE,aAClE,MACf,OAAO,SAAS,GAAG,CAAC;EAAA;CAGvB;CAEA,IACC,CAAC,iBACD,OAAO,mBACP,OAAO,SAAS,wBAAwB,YAExC,SAAS,oBAAoB,MAAM;MAEnC,OAAO;CAIR,OAAO,iBAAiB,CAAC;CAEzB,OAAO;AACR;;;;;;AChVA,eAA8B,KAAK,MAAgC;CAElE,OAAO,MAAM,SAAS,IADN,IAAI,MAAM,SAAS,SAAS,IACtB,CAAG;AAC1B"}
|
package/dist/nav.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { n as getBasePath, t as addBaseToPath } from "./basePath-DQnbHc7o.mjs";
|
|
2
|
-
import { i as reload, t as load } from "./load-
|
|
2
|
+
import { i as reload, t as load } from "./load-G-4A435s.mjs";
|
|
3
3
|
import { n as DATA_REQUEST_HEADER, r as DATA_REUSE_HEADER } from "./read-DxMVAh5Y.mjs";
|
|
4
4
|
//#region src/nav/route.ts
|
|
5
5
|
/**
|
package/dist/nodeDev.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as nodeDev } from "./devPlugin-
|
|
1
|
+
export { t as nodeDev } from "./devPlugin-lLzauETn.mjs";
|
package/dist/run.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { n as run, o as runBuild, i as runDev, t as runOpenApi, r as runPreview } from "./runOpenApi-
|
|
1
|
+
export { n as run, o as runBuild, i as runDev, t as runOpenApi, r as runPreview } from "./runOpenApi-C5yMpQU1.mjs";
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
//#region src/server/runHooks.ts
|
|
2
|
+
/**
|
|
3
|
+
* Runs hooks around a request handler — the shared implementation of the
|
|
4
|
+
* enter/exit machine for both middleware (site.middleware, endpoint
|
|
5
|
+
* middleware) and server hooks (_hook.server.ts):
|
|
6
|
+
*
|
|
7
|
+
* - enter hooks run in phase order, then list order, until one returns a
|
|
8
|
+
* Response (short-circuit: the handler and remaining enters are skipped)
|
|
9
|
+
* - the handler runs only if no enter hook responded
|
|
10
|
+
* - exit hooks run in reverse entry order — for the hooks that were entered,
|
|
11
|
+
* even when the handler or an enter hook threw
|
|
12
|
+
*
|
|
13
|
+
* Errors are captured (and set on `options.event.error`) rather than thrown,
|
|
14
|
+
* so `options.onError` can render an error response before the exit hooks run
|
|
15
|
+
* (exits inspect `ev.error` to handle it). Callers rethrow `error` when the
|
|
16
|
+
* result carries no response.
|
|
17
|
+
*
|
|
18
|
+
* With `options.event` (the middleware flavor), `ev.response` is kept in sync
|
|
19
|
+
* with the running response, and an exit hook's returned Response replaces
|
|
20
|
+
* it — per the `MiddlewareFunction` contract. The server-hook flavor passes
|
|
21
|
+
* no event, and its exits return void.
|
|
22
|
+
*/
|
|
23
|
+
async function runHooks(phases, handler, options) {
|
|
24
|
+
const flat = phases.flatMap((phase) => phase.hooks.map((hook) => ({
|
|
25
|
+
hook,
|
|
26
|
+
arg: phase.arg
|
|
27
|
+
})));
|
|
28
|
+
let entered = 0;
|
|
29
|
+
let response = void 0;
|
|
30
|
+
let error = void 0;
|
|
31
|
+
const ev = options?.event;
|
|
32
|
+
try {
|
|
33
|
+
for (; entered < flat.length && !response; entered++) {
|
|
34
|
+
const result = await flat[entered].hook.enter?.(flat[entered].arg);
|
|
35
|
+
if (result) response = result;
|
|
36
|
+
}
|
|
37
|
+
if (!response) response = await handler();
|
|
38
|
+
} catch (e) {
|
|
39
|
+
error = e;
|
|
40
|
+
if (ev) ev.error = e;
|
|
41
|
+
if (options?.onError) response = await options.onError(ev, e);
|
|
42
|
+
} finally {
|
|
43
|
+
if (ev && response) ev.response = response;
|
|
44
|
+
while (entered > 0) {
|
|
45
|
+
entered--;
|
|
46
|
+
const result = await flat[entered].hook.exit?.(flat[entered].arg);
|
|
47
|
+
if (result && ev) {
|
|
48
|
+
response = result;
|
|
49
|
+
ev.response = result;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return {
|
|
54
|
+
response,
|
|
55
|
+
error
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
//#endregion
|
|
59
|
+
export { runHooks as t };
|
|
60
|
+
|
|
61
|
+
//# sourceMappingURL=runHooks-D5p1Rh7i.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"runHooks-D5p1Rh7i.mjs","names":[],"sources":["../src/server/runHooks.ts"],"sourcesContent":["import type ServerEvent from \"./ServerEvent\";\n\n/**\n * One entry in a hook list: middleware (`MiddlewareFunction`) and server hooks\n * (`ServerHook`) are structurally identical — an optional enter and exit.\n */\ninterface Hook {\n\tenter?: (arg: any) => any;\n\texit?: (arg: any) => any;\n}\n\n/**\n * A phase of hooks around a request: a hook list plus the argument its\n * enter/exit functions take (a ServerEvent for middleware, a ServerLoadEvent\n * for server hooks). Multiple phases run their enters in order; exits run in\n * the exact reverse of entry order, across phases too.\n */\nexport interface HookPhase {\n\thooks: Hook[];\n\targ: any;\n}\n\n/**\n * Runs hooks around a request handler — the shared implementation of the\n * enter/exit machine for both middleware (site.middleware, endpoint\n * middleware) and server hooks (_hook.server.ts):\n *\n * - enter hooks run in phase order, then list order, until one returns a\n * Response (short-circuit: the handler and remaining enters are skipped)\n * - the handler runs only if no enter hook responded\n * - exit hooks run in reverse entry order — for the hooks that were entered,\n * even when the handler or an enter hook threw\n *\n * Errors are captured (and set on `options.event.error`) rather than thrown,\n * so `options.onError` can render an error response before the exit hooks run\n * (exits inspect `ev.error` to handle it). Callers rethrow `error` when the\n * result carries no response.\n *\n * With `options.event` (the middleware flavor), `ev.response` is kept in sync\n * with the running response, and an exit hook's returned Response replaces\n * it — per the `MiddlewareFunction` contract. The server-hook flavor passes\n * no event, and its exits return void.\n */\nexport default async function runHooks(\n\tphases: HookPhase[],\n\thandler: () => Promise<Response | undefined>,\n\toptions?: {\n\t\tevent?: ServerEvent;\n\t\tonError?: (ev: ServerEvent, error: unknown) => Promise<Response | undefined>;\n\t},\n): Promise<{ response: Response | undefined; error: unknown }> {\n\tconst flat = phases.flatMap((phase) => phase.hooks.map((hook) => ({ hook, arg: phase.arg })));\n\tlet entered = 0;\n\tlet response: Response | undefined = undefined;\n\tlet error: unknown = undefined;\n\tconst ev = options?.event;\n\ttry {\n\t\tfor (; entered < flat.length && !response; entered++) {\n\t\t\t// A hook returns a Response to short-circuit the request\n\t\t\tconst result = await flat[entered].hook.enter?.(flat[entered].arg);\n\t\t\tif (result) {\n\t\t\t\tresponse = result;\n\t\t\t}\n\t\t}\n\t\tif (!response) {\n\t\t\tresponse = await handler();\n\t\t}\n\t} catch (e) {\n\t\t// Exits can handle the error by returning a Response (via\n\t\t// `onError`/the caller); if none does, the caller rethrows it\n\t\terror = e;\n\t\tif (ev) {\n\t\t\tev.error = e;\n\t\t}\n\t\tif (options?.onError) {\n\t\t\tresponse = await options.onError(ev!, e);\n\t\t}\n\t} finally {\n\t\tif (ev && response) {\n\t\t\tev.response = response;\n\t\t}\n\t\t// Run exit hooks in reverse order for the hooks that were entered.\n\t\t// An exit hook can return a Response to replace the response, or to\n\t\t// handle ev.error\n\t\twhile (entered > 0) {\n\t\t\tentered--;\n\t\t\tconst result = await flat[entered].hook.exit?.(flat[entered].arg);\n\t\t\tif (result && ev) {\n\t\t\t\tresponse = result;\n\t\t\t\tev.response = result;\n\t\t\t}\n\t\t}\n\t}\n\treturn { response, error };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AA2CA,eAA8B,SAC7B,QACA,SACA,SAI8D;CAC9D,MAAM,OAAO,OAAO,SAAS,UAAU,MAAM,MAAM,KAAK,UAAU;EAAE;EAAM,KAAK,MAAM;CAAI,EAAE,CAAC;CAC5F,IAAI,UAAU;CACd,IAAI,WAAiC,KAAA;CACrC,IAAI,QAAiB,KAAA;CACrB,MAAM,KAAK,SAAS;CACpB,IAAI;EACH,OAAO,UAAU,KAAK,UAAU,CAAC,UAAU,WAAW;GAErD,MAAM,SAAS,MAAM,KAAK,QAAQ,CAAC,KAAK,QAAQ,KAAK,QAAQ,CAAC,GAAG;GACjE,IAAI,QACH,WAAW;EAEb;EACA,IAAI,CAAC,UACJ,WAAW,MAAM,QAAQ;CAE3B,SAAS,GAAG;EAGX,QAAQ;EACR,IAAI,IACH,GAAG,QAAQ;EAEZ,IAAI,SAAS,SACZ,WAAW,MAAM,QAAQ,QAAQ,IAAK,CAAC;CAEzC,UAAU;EACT,IAAI,MAAM,UACT,GAAG,WAAW;EAKf,OAAO,UAAU,GAAG;GACnB;GACA,MAAM,SAAS,MAAM,KAAK,QAAQ,CAAC,KAAK,OAAO,KAAK,QAAQ,CAAC,GAAG;GAChE,IAAI,UAAU,IAAI;IACjB,WAAW;IACX,GAAG,WAAW;GACf;EACD;CACD;CACA,OAAO;EAAE;EAAU;CAAM;AAC1B"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
import { i as normalizeOrigin, r as normalizeBasePath } from "./basePath-DQnbHc7o.mjs";
|
|
2
2
|
import { i as buildOpenApiDocument, t as OPEN_API_STATE_KEY } from "./plugin-D8Www11B.mjs";
|
|
3
3
|
import { r as serverError } from "./response-C5EZsszY.mjs";
|
|
4
|
-
import { i as siteEntryPaths, n as prepareTemplate, r as detectSourceMode, t as devPlugin } from "./devPlugin-
|
|
4
|
+
import { i as siteEntryPaths, n as prepareTemplate, r as detectSourceMode, t as devPlugin } from "./devPlugin-lLzauETn.mjs";
|
|
5
5
|
import { t as ServerEvent } from "./ServerEvent-BY4f3RVF.mjs";
|
|
6
6
|
import { n as sitemapXml } from "./sitemap-4imxJVrG.mjs";
|
|
7
|
-
import { t as Server } from "./Server-
|
|
7
|
+
import { t as Server } from "./Server-dcRbdPXf.mjs";
|
|
8
8
|
import { createRequire, isBuiltin } from "node:module";
|
|
9
9
|
import fs, { existsSync, promises, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
10
10
|
import fpath from "node:path";
|
|
@@ -1694,4 +1694,4 @@ async function runOpenApi(site, vite, outFile = "openapi.json") {
|
|
|
1694
1694
|
//#endregion
|
|
1695
1695
|
export { loadSite as a, runDev as i, run as n, runBuild as o, runPreview as r, runOpenApi as t };
|
|
1696
1696
|
|
|
1697
|
-
//# sourceMappingURL=runOpenApi-
|
|
1697
|
+
//# sourceMappingURL=runOpenApi-C5yMpQU1.mjs.map
|