@k8ordo/framework 3.0.0 → 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 (55) hide show
  1. package/README.md +6 -4
  2. package/dist/cli.mjs +3 -3
  3. package/dist/generated.d.mts +12 -13
  4. package/dist/index.d.mts +3 -3
  5. package/dist/index.mjs +1 -1
  6. package/dist/paths-type-DXpmjaOr.d.mts +43 -0
  7. package/dist/runtime/app-router.mjs +1 -1
  8. package/dist/runtime/browser-payloads.mjs +1 -1
  9. package/dist/runtime/cookies.d.mts +2 -0
  10. package/dist/runtime/cookies.mjs +2 -1
  11. package/dist/runtime/ended.d.mts +7 -0
  12. package/dist/runtime/ended.mjs +14 -0
  13. package/dist/runtime/entry.browser.mjs +1 -1
  14. package/dist/runtime/entry.rsc.d.mts +17 -7
  15. package/dist/runtime/entry.rsc.mjs +42 -33
  16. package/dist/runtime/entry.ssr.d.mts +1 -0
  17. package/dist/runtime/entry.ssr.mjs +4 -3
  18. package/dist/runtime/guard.d.mts +15 -10
  19. package/dist/runtime/guard.mjs +8 -2
  20. package/dist/runtime/mount.mjs +1 -1
  21. package/dist/runtime/page-boundary.mjs +2 -2
  22. package/dist/runtime/params.d.mts +5 -4
  23. package/dist/runtime/params.mjs +2 -2
  24. package/dist/runtime/redirect.d.mts +13 -7
  25. package/dist/runtime/redirect.mjs +25 -9
  26. package/dist/runtime/request-scope.d.mts +37 -2
  27. package/dist/runtime/request-scope.mjs +60 -3
  28. package/dist/runtime/request.d.mts +6 -1
  29. package/dist/runtime/request.mjs +7 -2
  30. package/dist/runtime/route.d.mts +4 -2
  31. package/dist/runtime/route.mjs +13 -5
  32. package/dist/runtime/server.d.mts +5 -5
  33. package/dist/runtime/server.mjs +2 -2
  34. package/dist/runtime/shell.d.mts +2 -1
  35. package/dist/serve.d.mts +4 -0
  36. package/dist/serve.mjs +26 -13
  37. package/dist/{static-c-nX9Juk.d.mts → static-Be3xIqd8.d.mts} +19 -12
  38. package/dist/{static-file-BEk_xO5y.mjs → static-file-BS-WEiwu.mjs} +180 -136
  39. package/dist/{static-host-CyAmsL_7.mjs → static-host-tIDLqV8c.mjs} +1 -1
  40. package/dist/vercel.d.mts +18 -1
  41. package/dist/vercel.mjs +104 -7
  42. package/dist/vite.d.mts +6 -3
  43. package/dist/vite.mjs +155 -65
  44. package/docs/GUIDE.md +149 -21
  45. package/docs/llms.txt +102 -47
  46. package/docs/references/actions.md +14 -5
  47. package/docs/references/boundaries.md +23 -2
  48. package/docs/references/csp.md +91 -2
  49. package/docs/references/deploy.md +85 -16
  50. package/docs/references/errors.md +18 -10
  51. package/docs/references/guards.md +100 -29
  52. package/docs/references/params.md +91 -22
  53. package/docs/references/routing.md +171 -31
  54. package/package.json +15 -10
  55. package/dist/paths-type-DtsL8JuC.d.mts +0 -19
