@torpor/build 1.7.1 → 1.8.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Jsonify-hFz5OjtZ.d.mts +11 -0
- package/dist/Jsonify-hFz5OjtZ.d.mts.map +1 -0
- package/dist/{Site-CStKUF4L.d.mts → Site-ChHKbLUv.d.mts} +2 -2
- package/dist/{Site-CStKUF4L.d.mts.map → Site-ChHKbLUv.d.mts.map} +1 -1
- package/dist/bin/index.js +1 -1
- package/dist/clientEntry.mjs +8 -2
- package/dist/clientEntry.mjs.map +1 -1
- package/dist/dev.mjs +1 -1
- package/dist/{devPlugin-V689J6l6.mjs → devPlugin-CL0eu77n.mjs} +2 -2
- package/dist/{devPlugin-V689J6l6.mjs.map → devPlugin-CL0eu77n.mjs.map} +1 -1
- package/dist/discovery.d.mts +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/internal-BItAKrmV.mjs +79 -0
- package/dist/internal-BItAKrmV.mjs.map +1 -0
- package/dist/{load-GG7Shn4q.mjs → load-Clec6rli.mjs} +171 -27
- package/dist/load-Clec6rli.mjs.map +1 -0
- package/dist/nav.d.mts +24 -0
- package/dist/nav.d.mts.map +1 -1
- package/dist/nav.mjs +3 -2
- package/dist/nav.mjs.map +1 -1
- package/dist/nodeDev.d.mts +1 -1
- package/dist/nodeDev.mjs +1 -1
- package/dist/openapi.d.mts +1 -1
- package/dist/{dataRequest-JosDB_ig.mjs → read-DxMVAh5Y.mjs} +24 -2
- package/dist/read-DxMVAh5Y.mjs.map +1 -0
- package/dist/{response-sth6FQsj.mjs → response-C5EZsszY.mjs} +2 -2
- package/dist/{response-sth6FQsj.mjs.map → response-C5EZsszY.mjs.map} +1 -1
- package/dist/response.d.mts +4 -2
- package/dist/response.d.mts.map +1 -1
- package/dist/response.mjs +2 -2
- package/dist/run.d.mts +1 -1
- package/dist/run.mjs +1 -1
- package/dist/{runOpenApi-Cz7_PXSt.mjs → runOpenApi-BSoP2X_D.mjs} +30 -8
- package/dist/runOpenApi-BSoP2X_D.mjs.map +1 -0
- package/dist/{serverEntry-BcB9YQLk.mjs → serverEntry-DdNjmynd.mjs} +2 -2
- package/dist/{serverEntry-BcB9YQLk.mjs.map → serverEntry-DdNjmynd.mjs.map} +1 -1
- package/dist/serverEntry-fj0XfTs4.d.mts.map +1 -1
- package/dist/serverEntry.mjs +1 -1
- package/dist/{serverHandlers-vGPmArCU.mjs → serverHandlers-BpKfaFsD.mjs} +161 -15
- package/dist/serverHandlers-BpKfaFsD.mjs.map +1 -0
- package/dist/{sitemap-BjqN4d4W.d.mts → sitemap-DpwNjTjs.d.mts} +13 -1
- package/dist/sitemap-DpwNjTjs.d.mts.map +1 -0
- package/dist/test.d.mts +1 -1
- package/dist/test.mjs +1 -1
- package/dist/{unprocessable-CoMN2zFa.mjs → unprocessable-DwAG44Rh.mjs} +15 -4
- package/dist/unprocessable-DwAG44Rh.mjs.map +1 -0
- package/package.json +1 -1
- package/dist/Jsonify-Dg6gChd3.d.mts +0 -10
- package/dist/Jsonify-Dg6gChd3.d.mts.map +0 -1
- package/dist/dataRequest-JosDB_ig.mjs.map +0 -1
- package/dist/load-GG7Shn4q.mjs.map +0 -1
- package/dist/runOpenApi-Cz7_PXSt.mjs.map +0 -1
- package/dist/serverHandlers-vGPmArCU.mjs.map +0 -1
- package/dist/sitemap-BjqN4d4W.d.mts.map +0 -1
- package/dist/unprocessable-CoMN2zFa.mjs.map +0 -1
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
//#region src/types/Jsonify.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* The JSON-serialized form of a type: what a value looks like after a
|
|
4
|
+
* JSON.stringify / JSON.parse round trip. Dates become strings, functions and
|
|
5
|
+
* undefined properties are dropped. Promise values stay promises: they are
|
|
6
|
+
* streamed after the critical data instead of being serialized.
|
|
7
|
+
*/
|
|
8
|
+
type Jsonify<T> = T extends Promise<infer Deferred> ? Promise<Jsonify<Deferred>> : T extends string | number | boolean | null ? T : T extends undefined | ((...args: any[]) => any) ? never : T extends Date ? string : T extends Array<infer Item> ? Array<Jsonify<Item>> : T extends object ? { [Key in keyof T as T[Key] extends undefined | ((...args: any[]) => any) ? never : Key]: Jsonify<T[Key]>; } : T;
|
|
9
|
+
//#endregion
|
|
10
|
+
export { Jsonify as t };
|
|
11
|
+
//# sourceMappingURL=Jsonify-hFz5OjtZ.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"Jsonify-hFz5OjtZ.d.mts","names":[],"sources":["../src/types/Jsonify.ts"],"mappings":";;;;;;;KAMY,QAAQ,KACnB,UAAU,cAAc,YACrB,QAAQ,QAAQ,aAChB,6CACC,IACA,2BAA2B,+BAE1B,UAAU,gBAET,UAAU,YAAY,QACrB,MAAM,QAAQ,SACd,sBAGE,aAAa,KAAK,EAAE,8BAA8B,+BAE/C,MACD,QAAQ,EAAE,WAEb"}
|
|
@@ -3,7 +3,7 @@ import { t as Server } from "./Server-qn5Ws_d0.mjs";
|
|
|
3
3
|
import { a as RouteParamsOf } from "./ParseRouteParams-DBmqlmLh.mjs";
|
|
4
4
|
import { n as QueryRecord, r as ServerLoadEvent, t as FormDataRecord } from "./ServerLoadEvent-DzbxxkF8.mjs";
|
|
5
5
|
import { t as ServerHook } from "./ServerHook-BTSGfLiJ.mjs";
|
|
6
|
-
import { a as PageLoadReturn, i as PageEndPoint, t as SitemapOptions } from "./sitemap-
|
|
6
|
+
import { a as PageLoadReturn, i as PageEndPoint, t as SitemapOptions } from "./sitemap-DpwNjTjs.mjs";
|
|
7
7
|
import { t as StandardSchemaV1 } from "./StandardSchema-D28L8_zZ.mjs";
|
|
8
8
|
import { Plugin, UserConfig } from "vite";
|
|
9
9
|
//#region src/types/Adapter.d.ts
|
|
@@ -539,4 +539,4 @@ declare class Site {
|
|
|
539
539
|
}
|
|
540
540
|
//#endregion
|
|
541
541
|
export { ServerEndPoint as a, ActionBody as c, PageServerActionSchemas as d, PageServerEndPoint as f, Adapter as g, SitePlugin as h, SchemaQuery as i, LoadParams as l, PageServerAction as m, ParamsOf as n, ServerEndPointSchemas as o, PageServerLoad as p, SchemaBody as r, ServerRequest as s, Site as t, LoadQuery as u };
|
|
542
|
-
//# sourceMappingURL=Site-
|
|
542
|
+
//# sourceMappingURL=Site-ChHKbLUv.d.mts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Site-
|
|
1
|
+
{"version":3,"file":"Site-ChHKbLUv.d.mts","names":[],"sources":["../src/types/Adapter.ts","../src/types/SitePlugin.ts","../src/types/PageServerAction.ts","../src/types/PageServerLoad.ts","../src/types/PageServerEndPoint.ts","../src/types/ServerRequest.ts","../src/types/ServerEndPoint.ts","../src/types/RouteType.ts","../src/types/Route.ts","../src/site/Site.ts"],"mappings":";;;;;;;;;UAIyB;EACxB,YAAY,MAAM,SAAS;EAC3B,aAAa,MAAM,SAAS;;;;;;;EAO5B,OAAO,MAAM,SAAS,SAAS;;;;;EAK/B,QAAQ,QAAQ,QAAQ,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;KCG1C,cAAc,MAAM,gBAAgB;;;KCjBpC,iBACJ,8CACA,WAAW,gBACX,SAAS,cAAc,WAEvB,OAAO,gBAAgB,gBAAgB,UAAU,aAAa,YAC1D,8BAA8B,QAAQ;;;KCLtC,eACJ,8CACA,OAAO,qBACP,YAAY,aACZ,SAAS,cAAc,WAEvB,OAAO,gBAAgB,gBAAgB,gBAAgB,WAAW,YAC9D,eAAe,QAAQ,QAAQ,eAAe;;;;;;;;;;;;;;;;;;;;;KCavC;EACX,SAAS;EACT,OAAO;GACW,iBAAA;;;;;;KAOP,WAAW,gBAAgB,yBAAyB,wBAC/D,qBACgB,oBACd,QAAQ,cAAc,mBACrB,iBAAiB,YAAY,QAAQ,SACrC,iBACD;;;;KAKS,UAAU,gBAAgB,2BAA2B;EAChE,MAAM;IAEJ,iBAAiB,YAAY,mBAC7B;;;;KAKS,WACX,gBAAgB,yBA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AKnB,MAAM,cACL,OACA,WAAW,iBACX,gBACA,aACA,SAAS,SAAS;;;;EAKnB,UAAU,cACT,OACA,WAAW,qBACX,gBACA,aACA,SAAS,SAAS;;;;EAKnB,OAAO,cACN,gBAEA,gBACA,YAAY,kBACZ,SAAS,SAAS;;;;;;;EAQnB,aAAa;;;;cC7KD;cACA;cACA;cACA;cACA;cACA;cACA;cACA;KAED,mBACF,oBACA,2BACA,sBACA,sBACA,6BACA,oBACA,2BACA;;;;;;KCRE,iBAAiB,qBAAqB,iBAAiB,aAAa;;;;UAKvD;EACxB;;;;;EAKA;;;;;;EAMA,WAAW;EACX,MAAM;EACN;;;;;;;;cCOoB;;EACpB;;;;;;;;;;EAUA;EACA,QAAQ;;;;;;EAMR;IAAgB;IAAgB;;;;;;;;EAOhC,SAAS;;;;EAIT,aAAa;;;;;;;;;;EAUb,SAAS;;;;;;EAMT;;;;;;;EAOA,aAAa;;;;;EAKb;;;;;;;;;;;;;;;;EAgBA,aAAa,IAAI;;;;;;;EAOjB;;;;;;;EAOA;;;;;;;;;EASA,sBAAsB;;;;;;EAMtB;;;;;;;;;;;;EAYA,YAAY;;;;;;;;;;;EAWZ,UAAU;;;;;;;;;EASV,MAAM,0BAA0B;;;;;EAKhC,iBAAiB,eAAe;EAEhC;;MAKI;;;;;;;;;EAYJ,eAAqB,gBAAgB,qBAAqB;;;;;;;;;;;;EA0C1D,gBAAgB,OAAO;;;;;;;;EAwBvB,aACC,cACA,cACA,kHASA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+HD,SACC,cACA;IACC;IACA,sBAAsB;IACtB,kBAAkB;IAClB;IACA,wBAAwB;IACxB,sBAAsB;IACtB;KAED"}
|
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-BSoP2X_D.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-Clec6rli.mjs";
|
|
5
5
|
import manifest from "@torpor/build/manifest";
|
|
6
6
|
//#region src/site/clientEntry.ts
|
|
7
7
|
setBasePath(manifest.base);
|
|
@@ -16,7 +16,13 @@ window.addEventListener("click", async (e) => {
|
|
|
16
16
|
e.preventDefault();
|
|
17
17
|
const href = link.href;
|
|
18
18
|
const url = new URL(href);
|
|
19
|
-
|
|
19
|
+
let navigated = false;
|
|
20
|
+
try {
|
|
21
|
+
navigated = await navigate(url);
|
|
22
|
+
} catch (error) {
|
|
23
|
+
console.error(error);
|
|
24
|
+
}
|
|
25
|
+
if (navigated) {
|
|
20
26
|
window.history.replaceState({ scroll: window.scrollY }, "", document.location.href);
|
|
21
27
|
window.history.pushState({ scroll: 0 }, "", url);
|
|
22
28
|
} else window.location.href = href;
|
package/dist/clientEntry.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"clientEntry.mjs","names":[],"sources":["../src/site/clientEntry.ts"],"sourcesContent":["import manifest from \"@torpor/build/manifest\";\nimport loadData from \"../nav/loadData.ts\";\nimport navigate from \"../nav/navigate.ts\";\nimport $page from \"../state/$page.ts\";\nimport client from \"../state/client\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport Router from \"./Router.ts\";\nimport { setBasePath } from \"./basePath.ts\";\n\nsetBasePath(manifest.base);\n\n// Build the router from the Site object created by the user\nconst router = new Router();\nrouter.addPages(manifest.routes);\n\n// Put it in client state so that it can be accessed from navigate. We can't\n// just import it to navigate because that gets built by tsdown, without Vite\n// and the manifest\nclient.router = router;\nclient.viewTransitions = manifest.viewTransitions ?? false;\n\n// Intercept clicks on links\nwindow.addEventListener(\"click\", async (e) => {\n\tconst link = getLink(e.target);\n\tif (link) {\n\t\tif (ignoreAnchorMouseEvent(link, e)) {\n\t\t\treturn;\n\t\t}\n\n\t\te.preventDefault();\n\n\t\tconst href = link.href;\n\t\tconst url = new URL(href);\n\n\t\
|
|
1
|
+
{"version":3,"file":"clientEntry.mjs","names":[],"sources":["../src/site/clientEntry.ts"],"sourcesContent":["import manifest from \"@torpor/build/manifest\";\nimport loadData from \"../nav/loadData.ts\";\nimport navigate from \"../nav/navigate.ts\";\nimport $page from \"../state/$page.ts\";\nimport client from \"../state/client\";\nimport type LayoutPath from \"../types/LayoutPath\";\nimport type PageEndPoint from \"../types/PageEndPoint\";\nimport Router from \"./Router.ts\";\nimport { setBasePath } from \"./basePath.ts\";\n\nsetBasePath(manifest.base);\n\n// Build the router from the Site object created by the user\nconst router = new Router();\nrouter.addPages(manifest.routes);\n\n// Put it in client state so that it can be accessed from navigate. We can't\n// just import it to navigate because that gets built by tsdown, without Vite\n// and the manifest\nclient.router = router;\nclient.viewTransitions = manifest.viewTransitions ?? false;\n\n// Intercept clicks on links\nwindow.addEventListener(\"click\", async (e) => {\n\tconst link = getLink(e.target);\n\tif (link) {\n\t\tif (ignoreAnchorMouseEvent(link, e)) {\n\t\t\treturn;\n\t\t}\n\n\t\te.preventDefault();\n\n\t\tconst href = link.href;\n\t\tconst url = new URL(href);\n\n\t\tlet navigated = false;\n\t\ttry {\n\t\t\tnavigated = await navigate(url);\n\t\t} catch (error) {\n\t\t\t// `navigate` already catches its own failures, but never let an\n\t\t\t// unexpected throw swallow the full-page fallback\n\t\t\tconsole.error(error);\n\t\t}\n\t\tif (navigated) {\n\t\t\t// Save the scroll position of the outgoing page on the current\n\t\t\t// history entry, so that going (or coming) back can restore it\n\t\t\twindow.history.replaceState({ scroll: window.scrollY }, \"\", document.location.href);\n\t\t\twindow.history.pushState({ scroll: 0 }, \"\", url);\n\t\t} else {\n\t\t\twindow.location.href = href;\n\t\t}\n\t}\n});\n\n// Intercept mouseover/focus/touchstart on links for prefetching\n// TODO: settings e.g. <a href=\"\" data-tb-prefetch=\"eager\"/\"visible\"/\"hover\"/\"touch\">\nwindow.addEventListener(\"mouseover\", maybePrefetch);\nwindow.addEventListener(\"touchstart\", maybePrefetch);\n// Keyboard focus, and the press-down that precedes a click (a fast click can\n// land before any hover), warm the target too, so the navigation can await the\n// same in-flight request rather than starting its own\nwindow.addEventListener(\"focusin\", maybePrefetch);\nwindow.addEventListener(\"pointerdown\", maybePrefetch);\n\nasync function maybePrefetch(e: Event) {\n\tconst link = getLink(e.target);\n\tif (link) {\n\t\tif (ignoreAnchorMouseEvent(link, e)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst href = link.href;\n\t\tconst url = new URL(href);\n\n\t\tconst path = url.pathname;\n\t\t// Nothing to warm for the page we're already on\n\t\tif (path === document.location.pathname) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst query = url.searchParams;\n\t\tconst route = router.match(path, query);\n\t\tif (route) {\n\t\t\tconst handler = route.handler;\n\t\t\tconst params = route.params || {};\n\n\t\t\ttry {\n\t\t\t\t// A route with no client endpoint (a pure `+server` route) has\n\t\t\t\t// nothing to prefetch\n\t\t\t\tconst clientEndPoint: PageEndPoint | undefined = handler.endPoint\n\t\t\t\t\t? (await handler.endPoint())?.default\n\t\t\t\t\t: undefined;\n\t\t\t\tif (!clientEndPoint?.component) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\t// Just dummy this up\n\t\t\t\tlet newStack: LayoutPath[] = [];\n\n\t\t\t\tawait loadData(handler, params, path, query, newStack, clientEndPoint, true);\n\t\t\t} catch {\n\t\t\t\t// A prefetch is best-effort: the real navigation retries\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunction getLink(target: EventTarget | null): HTMLAnchorElement | undefined {\n\t// The target may be a child element of the link (e.g. an icon inside it),\n\t// so walk up to the nearest actual link. Fragment-only links (href=\"#...\")\n\t// are left to the browser's native jump-to-anchor behavior\n\tif (!(target instanceof Element)) return;\n\tconst link = target.closest(\"a[href]\");\n\tif (link?.getAttribute(\"href\")?.startsWith(\"#\")) return;\n\treturn (link as HTMLAnchorElement) ?? undefined;\n}\n\nfunction ignoreAnchorMouseEvent(link: HTMLAnchorElement, e: Event) {\n\t// Ignore the event if it was already handled (e.g. a user handler calling\n\t// preventDefault), a modifier key is pressed, the target is not \"_self\"\n\t// (e.g. \"_blank\"), rel=\"external\", it's a download link, or it's in a\n\t// contenteditable region\n\tconst mouse = e as MouseEvent;\n\treturn (\n\t\te.defaultPrevented ||\n\t\tmouse.altKey ||\n\t\tmouse.ctrlKey ||\n\t\tmouse.metaKey ||\n\t\tmouse.shiftKey ||\n\t\t(link.target && link.target !== \"_self\") ||\n\t\tlink.rel === \"external\" ||\n\t\tlink.hasAttribute(\"download\") ||\n\t\tlink.isContentEditable\n\t);\n}\n\n// Listen for changes to the URL that occur when the user navigates using the\n// back or forward buttons\nwindow.addEventListener(\"popstate\", async () => {\n\tconst navigated = await navigateToLocation(document.location);\n\tif (!navigated) {\n\t\twindow.location.reload();\n\t\treturn;\n\t}\n\t// Restore the scroll position that was saved on the history entry\n\trequestAnimationFrame(() => {\n\t\tconst state = window.history.state as { scroll?: number } | null;\n\t\twindow.scrollTo(0, state?.scroll ?? 0);\n\t});\n});\n\n// Do the initial navigation and hydration\nawait navigateToLocation(document.location, true);\n\nasync function navigateToLocation(location: Location, firstTime = false) {\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\treturn await navigate(new URL(location.toString()), firstTime);\n}\n"],"mappings":";;;;;;AAUA,YAAY,SAAS,IAAI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EAAA,EAAI,UAC5B,KAAA;IACH,IAAI,CAAC,gBAAgB,WACpB;IAMD,MAAM,SAAS,SAAS,QAAQ,MAAM,OAAO,CAAO,GAAG,gBAAgB,IAAI;GAC5E,QAAQ,CAER;EACD;CACD;AACD;AAEA,SAAS,QAAQ,QAA2D;CAI3E,IAAI,EAAE,kBAAkB,UAAU;CAClC,MAAM,OAAO,OAAO,QAAQ,SAAS;CACrC,IAAI,MAAM,aAAa,MAAM,CAAC,EAAE,WAAW,GAAG,GAAG;CACjD,OAAQ,QAA8B,KAAA;AACvC;AAEA,SAAS,uBAAuB,MAAyB,GAAU;CAKlE,MAAM,QAAQ;CACd,OACC,EAAE,oBACF,MAAM,UACN,MAAM,WACN,MAAM,WACN,MAAM,YACL,KAAK,UAAU,KAAK,WAAW,WAChC,KAAK,QAAQ,cACb,KAAK,aAAa,UAAU,KAC5B,KAAK;AAEP;AAIA,OAAO,iBAAiB,YAAY,YAAY;CAE/C,IAAI,CAAC,MADmB,mBAAmB,SAAS,QAAQ,GAC5C;EACf,OAAO,SAAS,OAAO;EACvB;CACD;CAEA,4BAA4B;EAC3B,MAAM,QAAQ,OAAO,QAAQ;EAC7B,OAAO,SAAS,GAAG,OAAO,UAAU,CAAC;CACtC,CAAC;AACF,CAAC;AAGD,MAAM,mBAAmB,SAAS,UAAU,IAAI;AAEhD,eAAe,mBAAmB,UAAoB,YAAY,OAAO;CAGxE,MAAM,OAAO,KAAA;CAEb,OAAO,MAAM,SAAS,IAAI,IAAI,SAAS,SAAS,CAAC,GAAG,SAAS;AAC9D"}
|
package/dist/dev.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as serverError } from "./response-
|
|
1
|
+
import { r as serverError } from "./response-C5EZsszY.mjs";
|
|
2
2
|
import { t as Server } from "./Server-C0PGzSQO.mjs";
|
|
3
3
|
import { t as flattenHeaders } from "./flattenHeaders-DM5qsSqO.mjs";
|
|
4
4
|
import { existsSync, promises, realpathSync } from "node:fs";
|
|
@@ -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-CL0eu77n.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"devPlugin-V689J6l6.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,YAAqC;CACrF,MAAM,SAASA,MAAK,QACnB,UACA,8BACA,aAAa,aAAa,MAC3B;CACA,MAAM,MAAM,aAAa,QAAQ;CACjC,OAAO;EACN,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,aAAaA,MAAK,KAAK,QAAQ,cAAc,K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AAC;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-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,CADM,aAAa,IACf,CAAC,CAAC,SAAS,cAAc;EACrC,QAAQ;GACP,OAAO;EACR;CACD,CAAC;AACF;;;;;;AAOA,SAAgB,eAAe,UAAkB,YAAqC;CACrF,MAAM,SAASA,MAAK,QACnB,UACA,8BACA,aAAa,aAAa,MAC3B;CACA,MAAM,MAAM,aAAa,QAAQ;CACjC,OAAO;EACN,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,aAAaA,MAAK,KAAK,QAAQ,cAAc,KAAK;EAClD,gBAAgBA,MAAK,KAAK,QAAQ,iBAAiB,KAAK;CACzD;AACD;;;ACvDA,SAAwB,gBACvB,UACA,cACA,iBACS;CACT,IAAI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AG;AAChG"}
|
package/dist/discovery.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { n as sitemapResponse, r as HeadElement, t as SitemapOptions } from "./sitemap-
|
|
1
|
+
import { n as sitemapResponse, r as HeadElement, t as SitemapOptions } from "./sitemap-DpwNjTjs.mjs";
|
|
2
2
|
//#region src/discovery/seo.d.ts
|
|
3
3
|
/**
|
|
4
4
|
* The elements to build head markup from: a page title, a description and
|
package/dist/index.d.mts
CHANGED
|
@@ -2,11 +2,11 @@ import { t as Router } from "./Router-dAu_5PlG.mjs";
|
|
|
2
2
|
import { a as RouteParamsOf, i as RouteArgsOf, n as ParseRouteParams, r as RouteArgs } from "./ParseRouteParams-DBmqlmLh.mjs";
|
|
3
3
|
import { n as QueryRecord, r as ServerLoadEvent, t as FormDataRecord } from "./ServerLoadEvent-DzbxxkF8.mjs";
|
|
4
4
|
import { t as ServerHook } from "./ServerHook-BTSGfLiJ.mjs";
|
|
5
|
-
import { a as PageLoadReturn, i as PageEndPoint, o as PageLoadEvent } from "./sitemap-
|
|
5
|
+
import { a as PageLoadReturn, i as PageEndPoint, o as PageLoadEvent } from "./sitemap-DpwNjTjs.mjs";
|
|
6
6
|
import { n as UntypedResponse, t as TypedResponse } from "./TypedResponse-6lznqN4U.mjs";
|
|
7
7
|
import { t as StandardSchemaV1 } from "./StandardSchema-D28L8_zZ.mjs";
|
|
8
|
-
import { a as ServerEndPoint, c as ActionBody, d as PageServerActionSchemas, f as PageServerEndPoint, g as Adapter, h as SitePlugin, i as SchemaQuery, l as LoadParams, m as PageServerAction, n as ParamsOf, o as ServerEndPointSchemas, p as PageServerLoad, r as SchemaBody, s as ServerRequest, t as Site, u as LoadQuery } from "./Site-
|
|
9
|
-
import { t as Jsonify } from "./Jsonify-
|
|
8
|
+
import { a as ServerEndPoint, c as ActionBody, d as PageServerActionSchemas, f as PageServerEndPoint, g as Adapter, h as SitePlugin, i as SchemaQuery, l as LoadParams, m as PageServerAction, n as ParamsOf, o as ServerEndPointSchemas, p as PageServerLoad, r as SchemaBody, s as ServerRequest, t as Site, u as LoadQuery } from "./Site-ChHKbLUv.mjs";
|
|
9
|
+
import { t as Jsonify } from "./Jsonify-hFz5OjtZ.mjs";
|
|
10
10
|
//#region src/types/PageData.d.ts
|
|
11
11
|
/**
|
|
12
12
|
* The page data produced by an endpoint's `load` function, e.g.
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
//#region src/deferred.ts
|
|
2
|
+
/**
|
|
3
|
+
* A thenable is anything awaitable. Load data containing one is split into
|
|
4
|
+
* critical data plus a deferred entry rather than being serialized as `{}`.
|
|
5
|
+
*/
|
|
6
|
+
function isThenable(value) {
|
|
7
|
+
return value !== null && (typeof value === "object" || typeof value === "function") && typeof value.then === "function";
|
|
8
|
+
}
|
|
9
|
+
/**
|
|
10
|
+
* Splits a load's data into the part that can be serialized immediately and
|
|
11
|
+
* the promise-valued properties that should be streamed. Nested objects and
|
|
12
|
+
* arrays are supported; the critical copy has `undefined` at each deferred
|
|
13
|
+
* path (object keys are dropped by JSON.stringify, array slots become null).
|
|
14
|
+
*/
|
|
15
|
+
function splitDeferred(value) {
|
|
16
|
+
const entries = [];
|
|
17
|
+
return {
|
|
18
|
+
critical: splitValue(value, [], entries),
|
|
19
|
+
entries
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
function splitValue(value, path, entries) {
|
|
23
|
+
if (isThenable(value)) {
|
|
24
|
+
entries.push({
|
|
25
|
+
path,
|
|
26
|
+
promise: value
|
|
27
|
+
});
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
if (Array.isArray(value)) return value.map((item, index) => splitValue(item, [...path, index], entries));
|
|
31
|
+
if (isPlainObject(value)) {
|
|
32
|
+
const result = {};
|
|
33
|
+
for (const key of Object.keys(value)) result[key] = splitValue(value[key], [...path, key], entries);
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
return value;
|
|
37
|
+
}
|
|
38
|
+
function isPlainObject(value) {
|
|
39
|
+
if (value === null || typeof value !== "object") return false;
|
|
40
|
+
const prototype = Object.getPrototypeOf(value);
|
|
41
|
+
return prototype === Object.prototype || prototype === null;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Assigns a value at a property path, creating intermediate objects/arrays
|
|
45
|
+
* when the critical JSON dropped them.
|
|
46
|
+
*/
|
|
47
|
+
function setAtPath(target, path, value) {
|
|
48
|
+
let current = target;
|
|
49
|
+
for (let i = 0; i < path.length - 1; i++) {
|
|
50
|
+
const key = path[i];
|
|
51
|
+
if (current[key] === void 0 || current[key] === null) current[key] = typeof path[i + 1] === "number" ? [] : {};
|
|
52
|
+
current = current[key];
|
|
53
|
+
}
|
|
54
|
+
current[path[path.length - 1]] = value;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* JSON for embedding inside an inline `<script>`. `<` is escaped so a value
|
|
58
|
+
* can't close the script or start a comment, and U+2028/U+2029 are escaped
|
|
59
|
+
* because they are valid in JSON but line terminators in JavaScript.
|
|
60
|
+
*/
|
|
61
|
+
function jsonForScript(value) {
|
|
62
|
+
const json = JSON.stringify(value);
|
|
63
|
+
if (json === void 0) return "null";
|
|
64
|
+
return json.replaceAll("<", "\\u003c").replaceAll("\u2028", "\\u2028").replaceAll("\u2029", "\\u2029");
|
|
65
|
+
}
|
|
66
|
+
//#endregion
|
|
67
|
+
//#region src/response/internal.ts
|
|
68
|
+
/**
|
|
69
|
+
* The body an endpoint passed to `response()`/`ok()`, before JSON
|
|
70
|
+
* serialization. Server code reads deferred promises from it without parsing
|
|
71
|
+
* the serialized copy.
|
|
72
|
+
*/
|
|
73
|
+
const INTERNAL_RESPONSE_BODY = Symbol.for("torpor.response.body");
|
|
74
|
+
/** The deferred (promise-valued) properties split out of the response body. */
|
|
75
|
+
const INTERNAL_RESPONSE_DEFERRED = Symbol.for("torpor.response.deferred");
|
|
76
|
+
//#endregion
|
|
77
|
+
export { splitDeferred as a, setAtPath as i, INTERNAL_RESPONSE_DEFERRED as n, jsonForScript as r, INTERNAL_RESPONSE_BODY as t };
|
|
78
|
+
|
|
79
|
+
//# sourceMappingURL=internal-BItAKrmV.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"internal-BItAKrmV.mjs","names":[],"sources":["../src/deferred.ts","../src/response/internal.ts"],"sourcesContent":["/**\n * A promise-valued property of a route's load data. Deferred values are\n * streamed to the browser after the critical (non-promise) data, so a page can\n * render before they resolve.\n */\nexport type DeferredEntry = {\n\t/** The property path within the load's data object. */\n\tpath: (string | number)[];\n\tpromise: PromiseLike<unknown>;\n};\n\n/** The shape the client uses for a deferred entry's metadata. */\nexport type DeferredMeta = {\n\t/** An identifier unique within the response. */\n\tid: string;\n\t/** The index in `loads` (layout index, then the page). */\n\tindex: number;\n\t/** The property path within that load's data object. */\n\tpath: (string | number)[];\n};\n\n/**\n * A thenable is anything awaitable. Load data containing one is split into\n * critical data plus a deferred entry rather than being serialized as `{}`.\n */\nexport function isThenable(value: unknown): value is PromiseLike<unknown> {\n\treturn (\n\t\tvalue !== null &&\n\t\t(typeof value === \"object\" || typeof value === \"function\") &&\n\t\ttypeof (value as { then?: unknown }).then === \"function\"\n\t);\n}\n\n/**\n * Splits a load's data into the part that can be serialized immediately and\n * the promise-valued properties that should be streamed. Nested objects and\n * arrays are supported; the critical copy has `undefined` at each deferred\n * path (object keys are dropped by JSON.stringify, array slots become null).\n */\nexport function splitDeferred(value: unknown): {\n\tcritical: unknown;\n\tentries: DeferredEntry[];\n} {\n\tconst entries: DeferredEntry[] = [];\n\tconst critical = splitValue(value, [], entries);\n\treturn { critical, entries };\n}\n\nfunction splitValue(value: unknown, path: (string | number)[], entries: DeferredEntry[]): unknown {\n\tif (isThenable(value)) {\n\t\tentries.push({ path, promise: value });\n\t\treturn undefined;\n\t}\n\tif (Array.isArray(value)) {\n\t\treturn value.map((item, index) => splitValue(item, [...path, index], entries));\n\t}\n\tif (isPlainObject(value)) {\n\t\tconst result: Record<string, unknown> = {};\n\t\tfor (const key of Object.keys(value)) {\n\t\t\tresult[key] = splitValue(value[key], [...path, key], entries);\n\t\t}\n\t\treturn result;\n\t}\n\treturn value;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\tif (value === null || typeof value !== \"object\") return false;\n\tconst prototype = Object.getPrototypeOf(value);\n\treturn prototype === Object.prototype || prototype === null;\n}\n\n/**\n * Assigns a value at a property path, creating intermediate objects/arrays\n * when the critical JSON dropped them.\n */\nexport function setAtPath(target: object, path: (string | number)[], value: unknown): void {\n\tlet current = target as Record<string | number, any>;\n\tfor (let i = 0; i < path.length - 1; i++) {\n\t\tconst key = path[i];\n\t\tif (current[key] === undefined || current[key] === null) {\n\t\t\tcurrent[key] = typeof path[i + 1] === \"number\" ? [] : {};\n\t\t}\n\t\tcurrent = current[key];\n\t}\n\tcurrent[path[path.length - 1]] = value;\n}\n\n/**\n * JSON for embedding inside an inline `<script>`. `<` is escaped so a value\n * can't close the script or start a comment, and U+2028/U+2029 are escaped\n * because they are valid in JSON but line terminators in JavaScript.\n */\nexport function jsonForScript(value: unknown): string {\n\tconst json = JSON.stringify(value);\n\tif (json === undefined) return \"null\";\n\treturn json\n\t\t.replaceAll(\"<\", \"\\\\u003c\")\n\t\t.replaceAll(\"\\u2028\", \"\\\\u2028\")\n\t\t.replaceAll(\"\\u2029\", \"\\\\u2029\");\n}\n","import type { DeferredEntry } from \"../deferred\";\n\n/**\n * The body an endpoint passed to `response()`/`ok()`, before JSON\n * serialization. Server code reads deferred promises from it without parsing\n * the serialized copy.\n */\nexport const INTERNAL_RESPONSE_BODY: unique symbol = Symbol.for(\"torpor.response.body\");\n\n/** The deferred (promise-valued) properties split out of the response body. */\nexport const INTERNAL_RESPONSE_DEFERRED: unique symbol = Symbol.for(\"torpor.response.deferred\");\n\nexport type ResponseWithBody = Response & {\n\t[INTERNAL_RESPONSE_BODY]?: object;\n\t[INTERNAL_RESPONSE_DEFERRED]?: DeferredEntry[];\n};\n"],"mapp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rD,MAAM,OAAO,KAAK,UAAU,KAAK;CACjC,IAAI,SAAS,KAAA,GAAW,OAAO;CAC/B,OAAO,KACL,WAAW,KAAK,SAAS,CAAC,CAC1B,WAAW,UAAU,SAAS,CAAC,CAC/B,WAAW,UAAU,SAAS;AACjC;;;;;;;;AC7FA,MAAa,yBAAwC,OAAO,IAAI,sBAAsB;;AAGtF,MAAa,6BAA4C,OAAO,IAAI,0BAA0B"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { n as getBasePath, s as stripBaseFromUrl } from "./basePath-DQnbHc7o.mjs";
|
|
2
2
|
import { t as $page } from "./_page-CW6SLuT4.mjs";
|
|
3
|
-
import { n as
|
|
3
|
+
import { i as findErrorRoute, n as DATA_REQUEST_HEADER, r as DATA_REUSE_HEADER, t as readResponseBody } from "./read-DxMVAh5Y.mjs";
|
|
4
|
+
import { i as setAtPath } from "./internal-BItAKrmV.mjs";
|
|
4
5
|
import { clearLayoutSlot, fillLayoutSlot, hydrate, mount, unmount } from "@torpor/view";
|
|
5
6
|
//#region src/state/client.ts
|
|
6
7
|
const CLIENT_SYMBOL = Symbol.for("torp.Client");
|
|
@@ -76,34 +77,35 @@ async function loadData(handler, params, path, query, newLayoutStack, clientEndP
|
|
|
76
77
|
let layoutPath = layout.path;
|
|
77
78
|
for (let key in params) layoutPath = layoutPath.replace(`[${key}]`, params[key]);
|
|
78
79
|
const previous = layoutStack.at(index);
|
|
79
|
-
const
|
|
80
|
+
const rendered = previous?.path === layoutPath;
|
|
80
81
|
return {
|
|
81
82
|
layout,
|
|
82
83
|
index,
|
|
83
84
|
layoutPath,
|
|
84
85
|
previous,
|
|
85
|
-
|
|
86
|
+
rendered,
|
|
87
|
+
reuse: !prefetch && rendered
|
|
86
88
|
};
|
|
87
89
|
});
|
|
88
|
-
const server = await loadServerData(handler, path, query, layouts.filter((l) => l.
|
|
90
|
+
const server = clientEndPoint?.serverData === false && !handler.serverEndPoint && layouts.every((layout) => layout.rendered) ? {} : await loadServerData(handler, path, query, layouts.filter((l) => l.rendered).map((l) => l.layoutPath), prefetch);
|
|
89
91
|
if (server === void 0) return;
|
|
90
92
|
if ("error" in server) return {
|
|
91
93
|
data,
|
|
92
94
|
error: server.error
|
|
93
95
|
};
|
|
94
|
-
for (const { layout, index, layoutPath, previous, reuse } of layouts) {
|
|
96
|
+
for (const { layout, index, layoutPath, previous, rendered, reuse } of layouts) {
|
|
95
97
|
const stackLayout = {
|
|
96
98
|
path: layoutPath,
|
|
97
99
|
data: {},
|
|
98
100
|
reuse,
|
|
99
101
|
slotRegion: null
|
|
100
102
|
};
|
|
101
|
-
if (
|
|
102
|
-
stackLayout.slotRegion = previous.slotRegion;
|
|
103
|
+
if (rendered && previous) {
|
|
104
|
+
if (reuse) stackLayout.slotRegion = previous.slotRegion;
|
|
103
105
|
Object.assign(stackLayout.data, previous.data);
|
|
104
106
|
} else {
|
|
105
107
|
const layoutEndPoint = (await layout.endPoint())?.default;
|
|
106
|
-
const response = await runClientLoad(layoutEndPoint, clientLocation(layoutPath), query, params, stackLayout.data);
|
|
108
|
+
const response = await runClientLoad(layoutEndPoint, clientLocation(layoutPath), query, params, stackLayout.data, prefetch);
|
|
107
109
|
if (response) {
|
|
108
110
|
if (isRedirect(response)) return;
|
|
109
111
|
return {
|
|
@@ -117,7 +119,7 @@ async function loadData(handler, params, path, query, newLayoutStack, clientEndP
|
|
|
117
119
|
Object.assign(data, stackLayout.data);
|
|
118
120
|
newLayoutStack.push(stackLayout);
|
|
119
121
|
}
|
|
120
|
-
const response = await runClientLoad(clientEndPoint, clientLocation(path), query, params, data);
|
|
122
|
+
const response = await runClientLoad(clientEndPoint, clientLocation(path), query, params, data, prefetch);
|
|
121
123
|
if (response) {
|
|
122
124
|
if (isRedirect(response)) return;
|
|
123
125
|
return {
|
|
@@ -130,6 +132,57 @@ async function loadData(handler, params, path, query, newLayoutStack, clientEndP
|
|
|
130
132
|
return { data };
|
|
131
133
|
}
|
|
132
134
|
/**
|
|
135
|
+
* A request-local registry of deferred promises. Values arrive after the first
|
|
136
|
+
* frame (client navigation) or in inline scripts (initial hydration), and
|
|
137
|
+
* resolve the promises already placed in the page's `data`.
|
|
138
|
+
*/
|
|
139
|
+
var DeferredStore = class {
|
|
140
|
+
#entries = /* @__PURE__ */ new Map();
|
|
141
|
+
get(id) {
|
|
142
|
+
let entry = this.#entries.get(id);
|
|
143
|
+
if (!entry) {
|
|
144
|
+
let resolve;
|
|
145
|
+
let reject;
|
|
146
|
+
const promise = new Promise((res, rej) => {
|
|
147
|
+
resolve = res;
|
|
148
|
+
reject = rej;
|
|
149
|
+
});
|
|
150
|
+
promise.catch(() => {});
|
|
151
|
+
entry = {
|
|
152
|
+
promise,
|
|
153
|
+
resolve,
|
|
154
|
+
reject
|
|
155
|
+
};
|
|
156
|
+
this.#entries.set(id, entry);
|
|
157
|
+
}
|
|
158
|
+
return entry.promise;
|
|
159
|
+
}
|
|
160
|
+
resolve(id, value) {
|
|
161
|
+
const entry = this.#entries.get(id);
|
|
162
|
+
if (!entry) return;
|
|
163
|
+
this.#entries.delete(id);
|
|
164
|
+
entry.resolve(value);
|
|
165
|
+
}
|
|
166
|
+
reject(id, error) {
|
|
167
|
+
const entry = this.#entries.get(id);
|
|
168
|
+
if (!entry) return;
|
|
169
|
+
this.#entries.delete(id);
|
|
170
|
+
entry.reject(error instanceof Error ? error : new Error(String(error)));
|
|
171
|
+
}
|
|
172
|
+
rejectAll(error) {
|
|
173
|
+
for (const id of this.#entries.keys()) this.reject(id, error);
|
|
174
|
+
}
|
|
175
|
+
/** Places a promise for each deferred entry into the load that owns it. */
|
|
176
|
+
attach(server, get) {
|
|
177
|
+
for (const entry of server.deferred ?? []) {
|
|
178
|
+
const load = server.loads?.[entry.index];
|
|
179
|
+
if (!load) continue;
|
|
180
|
+
setAtPath(load, entry.path, get(entry.id));
|
|
181
|
+
}
|
|
182
|
+
return server;
|
|
183
|
+
}
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
133
186
|
* Fetches the page's combined server data for a navigation, reusing a prefetch
|
|
134
187
|
* when there is one.
|
|
135
188
|
*
|
|
@@ -141,7 +194,7 @@ async function loadData(handler, params, path, query, newLayoutStack, clientEndP
|
|
|
141
194
|
*/
|
|
142
195
|
async function loadServerData(handler, path, query, reusedLayouts, prefetch) {
|
|
143
196
|
const embedded = takeEmbeddedServerData();
|
|
144
|
-
if (embedded !== void 0) return embedded;
|
|
197
|
+
if (embedded !== void 0) return attachEmbeddedDeferred(embedded);
|
|
145
198
|
if (!hasServerData(handler)) return {};
|
|
146
199
|
const key = serverDataKey(path, query);
|
|
147
200
|
if (prefetch) {
|
|
@@ -181,10 +234,73 @@ async function requestServerData(path, query, reusedLayouts) {
|
|
|
181
234
|
});
|
|
182
235
|
if (isRedirect(response)) return;
|
|
183
236
|
if (!response.ok) return { error: await errorOf(response) };
|
|
184
|
-
|
|
237
|
+
const type = response.headers.get("Content-Type");
|
|
238
|
+
if (type?.includes("application/x-ndjson")) return await readServerDataStream(response);
|
|
239
|
+
if (!type?.includes("application/json")) return {};
|
|
185
240
|
return await response.json();
|
|
186
241
|
}
|
|
187
242
|
/**
|
|
243
|
+
* Reads a streamed data response: the first frame carries the critical loads
|
|
244
|
+
* and the list of deferred paths, later frames resolve those promises. The
|
|
245
|
+
* function returns as soon as the first frame is read, so a navigation mounts
|
|
246
|
+
* before slow values arrive.
|
|
247
|
+
*/
|
|
248
|
+
async function readServerDataStream(response) {
|
|
249
|
+
const reader = response.body?.getReader();
|
|
250
|
+
if (!reader) return {};
|
|
251
|
+
const decoder = new TextDecoder();
|
|
252
|
+
let buffer = "";
|
|
253
|
+
const readFrame = async () => {
|
|
254
|
+
while (true) {
|
|
255
|
+
const newline = buffer.indexOf("\n");
|
|
256
|
+
if (newline >= 0) {
|
|
257
|
+
const line = buffer.slice(0, newline).trim();
|
|
258
|
+
buffer = buffer.slice(newline + 1);
|
|
259
|
+
if (line) return JSON.parse(line);
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const { done, value } = await reader.read();
|
|
263
|
+
if (done) {
|
|
264
|
+
const line = buffer.trim();
|
|
265
|
+
buffer = "";
|
|
266
|
+
return line ? JSON.parse(line) : void 0;
|
|
267
|
+
}
|
|
268
|
+
buffer += decoder.decode(value, { stream: true });
|
|
269
|
+
}
|
|
270
|
+
};
|
|
271
|
+
const first = await readFrame();
|
|
272
|
+
if (!first) return {};
|
|
273
|
+
if (first.loads === void 0) return {};
|
|
274
|
+
const store = new DeferredStore();
|
|
275
|
+
const server = store.attach(first, (id) => store.get(id));
|
|
276
|
+
(async () => {
|
|
277
|
+
try {
|
|
278
|
+
for (;;) {
|
|
279
|
+
const frame = await readFrame();
|
|
280
|
+
if (!frame) break;
|
|
281
|
+
if (frame.type === "value" && frame.id !== void 0) store.resolve(frame.id, frame.value);
|
|
282
|
+
else if (frame.type === "error" && frame.id !== void 0) store.reject(frame.id, frame.message ?? "Deferred data failed");
|
|
283
|
+
}
|
|
284
|
+
store.rejectAll(/* @__PURE__ */ new Error("The deferred data stream ended before a value arrived"));
|
|
285
|
+
} catch (error) {
|
|
286
|
+
store.rejectAll(error);
|
|
287
|
+
}
|
|
288
|
+
})();
|
|
289
|
+
return server;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Recreates the promises for a page's embedded server data. The server emits
|
|
293
|
+
* a bootstrap store before the inline resolve scripts, so by the time this
|
|
294
|
+
* runs a value may already be resolved (or still be in flight).
|
|
295
|
+
*/
|
|
296
|
+
function attachEmbeddedDeferred(server) {
|
|
297
|
+
if (!server.deferred?.length) return server;
|
|
298
|
+
const globalStore = globalThis.__torporDeferred;
|
|
299
|
+
const store = new DeferredStore();
|
|
300
|
+
const get = globalStore ? (id) => globalStore.get(id) : (id) => store.get(id);
|
|
301
|
+
return store.attach(server, get);
|
|
302
|
+
}
|
|
303
|
+
/**
|
|
188
304
|
* Reads and removes the server data the initial render embedded in the HTML
|
|
189
305
|
* (a `t-server-data` script tag), or `undefined` when there is none (a later
|
|
190
306
|
* navigation, or a page with no server data).
|
|
@@ -211,31 +327,45 @@ function hasServerData(handler) {
|
|
|
211
327
|
/**
|
|
212
328
|
* Runs a route's client-side load, merging its json data into `data`. Returns
|
|
213
329
|
* a non-ok Response for the caller to turn into an error page.
|
|
330
|
+
*
|
|
331
|
+
* A prefetch caches the in-flight promise, not its resolved value, so a
|
|
332
|
+
* navigation that lands while the load is still running continues the same
|
|
333
|
+
* request instead of running it a second time. The navigation that follows
|
|
334
|
+
* consumes (and clears) the entry; a failed promise is dropped so the
|
|
335
|
+
* navigation retries.
|
|
214
336
|
*/
|
|
215
|
-
async function runClientLoad(endPoint, location, query, params, data) {
|
|
337
|
+
async function runClientLoad(endPoint, location, query, params, data, prefetch) {
|
|
216
338
|
if (!endPoint?.load) return;
|
|
217
339
|
const clientKey = location + (query.size > 0 ? `?${query}` : "");
|
|
218
340
|
const prefetchedData = client.prefetchedData;
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
return;
|
|
222
|
-
|
|
341
|
+
let pending = prefetchedData[clientKey];
|
|
342
|
+
if (!pending) {
|
|
343
|
+
if (!prefetch) return mergeClientLoad(await loadClientResponse(endPoint.load, query, params, data), data);
|
|
344
|
+
const promise = loadClientResponse(endPoint.load, query, params, data);
|
|
345
|
+
prefetchedData[clientKey] = promise;
|
|
346
|
+
pending = promise;
|
|
347
|
+
promise.catch(() => {
|
|
348
|
+
if (prefetchedData[clientKey] === promise) delete prefetchedData[clientKey];
|
|
349
|
+
});
|
|
350
|
+
} else if (!prefetch) delete prefetchedData[clientKey];
|
|
351
|
+
return mergeClientLoad(await pending, data);
|
|
352
|
+
}
|
|
353
|
+
async function loadClientResponse(load, query, params, data) {
|
|
223
354
|
const clientUrl = new URL(document.location.href);
|
|
224
355
|
for (let [name, value] of query) clientUrl.searchParams.append(name, value);
|
|
225
|
-
const
|
|
356
|
+
const response = await load({
|
|
226
357
|
url: clientUrl,
|
|
227
358
|
params,
|
|
228
359
|
data
|
|
229
360
|
});
|
|
230
|
-
if (
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
}
|
|
361
|
+
if (!response) return {};
|
|
362
|
+
if (!response.ok) return { response };
|
|
363
|
+
const body = await readResponseBody(response);
|
|
364
|
+
return body ? { data: body } : {};
|
|
365
|
+
}
|
|
366
|
+
function mergeClientLoad(result, data) {
|
|
367
|
+
if (result.data) Object.assign(data, result.data);
|
|
368
|
+
return result.response;
|
|
239
369
|
}
|
|
240
370
|
function clientLocation(path) {
|
|
241
371
|
return document.location.origin + getBasePath() + path;
|
|
@@ -278,6 +408,20 @@ function navigate(rawUrl, withHydration = false) {
|
|
|
278
408
|
return result;
|
|
279
409
|
}
|
|
280
410
|
async function navigateNow(rawUrl, withHydration) {
|
|
411
|
+
const previousUrl = $page.url;
|
|
412
|
+
const previousStatus = $page.status;
|
|
413
|
+
const previousError = $page.error;
|
|
414
|
+
try {
|
|
415
|
+
return await renderNavigation(rawUrl, withHydration);
|
|
416
|
+
} catch (error) {
|
|
417
|
+
$page.url = previousUrl;
|
|
418
|
+
$page.status = previousStatus;
|
|
419
|
+
$page.error = previousError;
|
|
420
|
+
console.error(error);
|
|
421
|
+
return false;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
async function renderNavigation(rawUrl, withHydration) {
|
|
281
425
|
let parent = document.getElementById("app");
|
|
282
426
|
if (!parent) {
|
|
283
427
|
console.log("500");
|
|
@@ -412,4 +556,4 @@ async function load(path) {
|
|
|
412
556
|
//#endregion
|
|
413
557
|
export { client as a, reload as i, navigate as n, loadData as r, load as t };
|
|
414
558
|
|
|
415
|
-
//# sourceMappingURL=load-
|
|
559
|
+
//# sourceMappingURL=load-Clec6rli.mjs.map
|