@torpor/build 1.8.7 → 1.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{MiddlewareFunction-BZilnEei.d.mts → MiddlewareFunction-7rIvFkjl.d.mts} +7 -1
- package/dist/MiddlewareFunction-7rIvFkjl.d.mts.map +1 -0
- package/dist/{Router-By9Nlg39.d.mts → Router-Bxm7K20d.d.mts} +4 -4
- package/dist/Router-Bxm7K20d.d.mts.map +1 -0
- package/dist/{Server-dcRbdPXf.mjs → Server-Djd9-NkU.mjs} +2 -2
- package/dist/{Server-dcRbdPXf.mjs.map → Server-Djd9-NkU.mjs.map} +1 -1
- package/dist/{Server-qn5Ws_d0.d.mts → Server-hwbZ7P2g.d.mts} +2 -2
- package/dist/{Server-qn5Ws_d0.d.mts.map → Server-hwbZ7P2g.d.mts.map} +1 -1
- package/dist/{ServerEvent-BY4f3RVF.mjs → ServerEvent-L0rT_mBJ.mjs} +10 -1
- package/dist/{ServerEvent-BY4f3RVF.mjs.map → ServerEvent-L0rT_mBJ.mjs.map} +1 -1
- package/dist/{ServerHook-W111nEhe.d.mts → ServerHook-CyVEr5OL.d.mts} +2 -2
- package/dist/{ServerHook-W111nEhe.d.mts.map → ServerHook-CyVEr5OL.d.mts.map} +1 -1
- package/dist/{ServerLoadEvent-BH6oG1o6.d.mts → ServerLoadEvent-F60w1TZt.d.mts} +14 -4
- package/dist/ServerLoadEvent-F60w1TZt.d.mts.map +1 -0
- package/dist/{Site-DGZJB7Do.d.mts → Site-CAeAqjkk.d.mts} +192 -7
- package/dist/Site-CAeAqjkk.d.mts.map +1 -0
- package/dist/bin/index.js +37 -2
- package/dist/bin/index.js.map +1 -1
- package/dist/clientEntry.mjs +45 -6
- package/dist/clientEntry.mjs.map +1 -1
- package/dist/dev.d.mts +2 -2
- package/dist/dev.mjs +2 -2
- package/dist/{devPlugin-lLzauETn.mjs → devPlugin-D9b5uhzm.mjs} +2 -2
- package/dist/{devPlugin-lLzauETn.mjs.map → devPlugin-D9b5uhzm.mjs.map} +1 -1
- package/dist/discovery.d.mts +1 -1
- package/dist/index.d.mts +5 -5
- package/dist/{load-G-4A435s.mjs → load-BODDzmH0.mjs} +162 -67
- package/dist/load-BODDzmH0.mjs.map +1 -0
- package/dist/nav.d.mts +65 -4
- package/dist/nav.d.mts.map +1 -1
- package/dist/nav.mjs +38 -10
- package/dist/nav.mjs.map +1 -1
- package/dist/nodeDev.d.mts +1 -1
- package/dist/nodeDev.mjs +1 -1
- package/dist/openapi.d.mts +24 -80
- package/dist/openapi.d.mts.map +1 -1
- package/dist/openapi.mjs +36 -1
- package/dist/openapi.mjs.map +1 -0
- package/dist/{plugin-D8Www11B.mjs → plugin-BQsMnkTj.mjs} +42 -3
- package/dist/plugin-BQsMnkTj.mjs.map +1 -0
- package/dist/run.d.mts +1 -1
- package/dist/run.mjs +1 -1
- package/dist/{runOpenApi-C5yMpQU1.mjs → runOpenApi-BZ314IiI.mjs} +44 -21
- package/dist/runOpenApi-BZ314IiI.mjs.map +1 -0
- package/dist/server/Server.d.mts +1 -1
- package/dist/server/Server.mjs +1 -1
- package/dist/server.d.mts +4 -4
- package/dist/server.mjs +2 -2
- package/dist/{serverEntry-D1hE-Jzt.mjs → serverEntry-8YnfpKTj.mjs} +2 -2
- package/dist/{serverEntry-D1hE-Jzt.mjs.map → serverEntry-8YnfpKTj.mjs.map} +1 -1
- package/dist/{serverEntry-BGii8bB6.d.mts → serverEntry-Da1PFlIU.d.mts} +3 -3
- package/dist/{serverEntry-BGii8bB6.d.mts.map → serverEntry-Da1PFlIU.d.mts.map} +1 -1
- package/dist/serverEntry.d.mts +1 -1
- package/dist/serverEntry.mjs +1 -1
- package/dist/{serverHandlers-CSBUEgJt.mjs → serverHandlers-Ba_35jpO.mjs} +38 -12
- package/dist/serverHandlers-Ba_35jpO.mjs.map +1 -0
- package/dist/{sitemap-xmE0zfme.d.mts → sitemap-CnIYTLhu.d.mts} +2 -2
- package/dist/{sitemap-xmE0zfme.d.mts.map → sitemap-CnIYTLhu.d.mts.map} +1 -1
- package/dist/test.d.mts +2 -2
- package/dist/test.mjs +2 -2
- package/package.json +10 -7
- package/dist/MiddlewareFunction-BZilnEei.d.mts.map +0 -1
- package/dist/Router-By9Nlg39.d.mts.map +0 -1
- package/dist/ServerLoadEvent-BH6oG1o6.d.mts.map +0 -1
- package/dist/Site-DGZJB7Do.d.mts.map +0 -1
- package/dist/load-G-4A435s.mjs.map +0 -1
- package/dist/plugin-D8Www11B.mjs.map +0 -1
- package/dist/runOpenApi-C5yMpQU1.mjs.map +0 -1
- package/dist/serverHandlers-CSBUEgJt.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"load-BODDzmH0.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. Returns whether\n * the page was rendered in place (see `load`).\n */\nexport default async function reload(): Promise<boolean> {\n\tconst url = new URL(document.location.href);\n\treturn (await navigate(url)).type === \"rendered\";\n}\n","import $page from \"../state/$page\";\nimport load from \"./load\";\nimport reload from \"./reload\";\n\n/**\n * The detail of the `torpor:submit-failed` window event.\n */\nexport type SubmitFailureDetail = {\n\t/** The url the form was submitted to. */\n\taction: string;\n\t/** The failure that stopped the submit. */\n\terror?: unknown;\n};\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\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(\n\t\t\taction,\n\t\t\t// @ts-ignore -- don't know what it's complaining about here\n\t\t\toptions,\n\t\t);\n\t} catch (error) {\n\t\t// A rejected fetch is a failed submission -- offline, or the server\n\t\t// couldn't be reached. Nothing navigates and the form keeps what the\n\t\t// user typed, so the app can show its own notice and let them retry.\n\t\tconsole.error(\"The form submit failed\", error);\n\t\thandleSubmitFailure(form, action, error);\n\t\treturn;\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\n/**\n * Tells the app that a client form submission failed (offline, or the server\n * couldn't be reached), so it can show its own notice. The form keeps the\n * values the user typed, ready for the app to retry.\n *\n * Dispatched on `window` as a cancelable `torpor:submit-failed` `CustomEvent`.\n * An app that cancels it asks for a native form submission after all, e.g. a\n * service worker serves the POST, or the browser's own offline handling is\n * preferred.\n */\nfunction handleSubmitFailure(form: HTMLFormElement, action: string, error: unknown): void {\n\tconst event = new CustomEvent<SubmitFailureDetail>(\"torpor:submit-failed\", {\n\t\tcancelable: true,\n\t\tdetail: { action, error },\n\t});\n\t// `dispatchEvent` returns false when a handler cancelled it\n\tif (!window.dispatchEvent(event)) {\n\t\t// The prototype call, because a field named \"submit\" shadows `form.submit`\n\t\tHTMLFormElement.prototype.submit.call(form);\n\t\treturn;\n\t}\n\n\tconsole.warn(\n\t\t`The form submission to ${action} failed; staying on the current page. ` +\n\t\t\t\"Listen for torpor:submit-failed to show your own notice.\",\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\tconst layoutPath = resolveLayoutPath(layout.path, params);\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 loaded = 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 (loaded?.redirect) return;\n\t\t\tif (loaded?.error) return { data, error: loaded.error };\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 loaded = 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 (loaded?.redirect) return;\n\tif (loaded?.error) return { data, error: loaded.error };\n\tconst pageServerData = server.loads?.[handler.layouts?.length ?? 0];\n\tif (pageServerData) Object.assign(data, pageServerData);\n\n\treturn { data };\n}\n\n/** The path of a layout with its `[param]` segments substituted. */\nfunction resolveLayoutPath(path: string, params: Record<string, string>): string {\n\tfor (let key in params) {\n\t\tpath = path.replace(`[${key}]`, params[key]);\n\t}\n\treturn path;\n}\n\n/**\n * Builds the layout stack for an error page whose own loads can't run (offline,\n * or the server is down): layouts already on screen keep their data and slot\n * regions, so the error renders over the shell instead of the shell being\n * replaced by a document load that would fail too. Layouts that aren't on\n * screen render with no data.\n */\nexport function errorLayoutStack(\n\thandler: RouteHandler,\n\tparams: Record<string, string>,\n): LayoutPath[] {\n\tconst stack: LayoutPath[] = [];\n\t(handler.layouts ?? []).forEach((layout, index) => {\n\t\tconst path = resolveLayoutPath(layout.path, params);\n\t\tconst previous = client.layoutStack.at(index);\n\t\tconst rendered = previous?.path === path;\n\t\tstack.push({\n\t\t\tpath,\n\t\t\tdata: rendered && previous ? { ...previous.data } : {},\n\t\t\treuse: rendered,\n\t\t\tslotRegion: rendered && previous ? previous.slotRegion : null,\n\t\t});\n\t});\n\treturn stack;\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: drop\n\t\t// the entry so that navigation retries. One that is already awaiting\n\t\t// this promise still sees the failure and renders the error page.\n\t\tvoid pending.then(\n\t\t\t(result) => {\n\t\t\t\tif (isLoadError(result)) dropPrefetch(client.prefetchedServerData, key, pending);\n\t\t\t},\n\t\t\t() => dropPrefetch(client.prefetchedServerData, key, pending),\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/** Whether a load resolved to an error result (as opposed to data/nothing). */\nfunction isLoadError(value: unknown): value is { error: { status: number; message: string } } {\n\treturn typeof value === \"object\" && value !== null && \"error\" in value;\n}\n\n/** Removes a failed prefetch, unless the navigation has already consumed it. */\nfunction dropPrefetch(prefetches: Record<string, any>, key: string, pending: unknown): void {\n\tif (prefetches[key] === pending) {\n\t\tdelete prefetches[key];\n\t}\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\t// A rejected fetch is the common offline failure (as is a body that fails\n\t// mid-read, e.g. the connection drops while streaming). Render it as an\n\t// error in place rather than throwing away the shell with a document load\n\t// that would fail too.\n\ttry {\n\t\tconst response = await fetch(url, {\n\t\t\tredirect: \"manual\",\n\t\t\theaders,\n\t\t});\n\t\tif (isRedirect(response)) {\n\t\t\treturn undefined;\n\t\t}\n\t\tif (!response.ok) {\n\t\t\treturn { error: await errorOf(response) };\n\t\t}\n\t\t// A site without a server (e.g. a static host) responds with the page's\n\t\t// html rather than json; there's nothing to merge\n\t\tconst type = response.headers.get(\"Content-Type\");\n\t\tif (type?.includes(\"application/x-ndjson\")) {\n\t\t\treturn await readServerDataStream(response);\n\t\t}\n\t\tif (!type?.includes(\"application/json\")) {\n\t\t\treturn {};\n\t\t}\n\t\treturn (await response.json()) as ServerData;\n\t} catch (error) {\n\t\tconsole.error(\"The server data request failed\", error);\n\t\treturn { error: unreachableError() };\n\t}\n}\n\n/** The error rendered when the server can't be reached at all. */\nfunction unreachableError(): { status: number; message: string } {\n\treturn {\n\t\tstatus: 503,\n\t\tmessage: navigator.onLine === false ? \"You're offline.\" : \"Could not reach the server.\",\n\t};\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 * a redirect the client can't follow, or an error to render in place. Cached\n * as a whole when a prefetch warms it, because a Response body can only be\n * read once.\n */\ntype ClientLoadResult = {\n\t/** The json the load returned, if any. */\n\tdata?: Record<string, any>;\n\t/** The load redirected: only a document load can follow it. */\n\tredirect?: true;\n\t/** The load failed: render the nearest error page. */\n\terror?: { status: number; message: string };\n};\n\n/**\n * Runs a route's client-side load, merging its json data into `data` and\n * returning the redirect or error for the caller to handle.\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 prefetch 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<ClientLoadResult | 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.then(\n\t\t\t(result) => {\n\t\t\t\tif (result.error) dropPrefetch(prefetchedData, clientKey, promise);\n\t\t\t},\n\t\t\t() => dropPrefetch(prefetchedData, clientKey, promise),\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\ttry {\n\t\tconst response = await load({ url: clientUrl, params, data });\n\t\tif (!response) return {};\n\t\tif (isRedirect(response)) return { redirect: true };\n\t\tif (!response.ok) return { error: await errorOf(response) };\n\t\tconst body = await readResponseBody(response);\n\t\treturn body ? { data: body } : {};\n\t} catch (error) {\n\t\t// A throwing load (or a body that fails mid-read) is a page error, not\n\t\t// a navigation failure: render the error page over the shell rather\n\t\t// than blanking it with a document load that would run the same load\n\t\t// again\n\t\tconsole.error(\"The client load failed\", error);\n\t\treturn { error: { status: 500, message: \"Internal error\" } };\n\t}\n}\n\nfunction mergeClientLoad(result: ClientLoadResult, data: Record<string, any>): ClientLoadResult {\n\tif (result.data) Object.assign(data, result.data);\n\treturn result;\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, { errorLayoutStack } from \"./loadData\";\n\n/**\n * What a navigation did, so its caller knows whether the page is rendered or\n * the document has to take over.\n *\n * - `rendered`: the route (or its nearest error page) is in place.\n * - `server-only`: the route has no client component (e.g. a `+server` route),\n * so only a document load can handle it.\n * - `redirect`: a load redirected, which a fetch can't follow.\n * - `failed`: nothing rendered; the caller keeps the current page and decides\n * between a document load and telling the app (see `handleNavigationFailure`).\n */\nexport type NavigationResult =\n\t| { type: \"rendered\" }\n\t| { type: \"server-only\" }\n\t| { type: \"redirect\" }\n\t| { type: \"failed\"; error?: unknown };\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\nexport default function navigate(rawUrl: URL, withHydration = false): Promise<NavigationResult> {\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<NavigationResult> {\n\t// A failed route-module import (e.g. a stale dev dep hash), a throwing\n\t// load or a failed render must not reject the click handler's promise: the\n\t// caller's fallback would never run and the link would appear dead.\n\tconst previousUrl = $page.url;\n\tconst previousStatus = $page.status;\n\tconst previousError = $page.error;\n\tlet result: NavigationResult;\n\ttry {\n\t\tresult = await renderNavigation(rawUrl, withHydration);\n\t} catch (error) {\n\t\tconsole.error(error);\n\t\tresult = { type: \"failed\", error };\n\t}\n\tif (result.type === \"failed\" && !withHydration) {\n\t\t// Nothing is on screen for this url: point the reactive state back at\n\t\t// the page that is still there, in case the caller keeps it (e.g. a\n\t\t// failed navigation while offline). The initial hydration already has\n\t\t// its server-rendered page on screen, so there is nothing to restore.\n\t\t$page.url = previousUrl;\n\t\t$page.status = previousStatus;\n\t\t$page.error = previousError;\n\t}\n\treturn result;\n}\n\nasync function renderNavigation(rawUrl: URL, withHydration: boolean): Promise<NavigationResult> {\n\tlet parent = document.getElementById(\"app\");\n\tif (!parent) {\n\t\t// TODO: 500\n\t\tconsole.log(\"500\");\n\t\treturn { type: \"failed\" };\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 { type: \"failed\" };\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 report `server-only` and let the caller do a full page\n\t// 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 { type: \"server-only\" };\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: the client can't follow it through fetch, so the\n\t\t// caller falls back to a full page load, which does\n\t\treturn { type: \"redirect\" };\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 { type: \"failed\" };\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 { type: \"failed\" };\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 { type: \"failed\" };\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 = [];\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) {\n\t\t\t// The error page's own load redirected: only a document load can\n\t\t\t// follow it\n\t\t\treturn { type: \"redirect\" };\n\t\t}\n\t\tif (errorResult.error) {\n\t\t\t// The error page's own data can't load either (offline, or the\n\t\t\t// server is down). Render it over the shell with the layouts and\n\t\t\t// data that are already on screen rather than blanking the page\n\t\t\t// with a document load that would fail too.\n\t\t\tnewLayoutStack = errorLayoutStack(handler, params);\n\t\t\tdata = {};\n\t\t} else {\n\t\t\tdata = errorResult.data;\n\t\t}\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 { type: \"rendered\" };\n}\n","import navigate from \"./navigate\";\n\n/**\n * Loads and renders the page at the supplied path. Returns whether the page\n * was rendered in place: `false` when the document has to take over (a\n * `+server` route, a redirect, or a failed navigation).\n */\nexport default async function load(path: string): Promise<boolean> {\n\tconst url = new URL(path, document.location.href);\n\treturn (await navigate(url)).type === \"rendered\";\n}\n"],"mappings":";;;;;;AAEA,MAAM,gBAA+B,OAAO,IAAI,aAAa;AAE7D,MAAM,SAEJ,WAAW,mBAAmB;CAE9B,QAAQ;CACR,aAAa,CAAC;CAEd,gBAAgB,CAAC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AAI,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,EAAE,MAAM,WAAW;AAC3B;;;;;;;;AC5WA,eAA8B,KAAK,MAAgC;CAElE,QAAQ,MAAM,SAAS,IADP,IAAI,MAAM,SAAS,SAAS,IACrB,CAAG,EAAA,CAAG,SAAS;AACvC"}
|
package/dist/nav.d.mts
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
import { n as ParseRouteParams, t as ExactRouteParams } from "./ParseRouteParams-BtC0eH3z.mjs";
|
|
2
2
|
import { t as TypedResponse } from "./TypedResponse-6lznqN4U.mjs";
|
|
3
|
+
import { t as StandardSchemaV1 } from "./StandardSchema-D28L8_zZ.mjs";
|
|
3
4
|
//#region src/nav/api.d.ts
|
|
5
|
+
/** The methods whose argument is a query object rather than a request body. */
|
|
6
|
+
type QueryMethod = "get" | "head";
|
|
7
|
+
/** A value a client call can serialize into a query param. Arrays repeat the key. */
|
|
8
|
+
type ApiQueryValue = string | number | boolean | bigint | Date | null | undefined;
|
|
9
|
+
/** The loose query object accepted for handlers that declare no schema. */
|
|
10
|
+
type ApiQuery = Record<string, ApiQueryValue | readonly ApiQueryValue[]>;
|
|
4
11
|
/**
|
|
5
12
|
* The value a client call resolves to: the endpoint's typed JSON body when it
|
|
6
13
|
* returns a typed response, or the raw Response when the body isn't JSON.
|
|
@@ -15,8 +22,22 @@ type ApiResult<Handler> = Handler extends ((event: any) => any) ? Awaited<Return
|
|
|
15
22
|
type ApiRequestBody<Handler> = Handler extends ((event: infer Event) => any) ? Event extends {
|
|
16
23
|
json: () => Promise<infer Body>;
|
|
17
24
|
} ? unknown extends Body ? BodyInit | object : Body : BodyInit | object : BodyInit | object;
|
|
25
|
+
/**
|
|
26
|
+
* The endpoint's declared schemas, when it has any. Handles both a `satisfies`
|
|
27
|
+
* export (where `schema` is present) and an endpoint annotated as
|
|
28
|
+
* `ServerEndPoint`, where it is optional. `never` when there are none.
|
|
29
|
+
*/
|
|
30
|
+
type EndpointSchemas<Endpoint extends object> = NonNullable<[Endpoint] extends [{
|
|
31
|
+
schema?: infer Schemas;
|
|
32
|
+
}] ? Schemas : undefined>;
|
|
33
|
+
/**
|
|
34
|
+
* The query object a client call accepts for a handler: the output of the
|
|
35
|
+
* endpoint's get/head schema (validated and typed by it), or a loose record
|
|
36
|
+
* when the handler declares no schema.
|
|
37
|
+
*/
|
|
38
|
+
type ApiQueryFor<Endpoint extends object, Method extends string> = [EndpointSchemas<Endpoint>] extends [never] ? ApiQuery : EndpointSchemas<Endpoint> extends (infer Schemas) ? Schemas extends Record<string, unknown> ? Method extends keyof Schemas ? Schemas[Method] extends StandardSchemaV1 ? StandardSchemaV1.InferOutput<Schemas[Method]> : ApiQuery : ApiQuery : ApiQuery : ApiQuery;
|
|
18
39
|
/** The callable methods of an endpoint, one per handler it defines. */
|
|
19
|
-
type ApiMethods<Endpoint extends object> = { [Method in string & keyof Endpoint as NonNullable<Endpoint[Method]> extends ((event: any) => any) ? Method : never]: (body?: ApiRequestBody<NonNullable<Endpoint[Method]>>, init?: RequestInit) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>; };
|
|
40
|
+
type ApiMethods<Endpoint extends object> = { [Method in string & keyof Endpoint as NonNullable<Endpoint[Method]> extends ((event: any) => any) ? Method : never]: Method extends QueryMethod ? (query?: ApiQueryFor<Endpoint, Method>, init?: RequestInit) => Promise<ApiResult<NonNullable<Endpoint[Method]>>> : (body?: ApiRequestBody<NonNullable<Endpoint[Method]>>, init?: RequestInit) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>; };
|
|
20
41
|
/**
|
|
21
42
|
* Creates typed client callers for a `+server` endpoint, e.g.
|
|
22
43
|
*
|
|
@@ -31,6 +52,11 @@ type ApiMethods<Endpoint extends object> = { [Method in string & keyof Endpoint
|
|
|
31
52
|
* parsed; non-JSON responses resolve to the raw Response. Failed requests
|
|
32
53
|
* (non-2xx) throw.
|
|
33
54
|
*
|
|
55
|
+
* `get` and `head` take a query object, typed by the handler's schema when it
|
|
56
|
+
* declares one, which is serialized into the query string (arrays repeat the
|
|
57
|
+
* key, `undefined`/`null` values are skipped). Other methods take a request
|
|
58
|
+
* body: objects are sent as JSON.
|
|
59
|
+
*
|
|
34
60
|
* @param path The endpoint's route path
|
|
35
61
|
* @param params The route params, required if the path has dynamic segments
|
|
36
62
|
* @returns An object with one caller per handler defined by the endpoint
|
|
@@ -39,13 +65,16 @@ declare function makeApi<Route extends string, Endpoint extends object, Params e
|
|
|
39
65
|
//#endregion
|
|
40
66
|
//#region src/nav/load.d.ts
|
|
41
67
|
/**
|
|
42
|
-
* Loads and renders the page at the supplied path.
|
|
68
|
+
* Loads and renders the page at the supplied path. Returns whether the page
|
|
69
|
+
* was rendered in place: `false` when the document has to take over (a
|
|
70
|
+
* `+server` route, a redirect, or a failed navigation).
|
|
43
71
|
*/
|
|
44
72
|
declare function load(path: string): Promise<boolean>;
|
|
45
73
|
//#endregion
|
|
46
74
|
//#region src/nav/reload.d.ts
|
|
47
75
|
/**
|
|
48
|
-
* Reloads data for the currently loaded page and rerenders it.
|
|
76
|
+
* Reloads data for the currently loaded page and rerenders it. Returns whether
|
|
77
|
+
* the page was rendered in place (see `load`).
|
|
49
78
|
*/
|
|
50
79
|
declare function reload(): Promise<boolean>;
|
|
51
80
|
//#endregion
|
|
@@ -63,6 +92,30 @@ declare function reload(): Promise<boolean>;
|
|
|
63
92
|
*/
|
|
64
93
|
declare function route<Route extends string, Params extends ParseRouteParams<Route> = ParseRouteParams<Route>>(path: Route, ...args: string extends Route ? [params?: Record<string, string>] : keyof ParseRouteParams<Route> extends never ? [] : [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]): string;
|
|
65
94
|
//#endregion
|
|
95
|
+
//#region src/nav/formSubmit.d.ts
|
|
96
|
+
/**
|
|
97
|
+
* The detail of the `torpor:submit-failed` window event.
|
|
98
|
+
*/
|
|
99
|
+
type SubmitFailureDetail = {
|
|
100
|
+
/** The url the form was submitted to. */
|
|
101
|
+
action: string;
|
|
102
|
+
/** The failure that stopped the submit. */
|
|
103
|
+
error?: unknown;
|
|
104
|
+
};
|
|
105
|
+
//#endregion
|
|
106
|
+
//#region src/nav/navigationFailure.d.ts
|
|
107
|
+
/**
|
|
108
|
+
* The detail of the `torpor:navigation-failed` window event.
|
|
109
|
+
*/
|
|
110
|
+
type NavigationFailureDetail = {
|
|
111
|
+
/** The url the navigation was headed to. */
|
|
112
|
+
href: string;
|
|
113
|
+
/** Why the page was kept: the network is unreachable. */
|
|
114
|
+
reason: "offline";
|
|
115
|
+
/** The failure that would have triggered the document fallback. */
|
|
116
|
+
error?: unknown;
|
|
117
|
+
};
|
|
118
|
+
//#endregion
|
|
66
119
|
//#region src/dataRequest.d.ts
|
|
67
120
|
/**
|
|
68
121
|
* The request header a client data request sets.
|
|
@@ -87,5 +140,13 @@ export declare const DATA_REQUEST_HEADER = "X-Torpor-Data";
|
|
|
87
140
|
*/
|
|
88
141
|
export declare const DATA_REUSE_HEADER = "X-Torpor-Reuse";
|
|
89
142
|
//#endregion
|
|
90
|
-
|
|
143
|
+
//#region src/nav.d.ts
|
|
144
|
+
declare global {
|
|
145
|
+
interface WindowEventMap {
|
|
146
|
+
"torpor:navigation-failed": CustomEvent<NavigationFailureDetail>;
|
|
147
|
+
"torpor:submit-failed": CustomEvent<SubmitFailureDetail>;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
//#endregion
|
|
151
|
+
export { type ApiMethods, type ApiQuery, type ApiQueryValue, type NavigationFailureDetail, type SubmitFailureDetail, load, makeApi, reload, route };
|
|
91
152
|
//# sourceMappingURL=nav.d.mts.map
|
package/dist/nav.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nav.d.mts","names":[],"sources":["../src/nav/api.ts","../src/nav/load.ts","../src/nav/reload.ts","../src/nav/route.ts","../src/dataRequest.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"nav.d.mts","names":[],"sources":["../src/nav/api.ts","../src/nav/load.ts","../src/nav/reload.ts","../src/nav/route.ts","../src/nav/formSubmit.ts","../src/nav/navigationFailure.ts","../src/dataRequest.ts","../src/nav.ts"],"mappings":";;;;;KAMK;;KAGO,qDAAqD;;KAGrD,WAAW,eAAe,yBAAyB;;;;;;KAO1D,UAAU,WAAW,kBAAiB,sBACxC,QAAQ,WAAW,kBAAkB,oBAAoB,QACxD,OAAO;;;;;;KASN,eAAe,WAAW,kBAAiB,aAAa,iBAC1D;EAAgB,YAAY,cAAc;oBACzB,OACf,oBACA,OACD,oBACD;;;;;;KAOE,gBAAgB,2BAA2B,aAC9C;EAAqB,eAAe;KAAa;;;;;;KAQ9C,YAAY,yBAAyB,0BACzC,gBAAgB,6BAEd,WACA,gBAAgB,yBAAwB,WACvC,gBAAgB,0BACf,qBAAqB,UACpB,QAAQ,gBAAgB,mBACvB,iBAAiB,YAAY,QAAQ,WACrC,WACD,WACD,WACD;;KAGQ,WAAW,8BAErB,yBAAyB,YAAY,YAAY,SAAS,mBAAkB,sBACzE,iBAED,eAAe,eAEf,QAAQ,YAAY,UAAU,SAC9B,OAAO,gBACH,QAAQ,UAAU,YAAY,SAAS,cAE3C,OAAO,eAAe,YAAY,SAAS,WAC3C,OAAO,gBACH,QAAQ,UAAU,YAAY,SAAS;;;;;;;;;;;;;;;;;;;;;;;;iBA4BvB,QACvB,sBACA,yBACA,eAAe,iBAAiB,SAAS,iBAAiB,QAE1D,MAAM,UAGH,qBAAqB,SACpB,SAAS,gCACJ,iBAAiB,6BAErB,QAAQ,SAAS,iBAAiB,QAAQ,iBAAiB,WAC9D,WAAW;;;;;;;;iBClHgB,KAAK,eAAe;;;;;;;iBCDpB,UAAU;;;;;;;;;;;;;;iBCQhB,MACvB,sBACA,eAAe,iBAAiB,SAAS,iBAAiB,QAE1D,MAAM,UACH,qBAAqB,SACpB,SAAS,gCACJ,iBAAiB,6BAErB,QAAQ,SAAS,iBAAiB,QAAQ,iBAAiB;;;;;;KChBrD;;EAEX;;EAEA;;;;;;;KCNW;;EAEX;;EAEA;;EAEA;;;;;;;;;;;;;;;;;;;qBCIY;;;;;;qBAOA;;;QCdE;YACJ;IACT,4BAA4B,YAAY;IACxC,wBAAwB,YAAY"}
|
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-BODDzmH0.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
|
/**
|
|
@@ -47,6 +47,11 @@ const METHODS = [
|
|
|
47
47
|
* parsed; non-JSON responses resolve to the raw Response. Failed requests
|
|
48
48
|
* (non-2xx) throw.
|
|
49
49
|
*
|
|
50
|
+
* `get` and `head` take a query object, typed by the handler's schema when it
|
|
51
|
+
* declares one, which is serialized into the query string (arrays repeat the
|
|
52
|
+
* key, `undefined`/`null` values are skipped). Other methods take a request
|
|
53
|
+
* body: objects are sent as JSON.
|
|
54
|
+
*
|
|
50
55
|
* @param path The endpoint's route path
|
|
51
56
|
* @param params The route params, required if the path has dynamic segments
|
|
52
57
|
* @returns An object with one caller per handler defined by the endpoint
|
|
@@ -54,24 +59,47 @@ const METHODS = [
|
|
|
54
59
|
function makeApi(path, ...args) {
|
|
55
60
|
const url = route(path, ...args);
|
|
56
61
|
const api = {};
|
|
57
|
-
for (const method of METHODS) api[method] = (
|
|
62
|
+
for (const method of METHODS) api[method] = (arg, init) => request(method, url, arg, init);
|
|
58
63
|
return api;
|
|
59
64
|
}
|
|
60
|
-
async function request(method, url,
|
|
65
|
+
async function request(method, url, arg, init) {
|
|
66
|
+
const httpMethod = method === "del" ? "delete" : method;
|
|
67
|
+
const isQueryMethod = method === "get" || method === "head";
|
|
68
|
+
const target = isQueryMethod ? appendQuery(url, arg) : url;
|
|
61
69
|
const options = {
|
|
62
|
-
method:
|
|
70
|
+
method: httpMethod.toUpperCase(),
|
|
63
71
|
...init
|
|
64
72
|
};
|
|
65
|
-
if (
|
|
66
|
-
if (typeof
|
|
73
|
+
if (!isQueryMethod && arg !== void 0 && options.body === void 0) {
|
|
74
|
+
if (typeof arg === "object") {
|
|
67
75
|
options.headers ??= { "Content-Type": "application/json" };
|
|
68
|
-
options.body = JSON.stringify(
|
|
69
|
-
} else options.body =
|
|
76
|
+
options.body = JSON.stringify(arg);
|
|
77
|
+
} else options.body = arg;
|
|
70
78
|
}
|
|
71
|
-
const response = await fetch(
|
|
72
|
-
if (!response.ok) throw new Error(`API ${method.toUpperCase()} ${
|
|
79
|
+
const response = await fetch(target, options);
|
|
80
|
+
if (!response.ok) throw new Error(`API ${method.toUpperCase()} ${target} failed: ${response.status}`);
|
|
73
81
|
return (response.headers.get("Content-Type") ?? "").includes("application/json") ? await response.json() : response;
|
|
74
82
|
}
|
|
83
|
+
/**
|
|
84
|
+
* Appends a query object to a url: arrays repeat the key, `undefined` and
|
|
85
|
+
* `null` values are skipped, and `Date`s are sent as ISO strings. Values are
|
|
86
|
+
* URI-encoded. Nested objects can't be represented in a query string, so they
|
|
87
|
+
* throw rather than being silently stringified.
|
|
88
|
+
*/
|
|
89
|
+
function appendQuery(url, query) {
|
|
90
|
+
if (query === void 0 || query === null) return url;
|
|
91
|
+
if (typeof query !== "object" || Array.isArray(query)) throw new TypeError("A GET or HEAD query must be an object");
|
|
92
|
+
const params = new URLSearchParams();
|
|
93
|
+
for (const [key, value] of Object.entries(query)) for (const item of Array.isArray(value) ? value : [value]) {
|
|
94
|
+
if (item === void 0 || item === null) continue;
|
|
95
|
+
if (item instanceof Date) params.append(key, item.toISOString());
|
|
96
|
+
else if (typeof item === "object") throw new TypeError(`Cannot serialize the query value for "${key}": only strings, numbers, booleans, bigints, Dates and arrays of them are supported`);
|
|
97
|
+
else params.append(key, String(item));
|
|
98
|
+
}
|
|
99
|
+
const search = params.toString();
|
|
100
|
+
if (!search) return url;
|
|
101
|
+
return url + (url.includes("?") ? "&" : "?") + search;
|
|
102
|
+
}
|
|
75
103
|
//#endregion
|
|
76
104
|
export { DATA_REQUEST_HEADER, DATA_REUSE_HEADER, load, makeApi, reload, route };
|
|
77
105
|
|
package/dist/nav.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nav.mjs","names":[],"sources":["../src/nav/route.ts","../src/nav/api.ts"],"sourcesContent":["import { addBaseToPath, getBasePath } from \"../site/basePath\";\nimport type { ExactRouteParams, ParseRouteParams } from \"../types/ParseRouteParams\";\n\n/**\n * Builds a route path in a type-safe manner, filling in dynamic segments, e.g.\n * `route(\"/posts/[id]\", { id: 5 })` returns `/posts/5`. The params object is\n * checked for exact keys: missing or unknown params error at compile time.\n *\n * NOTE: The rest args conditional must stay INLINE — routing it through a type\n * alias defeats `Params` inference, and excess keys stop being checked\n * @param path The route path\n * @param params The route params, required if the path has dynamic segments\n * @returns The path with the params filled in, URI-encoded\n */\nexport default function route<\n\tRoute extends string,\n\tParams extends ParseRouteParams<Route> = ParseRouteParams<Route>,\n>(\n\tpath: Route,\n\t...args: string extends Route\n\t\t? [params?: Record<string, string>]\n\t\t: keyof ParseRouteParams<Route> extends never\n\t\t\t? []\n\t\t\t: [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]\n): string {\n\tconst params = ((args as unknown[])[0] ?? {}) as Record<string, string>;\n\tconst filled = path.replace(\n\t\t/\\[(\\.\\.\\.)?([^\\]]+)\\]/g,\n\t\t(_, splat: string | undefined, name: string) => {\n\t\t\tconst value = params[name];\n\t\t\tif (value === undefined) {\n\t\t\t\tthrow new Error(`Missing param '${name}' for route '${path}'`);\n\t\t\t}\n\t\t\treturn splat\n\t\t\t\t? value\n\t\t\t\t\t\t.split(\"/\")\n\t\t\t\t\t\t.map((segment) => encodeURIComponent(segment))\n\t\t\t\t\t\t.join(\"/\")\n\t\t\t\t: encodeURIComponent(String(value));\n\t\t},\n\t);\n\t// Links are written base-free; the router strips the base before matching\n\treturn addBaseToPath(filled, getBasePath());\n}\n","import type { ExactRouteParams, ParseRouteParams } from \"../types/ParseRouteParams\";\nimport type TypedResponse from \"../response/TypedResponse\";\nimport route from \"./route\";\n\n/**\n * The value a client call resolves to: the endpoint's typed JSON body when it\n * returns a typed response, or the raw Response when the body isn't JSON.\n * Untyped endpoints resolve to `unknown`.\n */\ntype ApiResult<Handler> = Handler extends (event: any) => any\n\t? Awaited<ReturnType<Handler>> extends TypedResponse<infer Body>\n\t\t? Body | Response\n\t\t: unknown\n\t: never;\n\n/**\n * The body a client call accepts: the endpoint event's annotated JSON body\n * type (from `ServerLoadEvent<Route, Body>`), or a loose value when the\n * handler doesn't annotate one.\n */\ntype ApiRequestBody<Handler> = Handler extends (event: infer Event) => any\n\t? Event extends { json: () => Promise<infer Body> }\n\t\t? unknown extends Body\n\t\t\t? BodyInit | object\n\t\t\t: Body\n\t\t: BodyInit | object\n\t: BodyInit | object;\n\n/** The callable methods of an endpoint, one per handler it defines. */\nexport type ApiMethods<Endpoint extends object> = {\n\t[\n\t\tMethod in string & keyof Endpoint as NonNullable<Endpoint[Method]> extends (event: any) => any\n\t\t\t? Method\n\t\t\t: never\n\t]: (\n\t\tbody?: ApiRequestBody<NonNullable<Endpoint[Method]>>,\n\t\tinit?: RequestInit,\n\t) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>;\n};\n\nconst METHODS = [\"get\", \"post\", \"patch\", \"put\", \"del\", \"options\", \"head\"] as const;\n\n/**\n * Creates typed client callers for a `+server` endpoint, e.g.\n *\n * ```ts\n * import type endpoint from \"@/routes/api/posts/[id]/+server\";\n * const post = makeApi<\"/api/posts/[id]\", typeof endpoint>(\"/api/posts/[id]\");\n * const data = await post.get(); // typed from the endpoint's responses\n * ```\n *\n * Method names match the endpoint's handlers (`del` for DELETE). Params are\n * filled in and URI-encoded from the route path, and JSON responses are\n * parsed; non-JSON responses resolve to the raw Response. Failed requests\n * (non-2xx) throw.\n *\n * @param path The endpoint's route path\n * @param params The route params, required if the path has dynamic segments\n * @returns An object with one caller per handler defined by the endpoint\n */\nexport default function makeApi<\n\tRoute extends string,\n\tEndpoint extends object,\n\tParams extends ParseRouteParams<Route> = ParseRouteParams<Route>,\n>(\n\tpath: Route,\n\t// NOTE: The rest args conditional must stay INLINE — routing it through a\n\t// type alias defeats `Params` inference, and excess keys stop being checked\n\t...args: string extends Route\n\t\t? [params?: Record<string, string>]\n\t\t: keyof ParseRouteParams<Route> extends never\n\t\t\t? []\n\t\t\t: [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]\n): ApiMethods<Endpoint> {\n\tconst url = route(path as string, ...(args as [params?: Record<string, string>]));\n\tconst api: Record<string, (body?: unknown, init?: RequestInit) => Promise<unknown>> = {};\n\tfor (const method of METHODS) {\n\t\tapi[method] = (body, init) => request(method, url, body, init);\n\t}\n\treturn api as ApiMethods<Endpoint>;\n}\n\nasync function request(\n\tmethod: string,\n\turl: string,\n\tbody: unknown,\n\tinit?: RequestInit,\n): Promise<unknown> {\n\t// `del` is the endpoint handler name for DELETE requests\n\tconst httpMethod = method === \"del\" ? \"delete\" : method;\n\tconst options: RequestInit = { method: httpMethod.toUpperCase(), ...init };\n\tif (body !== undefined && options.body === undefined && method !== \"get\" && method !== \"head\") {\n\t\tif (typeof body === \"object\") {\n\t\t\toptions.headers ??= { \"Content-Type\": \"application/json\" };\n\t\t\toptions.body = JSON.stringify(body);\n\t\t} else {\n\t\t\toptions.body = body as BodyInit;\n\t\t}\n\t}\n\tconst response = await fetch(url, options);\n\tif (!response.ok) {\n\t\tthrow new Error(`API ${method.toUpperCase()} ${url} failed: ${response.status}`);\n\t}\n\tconst contentType = response.headers.get(\"Content-Type\") ?? \"\";\n\treturn contentType.includes(\"application/json\") ? await response.json() : response;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAwB,MAIvB,MACA,GAAG,MAKM;CACT,MAAM,SAAW,KAAmB,MAAM,CAAC;CAC3C,MAAM,SAAS,KAAK,QACnB,2BACC,GAAG,OAA2B,SAAiB;EAC/C,MAAM,QAAQ,OAAO;EACrB,IAAI,UAAU,KAAA,GACb,MAAM,IAAI,MAAM,kBAAkB,KAAK,eAAe,KAAK,EAAE;EAE9D,OAAO,QACJ,MACC,MAAM,GAAG,CAAC,CACV,KAAK,YAAY,mBAAmB,OAAO,CAAC,CAAC,CAC7C,KAAK,GAAG,IACT,mBAAmB,OAAO,KAAK,CAAC;CACpC,CACD;CAEA,OAAO,cAAc,QAAQ,YAAY,CAAC;AAC3C;;;ACHA,MAAM,UAAU;CAAC;CAAO;CAAQ;CAAS;CAAO;CAAO;CAAW;AAAM;;;;;;;;;;;;;;;;;;;AAoBxE,SAAwB,QAKvB,MAGA,GAAG,MAKoB;CACvB,MAAM,MAAM,MAAM,MAAgB,GAAI,IAA0C;CAChF,MAAM,MAAgF,CAAC;CACvF,KAAK,MAAM,UAAU,SACpB,IAAI,WAAW,MAAM,SAAS,QAAQ,QAAQ,KAAK,MAAM,IAAI;CAE9D,OAAO;AACR;AAEA,eAAe,QACd,QACA,KACA,MACA,MACmB;CAGnB,MAAM,UAAuB;EAAE,SADZ,WAAW,QAAQ,WAAW,OAAA,CACC,YAAY;EAAG,GAAG;CAAK;CACzE,IAAI,SAAS,KAAA,KAAa,QAAQ,SAAS,KAAA,KAAa,WAAW,SAAS,WAAW,QAAQ;EAC9F,IAAI,OAAO,SAAS,UAAU;GAC7B,QAAQ,YAAY,EAAE,gBAAgB,mBAAmB;GACzD,QAAQ,OAAO,KAAK,UAAU,IAAI;EACnC,OACC,QAAQ,OAAO;CAEjB;CACA,MAAM,WAAW,MAAM,MAAM,KAAK,OAAO;CACzC,IAAI,CAAC,SAAS,IACb,MAAM,IAAI,MAAM,OAAO,OAAO,YAAY,EAAE,GAAG,IAAI,WAAW,SAAS,QAAQ;CAGhF,QADoB,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAA,CACzC,SAAS,kBAAkB,IAAI,MAAM,SAAS,KAAK,IAAI;AAC3E"}
|
|
1
|
+
{"version":3,"file":"nav.mjs","names":[],"sources":["../src/nav/route.ts","../src/nav/api.ts"],"sourcesContent":["import { addBaseToPath, getBasePath } from \"../site/basePath\";\nimport type { ExactRouteParams, ParseRouteParams } from \"../types/ParseRouteParams\";\n\n/**\n * Builds a route path in a type-safe manner, filling in dynamic segments, e.g.\n * `route(\"/posts/[id]\", { id: 5 })` returns `/posts/5`. The params object is\n * checked for exact keys: missing or unknown params error at compile time.\n *\n * NOTE: The rest args conditional must stay INLINE — routing it through a type\n * alias defeats `Params` inference, and excess keys stop being checked\n * @param path The route path\n * @param params The route params, required if the path has dynamic segments\n * @returns The path with the params filled in, URI-encoded\n */\nexport default function route<\n\tRoute extends string,\n\tParams extends ParseRouteParams<Route> = ParseRouteParams<Route>,\n>(\n\tpath: Route,\n\t...args: string extends Route\n\t\t? [params?: Record<string, string>]\n\t\t: keyof ParseRouteParams<Route> extends never\n\t\t\t? []\n\t\t\t: [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]\n): string {\n\tconst params = ((args as unknown[])[0] ?? {}) as Record<string, string>;\n\tconst filled = path.replace(\n\t\t/\\[(\\.\\.\\.)?([^\\]]+)\\]/g,\n\t\t(_, splat: string | undefined, name: string) => {\n\t\t\tconst value = params[name];\n\t\t\tif (value === undefined) {\n\t\t\t\tthrow new Error(`Missing param '${name}' for route '${path}'`);\n\t\t\t}\n\t\t\treturn splat\n\t\t\t\t? value\n\t\t\t\t\t\t.split(\"/\")\n\t\t\t\t\t\t.map((segment) => encodeURIComponent(segment))\n\t\t\t\t\t\t.join(\"/\")\n\t\t\t\t: encodeURIComponent(String(value));\n\t\t},\n\t);\n\t// Links are written base-free; the router strips the base before matching\n\treturn addBaseToPath(filled, getBasePath());\n}\n","import type { ExactRouteParams, ParseRouteParams } from \"../types/ParseRouteParams\";\nimport type { StandardSchemaV1 } from \"../types/StandardSchema\";\nimport type TypedResponse from \"../response/TypedResponse\";\nimport route from \"./route\";\n\n/** The methods whose argument is a query object rather than a request body. */\ntype QueryMethod = \"get\" | \"head\";\n\n/** A value a client call can serialize into a query param. Arrays repeat the key. */\nexport type ApiQueryValue = string | number | boolean | bigint | Date | null | undefined;\n\n/** The loose query object accepted for handlers that declare no schema. */\nexport type ApiQuery = Record<string, ApiQueryValue | readonly ApiQueryValue[]>;\n\n/**\n * The value a client call resolves to: the endpoint's typed JSON body when it\n * returns a typed response, or the raw Response when the body isn't JSON.\n * Untyped endpoints resolve to `unknown`.\n */\ntype ApiResult<Handler> = Handler extends (event: any) => any\n\t? Awaited<ReturnType<Handler>> extends TypedResponse<infer Body>\n\t\t? Body | Response\n\t\t: unknown\n\t: never;\n\n/**\n * The body a client call accepts: the endpoint event's annotated JSON body\n * type (from `ServerLoadEvent<Route, Body>`), or a loose value when the\n * handler doesn't annotate one.\n */\ntype ApiRequestBody<Handler> = Handler extends (event: infer Event) => any\n\t? Event extends { json: () => Promise<infer Body> }\n\t\t? unknown extends Body\n\t\t\t? BodyInit | object\n\t\t\t: Body\n\t\t: BodyInit | object\n\t: BodyInit | object;\n\n/**\n * The endpoint's declared schemas, when it has any. Handles both a `satisfies`\n * export (where `schema` is present) and an endpoint annotated as\n * `ServerEndPoint`, where it is optional. `never` when there are none.\n */\ntype EndpointSchemas<Endpoint extends object> = NonNullable<\n\t[Endpoint] extends [{ schema?: infer Schemas }] ? Schemas : undefined\n>;\n\n/**\n * The query object a client call accepts for a handler: the output of the\n * endpoint's get/head schema (validated and typed by it), or a loose record\n * when the handler declares no schema.\n */\ntype ApiQueryFor<Endpoint extends object, Method extends string> = [\n\tEndpointSchemas<Endpoint>,\n] extends [never]\n\t? ApiQuery\n\t: EndpointSchemas<Endpoint> extends infer Schemas\n\t\t? Schemas extends Record<string, unknown>\n\t\t\t? Method extends keyof Schemas\n\t\t\t\t? Schemas[Method] extends StandardSchemaV1\n\t\t\t\t\t? StandardSchemaV1.InferOutput<Schemas[Method]>\n\t\t\t\t\t: ApiQuery\n\t\t\t\t: ApiQuery\n\t\t\t: ApiQuery\n\t\t: ApiQuery;\n\n/** The callable methods of an endpoint, one per handler it defines. */\nexport type ApiMethods<Endpoint extends object> = {\n\t[\n\t\tMethod in string & keyof Endpoint as NonNullable<Endpoint[Method]> extends (event: any) => any\n\t\t\t? Method\n\t\t\t: never\n\t]: Method extends QueryMethod\n\t\t? (\n\t\t\t\tquery?: ApiQueryFor<Endpoint, Method>,\n\t\t\t\tinit?: RequestInit,\n\t\t\t) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>\n\t\t: (\n\t\t\t\tbody?: ApiRequestBody<NonNullable<Endpoint[Method]>>,\n\t\t\t\tinit?: RequestInit,\n\t\t\t) => Promise<ApiResult<NonNullable<Endpoint[Method]>>>;\n};\n\nconst METHODS = [\"get\", \"post\", \"patch\", \"put\", \"del\", \"options\", \"head\"] as const;\n\n/**\n * Creates typed client callers for a `+server` endpoint, e.g.\n *\n * ```ts\n * import type endpoint from \"@/routes/api/posts/[id]/+server\";\n * const post = makeApi<\"/api/posts/[id]\", typeof endpoint>(\"/api/posts/[id]\");\n * const data = await post.get(); // typed from the endpoint's responses\n * ```\n *\n * Method names match the endpoint's handlers (`del` for DELETE). Params are\n * filled in and URI-encoded from the route path, and JSON responses are\n * parsed; non-JSON responses resolve to the raw Response. Failed requests\n * (non-2xx) throw.\n *\n * `get` and `head` take a query object, typed by the handler's schema when it\n * declares one, which is serialized into the query string (arrays repeat the\n * key, `undefined`/`null` values are skipped). Other methods take a request\n * body: objects are sent as JSON.\n *\n * @param path The endpoint's route path\n * @param params The route params, required if the path has dynamic segments\n * @returns An object with one caller per handler defined by the endpoint\n */\nexport default function makeApi<\n\tRoute extends string,\n\tEndpoint extends object,\n\tParams extends ParseRouteParams<Route> = ParseRouteParams<Route>,\n>(\n\tpath: Route,\n\t// NOTE: The rest args conditional must stay INLINE — routing it through a\n\t// type alias defeats `Params` inference, and excess keys stop being checked\n\t...args: string extends Route\n\t\t? [params?: Record<string, string>]\n\t\t: keyof ParseRouteParams<Route> extends never\n\t\t\t? []\n\t\t\t: [params: Params & ExactRouteParams<Params, ParseRouteParams<Route>>]\n): ApiMethods<Endpoint> {\n\tconst url = route(path as string, ...(args as [params?: Record<string, string>]));\n\tconst api: Record<string, (arg?: unknown, init?: RequestInit) => Promise<unknown>> = {};\n\tfor (const method of METHODS) {\n\t\tapi[method] = (arg, init) => request(method, url, arg, init);\n\t}\n\treturn api as ApiMethods<Endpoint>;\n}\n\nasync function request(\n\tmethod: string,\n\turl: string,\n\targ: unknown,\n\tinit?: RequestInit,\n): Promise<unknown> {\n\t// `del` is the endpoint handler name for DELETE requests\n\tconst httpMethod = method === \"del\" ? \"delete\" : method;\n\tconst isQueryMethod = method === \"get\" || method === \"head\";\n\t// GET and HEAD take a query object (there is no request body to send)\n\tconst target = isQueryMethod ? appendQuery(url, arg) : url;\n\tconst options: RequestInit = { method: httpMethod.toUpperCase(), ...init };\n\tif (!isQueryMethod && arg !== undefined && options.body === undefined) {\n\t\tif (typeof arg === \"object\") {\n\t\t\toptions.headers ??= { \"Content-Type\": \"application/json\" };\n\t\t\toptions.body = JSON.stringify(arg);\n\t\t} else {\n\t\t\toptions.body = arg as BodyInit;\n\t\t}\n\t}\n\tconst response = await fetch(target, options);\n\tif (!response.ok) {\n\t\tthrow new Error(`API ${method.toUpperCase()} ${target} failed: ${response.status}`);\n\t}\n\tconst contentType = response.headers.get(\"Content-Type\") ?? \"\";\n\treturn contentType.includes(\"application/json\") ? await response.json() : response;\n}\n\n/**\n * Appends a query object to a url: arrays repeat the key, `undefined` and\n * `null` values are skipped, and `Date`s are sent as ISO strings. Values are\n * URI-encoded. Nested objects can't be represented in a query string, so they\n * throw rather than being silently stringified.\n */\nfunction appendQuery(url: string, query: unknown): string {\n\tif (query === undefined || query === null) return url;\n\tif (typeof query !== \"object\" || Array.isArray(query)) {\n\t\tthrow new TypeError(\"A GET or HEAD query must be an object\");\n\t}\n\tconst params = new URLSearchParams();\n\tfor (const [key, value] of Object.entries(query as Record<string, unknown>)) {\n\t\tfor (const item of Array.isArray(value) ? value : [value]) {\n\t\t\tif (item === undefined || item === null) continue;\n\t\t\tif (item instanceof Date) {\n\t\t\t\tparams.append(key, item.toISOString());\n\t\t\t} else if (typeof item === \"object\") {\n\t\t\t\tthrow new TypeError(\n\t\t\t\t\t`Cannot serialize the query value for \"${key}\": only strings, numbers, ` +\n\t\t\t\t\t\t`booleans, bigints, Dates and arrays of them are supported`,\n\t\t\t\t);\n\t\t\t} else {\n\t\t\t\tparams.append(key, String(item));\n\t\t\t}\n\t\t}\n\t}\n\tconst search = params.toString();\n\tif (!search) return url;\n\treturn url + (url.includes(\"?\") ? \"&\" : \"?\") + search;\n}\n"],"mappings":";;;;;;;;;;;;;;;AAcA,SAAwB,MAIvB,MACA,GAAG,MAKM;CACT,MAAM,SAAW,KAAmB,MAAM,CA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AG,OAAO,WAAW,SAAS,QAAQ;CAGnF,QADoB,SAAS,QAAQ,IAAI,cAAc,KAAK,GAAA,CACzC,SAAS,kBAAkB,IAAI,MAAM,SAAS,KAAK,IAAI;AAC3E;;;;;;;AAQA,SAAS,YAAY,KAAa,OAAwB;CACzD,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,IAAI,OAAO,UAAU,YAAY,MAAM,QAAQ,KAAK,GACnD,MAAM,IAAI,UAAU,uCAAuC;CAE5D,MAAM,SAAS,IAAI,gBAAgB;CACnC,KAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,GACzE,KAAK,MAAM,QAAQ,MAAM,QAAQ,KAAK,IAAI,QAAQ,CAAC,KAAK,GAAG;EAC1D,IAAI,SAAS,KAAA,KAAa,SAAS,MAAM;EACzC,IAAI,gBAAgB,MACnB,OAAO,OAAO,KAAK,KAAK,YAAY,CAAC;OAC/B,IAAI,OAAO,SAAS,UAC1B,MAAM,IAAI,UACT,yCAAyC,IAAI,oFAE9C;OAEA,OAAO,OAAO,KAAK,OAAO,IAAI,CAAC;CAEjC;CAED,MAAM,SAAS,OAAO,SAAS;CAC/B,IAAI,CAAC,QAAQ,OAAO;CACpB,OAAO,OAAO,IAAI,SAAS,GAAG,IAAI,MAAM,OAAO;AAChD"}
|
package/dist/nodeDev.d.mts
CHANGED
package/dist/nodeDev.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export { t as nodeDev } from "./devPlugin-
|
|
1
|
+
export { t as nodeDev } from "./devPlugin-D9b5uhzm.mjs";
|
package/dist/openapi.d.mts
CHANGED
|
@@ -1,82 +1,5 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
//#region src/openapi/types.d.ts
|
|
4
|
-
/**
|
|
5
|
-
* A JSON Schema object, as produced by a schema library's converter (e.g.
|
|
6
|
-
* `z.toJSONSchema`, valibot's `toJsonSchema`, arktype's `toJsonSchema`).
|
|
7
|
-
*/
|
|
8
|
-
type JsonSchema = Record<string, unknown>;
|
|
9
|
-
/**
|
|
10
|
-
* Converts a Standard Schema (zod, valibot, arktype, ...) into a JSON Schema
|
|
11
|
-
* object, for inclusion in an OpenAPI document. Supplied to the openApi
|
|
12
|
-
* plugin, since each schema library has its own conversion function:
|
|
13
|
-
*
|
|
14
|
-
* ```ts
|
|
15
|
-
* // zod
|
|
16
|
-
* openApi({ toJsonSchema: (s) => z.toJSONSchema(s as z.ZodType, { io: "input" }) })
|
|
17
|
-
* // arktype
|
|
18
|
-
* openApi({ toJsonSchema: (s) => (s as Type).toJsonSchema() })
|
|
19
|
-
* ```
|
|
20
|
-
*/
|
|
21
|
-
type ToJsonSchema = (schema: StandardSchemaV1) => JsonSchema;
|
|
22
|
-
/**
|
|
23
|
-
* Options for the openApi plugin.
|
|
24
|
-
*/
|
|
25
|
-
type OpenApiPluginOptions = {
|
|
26
|
-
/**
|
|
27
|
-
* The path to serve the OpenAPI document at. Defaults to `/openapi.json`.
|
|
28
|
-
*/
|
|
29
|
-
path?: string;
|
|
30
|
-
/**
|
|
31
|
-
* The path to serve interactive API docs at, or `false` to disable the
|
|
32
|
-
* docs page. Defaults to `/docs`.
|
|
33
|
-
*/
|
|
34
|
-
docs?: string | false;
|
|
35
|
-
/**
|
|
36
|
-
* The API title for the document's `info` section. Defaults to `"API"`.
|
|
37
|
-
*/
|
|
38
|
-
title?: string;
|
|
39
|
-
/**
|
|
40
|
-
* The API version for the document's `info` section. Defaults to
|
|
41
|
-
* `"1.0.0"`.
|
|
42
|
-
*/
|
|
43
|
-
version?: string;
|
|
44
|
-
/**
|
|
45
|
-
* Converts an endpoint's schemas into JSON Schema. Required for endpoints
|
|
46
|
-
* that declare schemas; endpoints without schemas are documented with
|
|
47
|
-
* their paths and methods only.
|
|
48
|
-
*/
|
|
49
|
-
toJsonSchema?: ToJsonSchema;
|
|
50
|
-
};
|
|
51
|
-
/**
|
|
52
|
-
* OpenApi options with defaults applied. Created by the openApi plugin and
|
|
53
|
-
* consumed by the document builder.
|
|
54
|
-
*/
|
|
55
|
-
type ResolvedOpenApiOptions = {
|
|
56
|
-
path: string;
|
|
57
|
-
/** Undefined when the docs page is disabled */
|
|
58
|
-
docs: string | undefined;
|
|
59
|
-
title: string;
|
|
60
|
-
version: string;
|
|
61
|
-
toJsonSchema: ToJsonSchema | undefined;
|
|
62
|
-
};
|
|
63
|
-
/**
|
|
64
|
-
* A ServerEndPoint shape, loosely typed so that endpoint modules loaded from
|
|
65
|
-
* anywhere can be passed to the document builder.
|
|
66
|
-
*/
|
|
67
|
-
type OpenApiEndPoint = {
|
|
68
|
-
schema?: Record<string, StandardSchemaV1 | undefined> | undefined;
|
|
69
|
-
[method: string]: unknown;
|
|
70
|
-
};
|
|
71
|
-
/**
|
|
72
|
-
* A single API endpoint to include in an OpenAPI document: its route path
|
|
73
|
-
* (with `[param]` segments) and its default-exported endpoint object.
|
|
74
|
-
*/
|
|
75
|
-
type OpenApiRouteEntry = {
|
|
76
|
-
path: string;
|
|
77
|
-
endPoint: OpenApiEndPoint;
|
|
78
|
-
};
|
|
79
|
-
//#endregion
|
|
1
|
+
import { r as ServerLoadEvent } from "./ServerLoadEvent-F60w1TZt.mjs";
|
|
2
|
+
import { E as SitePlugin, _ as ResolvedOpenApiOptions, c as JsonSchema, d as OpenApiExtend, f as OpenApiLoader, g as OpenApiRouteEntry, h as OpenApiPluginOptions, l as OpenApiEndPoint, m as OpenApiOperation, p as OpenApiMethod, u as OpenApiEndpointOverrides, v as ToJsonSchema } from "./Site-CAeAqjkk.mjs";
|
|
80
3
|
//#region src/openapi/document.d.ts
|
|
81
4
|
/**
|
|
82
5
|
* Builds an OpenAPI 3.1 document from a list of +server endpoints.
|
|
@@ -134,11 +57,32 @@ export declare const OPEN_API_STATE_KEY: symbol;
|
|
|
134
57
|
* parameters, `get`/`head` schemas become query parameters, and
|
|
135
58
|
* `post`/`patch`/`put`/`del`/`options` schemas become request bodies.
|
|
136
59
|
*
|
|
60
|
+
* Pass `extend` to build the document per request (e.g. one per workspace),
|
|
61
|
+
* with the request's event available; `tb --openapi` writes the base document
|
|
62
|
+
* only.
|
|
63
|
+
*
|
|
137
64
|
* The resolved options are stored in `site.pluginState` under
|
|
138
65
|
* `OPEN_API_STATE_KEY`, which the manifest plugin reads at build time to
|
|
139
66
|
* generate the document endpoint.
|
|
140
67
|
*/
|
|
141
68
|
export declare function openApi(options?: OpenApiPluginOptions): SitePlugin;
|
|
142
69
|
//#endregion
|
|
143
|
-
|
|
70
|
+
//#region src/openapi/serve.d.ts
|
|
71
|
+
/**
|
|
72
|
+
* Creates the request handler for the OpenAPI document endpoint (the route the
|
|
73
|
+
* manifest plugin generates). The base document is built from the route
|
|
74
|
+
* loaders once, on the first request; each request then gets a copy with the
|
|
75
|
+
* plugin's `extend` hook applied, if it has one.
|
|
76
|
+
*
|
|
77
|
+
* The options come from a getter rather than being captured here: the
|
|
78
|
+
* generated module runs in the site, and reads them from `site.pluginState`
|
|
79
|
+
* at runtime, so functions like `toJsonSchema` and `extend` are the site's
|
|
80
|
+
* real functions instead of being serialized into the generated module.
|
|
81
|
+
*
|
|
82
|
+
* @param loaders Route path (with `[param]` segments) -> endpoint loader
|
|
83
|
+
* @param getOptions Reads the plugin's resolved options
|
|
84
|
+
*/
|
|
85
|
+
export declare function createOpenApiHandler(loaders: Record<string, OpenApiLoader>, getOptions: () => OpenApiPluginOptions): (event: ServerLoadEvent) => Promise<Response>;
|
|
86
|
+
//#endregion
|
|
87
|
+
export { type JsonSchema, type OpenApiEndPoint, type OpenApiEndpointOverrides, type OpenApiExtend, type OpenApiLoader, type OpenApiMethod, type OpenApiOperation, type OpenApiPluginOptions, type OpenApiRouteEntry, type ResolvedOpenApiOptions, type ToJsonSchema, buildOpenApiDocument, openApiDocsHtml };
|
|
144
88
|
//# sourceMappingURL=openapi.d.mts.map
|
package/dist/openapi.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"openapi.d.mts","names":[],"sources":["../src/openapi/
|
|
1
|
+
{"version":3,"file":"openapi.d.mts","names":[],"sources":["../src/openapi/document.ts","../src/openapi/docsHtml.ts","../src/openapi/plugin.ts","../src/openapi/serve.ts"],"mappings":";;;;;;;;;;;;;;;;iBA8BwB,qBACvB,SAAS,qBACT,SAAS,uBACP;;;;;;;iBC7BqB,gBAAgB;;;;;;;;;qBCM3B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAoCG,QAAQ,UAAS,uBAA4B;;;;;;;;;;;;;;;;;wBC5B7C,qBACf,SAAS,eAAe,gBACxB,kBAAkB,wBACf,OAAO,oBAAoB,QAAQ"}
|
package/dist/openapi.mjs
CHANGED
|
@@ -1 +1,36 @@
|
|
|
1
|
-
|
|
1
|
+
import { i as buildOpenApiDocument, n as openApi, r as openApiDocsHtml, t as OPEN_API_STATE_KEY } from "./plugin-BQsMnkTj.mjs";
|
|
2
|
+
//#region src/openapi/serve.ts
|
|
3
|
+
/**
|
|
4
|
+
* Creates the request handler for the OpenAPI document endpoint (the route the
|
|
5
|
+
* manifest plugin generates). The base document is built from the route
|
|
6
|
+
* loaders once, on the first request; each request then gets a copy with the
|
|
7
|
+
* plugin's `extend` hook applied, if it has one.
|
|
8
|
+
*
|
|
9
|
+
* The options come from a getter rather than being captured here: the
|
|
10
|
+
* generated module runs in the site, and reads them from `site.pluginState`
|
|
11
|
+
* at runtime, so functions like `toJsonSchema` and `extend` are the site's
|
|
12
|
+
* real functions instead of being serialized into the generated module.
|
|
13
|
+
*
|
|
14
|
+
* @param loaders Route path (with `[param]` segments) -> endpoint loader
|
|
15
|
+
* @param getOptions Reads the plugin's resolved options
|
|
16
|
+
*/
|
|
17
|
+
function createOpenApiHandler(loaders, getOptions) {
|
|
18
|
+
let base;
|
|
19
|
+
return async (event) => {
|
|
20
|
+
const options = getOptions();
|
|
21
|
+
if (!base) {
|
|
22
|
+
const entries = [];
|
|
23
|
+
for (const [routePath, load] of Object.entries(loaders)) entries.push({
|
|
24
|
+
path: routePath,
|
|
25
|
+
endPoint: (await load()).default
|
|
26
|
+
});
|
|
27
|
+
base = buildOpenApiDocument(entries, options);
|
|
28
|
+
}
|
|
29
|
+
const doc = options.extend ? await options.extend(structuredClone(base), event) : base;
|
|
30
|
+
return new Response(JSON.stringify(doc), { headers: { "Content-Type": "application/json" } });
|
|
31
|
+
};
|
|
32
|
+
}
|
|
33
|
+
//#endregion
|
|
34
|
+
export { OPEN_API_STATE_KEY, buildOpenApiDocument, createOpenApiHandler, openApi, openApiDocsHtml };
|
|
35
|
+
|
|
36
|
+
//# sourceMappingURL=openapi.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"openapi.mjs","names":[],"sources":["../src/openapi/serve.ts"],"sourcesContent":["import type ServerLoadEvent from \"../types/ServerLoadEvent\";\nimport buildOpenApiDocument from \"./document\";\nimport type { OpenApiLoader, OpenApiPluginOptions, OpenApiRouteEntry } from \"./types\";\n\n/**\n * Creates the request handler for the OpenAPI document endpoint (the route the\n * manifest plugin generates). The base document is built from the route\n * loaders once, on the first request; each request then gets a copy with the\n * plugin's `extend` hook applied, if it has one.\n *\n * The options come from a getter rather than being captured here: the\n * generated module runs in the site, and reads them from `site.pluginState`\n * at runtime, so functions like `toJsonSchema` and `extend` are the site's\n * real functions instead of being serialized into the generated module.\n *\n * @param loaders Route path (with `[param]` segments) -> endpoint loader\n * @param getOptions Reads the plugin's resolved options\n */\nexport function createOpenApiHandler(\n\tloaders: Record<string, OpenApiLoader>,\n\tgetOptions: () => OpenApiPluginOptions,\n): (event: ServerLoadEvent) => Promise<Response> {\n\tlet base: Record<string, unknown> | undefined;\n\treturn async (event) => {\n\t\tconst options = getOptions();\n\t\tif (!base) {\n\t\t\tconst entries: OpenApiRouteEntry[] = [];\n\t\t\tfor (const [routePath, load] of Object.entries(loaders)) {\n\t\t\t\tentries.push({ path: routePath, endPoint: (await load()).default });\n\t\t\t}\n\t\t\tbase = buildOpenApiDocument(entries, options);\n\t\t}\n\t\t// A fresh copy per request, so a hook can mutate it (merging in this\n\t\t// request's paths, say) without affecting the cached document or a\n\t\t// concurrent request\n\t\tconst doc = options.extend ? await options.extend(structuredClone(base), event) : base;\n\t\treturn new Response(JSON.stringify(doc), {\n\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t});\n\t};\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,SAAgB,qBACf,SACA,YACgD;CAChD,IAAI;CACJ,OAAO,OAAO,UAAU;EACvB,MAAM,UAAU,WAAW;EAC3B,IAAI,CAAC,MAAM;GACV,MAAM,UAA+B,CAAC;GACtC,KAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,OAAO,GACrD,QAAQ,KAAK;IAAE,MAAM;IAAW,WAAW,MAAM,KAAK,EAAA,CAAG;GAAQ,CAAC;GAEnE,OAAO,qBAAqB,SAAS,OAAO;EAC7C;EAIA,MAAM,MAAM,QAAQ,SAAS,MAAM,QAAQ,OAAO,gBAAgB,IAAI,GAAG,KAAK,IAAI;EAClF,OAAO,IAAI,SAAS,KAAK,UAAU,GAAG,GAAG,EACxC,SAAS,EAAE,gBAAgB,mBAAmB,EAC/C,CAAC;CACF;AACD"}
|