@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
@@ -23,8 +23,8 @@ dist/
23
23
  index.html
24
24
  index.rsc
25
25
  404.html not-found.tsx, rendered
26
- client-files.json what each page's client components load, for a navigation to link ahead
27
- sitemap.xml every page above, when `site` is set
26
+ client-files.json what each page loads beyond its payload, for a navigation to link ahead
27
+ sitemap.xml every page above, at `site`'s origin
28
28
  _redirects how a host reaches the shells, when there are any
29
29
  assets/… the client bundle
30
30
  rsc/ ssr/ the machinery that produced the above
@@ -92,8 +92,8 @@ rewrite: the host answers a URL no file answers with the shell's file,
92
92
  under `200`, the URL left as the visitor asked for it. Whenever it writes a
93
93
  shell, the build writes the rules into `dist/client/_redirects`, in the
94
94
  format Netlify and Cloudflare both read. For
95
- `[locale]/posts/[id]/fallback.tsx`, with `paths` supplying `/en/posts/:id`
96
- and `/ja/posts/:id`, the ids `1` and `2`, and a
95
+ `[locale]/posts/[id]/fallback.tsx`, with `[locale]/paths.ts` returning `en`
96
+ and `ja`, `[locale]/posts/[id]/paths.ts` the ids `1` and `2`, and a
97
97
  `[locale]/posts/first/redirect.ts` beside them:
98
98
 
99
99
  ```
@@ -303,9 +303,13 @@ PORT=8080 HOST=0.0.0.0 node dist/server.js
303
303
  ```
304
304
 
305
305
  On `SIGTERM` or `SIGINT`, `server.js` stops taking connections, finishes the
306
- answers already under way, and exits with `0`. Run as a container's first
307
- process, where Node ignores a signal nothing handles, it still stops when
308
- the container is told to, rather than when the grace period runs out.
306
+ answers already under way and the work handed to
307
+ [`waitUntil()`](guards.md#work-after-the-answer), and exits with `0`. Run as
308
+ a container's first process, where Node ignores a signal nothing handles, it
309
+ still stops when the container is told to, rather than when the grace period
310
+ runs out. Nothing cuts that work short: a promise that never settles keeps
311
+ the process until the container's grace period ends it, so give such work a
312
+ limit of its own.
309
313
 
310
314
  **A dependency that cannot be bundled stays installed.** One that ships a
311
315
  native binary, or reads its own files by path, does not survive bundling.
@@ -341,7 +345,9 @@ directory); `port` (default `3000`); and `host` (default `localhost` —
341
345
  inside a container, `'0.0.0.0'`). `server.url` names the address it listens
342
346
  on, so under the default it is `http://[::1]:3000` wherever `localhost`
343
347
  gave Node `::1`. Stopping it on a signal is up to the server that calls it:
344
- `await server.close()`.
348
+ `await server.close()`, which stops taking connections and resolves once
349
+ the answers under way are written and every promise handed to `waitUntil()`
350
+ has settled — exit after it, and no work is cut off.
345
351
 
346
352
  For a server build, `serve` hands out the client build's files as they are
347
353
  and passes everything else to the request handler: HTML for a page, its RSC
@@ -398,11 +404,28 @@ import handler from './dist/rsc/index.js';
398
404
  const response = await handler(new Request('https://example.com/products/1'));
