foldkit-ssr 0.10.0 → 0.12.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 (74) hide show
  1. package/README.md +693 -61
  2. package/dist/{client-XnpTQZHw.d.ts → client-BEHlUHBv.d.ts} +10 -7
  3. package/dist/client-BEHlUHBv.d.ts.map +1 -0
  4. package/dist/client.d.ts +6 -5
  5. package/dist/client.js +66 -18
  6. package/dist/client.js.map +1 -1
  7. package/dist/context.d.ts +1 -1
  8. package/dist/context.js.map +1 -1
  9. package/dist/diagnostics.d.ts +2 -2
  10. package/dist/diagnostics.js +14 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/handoff.d.ts +23 -0
  13. package/dist/handoff.d.ts.map +1 -0
  14. package/dist/handoff.js +15 -0
  15. package/dist/handoff.js.map +1 -0
  16. package/dist/index.d.ts +108 -26
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +386 -51
  19. package/dist/index.js.map +1 -1
  20. package/dist/keep.d.ts +5 -1
  21. package/dist/keep.d.ts.map +1 -1
  22. package/dist/keep.js +55 -11
  23. package/dist/keep.js.map +1 -1
  24. package/dist/{listen-DaUPRKVR.d.ts → listen-7HzKBhqU.d.ts} +11 -2
  25. package/dist/{listen-DaUPRKVR.d.ts.map → listen-7HzKBhqU.d.ts.map} +1 -1
  26. package/dist/listen.d.ts +2 -2
  27. package/dist/listen.js +17 -7
  28. package/dist/listen.js.map +1 -1
  29. package/dist/loader.d.ts +13 -0
  30. package/dist/loader.d.ts.map +1 -0
  31. package/dist/loader.js +156 -0
  32. package/dist/loader.js.map +1 -0
  33. package/dist/marks-CX15BwOw.d.ts +39 -0
  34. package/dist/marks-CX15BwOw.d.ts.map +1 -0
  35. package/dist/marks.d.ts +2 -0
  36. package/dist/marks.js +41 -0
  37. package/dist/marks.js.map +1 -0
  38. package/dist/pageCache-DO0pOgnc.d.ts +80 -0
  39. package/dist/pageCache-DO0pOgnc.d.ts.map +1 -0
  40. package/dist/pageCache.d.ts +2 -0
  41. package/dist/pageCache.js +112 -0
  42. package/dist/pageCache.js.map +1 -0
  43. package/dist/{requestContext-D9nsbGSJ.d.ts → requestContext-DmwmQeci.d.ts} +12 -2
  44. package/dist/requestContext-DmwmQeci.d.ts.map +1 -0
  45. package/dist/requestContext.d.ts +2 -2
  46. package/dist/requestContext.js +30 -13
  47. package/dist/requestContext.js.map +1 -1
  48. package/dist/{resumable-BPN_qQHU.d.ts → resumable-BV9_OKxr.d.ts} +7 -10
  49. package/dist/resumable-BV9_OKxr.d.ts.map +1 -0
  50. package/dist/resumable.d.ts +2 -1
  51. package/dist/resumable.js +16 -19
  52. package/dist/resumable.js.map +1 -1
  53. package/dist/runtimeChunk.d.ts +13 -0
  54. package/dist/runtimeChunk.d.ts.map +1 -0
  55. package/dist/runtimeChunk.js +36 -0
  56. package/dist/runtimeChunk.js.map +1 -0
  57. package/dist/runtimeUrl.d.ts +10 -0
  58. package/dist/runtimeUrl.d.ts.map +1 -0
  59. package/dist/runtimeUrl.js +13 -0
  60. package/dist/runtimeUrl.js.map +1 -0
  61. package/dist/{shared-DbupL3vO.d.ts → shared-mQ8CXr-r.d.ts} +69 -22
  62. package/dist/shared-mQ8CXr-r.d.ts.map +1 -0
  63. package/dist/shared.d.ts +3 -2
  64. package/dist/shared.js +40 -18
  65. package/dist/shared.js.map +1 -1
  66. package/dist/vite.d.ts +3 -2
  67. package/dist/vite.d.ts.map +1 -1
  68. package/dist/vite.js +2 -1
  69. package/dist/vite.js.map +1 -1
  70. package/package.json +11 -6
  71. package/dist/client-XnpTQZHw.d.ts.map +0 -1
  72. package/dist/requestContext-D9nsbGSJ.d.ts.map +0 -1
  73. package/dist/resumable-BPN_qQHU.d.ts.map +0 -1
  74. package/dist/shared-DbupL3vO.d.ts.map +0 -1
package/README.md CHANGED
@@ -12,7 +12,7 @@ change between minor versions.
12
12
  pnpm add foldkit-ssr foldkit-surface foldkit effect
13
13
  ```
14
14
 
15
- ```ts
15
+ ```ts sketch
16
16
  // In outline; `App`, `config` and `template` are the application's own, and
17
17
  // [A first page](#a-first-page) splits this into its modules.
18
18
 
@@ -104,6 +104,88 @@ Message as Foldkit types them.
104
104
  The code is in three modules, because the server and the browser import
105
105
  different things:
106
106
 
107
+ <!-- docs-check standalone define ssr-app
108
+ import { Effect, Layer, Option, Schema } from 'effect'
109
+ import { Command } from 'foldkit'
110
+ import type { HtmlBuilder } from 'foldkit/html'
111
+ import { defineMessageUnion } from 'foldkit/message'
112
+ import { defineRouteUnion } from 'foldkit/route'
113
+ import { Remote } from 'foldkit-remote'
114
+ import { Projection, Surface } from 'foldkit-surface'
115
+
116
+ const AppRoute = defineRouteUnion({ Home: {}, Post: { id: Schema.String }, NotFound: {} })
117
+ const Model = Schema.Struct({
118
+ route: AppRoute,
119
+ post: Schema.Struct({
120
+ id: Schema.String,
121
+ title: Schema.String,
122
+ body: Schema.String,
123
+ excerpt: Schema.String,
124
+ publishedAt: Schema.String,
125
+ liked: Schema.Boolean,
126
+ }),
127
+ draft: Schema.String,
128
+ menuOpen: Schema.Boolean,
129
+ remote: Remote.Model,
130
+ })
131
+ type Model = typeof Model.Type
132
+ const Modifiers = Schema.Struct({
133
+ shiftKey: Schema.Boolean,
134
+ ctrlKey: Schema.Boolean,
135
+ altKey: Schema.Boolean,
136
+ metaKey: Schema.Boolean,
137
+ })
138
+ const Message = defineMessageUnion({
139
+ ...Remote.messages,
140
+ Liked: { id: Schema.String },
141
+ ChangedDraft: { value: Schema.String },
142
+ Renamed: { id: Schema.String, title: Schema.String },
143
+ Pressed: { key: Schema.String, modifiers: Modifiers },
144
+ })
145
+ type Message = typeof Message.Type
146
+ const initial: Model = {
147
+ route: AppRoute.Post({ id: 'p1' }),
148
+ post: { id: 'p1', title: 'Hello', body: '', excerpt: '', publishedAt: '2026-01-01', liked: false },
149
+ draft: '',
150
+ menuOpen: false,
151
+ remote: Remote.initial,
152
+ }
153
+ const App = Surface.application({ Model, Message, initial, update: (model: Model) => ({ model }) })
154
+ const Data = Remote.make({ model: App.model.remote, entities: [] })
155
+ const PostActions = App.surface('PostActions', {
156
+ params: { id: Schema.String },
157
+ model: ({ model }) => ({ liked: model.post.liked }),
158
+ messages: [Message.Liked],
159
+ })
160
+ const Menu = App.surface('Menu', { model: ({ model }) => ({ open: model.menuOpen }) })
161
+ const Like = App.surface('Like', {
162
+ model: ({ model }) => ({ id: model.post.id }),
163
+ messages: [Message.Liked],
164
+ })
165
+ const PostActionsAt = Surface.when(PostActions, App.model.route, AppRoute.Post, route => ({
166
+ id: route.id,
167
+ }))
168
+ const PostPageAt = Surface.at(Menu, undefined)
169
+ const LoadPreferences = Command.define('LoadPreferences', {
170
+ messages: [Message.ChangedDraft],
171
+ execute: Effect.succeed(Message.ChangedDraft({ value: '' })),
172
+ })
173
+ const config = {
174
+ Model,
175
+ init: () => ({ model: initial }),
176
+ update: (model: Model, _message: Message) => ({ model }),
177
+ view: (model: Model, h: HtmlBuilder<Message>) => ({
178
+ title: model.post.title,
179
+ body: h.p([], [model.draft]),
180
+ }),
181
+ container: null,
182
+ }
183
+ declare const template: string
184
+ declare const buildId: string
185
+ declare const url: string
186
+ declare const request: Request
187
+ -->
188
+
107
189
  ```ts
