@k8ordo/framework 2.3.1 → 4.0.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.
Files changed (65) hide show
  1. package/README.md +28 -13
  2. package/dist/cli.mjs +3 -3
  3. package/dist/generated.d.mts +13 -13
  4. package/dist/headers-BxB_jJVk.mjs +73 -0
  5. package/dist/index.d.mts +3 -2
  6. package/dist/index.mjs +1 -1
  7. package/dist/paths-type-DXpmjaOr.d.mts +43 -0
  8. package/dist/runtime/app-router.mjs +21 -8
  9. package/dist/runtime/browser-payloads.mjs +1 -1
  10. package/dist/runtime/client-files.d.mts +6 -5
  11. package/dist/runtime/client-files.mjs +17 -9
  12. package/dist/runtime/client-ready.d.mts +7 -1
  13. package/dist/runtime/client-ready.mjs +2 -1
  14. package/dist/runtime/cookies.d.mts +2 -0
  15. package/dist/runtime/cookies.mjs +2 -1
  16. package/dist/runtime/ended.d.mts +7 -0
  17. package/dist/runtime/ended.mjs +14 -0
  18. package/dist/runtime/entry.browser.mjs +1 -1
  19. package/dist/runtime/entry.rsc.d.mts +38 -2
  20. package/dist/runtime/entry.rsc.mjs +97 -31
  21. package/dist/runtime/entry.ssr.d.mts +7 -1
  22. package/dist/runtime/entry.ssr.mjs +12 -6
  23. package/dist/runtime/guard.d.mts +15 -10
  24. package/dist/runtime/guard.mjs +8 -2
  25. package/dist/runtime/mount.mjs +1 -1
  26. package/dist/runtime/page-boundary.mjs +2 -2
  27. package/dist/runtime/params.d.mts +5 -4
  28. package/dist/runtime/params.mjs +2 -2
  29. package/dist/runtime/payload.d.mts +19 -4
  30. package/dist/runtime/payload.mjs +20 -5
  31. package/dist/runtime/prefetch.d.mts +29 -8
  32. package/dist/runtime/prefetch.mjs +95 -24
  33. package/dist/runtime/redirect.d.mts +13 -7
  34. package/dist/runtime/redirect.mjs +25 -9
  35. package/dist/runtime/request-scope.d.mts +37 -2
  36. package/dist/runtime/request-scope.mjs +60 -3
  37. package/dist/runtime/request.d.mts +6 -1
  38. package/dist/runtime/request.mjs +7 -2
  39. package/dist/runtime/route.d.mts +4 -2
  40. package/dist/runtime/route.mjs +13 -5
  41. package/dist/runtime/server.d.mts +5 -5
  42. package/dist/runtime/server.mjs +2 -2
  43. package/dist/runtime/shell.d.mts +2 -1
  44. package/dist/serve.d.mts +4 -0
  45. package/dist/serve.mjs +29 -14
  46. package/dist/static-Be3xIqd8.d.mts +62 -0
  47. package/dist/{static-file-BAjwBMMl.mjs → static-file-BS-WEiwu.mjs} +311 -134
  48. package/dist/{static-host-B-1fAfAw.mjs → static-host-tIDLqV8c.mjs} +1 -1
  49. package/dist/vercel.d.mts +18 -1
  50. package/dist/vercel.mjs +131 -19
  51. package/dist/vite.d.mts +6 -3
  52. package/dist/vite.mjs +366 -156
  53. package/docs/GUIDE.md +173 -46
  54. package/docs/llms.txt +129 -65
  55. package/docs/references/actions.md +14 -5
  56. package/docs/references/boundaries.md +23 -2
  57. package/docs/references/csp.md +91 -2
  58. package/docs/references/deploy.md +154 -25
  59. package/docs/references/errors.md +57 -12
  60. package/docs/references/guards.md +100 -29
  61. package/docs/references/params.md +234 -126
  62. package/docs/references/routing.md +358 -75
  63. package/package.json +18 -13
  64. package/dist/shared-dir-CNXFRZgP.mjs +0 -9
  65. package/dist/static-DnbgGIoy.d.mts +0 -61
package/README.md CHANGED
@@ -33,13 +33,14 @@ dependencies in either mode: the build bundles what the application runs.
33
33
 
34
34
  <!-- peers -->
35
35
 