399
405
  ```
400
406
 
401
- `dist/rsc/index.js` default-exports `(request: Request) => Promise<Response>`,
402
- the same handler a static build calls for each route at build time. It loads
407
+ `dist/rsc/index.js` default-exports
408
+ `(request: Request, context?: HandlerContext) => Promise<Response>`, the
409
+ same handler a static build calls for each route at build time. It loads
403
410
  `dist/ssr/` from beside itself, so the two travel together, and has every
404
411
  dependency bundled in, so nothing has to be installed where it runs.
405
412
 
413
+ **The second argument is the host's `waitUntil`.** `HandlerContext` (a type
414
+ from `@k8ordo/framework/server`) is `{ waitUntil?: (promise) => void }`:
415
+ what the handler calls with each promise the application handed
416
+ [`waitUntil()`](guards.md#work-after-the-answer), so the runtime keeps going
417
+ until it settles. A Worker's `ctx` fits as it is. Left out, the handler
418
+ holds the promises itself, which is enough wherever the process outlives
419
+ the response. The promise it hands over never rejects — a rejection has been
420
+ logged by then.
421
+
422
+ ```js
423
+ // Cloudflare Workers — worker.js
424
+ export default {
425
+ fetch: (request, env, ctx) => handler(request, ctx),
426
+ };
427
+ ```
428
+
406
429
  **It runs wherever `AsyncLocalStorage` does.** Past the web platform's
407
430
  `Request`, `Response` and streams, the one thing the handler takes from its
408
431
  runtime is `AsyncLocalStorage` from `node:async_hooks`: React keeps each
@@ -418,7 +441,7 @@ Deno.serve(handler);
418
441
  Bun.serve({ fetch: handler });
419
442
 
420
443
  // Cloudflare Workers — worker.js
421
- export default { fetch: handler };
444
+ export default { fetch: (request, env, ctx) => handler(request, ctx) };
422
445
  ```
423
446
 
424
447
  What the handler runs keeps that promise only as long as it imports nothing
@@ -499,6 +522,51 @@ nothing but its own directory, which is all the handler needs: server mode
499
522
  bundles every dependency into it. A dependency left out with
500
523
  `resolve.external` is not in the function, so it does not work there.
501
524
 
525
+ **How long the function may run, and where, is `vercel()`'s to say.**
526
+ Server mode only:
527
+
528
+ ```ts
529
+ vercel({ maxDuration: 300, regions: ['hnd1'] });
530
+ ```
531
+
532
+ `maxDuration` is the seconds one request may take — a long answer streamed
533
+ from a `route.ts` needs more than the plan's default — or `'max'` for the
534
+ plan's maximum; `regions` is the Vercel regions the function is deployed
535
+ to. Both are written into the function's configuration as given, and left
536
+ out when not given, which leaves them to the plan's default and the
537
+ project's own setting. There is one function, so one value answers every
538
+ route. Under `mode: 'static'` the build refuses them:
539
+
540
+ ```text
541
+ vercel() takes maxDuration and regions under mode: 'server' only — under mode: 'static' there is no function for them to configure
542
+ ```
543
+
544
+ **`waitUntil()` needs `@vercel/functions` installed.** Vercel stops a
545
+ function once its response ends unless told through that package, so an
546
+ application that imports `waitUntil` from `@k8ordo/framework/server` —
547
+ in its own code or in a dependency — installs it:
548
+
549
+ ```bash
550
+ npm install @vercel/functions
551
+ ```
552
+
553
+ The build then bundles the package's `waitUntil` into the function and
554
+ hands it to the handler with every request; nothing in the application
555
+ imports `@vercel/functions` itself. Without the package the build stops,
556
+ naming what imports `waitUntil`:
557
+
558
+ ```
559
+ the build for Vercel cannot keep the function running after its answer — on Vercel waitUntil() goes through @vercel/functions, which is not installed here, and this imports waitUntil from @k8ordo/framework/server:
560
+ src/routes/api/chat/route.ts
561
+ install @vercel/functions in this application
562
+ ```
563
+
564
+ A module that reaches the entry through `import * as` or `export * from`
565
+ counts as importing it, since neither says which names it uses. An
566
+ application that never imports `waitUntil` needs no `@vercel/functions`, and
567
+ its function is written as before. How long the function may go on is
568
+ its `maxDuration` (above), not the framework's.
569
+
502
570
  **Under `mode: 'static'`** there is no function. The client build becomes
503
571
  static files at the base — a file under `assets/` sent `immutable`, and
504
572
  `_redirects` left out, since Vercel never reads it and would serve it as a