@@ -95,6 +95,7 @@ export default defineConfig({
95
95
  plugins: [
96
96
  framework({
97
97
  mode: 'static',
98
+ site: 'https://example.com',
98
99
  csp: {
99
100
  'script-src': ["'self'", await colorSchemeScriptHash()],
100
101
  'object-src': ["'none'"],
@@ -111,8 +112,11 @@ made from `default-src` — unless the policy lets it in already with
111
112
  `'unsafe-inline'`: a hash beside that would turn `'unsafe-inline'` off for
112
113
  every `style` attribute as well.
113
114
 
114
- An inline script of the application's is allowed by its hash in that policy,
115
- as `colorSchemeScriptHash()` gives `@k8ordo/color-scheme`'s (pass it the
115
+ An inline script of the application's is allowed by its hash in that policy:
116
+ `scriptHash(text)` from `@k8ordo/framework/vite` resolves to the source,
117
+ `'sha256-…'`, for the text its `<script>` is given
118
+ ([A script of the application's that runs before the first paint](#a-script-of-the-applications-that-runs-before-the-first-paint)),
119
+ as `colorSchemeScriptHash()` does for `@k8ordo/color-scheme`'s (pass it the
116
120
  props `ColorSchemeScript` is given, `nonce` aside); any other inline script
117
121
  on the page — one that reached it from content — is refused. The framework's module
118
122
  script is allowed by where it comes from (`'self'`), since nothing in a file
@@ -139,3 +143,88 @@ browser fetches
139
143
  so a policy that restricts `connect-src`, or `default-src` in its place,
140
144
  names the API's origin there:
141
145
  `'connect-src': ["'self'", 'https://api.example.com']`.
146
+
147
+ ## A script of the application's that runs before the first paint
148
+
149
+ A preference only the browser applies — a density kept with
150
+ `@k8ordo/state`'s `defineLocalState`, say — reaches `<html>` before the
151
+ first paint through an inline script in the root layout's `<head>`, which
152
+ reads the stored value with `inlineRead()`
153
+ ([Routing](routing.md#how-a-page-is-sent) says why `<head>`). Write it the
154
+ way `@k8ordo/color-scheme` writes its own, under either mode:
155
+
156
+ - **A `'use client'` component, not a `<script>` in the layout.** The text of
157
+ a `<script>` a Server Component renders goes into every page's payload —
158
+ each `.rsc`, and the copy written into the HTML for hydration — though a
159
+ script that arrives with a navigation never runs. A client component's
160
+ payload carries only its props, and the server render and hydration both
161
+ build the text from its module.
162
+ - **The nonce as a prop.** The root layout passes `nonce()` under server
163
+ mode. Under static mode it passes nothing, and `csp` names the hash of the
164
+ same text, `scriptHash(densityScript)`, which a module without a directive
165
+ exports for both the component and `vite.config.ts`.
166
+
167
+ ```ts
168
+ // src/lib/density-script.ts
169
+ import { densityState } from '../state';
170
+
171
+ export const densityScript = `(() => {
172
+ const s = ${densityState.inlineRead()};
173
+ if (s && s.density === 'compact') {
174
+ document.documentElement.dataset.density = 'compact';
175
+ }
176
+ })();`;
177
+ ```
178
+
179
+ ```tsx
180
+ // src/components/density-script.tsx
181
+ 'use client';
182
+
183
+ import { densityScript } from '../lib/density-script';
184
+
185
+ export function DensityScript({ nonce }: { nonce?: string }) {
186
+ return <script nonce={nonce}>{densityScript}</script>;
187
+ }
188
+ ```
189
+
190
+ ```tsx
191
+ // src/routes/layout.tsx — server mode; under static mode, no nonce
192
+ <head>
193
+ <ColorSchemeScript nonce={nonce()} />
194
+ <DensityScript nonce={nonce()} />
195
+ </head>
196
+ ```
197
+
198
+ ```ts
199
+ // vite.config.ts — static mode
200
+ import { colorSchemeScriptHash } from '@k8ordo/color-scheme';
201
+ import { framework, scriptHash } from '@k8ordo/framework/vite';
202
+ import { defineConfig } from 'vite';
203
+
204
+ import { densityScript } from './src/lib/density-script';
205
+
206
+ export default defineConfig({
207
+ plugins: [
208
+ framework({
209
+ mode: 'static',
210
+ site: 'https://example.com',
211
+ csp: {
212
+ 'script-src': [
213
+ "'self'",
214
+ await colorSchemeScriptHash(),
215
+ await scriptHash(densityScript),
216
+ ],
217
+ },
218
+ }),
219
+ ],
220
+ });
221
+ ```
222
+
223
+ `scriptHash()` hashes the text as it is, so give it the very string the
224
+ `<script>` is given: a character more or less, a space included, is another
225
+ script, and the policy refuses it. A line break counts as the browser parses
226
+ the page, a CR LF as one LF, so a text read from a file checked out with
227
+ CR LF hashes as the script that runs.
228
+
229
+ The script changes `<html>` before React hydrates it, so `<html>` carries
230
+ `suppressHydrationWarning`, as it does for `@k8ordo/color-scheme`.
@@ -24,7 +24,7 @@ dist/
24
24
  index.rsc
25
25
  404.html not-found.tsx, rendered
26
26
  client-files.json what each page loads beyond its payload, for a navigation to link ahead
27
- sitemap.xml every page above, when `site` is set
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
@@ -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
@@ -560,7 +628,7 @@ const acceptsMarkdown = [
560
628
 
561
629
  export default defineConfig({
562
630
  plugins: [
563
- framework({ mode: 'static' }),
631
+ framework({ mode: 'static', site: 'https://example.com' }),
564
632
  vercel({
565
633
  beforeFiles: [
566
634
  {
@@ -675,6 +743,7 @@ export default defineConfig({
675
743
  plugins: [
676
744
  framework({
677
745
  mode: 'static',
746
+ site: 'https://example.com',
678
747
  headers: {
679
748
  'X-Content-Type-Options': 'nosniff',
680
749
  'Referrer-Policy': 'strict-origin-when-cross-origin',
@@ -744,7 +813,7 @@ An application served below the root of its origin — `https://example.com/docs
744
813
  // vite.config.ts
745
814
  export default defineConfig({
746
815
  base: '/docs/',
747
- plugins: [framework({ mode: 'static' })],
816
+ plugins: [framework({ mode: 'static', site: 'https://example.com' })],
748
817
  });
749
818
  ```
750
819
 
@@ -753,18 +822,18 @@ export default defineConfig({
753
822
  in the address bar. What crosses between the two gains or loses the base on
754
823
  the way:
755
824
 
756
- - 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
757
827
  `pathname` without it, and `usePathname()` returns it without it.
758
828
  - A page's payload sits beside it — `/docs/products/index.rsc` — and the
759
829
  client build's files are under `/docs/assets/`.
760
830
  - A `redirect.ts` target is written from the root, like the table, and is
761
831
  sent with the base in front; one that names another origin is sent as
762
832
  written.
763
- - Under `mode: 'server'`, a redirect the application builds itself is sent
764
- as written: `redirect()` from a Server Action, and the `location` of a
765
- `Response` a `guard.ts` returns. Both are URLs, so build them with
766
- `href()` — `redirect(href('/talks'))`, `location: href('/login')` — or
767
- 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()`.
768
837
  - A URL outside the base is none of the application's: the handler answers
769
838
  it with a `404`, and the client runtime leaves it to the browser.
770
839
 
@@ -124,7 +124,11 @@ is also what a URL nothing matches gets from such an application; under
124
124
  `mode: 'static'` no `404.html` is written, so such a URL gets the host's own 404.
125
125
 
126
126
  `notFound()` is the page's word about itself: thrown from the page's own
127
- 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.
128
132
 
129
133
  **Under `mode: 'server'` a document waits for its page.** A status leaves
130
134
  before the body it heads, so a page's HTML is not sent until the page's own
@@ -167,15 +171,15 @@ export default '/products';
167
171
  ```
168
172
 
169
173
  The target is a pattern the matched params fill in, so `/:locale/legacy` can
170
- 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
171
177
  does, so a literal directory beside a `[slug]/redirect.ts` keeps its URL; a
172
178
  directory that redirects has no page to render, so it cannot hold both. The
173
- generated table checks the default export's shape; `RedirectTarget` is that
174
- type, for a file that wants the error where it is written
175
- (`export default '/products' satisfies RedirectTarget`, with
176
- `import type { RedirectTarget } from '@k8ordo/framework/server'`, which
177
- `mode: 'static'` lets through; `import { type RedirectTarget }` is kept as an
178
- 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`).
179
183
 
180
184
  **Under `mode: 'server'`** the answer to a `GET` or `HEAD` is a `307`, or a
181
185
  `308` when `permanent`, and any other method gets a `405`; a client
@@ -189,6 +193,10 @@ ever send the status; there is no `index.rsc` beside it, so a client
189
193
  navigation to it hands the URL to the browser, which loads that page and
190
194
  follows it.
191
195
 
192
- 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
193
198
  ([Ending with a redirect](actions.md#ending-with-a-redirect)), under
194
- `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