36
- | Package | Version | Required | Needed for |
37
- | --------------------- | -------- | -------- | ------------------------------------------ |
38
- | `@k8ordo/router` | ^2.3.1 | yes | routing, re-exported by the framework |
39
- | `react` | ≥19.3.0 | yes | rendering |
40
- | `react-dom` | ≥19.3.0 | yes | rendering |
41
- | `vite` | ≥8.1.0 | yes | the build (`framework()` is a Vite plugin) |
42
- | `oxc-transform-react` | ^0.152.0 | optional | `reactCompiler: true` (React Compiler) |
36
+ | Package | Version | Required | Needed for |
37
+ | --------------------- | ----------------- | -------- | ------------------------------------------ |
38
+ | `@k8ordo/router` | ^4.0.0 | yes | routing, re-exported by the framework |
39
+ | `react` | ≥19.3.0 | yes | rendering |
40
+ | `react-dom` | ≥19.3.0 | yes | rendering |
41
+ | `vite` | ≥8.1.0 | yes | the build (`framework()` is a Vite plugin) |
42
+ | `oxc-transform-react` | ≥0.152.0 <0.157.0 | optional | `reactCompiler: true` (React Compiler) |
43
+ | `@vercel/functions` | ^3.0.0 | optional | `waitUntil()` on Vercel, under `vercel()` |
43
44
 
44
45
  <!-- /peers -->
45
46
 
@@ -54,8 +55,7 @@ export default defineConfig({
54
55
  plugins: [
55
56
  framework({
56
57
  mode: 'static',
57
- paths: () => ['/products/1', '/products/2'], // for routes with parameters
58
- site: 'https://example.com', // and a sitemap.xml
58
+ site: 'https://example.com', // the origin it is served from: its URLs, sitemap.xml
59
59
  }),
60
60
  ],
61
61
  });
@@ -70,7 +70,8 @@ src/routes/
70
70
  error.tsx shown in place of what is below when it throws
71
71
  products/[id]/
72
72
  page.tsx /products/:id — `export const paramsSchema` types :id
73
- fallback.tsx static: the shell for the ids paths does not list
73
+ paths.ts static: the ids the build writes
74
+ fallback.tsx static: the shell for the ids paths.ts does not return
74
75
  old/redirect.ts /old sends the visitor elsewhere
75
76
  feed.xml/route.ts /feed.xml answered by its GET — a Response, not a page
76
77
  admin/guard.ts server mode: runs before everything under /admin