@@ -537,6 +605,10 @@ expression for the pathname, with `dest`, `status`, `headers`, `continue`,
537
605
  assets/ sent immutable
538
606
  ```
539
607
 
608
+ The headers `framework()` declared
609
+ ([Headers on every response](#headers-on-every-response)) are a route ahead
610
+ of `beforeFiles`, which may write the same name over for the paths it names.
611
+
540
612
  `beforeFiles` is tried before any file, so it is where headers for every
541
613
  answer go, and a redirect or a rewrite that has to win over a file that is
542
614
  there. `beforeNotFound` is tried once neither a file nor a shell answered,
@@ -556,7 +628,7 @@ const acceptsMarkdown = [
556
628
 
557
629
  export default defineConfig({
558
630
  plugins: [
559
- framework({ mode: 'static' }),
631
+ framework({ mode: 'static', site: 'https://example.com' }),
560
632
  vercel({
561
633
  beforeFiles: [
562
634
  {
@@ -616,8 +688,8 @@ export default defineConfig({
616
688
  matching goes on with `dest` as the pathname: `beforeNotFound` sees
617
689
  `/posts/nope/article.md`, not `/posts/nope`. Here a `route.ts` at
618
690
  `routes/posts/[slug]/article.md/` wrote each post's markdown beside its
619
- page, and a client asking for markdown is answered with it. Have `paths`
620
- give the pages and their markdown from one list of posts, so no post is
691
+ page, and a client asking for markdown is answered with it. Both are
692
+ written for the slugs `posts/[slug]/paths.ts` returns, so no post is
621
693
  written without the other.
622
694
  - `has` matches the header's text against `value`, a regular expression,
623
695
  and negotiates nothing: `.*text/markdown.*` takes
@@ -636,7 +708,8 @@ What to keep in mind:
636
708
  query: `^/posts/` does not match `/posts/first`, and `^/posts/.+$` does.
637
709
  - **Only Vercel applies them.** `vite dev`, `vite preview` and `serve`
638
710
  answer as if they were not there — no header, no redirect, nothing decided
639
- by `Accept` — since an imitation of Vercel's routing that differed from it
711
+ by `Accept` (the headers every response carries go in `framework()`'s
712
+ `headers`, which all of them send) — since an imitation of Vercel's routing that differed from it
640
713
  would pass locally and fail once deployed. A URL only a route of yours
641
714
  answers is a 404 there.
642
715
  - **No `Cache-Control` in a route every path takes.** It reaches every file
@@ -659,6 +732,62 @@ What to keep in mind:
659
732
  vercel() takes beforeFiles and beforeNotFound under mode: 'static' only — under mode: 'server' the handler answers every URL no file names
660
733
  ```
661
734
 