108
190
  // post.ts, read by both: the plan. Which part of the Model the browser owns;
109
191
  // the rest starts from the baseline, by default the application's initial Model.
@@ -116,6 +198,14 @@ export const Post = SSR.plan(App, {
116
198
  })
117
199
  ```
118
200
 
201
+ <!-- docs-check standalone use ssr-app
202
+ import { SSR as Plans } from 'foldkit-ssr/client'
203
+ const Post = Plans.plan(App, {
204
+ id: 'post',
205
+ state: Projection.pick(App.model.route, App.model.draft),
206
+ })
207
+ -->
208
+
119
209
  ```ts
120
210
  // server.ts, per request.
121
211
  import { Effect } from 'effect'
@@ -125,6 +215,14 @@ const result = await Effect.runPromise(SSR.render(config, Post, { buildId, url:
125
215
  const html = SSR.page(template, result)
126
216
  ```
127
217
 
218
+ <!-- docs-check standalone use ssr-app
219
+ import { SSR as Plans } from 'foldkit-ssr/client'
220
+ const Post = Plans.plan(App, {
221
+ id: 'post',
222
+ state: Projection.pick(App.model.route, App.model.draft),
223
+ })
224
+ -->
225
+
128
226
  ```ts
129
227
  // client.ts, the page's script, instead of Runtime.hydrate.
130
228
  import { SSR } from 'foldkit-ssr/client'
@@ -133,7 +231,7 @@ SSR.hydrate(config, Post, { buildId })
133
231
  ```
134
232
 
135
233
  `foldkit-ssr/client` is the browser's part: `SSR.plan`, `SSR.resume`,
136
- `SSR.hydrate`, `SSR.static`, `SSR.serving`, `Resume`, and the attribute names,
234
+ `SSR.hydrate`, `SSR.static`, `SSR.unbound`, `SSR.serving`, `Resume`, and the attribute names,
137
235
  Foldkit's root stamp (`FOLDKIT_APP_ATTRIBUTE`) among them. It imports nothing
138
236
  of `foldkit/experimental/server`, whose renderer and HTML parser `foldkit-ssr`
139
237
  brings along: about 200 kB minified (60 kB gzipped) off a page's script in the
@@ -168,6 +266,10 @@ The browser does not run `init`, so the Commands it returns would run nowhere.
168
266
  `SSR.render` refuses a plan that would drop them, naming them. Say what the
169
267
  browser runs on load in `boot`:
170
268
 
269
+ <!-- docs-check standalone use ssr-app
270
+ import { SSR } from 'foldkit-ssr'
271
+ -->
272
+
171
273
  ```ts
172
274
  const Post = SSR.plan(App, {
173
275
  id: 'post',
@@ -179,27 +281,42 @@ const Post = SSR.plan(App, {
179
281
  An application assembled with `foldkit-bundle` runs its assembly's startup
180
282
  Commands, which is where a `Mirror.kv` restores what the user saved:
181
283
 
182
- ```ts
284
+ ```ts sketch
183
285
  boot: model => assembly.init(model).commands ?? []
184
286
  ```
185
287
 
186
288
  ### Styles in the first paint
187
289
 
188
290
  A generated page styled with `foldkit-mixins` can ship the CSS its markup uses
189
- in the head, so it is styled before any script runs. `head` is given the rendered
190
- application; `Style.usedIn` returns the CSS of every compiled class the markup
191
- carries, with the global rules (keyframes, `raise`'s depth rules) of the Styles
192
- those classes came from. In the browser, Styles bring their rules as they draw and skip what
193
- this sheet already carries, so nothing is added twice.
291
+ in the head, so it is styled before any script runs. `head` is given the
292
+ rendered application and the compiled classes the render drew; `Style.usedDrawn`
293
+ writes the CSS of those classes, with the global rules (keyframes, `raise`'s
294
+ depth rules) of the Styles they came from, without scanning the HTML. In the
295
+ browser, Styles bring their rules as they draw and skip what this sheet already
296
+ carries, so nothing is added twice.
297
+
298
+ <!-- docs-check
299
+ const result = await Effect.runPromise(SSR.render(config, Post, { buildId, url }))
300
+ -->
194
301
 
195
302
  ```ts
196
303
  import { Style } from 'foldkit-mixins'
197
304
 
198
305
  const html = SSR.page(template, result, {
199
- head: rendered => `<style>${Style.usedIn(rendered.html)}</style>`,
306
+ head: (_rendered, drawn) => `<style>${Style.usedDrawn(drawn)}</style>`,
200
307
  })
201
308
  ```
202
309
 
310
+ The drawn classes are also on the rendered page (`result.drawn`) for a host
311
+ that writes its own head, and `Style.usedIn(rendered.html)` still works for a
312
+ caller holding only the HTML.
313
+
314
+ With `foldkit-mixins/vite`, the stylesheet is a hashed file, and the page
315
+ links it from the document's head instead (`renderDocument`'s `head`):
316
+ `<link rel="stylesheet" href="${href}" data-foldkit-styles-href>`. A link in
317
+ the head is fetched before the first paint; `styles`, below, is written as the
318
+ root's last children, so a large page paints unstyled until it has all arrived.
319
+
203
320
  A served page has no template head to write to, so `SSR.render`, `SSR.entry`
204
321
  and `SSR.handle` take the same function as `styles` instead, carried as the
205
322
  rendered root's last children. `foldkit-mixins/foundations` writes the theme
@@ -207,11 +324,15 @@ into `index.html` only, never into a page the server renders, so a served
207
324
  page carries the theme's stylesheet here too, beside the classes it draws
208
325
  (`examples/foldkit/ssr/src/renderPage.ts`):
209
326
 
327
+ <!-- docs-check
328
+ declare const stylesheet: string
329
+ -->
330
+
210
331
  ```ts
211
- const styles = (rendered: { readonly html: string }): string =>
212
- `<style>${stylesheet}</style><style>${Style.usedIn(rendered.html)}</style>`
332
+ const styles = (_rendered: { readonly html: string }, drawn: ReadonlySet<string>): string =>
333
+ `<style>${stylesheet}</style><style>${Style.usedDrawn(drawn)}</style>`
213
334
 
214
- SSR.entry(config, plan, { buildId, styles })
335
+ SSR.entry(config, Post, { buildId, styles })
215
336
  ```
216
337
 
217
338
  Without it, every served page flashes unstyled until the script runs. Keep
@@ -221,8 +342,8 @@ again would keep its classes without their rules; `SSR.hydrate` moves them
221
342
  into the document's head before anything adopts the page, whether it resumes
222
343
  or is contained, and the browser's Styles find them there and add nothing
223
344
  twice. A void root holds no children, so styles for one are refused with
224
- `VoidRootWithStyles`, naming the tag. Anything else a head owns (`meta`)
225
- stays with `SSR.generate`.
345
+ `VoidRootWithStyles`, naming the tag. A plan's `meta` rides in the root too,
346
+ for the host to move (`SSR.headed`, under Serving pages).
226
347
 
227
348
  `SSR.generate` takes the same `head`, and answers a `head` that throws `500`,
228
349
  as it does a render that fails. `SSR.entry` takes no `head`: the host owns
@@ -247,6 +368,10 @@ A search result and a link preview read more than Foldkit's `Document`: a
247
368
  description, an image, Open Graph, a post's dates and structured data. The
248
369
  plan's `meta` gives them from the Model:
249
370
 
371
+ <!-- docs-check standalone use ssr-app
372
+ import { SSR } from 'foldkit-ssr'
373
+ -->
374
+
250
375
  ```ts
251
376
  const Post = SSR.plan(App, {
252
377
  id: 'post',
@@ -293,7 +418,7 @@ export default {
293
418
  }
294
419
  ```
295
420
 
296
- ```ts
421
+ ```ts standalone
297
422
  // vite.config.ts, for the dev server and the build id both entries compile in.
298
423
  import { foldkit } from '@foldkit/vite-plugin'
299
424
  import { defineConfig } from 'vite'
@@ -303,7 +428,7 @@ export default defineConfig({
303
428
  })
304
429
  ```
305
430
 
306
- ```ts
431
+ ```ts sketch
307
432
  // entry.server.ts and the browser's entry.ts alike.
308
433
  buildId: import.meta.env.FOLDKIT_BUILD_ID,
309
434
  ```
@@ -343,7 +468,8 @@ the Message is checked against the active Surfaces and `update` runs, so the
343
468
  post starts from the Model the page it came from was drawn with, and one
344
469
  entry, made once, serves every request. A `prepare` that fails is answered
345
470
  `500` and reported; one that would rather draw the page unread recovers
346
- inside its Effect. `POST` is handled only for a plan with a
471
+ inside its Effect. A page the prepared Model says to send elsewhere is a
472
+ `303` ([`redirect`](#sending-a-page-elsewhere-redirect)). `POST` is handled only for a plan with a
347
473
  [server fallback](#forms-that-work-without-scripts). `OPTIONS` is answered
348
474
  `204` and any other method `405`, each with the methods the entry answers in
349
475
  `allow`. A render that fails or throws, `flags` that reject, and a plan the
@@ -357,6 +483,14 @@ the Model. `model` is an `Option`: `some` of the Model the server reached for
357
483
  a rendered page (a posted form's, after `update`), `none` for an answer that
358
484
  rendered nothing (`OPTIONS`, a `405`, a refused post, a `500`).
359
485
 
486
+ <!-- docs-check standalone use ssr-app
487
+ import { SSR } from 'foldkit-ssr'
488
+ const Post = SSR.plan(App, {
489
+ id: 'post',
490
+ state: Projection.pick(App.model.route, App.model.draft),
491
+ })
492
+ -->
493
+
360
494
  ```ts
361
495
  SSR.entry(config, Post, {
362
496
  buildId,
@@ -395,15 +529,40 @@ SSR.entry(config, Post, {
395
529
  ```
396
530
 
397
531
  The page is rendered and resumed as any other; only the response's status
398
- changes. A status outside `200`–`599`, or a `status` that throws, is answered
399
- `500` and reported.
532
+ changes. A status outside `200`–`599`, a `204`, `205` or `304` that cannot
533
+ carry the page, or a `status` that throws, is answered `500` and reported.
534
+
535
+ What the page says of itself (`meta`) belongs in the head, which the host
536
+ owns here, and link previews and crawlers read only the served head. The
537
+ entry carries a plan's `meta` in the rendered root, between two marker
538
+ comments, and `SSR.headed` wraps the host's document renderer to move it
539
+ before `</head>`:
400
540
 
401
- What the page says of itself (`meta`) and per-page `head` markup are written
402
- into a template's head, which the host owns here: a plan with `meta` is
403
- refused when the entry is made, and served with `SSR.generate` below, which
404
- owns its template.
541
+ ```ts
542
+ import { injectIntoTemplate, renderDocument as renderShell } from 'foldkit/experimental/server'
543
+
544
+ // A server entry's document renderer, as the Foldkit Vite plugin takes it
545
+ // (export it as `renderDocument`):
546
+ const headedShell = SSR.headed(renderShell)
547
+
548
+ // A host that hands Foldkit a template instead:
549
+ const headedTemplate = SSR.headed((application: Parameters<typeof injectIntoTemplate>[1]) =>
550
+ injectIntoTemplate(template, application),
551
+ )
552
+ ```
553
+
554
+ Each request's page carries its own `meta`, so nothing of one request reaches
555
+ another's document, and `SSR.keptDocuments(SSR.headed(render))` keeps a kept
556
+ page's document with its head. A host that leaves the wrapper out serves the
557
+ `meta` in the body, where nothing reads it: `SSR.hydrate` then removes it,
558
+ reports `HeadNotMoved`, and the head gets it once the page runs. An e2e test
559
+ reading a served page's head is the check before deploying. `SSR.headed`
560
+ takes the markup only from where the entry put it, at the root's end, so
561
+ marker comments a view draws in its own text (a `<style>`) are not moved. A
562
+ root a parser does not keep `<meta>` in (a void element, a table's, `svg`,
563
+ raw text) is refused (`RootRefusesHead`).
405
564
  [foldkit#1448](https://github.com/foldkit/foldkit/issues/1448) asks Foldkit
406
- for a per-request head channel beside the envelope.
565
+ for a per-request head channel, which would retire `SSR.headed`.
407
566
 
408
567
  ### What the host hands the page: `SSR.requestContext`
409
568
 
@@ -414,6 +573,10 @@ bindings, or a reader built from them. `SSR.requestContext` carries it on the
414
573
  request. The host attaches a value, and `renderPage`, given the same request
415
574
  by `handleRequest`, reads it back:
416
575
 
576
+ <!-- docs-check
577
+ const actives = { page: PostActionsAt }
578
+ -->
579
+
417
580
  ```ts
418
581
  import { Effect, Option, type Layer } from 'effect'
419
582
  import type { RemoteClient, RemoteUnauthenticated } from 'foldkit-remote'
@@ -454,6 +617,152 @@ serves. [`examples/auth`](../../examples/auth)'s `src/host.ts` is the whole
454
617
  site behind one handler; its development server, another process, attaches
455
618
  an HTTP reader instead.
456
619
 
620
+ ### Sending a page elsewhere: `redirect`
621
+
622
+ A page the reader may not see (a notebook asked for by a visitor) is answered
623
+ with a `303` to where they belong, decided from the Model `prepare` read as
624
+ them. `redirect: (model, request) => Option<string>` says so, in the entry
625
+ made once:
626
+
627
+ ```text
628
+ GET url -> init -> prepare (read as the reader) -> redirect(model)
629
+ -> some(path): 303, location: path, cache-control: private, no-store
630
+ -> none: render the page from that same Model
631
+ ```
632
+
633
+ <!-- docs-check
634
+ import { Access } from 'foldkit-site'
635
+ declare const accessOf: (model: Model) => Access
636
+ -->
637
+
638
+ ```ts
639
+ export const guarded = SSR.entry(config, Post, {
640
+ buildId,
641
+ prepare: (model, request) =>
642
+ Option.match(PageContext.of(request), {
643
+ onNone: () => Effect.fail(new Error('No reader for this page.')),
644
+ onSome: ({ reader }) => Data.satisfy(model, actives).pipe(Effect.provide(reader)),
645
+ }),
646
+ redirect: model =>
647
+ Access.match(accessOf(model), {
648
+ Denied: ({ url }) => Option.some(url),
649
+ Allowed: () => Option.none(),
650
+ Pending: () => Option.none(),
651
+ }),
652
+ })
653
+ ```
654
+
655
+ `redirect` runs for `GET` and `HEAD`, after `prepare` and before anything is
656
+ rendered, so the decision and the page come from one read; a page sent
657
+ elsewhere never runs its view. A posted form is answered by
658
+ [`answerPost`](#answering-a-post-with-a-redirect), not by `redirect`.
659
+
660
+ - **It is never kept, for anyone.** A redirect is one reader's answer, so it
661
+ says `cache-control: private, no-store` over whatever `headers` set, and
662
+ `cache` never stores it, however public the reads behind it were. The next
663
+ request is decided again.
664
+ - **It carries the entry's `headers`,** given the Model the redirect was
665
+ decided on (a cookie written from it, `vary`); only `cache-control` is the
666
+ entry's own.
667
+ - **It goes nowhere but a path on this origin.** The path must start with a
668
+ single `/` and, resolved against the request's address, keep its origin:
669
+ an absolute URL (even this origin's), `//elsewhere.test`,
670
+ `/\elsewhere.test` (which a browser reads as `//`), a relative path or a
671
+ scheme is answered `500` and reported, as a `redirect` that throws is. The
672
+ `location` written is the path as resolved.
673
+
674
+ ### Keeping pages: `cache`
675
+
676
+ A page drawn from its URL alone is the same page for everyone who asks for
677
+ that URL, and drawing it again costs the same every time. With `cache`, the
678
+ entry keeps such a page and answers the next request for it from a store:
679
+
680
+ ```text
681
+ GET url -> kept for this build and url, and the request lacks every header it read?
682
+ -> yes: the kept page
683
+ -> no: render, watching what the render reads
684
+ every read public, every header it read absent, no cookie set, 200?
685
+ -> keep it, cache-control: public, max-age=…, vary: <headers read>
686
+ -> otherwise cache-control: private, no-store
687
+ ```
688
+
689
+ ```ts
690
+ import { CacheStore } from 'foldkit-surface'
691
+
692
+ export const cached = SSR.entry(config, Post, {
693
+ buildId,
694
+ cache: { store: CacheStore.memory(), maxAge: '60 seconds' },
695
+ })
696
+ ```
697
+
698
+ Whether a page may be kept is decided from what its render read, not from
699
+ a declaration. The render is handed a request that records each header
700
+ `flags`, `prepare`, `redirect`, `headers` or `status` reads; a page is kept only when
701
+ every one of them was absent from the request, so it was drawn from the URL
702
+ alone. A header read by name (the cart cookie, say) that was absent goes in
703
+ `vary`, and the kept page serves only requests that lack it too: a request
704
+ with that cookie is drawn for itself, and is never kept. Reading every
705
+ header, cloning the request, or reading an `SSR.requestContext` (which may
706
+ say who is asking) keeps nothing. Handing the request itself to `fetch` or
707
+ `new Request` fails the render, since the platform cannot read the watched
708
+ request.
709
+
710
+ Reads count through `foldkit-remote-server`'s `pageReader`, which notes each
711
+ one (`PageReads`): the page is kept only when every read was public, for the
712
+ shortest of `maxAge` and their freshness, tagged with the rows they hold. A
713
+ write `serveFetch` answers purges, from the same store, the pages holding a
714
+ row it names. A read made other than through `pageReader` is not seen, so
715
+ `maxAge` is all that bounds it. A page whose `headers` set a cookie or a
716
+ `cache-control` of their own, one not `200`, and every post, are not kept;
717
+ an unkept page says `private, no-store` unless `headers` said otherwise.
718
+
719
+ The key is the build id and the full URL, so a deploy never serves another
720
+ build's page (the browser would refuse it anyway, as `OtherBuild`).
721
+ `CacheStore.workers(caches.default)` keeps pages in the Workers Cache API.
722
+
723
+ A page is kept for its freshness, often a minute, so a URL asked again after
724
+ that renders again. `CacheStore.kv(env.CACHE, { keep: '6 hours' })` keeps
725
+ pages in Workers KV and serves each for `keep` after it was kept, past a
726
+ shorter `maxAge`: the page carries when each of its reads was made, and a
727
+ browser whose Remote freshness has a `maxAge`
728
+ (`RemotePolicy.staleWhileRevalidate`) reads again what is past it, so the
729
+ server renders a page once in `keep` instead of once a minute. KV writes a page only on its second
730
+ ask and fails open (`foldkit-remote-server`'s README says how). With
731
+ `keep` it is a `PageCacheStore`, which `cache.store` here takes and
732
+ `serveFetch` refuses: a read's answer carries no age.
733
+
734
+ The host draws each page into its document, which parses the page again
735
+ (Foldkit's `injectIntoTemplate`), so a kept page would still cost that on
736
+ every request. Wrap the server entry's `renderDocument` in
737
+ `SSR.keptDocuments` and the document of a kept page is drawn once per set
738
+ of assets (the last 32 are held):
739
+
740
+ ```ts
741
+ import { renderDocument as renderShell, type DocumentRenderer } from 'foldkit/experimental/server'
742
+
743
+ export const renderDocument: DocumentRenderer = SSR.keptDocuments(SSR.headed(renderShell))
744
+ ```
745
+
746
+ The checker draws a kept page again for each request it serves.
747
+ `cache.check` does so on every request a kept page serves, and where the
748
+ two differ reports `CachedPageDiffers` and answers with the page drawn
749
+ again: a development mode. Times stamped on the page (13 digits within a day
750
+ of now, as a read's `updatedAt`) are not compared. `SSR.checkCache(make,
751
+ requests)` is the same, for a test: `make` builds the entry from the
752
+ `cache` and `diagnostics` it is given, and each request is answered twice;
753
+ it rejects a difference, or a set of requests that kept no page. Give it
754
+ requests from more than one reader, a visitor's and one with a cookie:
755
+
756
+ ```ts
757
+ export const checked = SSR.checkCache(
758
+ options => SSR.entry(config, Post, { buildId, ...options }),
759
+ [
760
+ () => new Request('https://example.com/posts/1'),
761
+ () => new Request('https://example.com/posts/1', { headers: { cookie: 'session=abc' } }),
762
+ ],
763
+ )
764
+ ```
765
+
457
766
  ### At build time
458
767
 
459
768
  ```ts
@@ -492,27 +801,6 @@ The Message goes into the starting Model rather than after boot, so a URL
492
801
  mirror does not write the served address back over the real one. A
493
802
  server-rendered page records its path and query, and resumes only there.
494
803
 
495
- Foldkit's Vite plugin prerenders pages through the server entry itself
496
- (`ssr.build.prerender`), so `SSR.entry` cannot tell a build's request from a
497
- visitor's. Name those paths in `prerendered`, and a request for one with no
498
- query records its path alone, as `SSR.generate` does; export the same list
499
- as `prerenderPaths`, which the plugin reads:
500
-
501
- ```ts
502
- export const prerenderPaths = ['/']
503
-
504
- export const { renderPage } = SSR.entry(config, Post, { buildId, prerendered: prerenderPaths })
505
- ```
506
-
507
- A prerendered file the entry was not told of is refused at any other query,
508
- and the reason says so.
509
-
510
- Until the bundle runs, a file shows the state it was recorded with: the
511
- query reaches the Model only when the browser starts. A page whose first
512
- paint depends on its query (a search box filled from `?q=`) is better
513
- rendered per request, which records the query and resumes with nothing
514
- redrawn; `examples/foldkit/domains-plus` prerenders nothing for that reason.
515
-
516
804
  A generated site also wants a sitemap and a `robots.txt` that names it.
517
805
  `SSR.sitemap` takes the pages, with a `modified` date where one is known, and
518
806
  `SSR.robots` the origin:
@@ -541,7 +829,7 @@ The application describes its site in a module (`src/site.ts`) and the plugin
541
829
  evaluates it through a server, so `vite.config.ts` names a file, never
542
830
  application code:
543
831
 
544
- ```ts
832
+ ```ts standalone
545
833
  // vite.config.ts
546
834
  import { foldkit } from '@foldkit/vite-plugin'
547
835
  import { staticSite } from 'foldkit-ssr/vite'
@@ -560,15 +848,24 @@ from the generated pages. `files` is the host's layout — `'directory'`
560
848
  (`/about` as `about/index.html`, the default) or `'flat'` (`about.html`, for a
561
849
  host with clean addresses and no directory indexes):
562
850
 
851
+ <!-- docs-check standalone use ssr-app
852
+ import { Resume, SSR } from 'foldkit-ssr'
853
+ const Post = SSR.plan(App, {
854
+ id: 'post',
855
+ state: Projection.pick(App.model.route, App.model.draft),
856
+ })
857
+ -->
858
+
563
859
  ```ts
564
860
  // src/site.ts
861
+ import { Style } from 'foldkit-mixins'
565
862
  import type { SiteModule } from 'foldkit-ssr/vite'
566
863
  export const site = {
567
864
  origin: 'https://example.com',
568
865
  paths: ['/', '/about'],
569
- config: { Model, init, update, view, container: null, routing },
570
- plan,
571
- head: rendered => `<style>${Style.usedIn(rendered.html)}</style>`,
866
+ config,
867
+ plan: Post,
868
+ head: (_rendered, drawn) => `<style>${Style.usedDrawn(drawn)}</style>`,
572
869
  files: 'directory',
573
870
  sitemap: true,
574
871
  robots: true,
@@ -588,6 +885,78 @@ emitted)` writes the emitted files as the plugin does. `fileFor(path, layout)` m
588
885
  one path to the file a host serves it from, so a caller writes the files
589
886
  itself; `generateStaticSite` refuses two paths that would claim one file.
590
887
 
888
+ ### Pages rendered once, at build: `prerendered`
889
+
890
+ A page that is the same for every visitor need not be rendered by the
891
+ server at all. Rendered once when the application is built, it is a file
892
+ the host serves before any server code runs: on Workers, a static asset,
893
+ which costs no CPU.
894
+
895
+ Foldkit's Vite plugin prerenders pages through the server entry itself
896
+ (`ssr.build.prerender`), so `SSR.entry` cannot tell a build's request from a
897
+ visitor's. Name those paths in `prerendered`, and export the same list as
898
+ `prerenderPaths`, which the plugin reads:
899
+
900
+ ```ts
901
+ export const prerenderPaths = ['/']
902
+
903
+ export const { renderPage } = SSR.entry(config, Post, { buildId, prerendered: prerenderPaths })
904
+ ```
905
+
906
+ ```ts
907
+ // vite.config.ts
908
+ import { foldkit } from '@foldkit/vite-plugin'
909
+
910
+ foldkit({
911
+ ssr: {
912
+ serverEntry: '/src/entry.server.ts',
913
+ clientEntry: '/src/entry.ts',
914
+ build: { prerender: true },
915
+ },
916
+ })
917
+ ```
918
+
919
+ A file is given to every visitor, so a prerendered page is held to the rule
920
+ `cache` keeps a page by, and stricter on headers, since a file cannot vary:
921
+
922
+ ```text
923
+ render "/" -> every read through pageReader public?
924
+ -> no request header read, not even an absent one?
925
+ -> headers set nothing, status 200?
926
+ -> yes: the page, with no headers of its own, written to a file
927
+ -> no: renderPage rejects naming the read, header or status,
928
+ and the build fails
929
+ ```
930
+
931
+ ```text
932
+ foldkit-ssr: / is prerendered, a file every visitor is given, but it read the
933
+ request's cookie header; render it per request instead (leave it out of prerendered)
934
+ ```
935
+
936
+ A read made other than through `pageReader` is not seen. The rule is checked
937
+ on every render of the path, a request for it in development included, and
938
+ the page cache is not consulted for it.
939
+
940
+ The page is fresh as of the build, and the server never renders it again.
941
+ Its resumed Model says when each read was made, so a browser whose Remote
942
+ freshness has a `maxAge` (`RemotePolicy.staleWhileRevalidate`) reads again,
943
+ at boot, every read older than that. The client refreshes the data through
944
+ Remote, which is cheap; only a deploy renders the page anew.
945
+
946
+ A request for a prerendered path with no query records its path alone, as
947
+ `SSR.generate` does, so the file resumes at `/?q=…` too, and the application
948
+ starts from that URL. A prerendered file the entry was not told of is
949
+ refused at any other query, and the reason says so.
950
+
951
+ Until the bundle runs, a file shows the state it was recorded with: the
952
+ query reaches the Model only when the browser starts. And the host, not the
953
+ entry, decides which requests get the file: Workers static assets match by
954
+ path alone, so a prerendered `/` answers `/?q=…` as well, before the Worker
955
+ runs. A page whose first paint depends on its query (a search box filled from
956
+ `?q=`) is better rendered per request, which records the query and resumes
957
+ with nothing redrawn. `examples/foldkit/domains-plus` prerenders nothing for
958
+ that reason, and because its pages read the cart cookie.
959
+
591
960
  ## Checking what the browser will read
592
961
 
593
962
  The view check sees what the first render shows. A Surface can read a field the
@@ -595,6 +964,10 @@ first view never shows: a like button's state, a menu's contents. Name the
595
964
  Surfaces the browser may activate, and the fields that may start from the
596
965
  baseline on purpose:
597
966
 
967
+ <!-- docs-check standalone use ssr-app
968
+ import { Resume, SSR } from 'foldkit-ssr'
969
+ -->
970
+
598
971
  ```ts
599
972
  const Post = SSR.plan(App, {
600
973
  id: 'post',
@@ -608,13 +981,63 @@ const Post = SSR.plan(App, {
608
981
  ```
609
982
 
610
983
  `SSR.render` then refuses the plan, naming the Surface and the field, when an
611
- active Surface reads a field that is in neither `state` nor `local`, is
612
- activated by one, reads data no part of the plan resumes, or would activate
984
+ active Surface reads a field that is in none of `state`, `restored` or `local`,
985
+ is activated by one, reads data no part of the plan resumes, or would activate
613
986
  differently from the Model the browser starts from. The check runs for the
614
987
  server's Model, because a Surface's reads follow its params.
615
988
  `SSR.inspect(plan, model)` returns the same findings as data, for a test or a
616
989
  debugging session: for each Surface, whether it is active, and where each read
617
- comes from, `state`, `local` or `missing`.
990
+ comes from, `state`, `restored`, `local` or `missing`.
991
+
992
+ ### Fields the browser reads again
993
+
994
+ A field a URL or cookie mirror owns is one the browser can read for itself, so
995
+ the envelope need not carry it. Name it in `restored` and give `restore` a
996
+ function applying the browser's values before the first render:
997
+
998
+ <!-- docs-check standalone
999
+ import { Schema } from 'effect'
1000
+ import { defineMessageUnion } from 'foldkit/message'
1001
+ import { Mirror } from 'foldkit-mirror'
1002
+ import { Projection, Surface } from 'foldkit-surface'
1003
+ import { SSR } from 'foldkit-ssr'
1004
+
1005
+ const Model = Schema.Struct({
1006
+ route: Schema.String,
1007
+ results: Schema.Array(Schema.String),
1008
+ query: Schema.String,
1009
+ tld: Schema.String,
1010
+ })
1011
+ type Model = typeof Model.Type
1012
+ const initial: Model = { route: '/', results: [], query: '', tld: '' }
1013
+ const App = Surface.application({
1014
+ Model,
1015
+ Message: defineMessageUnion({ Searched: {} }),
1016
+ initial,
1017
+ update: (model: Model) => ({ model }),
1018
+ })
1019
+ const SearchInUrl = Mirror.url(App, { name: 'search', fields: [App.model.query, App.model.tld] })
1020
+ const SearchFilters = App.surface('SearchFilters', {
1021
+ model: ({ model }) => ({ query: model.query, tld: model.tld }),
1022
+ })
1023
+ -->
1024
+
1025
+ ```ts
1026
+ const SearchPlan = SSR.plan(App, {
1027
+ id: 'search',
1028
+ state: Projection.pick(App.model.route, App.model.results),
1029
+ restored: [App.model.query, App.model.tld],
1030
+ restore: model => SearchInUrl.reduce(model, window.location.href),
1031
+ surfaces: [Surface.at(SearchFilters, undefined)],
1032
+ })
1033
+ ```
1034
+
1035
+ Each restored path is handed the server's value for the coverage check, since
1036
+ the browser reads the same address or cookie; a path that `state` also sends is
1037
+ refused. The first render differs from the served page only where the browser's
1038
+ values differ from the server's, and Foldkit rebuilds that part, as a
1039
+ navigation would. `restore` runs in the browser alone, before adoption, and may
1040
+ throw; the page is then contained and reported as `Invalid`.
618
1041
 
619
1042
  A `Surface.each` family is one entry of `surfaces`: the envelope carries its
620
1043
  parent's reads with its instances', and coverage inspects each instance by key
@@ -629,6 +1052,10 @@ server read, most of which the page never shows. A **part** is a package's own
629
1052
  contribution to the envelope: it captures what the plan's active Surfaces read,
630
1053
  and restores it in the browser.
631
1054
 
1055
+ <!-- docs-check standalone use ssr-app
1056
+ import { Resume, SSR } from 'foldkit-ssr'
1057
+ -->
1058
+
632
1059
  ```ts
633
1060
  const Post = SSR.plan(App, {
634
1061
  id: 'post',
@@ -652,6 +1079,12 @@ An article body, a product description, highlighted code: a part of the page no
652
1079
  Message changes need not render in the browser at all, and what it reads need
653
1080
  not be sent. Mark it with `SSR.static`:
654
1081
 
1082
+ <!-- docs-check
1083
+ import type { Html } from 'foldkit/html'
1084
+
1085
+ declare const PostActionsView: (model: Model, h: HtmlBuilder<Message>) => Html
1086
+ -->
1087
+
655
1088
  ```ts
656
1089
  const view = (model: Model, h: HtmlBuilder<Message>) => ({
657
1090
  title: 'Post', // not the post's title: the browser does not have it
@@ -677,6 +1110,28 @@ needs that is not in the page, say after a Message shows one, is reported
677
1110
  ([`StaticRegionMissing`](#diagnostics), once per page) and rendered in the
678
1111
  browser.
679
1112
 
1113
+ `ih` is `HtmlBuilder<never>`, so an attribute that binds one of the page's
1114
+ Messages does not compile in it. A Slot's attributes are typed with the page's
1115
+ Message whatever its Mixins add, so a Style looks like a handler to the
1116
+ compiler. Pass them through `SSR.unbound`, which types them as binding nothing
1117
+ and throws, when the region is drawn, on a handler or a Submodel's attribute
1118
+ among them:
1119
+
1120
+ <!-- docs-check
1121
+ import type { SlotBuilder } from 'foldkit-mixins'
1122
+
1123
+ declare const slots: { readonly title: SlotBuilder<Message> }
1124
+ declare const model: Model
1125
+ -->
1126
+
1127
+ ```ts
1128
+ SSR.static('post-title', ih => [ih.h1(SSR.unbound(slots.title.attrs()), [model.post.title])])
1129
+ ```
1130
+
1131
+ Attributes `SSR.unbound` returns fit any builder, so one drawing can serve a
1132
+ region and the live page alike: type it over its builder's Message
1133
+ (`<M>(h: HtmlBuilder<M>) => …`).
1134
+
680
1135
  ### What only the browser has: `prepare`
681
1136
 
682
1137
  The server cannot send what it cannot see. What this browser stored (a
@@ -704,6 +1159,34 @@ Remote's durable outbox is the case it was made for. A page that makes
704
1159
  durable writes ([`foldkit-remote`'s outbox](../remote/README.md#a-write-that-outlives-the-page-outbox))
705
1160
  resumes from the outbox's `session`:
706
1161
 
1162
+ <!-- docs-check standalone
1163
+ import { Schema } from 'effect'
1164
+ import type { HtmlBuilder } from 'foldkit/html'
1165
+ import { defineMessageUnion } from 'foldkit/message'
1166
+ import { Remote } from 'foldkit-remote'
1167
+ import { Projection, Surface } from 'foldkit-surface'
1168
+ import { SSR } from 'foldkit-ssr'
1169
+
1170
+ const Model = Schema.Struct({ userId: Schema.String, remote: Remote.Model })
1171
+ type Model = typeof Model.Type
1172
+ const App = Surface.application({
1173
+ Model,
1174
+ Message: defineMessageUnion({ ...Remote.messages }),
1175
+ initial: { userId: 'ada', remote: Remote.initial },
1176
+ update: (model: Model) => ({ model }),
1177
+ })
1178
+ const Data = Remote.make({ model: App.model.remote, entities: [] })
1179
+ const plan = SSR.plan(App, { id: 'outbox', state: Projection.pick(App.model.userId) })
1180
+ const config = {
1181
+ Model,
1182
+ init: () => ({ model: App.initial }),
1183
+ update: (model: Model) => ({ model }),
1184
+ view: (_model: Model, h: HtmlBuilder<never>) => h.p([], []),
1185
+ container: null,
1186
+ }
1187
+ declare const buildId: string
1188
+ -->
1189
+
707
1190
  ```ts
708
1191
  import { outbox } from 'foldkit-remote/outbox'
709
1192
 
@@ -754,6 +1237,10 @@ browser event ──▶ the markers name its Messages ──▶ queued ──
754
1237
  It rests on the fact that a Foldkit handler is already a Message value.
755
1238
  `Resume.builder(h)` is `h` that writes those values into the server's markup:
756
1239
 
1240
+ <!-- docs-check standalone use ssr-app
1241
+ import { Resume, SSR } from 'foldkit-ssr'
1242
+ -->
1243
+
757
1244
  ```ts
758
1245
  const view = (model: Model, h: HtmlBuilder<Message>) => {
759
1246
  const rh = Resume.builder(h)
@@ -800,6 +1287,10 @@ const LikeView = Surface.rootView(
800
1287
 
801
1288
  Then say when the runtime starts:
802
1289
 
1290
+ <!-- docs-check standalone use ssr-app
1291
+ import { Resume, SSR } from 'foldkit-ssr'
1292
+ -->
1293
+
803
1294
  ```ts
804
1295
  const Post = SSR.plan(App, {
805
1296
  id: 'post',
@@ -827,6 +1318,10 @@ boots it, so the Model ends where an eager boot would have taken it.
827
1318
  does. `SSR.render` refuses a deferred plan while one would be active,
828
1319
  naming each, until the plan declares it:
829
1320
 
1321
+ <!-- docs-check standalone use ssr-app
1322
+ import { Resume, SSR } from 'foldkit-ssr'
1323
+ -->
1324
+
830
1325
  ```ts
831
1326
  const Post = SSR.plan(App, {
832
1327
  id: 'post',
@@ -841,6 +1336,12 @@ boots it, so the Model ends where an eager boot would have taken it.
841
1336
  `managedResources` in the config given to `SSR.render`, as you would to
842
1337
  Foldkit. `boot` Commands run at boot, so a deferred page's `Mirror.kv`
843
1338
  restore waits for the first interaction.
1339
+ - **Its fields kept.** On a deferred plan, a field whose binding names its
1340
+ typing (a hole-form `OnInput` or `OnChange`; on a checkbox or radio, any
1341
+ named `OnChange`, `OnInput` or `OnClick`) must carry `rh.KeepTyped()`, or
1342
+ `SSR.render` refuses the page (`UnkeptField`), naming each: what is typed
1343
+ into it before boot would be lost at the first render. A page that starts
1344
+ `'now'` has the same gap for a shorter time and is not refused.
844
1345
 
845
1346
  ### Bundles whose code loads on demand
846
1347
 
@@ -849,7 +1350,7 @@ of the boot chunk. Name each in the config's `lazy` list. A sketch, after
849
1350
  `test/lazyFixture.ts`: `Upload` is the lazy bundle, `PlacedUpload` its
850
1351
  placement, and `placements` their `Bundle.assemble`:
851
1352
 
852
- ```ts
1353
+ ```ts sketch
853
1354
  const config = {
854
1355
  Model,
855
1356
  init: () => placements.init({ title: 'Uploads', upload }),
@@ -877,6 +1378,12 @@ later, and hydration re-asserts each field's value to the Model's: what was
877
1378
  typed in between would vanish. A field marked `rh.KeepTyped()` keeps it,
878
1379
  whatever the plan's `start`:
879
1380
 
1381
+ <!-- docs-check
1382
+ declare const h: HtmlBuilder<Message>
1383
+ declare const model: Model
1384
+ const rh = Resume.builder(h)
1385
+ -->
1386
+
880
1387
  ```ts
881
1388
  rh.input([rh.Value(model.draft), rh.OnInput(Message.ChangedDraft), rh.KeepTyped()])
882
1389
  ```
@@ -903,13 +1410,18 @@ bundle is replayed once the bundle's code has loaded.
903
1410
 
904
1411
  Only a field the page can replay may be marked: an `input` that takes text, a
905
1412
  `textarea` or a `select`, built by `rh` (`rh.input`, not `h.input`), with
906
- `OnInput` or `OnChange` given a Message member. The resumable builder marks
1413
+ `OnInput` or `OnChange` given a Message member; or a checkbox or radio, whose
1414
+ `checked` is compared with what the server rendered and replays its `OnChange`
1415
+ (else `OnInput`, else `OnClick`) Message, in either form. A radio the person
1416
+ moved off replays nothing, since the browser sent it no change; the one now
1417
+ checked replays its own. The resumable builder marks
907
1418
  the bindings of the elements it builds; on an element `h` builds, the hole
908
1419
  forms are plain closures to the page and nothing names the Message to replay.
909
1420
  Anything else is refused on the server (`UnkeepableField`), naming the
910
1421
  element. What is not kept: an unmarked field (re-asserted to the served value,
911
1422
  as before); a key press or click before the script (the browser's own, so a
912
- form submitted then posts, which `fallback: 'server'` answers); a page that is
1423
+ form submitted then posts, which `fallback: 'server'` answers; under
1424
+ [the loader](#the-runtime-on-intent-foldkit-ssrloader) a marked one is held); a page that is
913
1425
  contained, declined or stale; and an IME composition in progress at boot,
914
1426
  which the first render's reset ends, though its text is kept. A value the
915
1427
  browser restored into the field on a reload or a history visit is kept like
@@ -936,6 +1448,66 @@ refused at any query but its own. Markup such a script changes is the
936
1448
  served page no longer, and Foldkit reconciles it at hydration to the Model's
937
1449
  first render.
938
1450
 
1451
+ ### The runtime on intent: `foldkit-ssr/loader`
1452
+
1453
+ `start` defers the runtime's boot, not its code: the entry script still
1454
+ imports the application, so the whole chunk is fetched and evaluated at load.
1455
+ `foldkit-ssr/loader` is an entry script that imports nothing of `effect`,
1456
+ Foldkit or the application (about 2 KB brotli), and runs the chunk when the
1457
+ plan's `start` says:
1458
+
1459
+ ```ts sketch
1460
+ // src/client/loader.ts, the page's entry script
1461
+ import { load } from 'foldkit-ssr/loader'
1462
+
1463
+ load({ runtime: () => import('./entry.js') }) // entry.ts calls SSR.hydrate
1464
+ ```
1465
+
1466
+ ```text
1467
+ load ──▶ read start from the envelope
1468
+ 'now' ──▶ run the chunk
1469
+ 'idle' ──▶ fetch the chunk now ──▶ idle after load, chunk here: run it
1470
+ 'on-interaction' ──▶ fetch the chunk now ──▶ first intent: run it
1471
+ until SSR.hydrate takes over: a marked event ──▶ held (a submission prevented)
1472
+ SSR.hydrate ──▶ starts now ──▶ answers each held event from the markers, once
1473
+ ```
1474
+
1475
+ - **`start` stays the plan's.** The server writes it into the envelope, and
1476
+ the loader adds no policy of its own; the chunk it runs starts at once,
1477
+ since the loader already waited as the plan said.
1478
+ - **Intent** is a pointer over or down, focus, or a key on an element the
1479
+ server marked (a binding of any event, or a kept field), or under
1480
+ `'on-interaction'` a scroll. A pointer crossing unmarked text runs nothing;
1481
+ a reader who only reads is covered by `'idle'`.
1482
+ - **Held, then answered once.** An event of a type the markers name, on a
1483
+ marked element, is held until `SSR.hydrate` claims the loader; a form's
1484
+ submission is prevented while held. `SSR.hydrate` answers each from the
1485
+ markers, as it answers events on a deferred page, so it reaches `update`
1486
+ once. An event on a kept field is not held: the field keeps it in its own
1487
+ state, which `SSR.hydrate` reads.
1488
+ - **Released, never both.** A held event the runtime has not taken 3 s after
1489
+ it happened (`UNTIL_LIMIT_MS`) is released: a submission goes to the
1490
+ browser (`requestSubmit`, with its submitter), so a GET form or a
1491
+ `fallback: 'server'` form still works; anything else is dropped. A chunk
1492
+ that fails to load releases everything at once and holds nothing after,
1493
+ and a page that does not resume (another build, declined, contained)
1494
+ releases what was held as `SSR.hydrate` refuses it.
1495
+ - **Fetched without running.** With `runtimeChunk` from `foldkit-ssr/vite`
1496
+ naming the same module, a client build writes the chunk's address into the
1497
+ loader, which fetches it as it starts, at load and before any idle or intent,
1498
+ with `<link rel="modulepreload">`:
1499
+
1500
+ ```ts sketch
1501
+ plugins: [foldkit({ ssr: { clientEntry: '/src/client/loader.ts', … } }),
1502
+ runtimeChunk({ entry: '/src/client/entry.ts' })]
1503
+ ```
1504
+
1505
+ Fetching is not running: a press before the chunk runs still waits for its
1506
+ evaluation, which a page that evaluates at once (no loader) has begun
1507
+ already. Without it, or under the development server, the chunk is fetched
1508
+ as it runs. A modulepreload fetches that one file; a chunk the runtime shares
1509
+ with another dynamic import is fetched when the runtime runs.
1510
+
939
1511
  ## Forms that work without scripts
940
1512
 
941
1513
  A form whose `OnSubmit` names a Message can be answered by the server, before
@@ -944,6 +1516,40 @@ server can run it. This example is a to-do list, not the post page: its Model
944
1516
  holds `draft` and `todos`, its Message `Added({ title })` and `Typed({ value
945
1517
  })`, and the `TodoList` Surface lists both. The plan opts in:
946
1518
 
1519
+ <!-- docs-check standalone
1520
+ import { Option, Schema } from 'effect'
1521
+ import type { HtmlBuilder } from 'foldkit/html'
1522
+ import { defineMessageUnion } from 'foldkit/message'
1523
+ import { Projection, Surface } from 'foldkit-surface'
1524
+ import { Resume, SSR } from 'foldkit-ssr'
1525
+
1526
+ const Model = Schema.Struct({
1527
+ draft: Schema.String,
1528
+ todos: Schema.Array(Schema.Struct({ title: Schema.String })),
1529
+ })
1530
+ type Model = typeof Model.Type
1531
+ const Message = defineMessageUnion({ Added: { title: Schema.String }, Typed: { value: Schema.String } })
1532
+ type Message = typeof Message.Type
1533
+ const App = Surface.application({
1534
+ Model,
1535
+ Message,
1536
+ initial: { draft: '', todos: [] },
1537
+ update: (model: Model) => ({ model }),
1538
+ })
1539
+ const TodoList = App.surface('TodoList', {
1540
+ model: ({ model }) => ({ draft: model.draft, todos: model.todos }),
1541
+ messages: [Message.Added, Message.Typed],
1542
+ })
1543
+ const config = {
1544
+ Model,
1545
+ init: () => ({ model: App.initial }),
1546
+ update: (model: Model, _message: Message) => ({ model }),
1547
+ view: (model: Model, h: HtmlBuilder<Message>) => ({ title: 'Todos', body: h.p([], [model.draft]) }),
1548
+ container: null,
1549
+ }
1550
+ declare const buildId: string
1551
+ -->
1552
+
947
1553
  ```ts
948
1554
  const Todos = SSR.plan(App, {
949
1555
  id: 'todos',
@@ -953,6 +1559,12 @@ const Todos = SSR.plan(App, {
953
1559
  })
954
1560
  ```
955
1561
 
1562
+ <!-- docs-check
1563
+ declare const h: HtmlBuilder<Message>
1564
+ declare const model: Model
1565
+ const rh = Resume.builder(h)
1566
+ -->
1567
+
956
1568
  ```ts
957
1569
  rh.form(
958
1570
  [rh.OnSubmit(Message.Added({ title: model.draft }))],
@@ -1155,9 +1767,9 @@ of:
1155
1767
 
1156
1768
  | `reason` | What it means | The fix |
1157
1769
  | -------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------- |
1158
- | `ViewDependsOnUnsentState` | The view, or its head, renders differently from the browser's Model | Add the field the message names to `state`, or stop the view reading it |
1770
+ | `ViewDependsOnUnsentState` | The view, or its head, renders differently from the browser's Model | Add the field the message names to `state`, name it `restored` with a `restore`, or stop the view reading it |
1159
1771
  | `UndeclaredStartup` | `init` returned Commands and the plan has no `boot` | Name them in `boot` |
1160
- | `Uncovered` | An active Surface reads or is activated by an unsent field, or a binding sends a Message no active Surface lists | Send the field, name it `local`, or list the Message on the Surface |
1772
+ | `Uncovered` | An active Surface reads or is activated by an unsent field, or a binding sends a Message no active Surface lists | Send the field, name it `restored` or `local`, or list the Message on the Surface |
1161
1773
  | `UnrestorablePart` | A part cannot restore its own capture | A bug in that part |
1162
1774
  | `DuplicateStaticRegion` | Two `SSR.static` regions share an id | Give each its own id |
1163
1775
  | `BindingInStaticRegion` | A handler inside an `SSR.static` region | Move the element out, into a Surface |
@@ -1165,7 +1777,8 @@ of:
1165
1777
  | `UnencodableBinding` | The plan has no Message Schema, or a binding's Message does not encode through it | Make the plan from the application; build the Message with its constructor |
1166
1778
  | `EagerStartRequired` | A deferred plan would start a Subscription or Managed Resource late | Declare it in `deferrable`, or start `'now'` |
1167
1779
  | `VoidRootWithStyles` | `styles` were given for a view whose root is void and holds nothing | Put the styles in the template's head with `SSR.generate`, or return an element root |
1168
- | `UnkeepableField` | `KeepTyped` on an element that holds no typed value, one `h` built rather than `rh`, or with no `OnInput`/`OnChange` given a Message member | Mark only a text `input`, `textarea` or `select` that `rh` builds, and give its binding the Message's member |
1780
+ | `UnkeepableField` | `KeepTyped` on an element that holds nothing typed or ticked, one `h` built rather than `rh`, or with no binding that names its Message | Mark only a text `input`, `textarea`, `select`, checkbox or radio that `rh` builds, and give its binding the Message's member |
1781
+ | `UnkeptField` | A deferred plan has a field whose binding names its typing and no `KeepTyped` | Add `rh.KeepTyped()`, or start `'now'` |
1169
1782
  | `UngeneratablePath` | `SSR.generate` was given a path no file can be served at | Leave out the query and fragment; keep paths to distinct files |
1170
1783
 
1171
1784
  In the browser, `SSR.hydrate` checks in Foldkit's order: the build id first,
@@ -1194,8 +1807,20 @@ page's id. It never waits longer than `UNTIL_LIMIT_MS` (3 s). The CMS site
1194
1807
  waits for the route's read and its Blocks' reads, which its `Site.answered`
1195
1808
  checks with `RemoteData.answered` and `QueryBlock.active(...).answered`:
1196
1809
 
1810
+ <!-- docs-check standalone use ssr-app
1811
+ import { Resume, SSR } from 'foldkit-ssr'
1812
+ const Post = SSR.plan(App, {
1813
+ id: 'post',
1814
+ state: Projection.pick(App.model.route, App.model.draft),
1815
+ })
1816
+ import type { Diagnostic } from 'foldkit-ssr'
1817
+ declare const when: (document: Document) => boolean
1818
+ declare const Site: { readonly answered: (model: Model) => boolean }
1819
+ declare const send: (diagnostic: Diagnostic) => Effect.Effect<void>
1820
+ -->
1821
+
1197
1822
  ```ts
1198
- SSR.hydrate(config, plan, { buildId, when, otherwise: 'render', until: Site.answered })
1823
+ SSR.hydrate(config, Post, { buildId, when, otherwise: 'render', until: Site.answered })
1199
1824
  ```
1200
1825
 
1201
1826
  The served page stays as it was served while it waits: its links are plain
@@ -1223,9 +1848,9 @@ posted form's Commands included. `SSR.generate` reports to the reporter in
1223
1848
  its Effect's context.
1224
1849
 
1225
1850
  ```ts
1226
- SSR.hydrate(config, plan, { buildId, diagnostics: diagnostic => send(diagnostic) })
1851
+ SSR.hydrate(config, Post, { buildId, diagnostics: diagnostic => send(diagnostic) })
1227
1852
 
1228
- SSR.entry(config, plan, {
1853
+ SSR.entry(config, Post, {
1229
1854
  buildId,
1230
1855
  diagnostics: (diagnostic, request) =>
1231
1856
  Effect.logError(`${request.method} ${request.url}: ${diagnostic.message}`),
@@ -1304,6 +1929,13 @@ for a plan, as `Surface.when(PostActions, App.model.route, AppRoute.Post, route
1304
1929
  => ({ id: route.id }))` places one in
1305
1930
  [the coverage example](#checking-what-the-browser-will-read).
1306
1931
 
1932
+ <!-- docs-check standalone
1933
+ import { Schema } from 'effect'
1934
+ import { defineMessageUnion } from 'foldkit/message'
1935
+ import { defineRouteUnion } from 'foldkit/route'
1936
+ import { Remote } from 'foldkit-remote'
1937
+ -->
1938
+
1307
1939
  ```ts
1308
1940
  const AppRoute = defineRouteUnion({ Home: {}, Post: { id: Schema.String }, NotFound: {} })
1309
1941