@@ -90,6 +91,16 @@ export default async function ProductPage({
90
91
  }
91
92
  ```
92
93
 
94
+ ```ts
95
+ // src/routes/products/[id]/paths.ts — static mode: the ids to write
96
+ import type { Paths } from '@k8ordo/framework';
97
+
98
+ const paths: Paths<'/products/:id'> = async () =>
99
+ (await listProducts()).map((product) => product.id);
100
+
101
+ export default paths;
102
+ ```
103
+
93
104
  ```bash
94
105
  vite dev # renders per request, with Fast Refresh
95
106
  vite build # static: dist/client/ is the site
@@ -122,7 +133,8 @@ export async function createTalk(_previous: FormState, formData: FormData) {
122
133
  ```
123
134
 
124
135
  The built handler, `dist/rsc/index.js`, is a plain
125
- `(request: Request) => Promise<Response>` that needs nothing from its runtime
136
+ `(request: Request, context?: HandlerContext) => Promise<Response>`
137
+ (`context.waitUntil` is the host's own) that needs nothing from its runtime
126
138
  but `AsyncLocalStorage`, so Node.js, Bun, Deno and Cloudflare Workers
127
139
  (`nodejs_compat`) all run it, and `vercel()` from `@k8ordo/framework/vercel`
128
140
  writes a build for Vercel.
@@ -132,8 +144,11 @@ whatever needs one — a `'use server'` module, a `guard.ts`, an import of
132
144
  `@k8ordo/framework/server` — in `vite dev` as well: `this application wants
133
145
  mode: 'server'`.
134
146
 
135
- A value `paths` does not list — a product added after the build — is
136
- answered by a `fallback.tsx` beside the page: the build writes it once as a
147
+ A parameter's values come from a `paths.ts` in its own directory: a function
148
+ that returns them, run with the modules the pages read their data through,
149
+ and applied to every page, `route.ts` and `redirect.ts` below it. A value it
150
+ does not return — a product added after the build — is answered by a
151
+ `fallback.tsx` beside the page: the build writes it once as a
137
152
  shell, the layouts in HTML, and the browser draws the page from the URL.
138
153
  The build also writes the `_redirects` through which Netlify and Cloudflare
139
154
  reach the shell, and `vercel()` the same rewrites for Vercel — around them,
package/dist/cli.mjs CHANGED
@@ -8,9 +8,9 @@ when it begins, and builds nothing.
8
8
  `;
9
9
  /**
10
10
  * `.k8ordo/` without a build: the config resolved as `vite build` resolves
11
- * it, and the engine's plugin, which knows the routes directory and the
12
- * mode, asked to generate. No environment is built and no page rendered, so
13
- * `paths` and whatever data a page reads are never touched.
11
+ * it, and the engine's plugin, which knows the mode, asked to generate. No
12
+ * environment is built and no page rendered, so a `paths.ts` and whatever
13
+ * data a page reads are never touched.
14
14
  */
15
15
  const generate = async () => {
16
16
  const config = await resolveConfig({}, "build", "production", "production");
@@ -1,23 +1,23 @@
1
+ import { n as RedirectTarget, t as Paths } from "./paths-type-DXpmjaOr.mjs";
1
2
  import { ErrorComponent, ParamsOf, ParamsOf as ParamsOf$1, ParamsSchemaFor, ParsedParams, ParsedParamsMap, Register, defineRoutes } from "@k8ordo/router";
2
3
  /**
3
- * What a `guard.ts` receives: the request, and the params of the pattern its
4
- * directory puts it under, as the strings the pathname carried — a guard runs
5
- * above the page and every layout, where no schema has typed them.
4
+ * What a `guard.ts` receives: the request for the page — a client
5
+ * navigation's payload request too, under the page's URL — and the params of
6
+ * the pattern its directory puts it under, as the pathname carried them — a
7
+ * string each, a rest param its segments — since a guard runs above the page
8
+ * and every layout, where no schema has typed them.
6
9
  */
7
10
  type GuardContext<P extends string = string> = {
8
11
  readonly request: Request;
9
12
  readonly params: ParamsOf$1<P>;
10
13
  };
11
14
  /**
12
- * What a `guard.ts` default-exports. A `Response` ends the request there — a
13
- * redirect, a `401` — and returning nothing lets it through to what answers
14
- * below. There is no `next()` to run the page and rewrite its answer: a page
15
- * streams, and its headers leave before its body is written.
15
+ * What a `guard.ts` default-exports. `redirect(url)` ends the request there
16
+ * with a `303`, `notFound()` with the nearest not-found.tsx under 404, and a
17
+ * `Response` returned — a `401`, a `403` — is the answer itself; returning
18
+ * nothing lets it through to what answers below. There is no `next()` to run
19
+ * the page and rewrite its answer: a page streams, and its headers leave
20
+ * before its body is written.
16
21
  */
17
22
  type Guard<P extends string = string> = (context: GuardContext<P>) => Response | void | Promise<Response | void>;
18
- /** What a `redirect.ts` route file default-exports. */
19
- type RedirectTarget = string | {
20
- readonly to: string;
21
- readonly permanent?: boolean;
22
- };
23
- export { type ErrorComponent, type Guard, type ParamsOf, type ParamsSchemaFor, type ParsedParams, type ParsedParamsMap, type RedirectTarget, type Register, defineRoutes };
23
+ export { type ErrorComponent, type Guard, type ParamsOf, type ParamsSchemaFor, type ParsedParams, type ParsedParamsMap, type Paths, type RedirectTarget, type Register, defineRoutes };
@@ -0,0 +1,73 @@
1
+ import path from "node:path";
2
+ // ../framework-engine/dist/plugin/shared-dir.mjs
3
+ /** The deepest directory holding both `a` and `b`. */
4
+ const sharedDir = (a, b) => {
5
+ let dir = a;
6
+ while (path.relative(dir, b).startsWith("..")) dir = path.dirname(dir);
7
+ return dir;
8
+ };
9
+ // src/headers.ts
10
+ const PLUGIN = "k8ordo:headers";
11
+ /** A field name as HTTP spells one: a token. */
12
+ const NAME = /^[!#$%&'*+\-.^`|~\w]+$/u;
13
+ /** Bytes a field value cannot hold, a line break among them. */
14
+ const CONTROL = /[\u0000-\u0008\u000A-\u001F\u007F]/u;
15
+ /**
16
+ * What is wrong with the `headers` option, or `null`. A name or a value HTTP
17
+ * could not send is refused when the config loads rather than by whichever
18
+ * server meets it first — and a line break would start a rule of its own in
19
+ * the `_headers` file the build writes.
20
+ */
21
+ const headersRefusal = (given) => {
22
+ if (given === void 0) return null;
23
+ if (typeof given !== "object" || given === null || Array.isArray(given)) return "framework() takes headers as an object of names and values, sent with every response";
24
+ const seen = /* @__PURE__ */ new Set();
25
+ for (const [name, value] of Object.entries(given)) {
26
+ if (!NAME.test(name)) return `framework() cannot send a header named ${JSON.stringify(name)} — a header's name is letters, digits and the punctuation of a token`;
27
+ if (typeof value !== "string" || value === "" || value !== value.trim()) return `framework() needs the value of the header ${name} to be text, with nothing empty around it`;
28
+ if (CONTROL.test(value)) return `framework() cannot send the header ${name}: its value holds a control character`;
29
+ if (seen.has(name.toLowerCase())) return `framework() was given the header ${name} twice, in two spellings`;
30
+ seen.add(name.toLowerCase());
31
+ }
32
+ return null;
33
+ };
34
+ const HEADERS_COMMENT = "# @k8ordo/framework: the headers framework() declared for every response";
35
+ /**
36
+ * The `_headers` file Netlify and Cloudflare read: the declared headers for
37
+ * every path, then the application's own `public/_headers` verbatim. Both
38
+ * hosts send a response every rule that matches it, so a name in both is
39
+ * sent with both values.
40
+ */
41
+ const formatHeaders = (headers, own) => {
42
+ const ownText = own?.replace(/\s+$/u, "") ?? "";
43
+ return `${[
44
+ HEADERS_COMMENT,
45
+ "/*",
46
+ ...Object.entries(headers).map(([name, value]) => ` ${name}: ${value}`),
47
+ ...ownText === "" ? [] : ["", ownText]
48
+ ].join("\n")}\n`;
49
+ };
50
+ /**
51
+ * `vite dev` and `vite preview` sending the declared headers: set before
52
+ * anything answers, so they are on a module, a page, a file and an error
53
+ * alike, and whatever answers may still write the same name over them.
54
+ * Its `api` is where a host adapter reads what was declared.
55
+ */
56
+ const headersPlugin = (headers) => {
57
+ const declared = Object.entries(headers);
58
+ const send = (server) => {
59
+ server.middlewares.use((_request, response, next) => {
60
+ for (const [name, value] of declared) response.setHeader(name, value);
61
+ next();
62
+ });
63
+ };
64
+ return {
65
+ name: PLUGIN,
66
+ api: { headers },
67
+ configureServer: send,
68
+ configurePreviewServer: send
69
+ };
70
+ };
71
+ /** The headers the `framework()` among these plugins declared. */
72
+ const declaredHeaders = (plugins) => (plugins.find(({ name }) => name === PLUGIN)?.api)?.headers ?? {};
73
+ export { sharedDir as a, headersRefusal as i, formatHeaders as n, headersPlugin as r, declaredHeaders as t };
package/dist/index.d.mts CHANGED
@@ -1,2 +1,3 @@
1
- import { BoundLinks, BoundParams, ErrorProps, LayoutProps, MatchOptions, MatchablePattern, NavigateToOptions, PageProps, RegisteredNavigablePattern, RegisteredPageParams, RegisteredParams, RegisteredPattern, RouteContext, bindParams, href, isNotFound, matchPath, navigateTo, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase } from "@k8ordo/router";
2
- export { type BoundLinks, type BoundParams, type ErrorProps, type LayoutProps, type MatchOptions, type MatchablePattern, type NavigateToOptions, type PageProps, type RegisteredNavigablePattern, type RegisteredPageParams, type RegisteredParams, type RegisteredPattern, type RouteContext, bindParams, href, isNotFound, matchPath, navigateTo, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase };
1
+ import { n as RedirectTarget, t as Paths } from "./paths-type-DXpmjaOr.mjs";
2
+ import { BoundParams, ErrorProps, LayoutProps, MatchOptions, MatchablePattern, PageProps, RegisteredNavigablePattern, RegisteredPageParams, RegisteredParams, RegisteredPattern, RouteContext, bindParams, href, isNotFound, matchPath, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase } from "@k8ordo/router";
3
+ export { type BoundParams, type ErrorProps, type LayoutProps, type MatchOptions, type MatchablePattern, type PageProps, type Paths, type RedirectTarget, type RegisteredNavigablePattern, type RegisteredPageParams, type RegisteredParams, type RegisteredPattern, type RouteContext, bindParams, href, isNotFound, matchPath, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase };
package/dist/index.mjs CHANGED
@@ -1 +1 @@
1
- export { bindParams, href, isNotFound, matchPath, navigateTo, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase } from "@k8ordo/router";
1
+ export { bindParams, href, isNotFound, matchPath, normalizePathname, notFound, useMatch, usePathname, usePendingPathname, withBase } from "@k8ordo/router";
@@ -0,0 +1,43 @@
1
+ import { ParamsOf, Register, RegisteredParams } from "@k8ordo/router";
2
+ /** What a `redirect.ts` route file default-exports. */
3
+ type RedirectTarget = string | {
4
+ readonly to: string;
5
+ readonly permanent?: boolean;
6
+ };
7
+ /** The parameter a pattern ends in: `id` of `/:locale/posts/:id`. */
8
+ type LastParam<Pattern extends string> = Pattern extends `${string}/:${infer Rest}` ? Rest extends `${string}/:${string}` ? LastParam<`/${Rest}`> : Rest : never;
9
+ type Values<Pattern extends string> = ReadonlyArray<RegisteredParams<Pattern>[LastParam<Pattern> & keyof RegisteredParams<Pattern>]>;
10
+ type RegisteredAbove = Register extends {
11
+ pathsParams: infer M;
12
+ } ? M : object;
13
+ type Above<Pattern extends string> = Omit<Pattern extends keyof RegisteredAbove ? RegisteredAbove[Pattern] : ParamsOf<Pattern>, LastParam<Pattern>>;
14
+ /**
15
+ * What a `paths.ts` exports by default, under `mode: 'static'`: the values
16
+ * its directory's parameter takes, given the params of the directories above
17
+ * it — one call per combination of theirs. `Pattern` is the directory's own,
18
+ * ending in that parameter. The values are typed as a link takes them: what
19
+ * the page's `paramsSchema` produces (a number for a numeric id), or any
20
+ * value with one spelling where no schema says. The params above arrive as
21
+ * the layouts above the directory read them: spelled as the build writes
22
+ * them, then run through the `paramsSchema` exports of the layouts in the
23
+ * directories above, outer first, and typed as exactly what those produce —
24
+ * the string for a parameter none of them reads. When two `paths.ts` share a
25
+ * pattern under different layouts, the type is what both of them receive: a
26
+ * `year` one reads as a number and the other leaves alone is
27
+ * `number | string`. The page beside the file
28
+ * and a layout in its own directory take no part, since they may read the
29
+ * value the file is asked for. A `[year]` a layout above reads as a number
30
+ * arrives as one, whatever the `paths.ts` above returned, and values one of
31
+ * those schemas refuses are never handed over: the build names them instead.
32
+ * The build spells each value as `href` does (`café`, not `caf%C3%A9`, is
33
+ * the value).
34
+ *
35
+ * ```ts
36
+ * // src/routes/[locale]/posts/[id]/paths.ts
37
+ * const paths: Paths<'/:locale/posts/:id'> = async ({ locale }) =>
38
+ * (await postsIn(locale)).map((post) => post.id);
39
+ * export default paths;
40
+ * ```
41
+ */
42
+ type Paths<Pattern extends string> = (params: Above<Pattern>) => Values<Pattern> | Promise<Values<Pattern>>;
43
+ export { RedirectTarget as n, Paths as t };
@@ -1,13 +1,13 @@
1
1
  "use client";
2
- import { payloadPathFor } from "./payload-path.mjs";
3
2
  import { preloadClientFiles, readClientFiles } from "./client-files.mjs";
4
3
  import { whenClientReady } from "./client-ready.mjs";
5
4
  import { ShowNotFound } from "./fallback-boundary.mjs";
6
5
  import { doneHydrating, whenHydrated } from "./hydrating-pathname.mjs";
7
6
  import { isPayload } from "./is-payload.mjs";
7
+ import { payloadPathFor } from "./payload-path.mjs";
8
8
  import { createPageCache, prefetchInViewUnderTouch, prefetchOnIntent } from "./prefetch.mjs";
9
9
  import { Recover, markNavigated, navigationsApplied, reloadInstead } from "./recover.mjs";
10
- import { NavigationGeneration, PathnameProvider, TreePathname, normalizePathname, useInterceptedNavigation, withoutBase } from "@k8ordo/router";
10
+ import { NavigationGeneration, PathnameProvider, TreePathname, normalizePathname, useInterceptedNavigation, usePendingPathname, withoutBase } from "@k8ordo/router";
11
11
  import { createContext, startTransition, useDeferredValue, useEffect, useLayoutEffect, useRef, useState } from "react";
12
12
  import { jsx } from "react/jsx-runtime";
13
13
  // src/runtime/app-router.tsx
@@ -83,7 +83,7 @@ const streams = /* @__PURE__ */ new WeakMap();
83
83
  */
84
84
  const fetchPage = async (payloadPath, signal, priority = "auto") => {
85
85
  signal.throwIfAborted();
86
- preloadClientFiles(payloadPath);
86
+ preloadClientFiles(payloadPath, priority);
87
87
  const request = new AbortController();
88
88
  const cancel = () => {
89
89
  request.abort(signal.reason);
@@ -174,6 +174,8 @@ function AppRouter({ arrived, reread }) {
174
174
  const searchApplied = useRef(arrived.search);
175
175
  const streaming = useRef([]);
176
176
  const loading = useRef(0);
177
+ const inView = useRef(null);
178
+ const pendingPathname = usePendingPathname();
177
179
  useEffect(() => {
178
180
  if (!hydrating) return;
179
181
  startTransition(() => {
@@ -272,16 +274,27 @@ function AppRouter({ arrived, reread }) {
272
274
  useEffect(() => {
273
275
  if (!payloadsAreFiles()) return;
274
276
  cacheIn(prefetched).keep(payloadUrlFor(new URL(location.href)), arrived);
275
- readClientFiles();
276
277
  }, [arrived]);
277
278
  useEffect(() => {
278
- const prefetch = (priority) => (url) => cacheIn(prefetched).prefetch(payloadUrlFor(url), priority);
279
- const stops = payloadsAreFiles() ? [prefetchInViewUnderTouch(prefetch("low"))] : [];
280
- stops.push(prefetchOnIntent(prefetch("auto")));
279
+ const cache = cacheIn(prefetched);
280
+ const stopIntents = prefetchOnIntent((url) => cache.prefetch(payloadUrlFor(url), "auto"));
281
+ if (!payloadsAreFiles()) return stopIntents;
282
+ const listed = readClientFiles();
283
+ const watching = prefetchInViewUnderTouch(async (url, signal) => {
284
+ await listed;
285
+ signal.throwIfAborted();
286
+ return cache.prefetch(payloadUrlFor(url), "low", signal);
287
+ });
288
+ inView.current = watching;
281
289
  return () => {
282
- for (const stop of stops) stop();
290
+ stopIntents();
291
+ watching.stop();
292
+ inView.current = null;
283
293
  };
284
294
  }, []);
295
+ useEffect(() => {
296
+ inView.current?.pending(pendingPathname);
297
+ }, [pendingPathname]);
285
298
  const { generation } = useInterceptedNavigation({
286
299
  claim: (url) => url.origin === location.origin && withoutBase(url.pathname) !== null,
287
300
  load: async (url, signal) => {
@@ -1,6 +1,6 @@
1
+ import { answerAction, setPayloadReader } from "./app-router.mjs";
1
2
  import { ACTION_ID_HEADER } from "./payload.mjs";
2
3
  import { navigationsApplied } from "./recover.mjs";
3
- import { answerAction, setPayloadReader } from "./app-router.mjs";
4
4
  import { createFromFetch, createFromReadableStream, createTemporaryReferenceSet, encodeReply, setServerCallback } from "@vitejs/plugin-rsc/browser";
5
5
  // src/runtime/browser-payloads.ts
6
6
  /**
@@ -1,11 +1,12 @@
1
1
  /**
2
- * Reads the static build's list of the files each page's client components
3
- * need. Without one — `vite dev`, a host that lost it — a payload names its
4
- * files as it is read, as it always does.
2
+ * Reads the static build's list of the files each page needs beyond its
3
+ * payload. Without one — `vite dev`, a host that lost it — a payload names
4
+ * its files as it is read, as it always does.
5
5
  */
6
6
  export declare const readClientFiles: () => Promise<void>;
7
7
  /**
8
8
  * Links what the page whose payload is at `payloadPath` needs: its scripts
9
- * as module preloads, its stylesheets as preloads.
9
+ * as module preloads, its stylesheets as preloads, each at the priority its
10
+ * payload is asked for at.
10
11
  */
11
- export declare const preloadClientFiles: (payloadPath: string) => void;
12
+ export declare const preloadClientFiles: (payloadPath: string, priority: RequestPriority) => void;
@@ -1,12 +1,13 @@
1
1
  import { CLIENT_FILES_PATH } from "./payload.mjs";
2
2
  import { withBase } from "@k8ordo/router";
3
+ import { preload } from "react-dom";
3
4
  // src/runtime/client-files.ts
4
5
  /** Each page's files, by its payload's path; empty until the list is read. */
5
6
  let listed = /* @__PURE__ */ new Map();
6
7
  /**
7
- * Reads the static build's list of the files each page's client components
8
- * need. Without one — `vite dev`, a host that lost it — a payload names its
9
- * files as it is read, as it always does.
8
+ * Reads the static build's list of the files each page needs beyond its
9
+ * payload. Without one — `vite dev`, a host that lost it — a payload names
10
+ * its files as it is read, as it always does.
10
11
  */
11
12
  const readClientFiles = async () => {
12
13
  let read;
@@ -21,20 +22,27 @@ const readClientFiles = async () => {
21
22
  };
22
23
  /**
23
24
  * Links what the page whose payload is at `payloadPath` needs: its scripts
24
- * as module preloads, its stylesheets as preloads.
25
+ * as module preloads, its stylesheets as preloads, each at the priority its
26
+ * payload is asked for at.
25
27
  */
26
- const preloadClientFiles = (payloadPath) => {
28
+ const preloadClientFiles = (payloadPath, priority) => {
27
29
  const files = listed.get(new URL(payloadPath, location.href).pathname);
28
30
  if (files === void 0) return;
29
31
  const present = new Set(Array.from(document.querySelectorAll("link[href]"), (link) => link.href));
30
32
  for (const href of files) {
31
33
  if (present.has(new URL(href, location.href).href)) continue;
32
- const link = document.createElement("link");
33
34
  if (new URL(href, location.href).pathname.endsWith(".css")) {
34
- link.rel = "preload";
35
- link.as = "style";
36
- } else link.rel = "modulepreload";
35
+ preload(href, {
36
+ as: "style",
37
+ crossOrigin: "",
38
+ fetchPriority: priority
39
+ });
40
+ continue;
41
+ }
42
+ const link = document.createElement("link");
43
+ link.rel = "modulepreload";
37
44
  link.crossOrigin = "";
45
+ link.fetchPriority = priority;
38
46
  link.href = href;
39
47
  document.head.append(link);
40
48
  }
@@ -1,3 +1,7 @@
1
+ type Element = {
2
+ readonly type: unknown;
3
+ readonly props: Readonly<Record<string, unknown>>;
4
+ };
1
5
  type ClientReadyOptions = {
2
6
  /**
3
7
  * What to do with a row still on its way: `'wait'` for it; `'leave'` one
@@ -7,6 +11,8 @@ type ClientReadyOptions = {
7
11
  * walk it once it arrives, as an HTML render streaming it does.
8
12
  */
9
13
  readonly rows: 'wait' | 'leave' | 'follow';
14
+ /** Handed every element walked, a row's once it arrives. */
15
+ readonly element?: (element: Element) => void;
10
16
  };
11
17
  /**
12
18
  * Settles once the client components a payload's trees name have loaded.
@@ -26,5 +32,5 @@ type ClientReadyOptions = {
26
32
  * render, a module that would not load — ends the wait there, for the
27
33
  * render to meet where an error boundary takes it.
28
34
  */
29
- export declare const whenClientReady: (trees: readonly unknown[], { rows }: ClientReadyOptions) => Promise<void>;
35
+ export declare const whenClientReady: (trees: readonly unknown[], { rows, element }: ClientReadyOptions) => Promise<void>;
30
36
  export {};
@@ -41,7 +41,7 @@ const whenSettled = (thenable) => new Promise((resolve) => {
41
41
  * render, a module that would not load — ends the wait there, for the
42
42
  * render to meet where an error boundary takes it.
43
43
  */
44
- const whenClientReady = async (trees, { rows }) => {
44
+ const whenClientReady = async (trees, { rows, element }) => {
45
45
  const seen = /* @__PURE__ */ new WeakSet();
46
46
  let waiting = [];
47
47
  const settle = async () => {
@@ -86,6 +86,7 @@ const whenClientReady = async (trees, { rows }) => {
86
86
  return;
87
87
  }
88
88
  if (isElement(value)) {
89
+ element?.(value);
89
90
  if (isLazy(value.type)) read(value.type, inside, true);
90
91
  const below = inside || value.type === SUSPENSE;
91
92
  for (const [key, prop] of Object.entries(value.props)) visit(prop, key === "fallback" ? inside : below);
@@ -45,4 +45,6 @@ export type Cookies = {
45
45
  export declare const createCookies: (incoming: ReadonlyMap<string, string>, url: URL) => {
46
46
  readonly cookies: Cookies;
47
47
  readonly lines: () => string[];
48
+ /** The cookies as they stand: what the request carried, written over. */
49
+ readonly current: () => ReadonlyMap<string, string>;
48
50
  };
@@ -79,7 +79,8 @@ const createCookies = (incoming, url) => {
79
79
  say(name, scope, [`${name}=`, ...attributes(expired, secureByDefault)].join("; "));
80
80
  }
81
81
  },
82
- lines: () => [...lines.values()]
82
+ lines: () => [...lines.values()],
83
+ current: () => new Map(values)
83
84
  };
84
85
  };
85
86
  export { createCookies };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * A guard or a route.ts that said `notFound()`: the handler answers with the
3
+ * nearest not-found.tsx, under 404, as for a URL nothing answers.
4
+ */
5
+ export declare const SAID_NOT_FOUND: unique symbol;
6
+ export type SaidNotFound = typeof SAID_NOT_FOUND;
7
+ export declare const endedBy: (error: unknown) => Response | SaidNotFound;
@@ -0,0 +1,14 @@
1
+ import { Redirect, redirectResponse } from "./redirect.mjs";
2
+ import { isNotFound } from "@k8ordo/router";
3
+ // src/runtime/ended.ts
4
+ /**
5
+ * A guard or a route.ts that said `notFound()`: the handler answers with the
6
+ * nearest not-found.tsx, under 404, as for a URL nothing answers.
7
+ */
8
+ const SAID_NOT_FOUND = Symbol("notFound()");
9
+ const endedBy = (error) => {
10
+ if (error instanceof Redirect) return redirectResponse(error.to, 303);
11
+ if (isNotFound(error)) return SAID_NOT_FOUND;
12
+ throw error;
13
+ };
14
+ export { SAID_NOT_FOUND, endedBy };
@@ -1,5 +1,5 @@
1
- import { whenClientReady } from "./client-ready.mjs";
2
1
  import { connectAppRouter } from "./browser-payloads.mjs";
2
+ import { whenClientReady } from "./client-ready.mjs";
3
3
  import { mount, renderedHere } from "./mount.mjs";
4
4
  import { reportCaught } from "./page-boundary.mjs";
5
5
  import { whenRevealed } from "./revealed.mjs";
@@ -1,4 +1,6 @@
1
1
  import { Mode } from "../host.mjs";
2
+ import { HandlerContext } from "./request-scope.mjs";
3
+ import "virtual:k8ordo/locales";
2
4
  /**
3
5
  * Where Vite serves the application, as the build was told (`base`). A host
4
6
  * serving the client build's files needs it to find them — `serve` reads it
@@ -10,11 +12,45 @@ export declare const base: string;
10
12
  * serves a build into files — as a static host would — or runs the handler.
11
13
  */
12
14
  export declare const mode: Mode;
15
+ /**
16
+ * The payload a document written into a file was rendered from: what a
17
+ * request for that page's payload would answer, byte for byte, without
18
+ * rendering the page a second time. The build into files writes it beside
19
+ * the HTML, so a page reads its data once per build, and the HTML and the
20
+ * payload of a page can never be two renders that disagree. Kept by the
21
+ * answer itself, which under `'static'` is the handler's own — nothing there
22
+ * can add a header or a cookie for `answer()` to rebuild it around.
23
+ * `undefined` for any other answer, a running server's included.
24
+ */
25
+ export declare const payloadOf: (response: Response) => ArrayBuffer | undefined;
26
+ /**
27
+ * The headers `framework({ headers })` declared for every response. Whatever
28
+ * serves the build's files reads them from here, since a file never passes
29
+ * through the handler.
30
+ */
31
+ declare const everyAnswer: Readonly<Record<string, string>>;
32
+ /**
33
+ * What a `paths.ts` answers when asked for its parameter's values, given the
34
+ * params above it as the build spelled them. The build into files, and
35
+ * `vite dev`, ask through here, from the RSC environment, so the file runs
36
+ * as the pages do — the application's aliases, and the module instances the
37
+ * pages read their data through. The params above are first read by the
38
+ * schemas of the layouts in the directories above the file's, and the file
39
+ * receives what they produced; when one of them refuses, the file is not
40
+ * asked and the answer is `null`. Otherwise whatever it returned is handed
41
+ * back as it is, as `values`: the build is what says a value is not one.
42
+ */
43
+ export declare const pathValues: (file: string, above: Readonly<Record<string, string>>) => Promise<{
44
+ readonly values: unknown;
45
+ } | null>;
13
46
  /**
14
47
  * The one entry both modes share: a request in, a page out. mode: 'server'
15
48
  * calls it per request; mode: 'static' calls it at build time, for each
16
49
  * route's HTML and again for its payload, and writes the answers to files.
17
50
  * What it knows of the mode is compiled in (`K8ORDO_MODE`): whether a page
18
- * gets the request, and whether a failed render may still stream.
51
+ * gets the request, and whether a failed render may still stream. `host` is
52
+ * what the caller offers beside the request — its `waitUntil` — and may be
53
+ * left out: the build, `vite dev` and `vite preview` hand none.
19
54
  */
20
- export default function handler(request: Request): Promise<Response>;
55
+ export default function handler(request: Request, host?: HandlerContext): Promise<Response>;
56
+ export { everyAnswer as headers };