735
+ ## Headers on every response
736
+
737
+ Either mode. `framework()` takes the headers every response carries —
738
+ whatever answered: a page, a file of the build, a `404`, a redirect:
739
+
740
+ ```ts
741
+ // vite.config.ts
742
+ export default defineConfig({
743
+ plugins: [
744
+ framework({
745
+ mode: 'static',
746
+ site: 'https://example.com',
747
+ headers: {
748
+ 'X-Content-Type-Options': 'nosniff',
749
+ 'Referrer-Policy': 'strict-origin-when-cross-origin',
750
+ },
751
+ }),
752
+ ],
753
+ });
754
+ ```
755
+
756
+ Declared once, they are sent wherever the application runs:
757
+
758
+ | Where | How |
759
+ | -------------------------------------- | ----------------------------------------------------------------------------------- |
760
+ | `vite dev`, `vite preview` | set before anything answers |
761
+ | `serve`, `node dist/server.js` | set before anything answers, read from the build |
762
+ | the request handler, under server mode | added to its own answers, so a runtime that calls the handler itself sends them too |
763
+ | Vercel, with `vercel()` | a route ahead of every other, in either mode |
764
+ | Netlify, Cloudflare, under static mode | `dist/client/_headers`, a rule for `/*`, your own `public/_headers` kept after it |
765
+
766
+ A value that differs between `vite dev` and the build — a
767
+ `Content-Security-Policy` that allows `'unsafe-eval'` only in development —
768
+ is the config's to decide: `defineConfig(({ command }) => …)` says which of
769
+ the two is running.
770
+
771
+ - **An answer's own header wins.** Under server mode a header a `guard.ts`
772
+ or a `route.ts` set under the same name is left as it was set: declare a
773
+ `Content-Security-Policy` for the files, and the pages keep the one their
774
+ guard writes with a `nonce()`. Vercel is the one place not to rely on
775
+ that — which of a route's header and a function's it sends is Vercel's to
776
+ decide — so do not declare a name there that a guard also writes.
777
+ - **No `Cache-Control`.** It would reach every file, those under `assets/`
778
+ among them, and every page.
779
+ - **Every path, or the host's own means.** A header for some paths only is
780
+ written where the host reads it: a route of `vercel()`'s
781
+ ([Routes of your own](#routes-of-your-own)), a rule in `public/_headers`.
782
+ On Netlify and Cloudflare a response is sent the headers of every rule
783
+ that matches it, so a name both `headers` and your `public/_headers` give
784
+ is sent with both values.
785
+ - A name or a value HTTP could not send — a space in a name, a line break
786
+ in a value — is refused when the config loads.
787
+ - A server-mode `dist/` whose files a host of your own serves sends those
788
+ files however that host does: the handler adds the headers to what it
789
+ answers, and a file never passes through it.
790
+
662
791
  ## A tab opened before a deploy
663
792
 
664
793
  A tab keeps running the script it loaded, while every payload it fetches
@@ -684,7 +813,7 @@ An application served below the root of its origin — `https://example.com/docs
684
813
  // vite.config.ts
685
814
  export default defineConfig({
686
815
  base: '/docs/',
687
- plugins: [framework({ mode: 'static' })],
816
+ plugins: [framework({ mode: 'static', site: 'https://example.com' })],
688
817
  });
689
818
  ```
690
819
 
@@ -693,25 +822,25 @@ export default defineConfig({
693
822
  in the address bar. What crosses between the two gains or loses the base on
694
823
  the way:
695
824
 
696
- - A link built with `href()` or `navigateTo()` carries it. A page receives
825
+ - A link built with `href()` carries it, and so does a navigation started
826
+ from code with `navigation.navigate(href(…))`. A page receives
697
827
  `pathname` without it, and `usePathname()` returns it without it.
698
828
  - A page's payload sits beside it — `/docs/products/index.rsc` — and the
699
829
  client build's files are under `/docs/assets/`.
700
830
  - A `redirect.ts` target is written from the root, like the table, and is
701
831
  sent with the base in front; one that names another origin is sent as
702
832
  written.
703
- - Under `mode: 'server'`, a redirect the application builds itself is sent
704
- as written: `redirect()` from a Server Action, and the `location` of a
705
- `Response` a `guard.ts` returns. Both are URLs, so build them with
706
- `href()` — `redirect(href('/talks'))`, `location: href('/login')` — or
707
- give a pathname built some other way its base with `withBase()`.
833
+ - Under `mode: 'server'`, a redirect the application asks for is sent as
834
+ written: `redirect()` from a Server Action, a `guard.ts` or a `route.ts`.
835
+ It takes a URL, so build it with `href()` — `redirect(href('/talks'))` —
836
+ or give a pathname built some other way its base with `withBase()`.
708
837
  - A URL outside the base is none of the application's: the handler answers
709
838
  it with a `404`, and the client runtime leaves it to the browser.
710
839
 
711
840
  Under `mode: 'static'` the pages are written into `dist/client/` at their
712
- pathnames in the table, so the host serves that directory at `/docs/`; the
713
- `paths` option takes pathnames without the base, and `sitemap.xml` lists
714
- each page at its URL, base included. `_redirects` is written at the root of
841
+ pathnames in the table, so the host serves that directory at `/docs/`; a
842
+ `paths.ts` returns a parameter's values, which hold no base, and
843
+ `sitemap.xml` lists each page at its URL, base included. `_redirects` is written at the root of
715
844
  `dist/client/` too, with the base in every line
716
845
  (`/docs/posts/:p1 /docs/posts/!fallback/ 200`), but a host reads it only at
717
846
  the root of what it publishes: move it there. Under `mode: 'server'`, `serve` reads
@@ -57,6 +57,43 @@ above it, and the file is written; with none, it stops the build the same
57
57
  way. `error.tsx` under this mode is for what fails in the browser: a client
58
58
  component, after hydration.
59
59
 
60
+ ### Reporting, and what no `error.tsx` catches
61
+
62
+ An `error.tsx` is handed the `error` beside `reset`, so that is where a
63
+ failure it caught is reported from:
64
+
65
+ ```tsx
66
+ 'use client';
67
+
68
+ import type { ErrorProps } from '@k8ordo/framework';
69
+ import { useEffect } from 'react';
70
+
71
+ export default function RouteError({ error, reset }: ErrorProps) {
72
+ useEffect(() => {
73
+ void fetch('/reports', { method: 'POST', body: String(error) });
74
+ }, [error]);
75
+ return (
76
+ <button onClick={reset} type="button">
77
+ try again
78
+ </button>
79
+ );
80
+ }
81
+ ```
82
+
83
+ The root `error.tsx` sits inside the root layout, so it catches everything
84
+ below that layout and nothing of the layout itself: a client component the
85
+ layout renders — a header's menu, a theme switch — that throws has no
86
+ `error.tsx` above it. The framework then does what it does for a page with
87
+ none: after a client navigation it loads the document again, and on the
88
+ document's first render it lets the error through, React takes the tree
89
+ down, and the browser's `error` event carries it
90
+ (`window.addEventListener('error', …)` is where to report it). There is no
91
+ `global-error.tsx`: what could replace the layout would have to render
92
+ `<html>` itself, with none of the layout's providers. Put an error boundary
93
+ of your own inside the layout instead, around the parts that can fail — a
94
+ dozen lines of a class component with `getDerivedStateFromError`, which is
95
+ what an `error.tsx` is — and the rest of the frame stays up.
96
+
60
97
  ## A page that is not there
61
98
 
62
99
  A params schema decides what a URL's params look like; whether the thing they
@@ -87,7 +124,11 @@ is also what a URL nothing matches gets from such an application; under
87
124
  `mode: 'static'` no `404.html` is written, so such a URL gets the host's own 404.
88
125
 
89
126
  `notFound()` is the page's word about itself: thrown from the page's own
90
- component, before it returns.
127
+ component, before it returns. Under `mode: 'server'` a `guard.ts` and a
128
+ `route.ts` say it the same way, and the URL is answered with the same
129
+ not-found under the same 404 — the page below the guard never runs, and a
130
+ `route.ts` that wants a 404 of its own shape returns that `Response`
131
+ instead.
91
132
 
92
133
  **Under `mode: 'server'` a document waits for its page.** A status leaves
93
134
  before the body it heads, so a page's HTML is not sent until the page's own
@@ -102,8 +143,8 @@ its response has started, `notFound()` is an error like any other, and the
102
143
  nearest `error.tsx` answers it.
103
144
 
104
145
  **Under `mode: 'static'` a build waits for the whole page**, so `notFound()`
105
- counts from anywhere in it. A pathname the `paths` option supplied whose page
106
- says it fails the build, naming the pathname — it would otherwise be written
146
+ counts from anywhere in it. A value a `paths.ts` returned whose page says
147
+ it fails the build, naming the pathname — it would otherwise be written
107
148
  as a 404 page under a URL the site claims to have (see
108
149
  [Routes with parameters](params.md#routes-with-parameters)). The 404 itself
109
150
  is the host's to send: `not-found.tsx` is written as `404.html`
@@ -130,15 +171,15 @@ export default '/products';
130
171
  ```
131
172
 
132
173
  The target is a pattern the matched params fill in, so `/:locale/legacy` can
133
- send to `/:locale/new`. A redirect holds its place in the table as a page
174
+ send to `/:locale/new`, and `old/[...path]/redirect.ts` can send to
175
+ `/files/:path+`, every segment the rest parameter took moved as the URL
176
+ spelled it (server mode only, as every `[...name]` directory is). A redirect holds its place in the table as a page
134
177
  does, so a literal directory beside a `[slug]/redirect.ts` keeps its URL; a
135
178
  directory that redirects has no page to render, so it cannot hold both. The
136
- generated table checks the default export's shape; `RedirectTarget` is that
137
- type, for a file that wants the error where it is written
138
- (`export default '/products' satisfies RedirectTarget`, with
139
- `import type { RedirectTarget } from '@k8ordo/framework/server'`, which
140
- `mode: 'static'` lets through; `import { type RedirectTarget }` is kept as an
141
- import of the module under `verbatimModuleSyntax`, and refused).
179
+ generated table checks the default export's shape; `RedirectTarget`, on the
180
+ root `@k8ordo/framework` as every type a file of either mode is written
181
+ against, is that type, for a file that wants the error where it is written
182
+ (`export default '/products' satisfies RedirectTarget`).
142
183
 
143
184
  **Under `mode: 'server'`** the answer to a `GET` or `HEAD` is a `307`, or a
144
185
  `308` when `permanent`, and any other method gets a `405`; a client
@@ -152,6 +193,10 @@ ever send the status; there is no `index.rsc` beside it, so a client
152
193
  navigation to it hands the URL to the browser, which loads that page and
153
194
  follows it.
154
195
 
155
- A Server Action sends the visitor elsewhere with `redirect()` instead
196
+ A Server Action, a `guard.ts` and a `route.ts` send the visitor elsewhere
197
+ with `redirect()` instead
156
198
  ([Ending with a redirect](actions.md#ending-with-a-redirect)), under
157
- `mode: 'server'` only.
199
+ `mode: 'server'` only. The two speak different languages: a `redirect.ts`
200
+ `to` is a pattern in the table's terms — no base, `:name` filled from the
201
+ params it matched — while `redirect()` takes a URL, what `href()` returns,
202
+ base included.
@@ -15,36 +15,42 @@ run outer first, one at a time:
15
15
  ```ts
16
16
  // src/routes/admin/guard.ts
17
17
  import { href } from '@k8ordo/framework';
18
- import { cookies } from '@k8ordo/framework/server';
18
+ import { cookies, redirect } from '@k8ordo/framework/server';
19
19
  import type { Guard } from '@k8ordo/framework/server';
20
20
 
21
21
  const guard: Guard<'/admin'> = () => {
22
- if (cookies().has('session')) return;
23
- return new Response(null, {
24
- status: 303,
25
- headers: { location: href('/login') },
26
- });
22
+ if (!cookies().has('session')) redirect(href('/login'));
27
23
  };
28
24
 
29
25
  export default guard;
30
26
  ```
31
27
 
32
- It receives `{ request, params }` — the `Request` as it arrived, and the
28
+ It receives `{ request, params }` — the `Request` for the page, and the
33
29
  params of the pattern its directory puts it under, as the strings the URL
34
- carried: a guard runs above every layout, where no schema has typed them.
30
+ carried (a `[...name]` directory's as an array of them): a guard runs above
31
+ every layout, where no schema has typed them.
35
32
  `Guard<'/admin/:id'>` is its type (`GuardContext<'/admin/:id'>` its
36
33
  argument's), and the generated table checks each `guard.ts` against its
37
34
  directory's pattern either way.
38
35
 
39
- **A `Response` ends the request; nothing lets it through.** A redirect, a
40
- `401`, a `403` — whatever it returns is the answer, and the guards inside it
41
- and the page below never run. Returning nothing hands the request on to the
42
- next guard, and the last one to what answers the URL.
43
-
44
- A redirect's `location` goes out as the guard wrote it. It is a URL, not a
45
- pattern in the table's terms like a `redirect.ts` target, so build it with
46
- `href()`, which carries Vite's `base` when the application is served under
47
- one. A pathname built some other way gets its base from `withBase()`.
36
+ **A guard ends the request three ways; returning nothing lets it through.**
37
+ `redirect(url)` answers with a `303` to `url`; `notFound()` answers with
38
+ the nearest `not-found.tsx` under a 404, as for a URL nothing answers; and
39
+ a `Response` it returns — a `401`, a `403` — is the answer as it is. Both
40
+ functions throw, so the lines after them never run, and the guards inside it
41
+ and the page below never run either. What the guard wrote before it ended
42
+ the request — a cookie deleted, a header — goes out on the answer. Returning
43
+ nothing hands the request on to the next guard, and the last one to what
44
+ answers the URL. A redirect is `redirect()`, never a `Response` with a
45
+ `location` of your own: the one way an action ends with one too.
46
+
47
+ `redirect()` takes a URL, not a pattern in the table's terms like a
48
+ `redirect.ts` target, so build it with `href()`, which carries Vite's
49
+ `base` when the application is served under one. A pathname built some
50
+ other way gets its base from `withBase()`. A `303` is what a form posted
51
+ without JavaScript needs — the browser follows it with a `GET`, and a
52
+ guard runs before the Server Action a `POST` carries — and for a `GET` it
53
+ is the same as a `307`.
48
54
 
49
55
  Letting a request through can still add to its answer. `responseHeaders()`
50
56
  is the `Headers` the final response will carry, whatever answers — the page,
@@ -68,8 +74,9 @@ rewritten: a page streams, and its headers are on the wire before its body is
68
74
  written, so a guard decides before the page starts, never after.
69
75
 
70
76
  **What a guard covers.** A guard runs before every URL below its directory —
71
- each page, its payload for a client navigation, a `HEAD`, a Server Action
72
- posted to it, a `route.ts`, and a `not-found.tsx` below it; the root's also
77
+ each page, its payload for a client navigation (handed to the guard under
78
+ the page's URL, search included, so `new URL(request.url).pathname` is the
79
+ page's either way), a `HEAD`, a Server Action posted to it, a `route.ts`, and a `not-found.tsx` below it; the root's also
73
80
  runs for a URL nothing answers. A `redirect.ts` is answered before any guard
74
81
  runs: the URL it answers has no page to guard, and the pages below its
75
82
  directory are guarded as usual. A guard does not protect a Server Action as
@@ -113,24 +120,85 @@ RFC 6265's token characters throws.
113
120
  `delete` takes the `path` and `domain` the cookie was set with
114
121
  (`CookieScope`), since those are what a browser keys it by.
115
122
 
116
- A page never writes a cookie: it reads `request.cookies` from its props, the
117
- cookies the request carried.
123
+ A page never writes a cookie: it reads `request.cookies` from its props —
124
+ the cookies the request carried, with what the guards and a Server Action
125
+ wrote earlier in the same request, so a write is seen by the render that
126
+ answers it.
127
+
128
+ ## Work after the answer
129
+
130
+ `waitUntil(promise)` keeps the host from stopping before `promise` settles,
131
+ for work that goes on once the answer has left — a generation read to its
132
+ end and saved after the visitor closed the tab, a log line sent to another
133
+ service:
134
+
135
+ ```ts
136
+ // src/routes/api/chat/route.ts
137
+ import { waitUntil } from '@k8ordo/framework/server';
138
+
139
+ export async function POST({ request }: { request: Request }) {
140
+ const generation = await generate(await request.json());
141
+ const [forVisitor, forStore] = generation.tee();
142
+ // Reading forStore to its end does not depend on the visitor reading theirs.
143
+ waitUntil(save(forStore));
144
+ return new Response(forVisitor);
145
+ }
146
+ ```
147
+
148
+ It means what a Service Worker's `waitUntil` means. The work has already
149
+ started when it is called — `save(forStore)` above runs whether or not it is
150
+ handed over — and the framework never calls anything again; handing the
151
+ promise over only tells the host the request is not finished yet. Without it
152
+ a host is free to stop once the response ends: Vercel freezes the function,
153
+ and `node dist/server.js` told to stop exits with the save half done.
154
+
155
+ It can be called wherever the request is in progress: a `guard.ts`, a
156
+ `route.ts`, a Server Action, a layout or a page, and from inside the stream
157
+ a `route.ts` answered with. It writes nothing to the response, which is why
158
+ a render may call it where `cookies()` may not. Outside a request it throws,
159
+ and under `mode: 'static'` it is refused with the rest of
160
+ `@k8ordo/framework/server`.
161
+
162
+ A promise that rejects does not become an unhandled rejection. The handler
163
+ logs it once, with the request it belongs to, and goes on:
164
+
165
+ ```
166
+ k8ordo: waitUntil() of POST /api/chat failed Error: …
167
+ ```
168
+
169
+ What keeps the process alive is the host's own means, so it depends on where
170
+ the handler runs — `node dist/server.js` waits before it exits, Vercel needs
171
+ `@vercel/functions` installed, and a runtime that calls the handler itself
172
+ hands it its own `waitUntil`: [Running the build](deploy.md#running-the-build),
173
+ [The request handler](deploy.md#the-request-handler) and
174
+ [Deploying to Vercel](deploy.md#deploying-to-vercel). `vite dev` and
175
+ `vite preview` have no host to tell and need none: the process stays up.
118
176
 
119
177
  ## Reading the request
120
178
 
121
179
  A page and a layout receive `request` beside `params` and `pathname`: the
122
- headers, and the cookies parsed by name, both read-only.
180
+ headers as they arrived, and the cookies by name — what the request carried,
181
+ with what a guard or a Server Action wrote earlier in the same request —
182
+ both read-only.
123
183
 
124
184
  ```tsx
125
185
  // src/routes/layout.tsx
126
186
  import type { LayoutProps } from '@k8ordo/framework';
127
187
 
188
+ import { Analytics } from '../components/analytics';
189
+ import { Shell } from '../components/shell';
190
+ import { density } from '../state';
191
+
128
192
  export default function RootLayout({ children, request }: LayoutProps<'/'>) {
129
- const theme = request.cookies.get('theme') ?? 'light';
130
- const language = request.headers.get('accept-language') ?? 'en';
193
+ const optedOut = request.headers.get('sec-gpc') === '1';
131
194
  return (
132
- <html data-theme={theme} lang={language.split(',')[0]}>
133
- <body>{children}</body>
195
+ <html lang="en">
196
+ <body>
197
+ <Shell initialCookie={density.parseCookies(request.cookies)}>
198
+ {children}
199
+ </Shell>
200
+ {optedOut ? null : <Analytics />}
201
+ </body>
134
202
  </html>
135
203
  );
136
204
  }
@@ -142,9 +210,12 @@ export default function RootLayout({ children, request }: LayoutProps<'/'>) {
142
210
  takes it as a prop.
143
211
 
144
212
  A preference kept in a `@k8ordo/state` cookie state renders without a flash
145
- of the default this way: the layout reads it with
146
- `parseCookies(request.cookies)` and hands the result to the client component
147
- as `initialCookie`.
213
+ of the default this way: the layout above reads it with
214
+ `density.parseCookies(request.cookies)` and hands the result to the client
215
+ component as `initialCookie`. A guard, a `route.ts` or a Server Action reads
216
+ it with `density.parseCookies(cookies())`. The header the layout reads is
217
+ Global Privacy Control's `Sec-GPC`, which decides whether the page carries
218
+ an analytics script at all.
148
219
 
149
220
  Nothing lets a page write to the response — no status, no `Set-Cookie` —
150
221
  because a page is a render, and a render that answered the request would be