foldkit-ssr 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -22,7 +22,7 @@ const Post = SSR.plan(App, {
22
22
  // Server: render, and write that slice into the page.
23
23
  const html = SSR.page(template, await Effect.runPromise(SSR.render(config, Post, { buildId, url })))
24
24
 
25
- // Browser: take the page over from the slice, without running init.
25
+ // Browser (from 'foldkit-ssr/client'): take the page over from the slice, without running init.
26
26
  SSR.hydrate(config, Post, { buildId })
27
27
  ```
28
28
 
@@ -69,7 +69,7 @@ and the checks that the browser can start from it.
69
69
  ## The mental model
70
70
 
71
71
  ```text
72
- server init ──▶ Model ──┬── plan.state ──▶ slice ──▶ envelope (JSON in the page)
72
+ server init ──▶ Model ──┬── plan.state ──▶ slice ──▶ envelope (JSON on the stamped root)
73
73
  └── view ──▶ HTML (checked, see below)
74
74
 
75
75
  browser envelope ──▶ baseline with the slice set on it ──▶ Model
@@ -89,40 +89,64 @@ silently rebuilt in the browser.
89
89
  The examples in this README share one application, a post page, sketched [at
90
90
  the end](#the-application-in-these-examples). `App` is its Surface application
91
91
  from `foldkit-surface`, and `config` is what you would pass to
92
- `makeApplication`, the same object on both sides.
92
+ `makeApplication`, the same object on both sides: any of its four shapes, with
93
+ Flags or routing or neither, and `routing`'s callbacks typed from `update`'s
94
+ Message as Foldkit types them.
95
+
96
+ The code is in three modules, because the server and the browser import
97
+ different things:
93
98
 
94
99
  ```ts
95
- import { Effect } from 'effect'
100
+ // post.ts, read by both: the plan. Which part of the Model the browser owns;
101
+ // the rest starts from the baseline, by default the application's initial Model.
96
102
  import { Projection } from 'foldkit-surface'
97
- import { SSR } from 'foldkit-ssr'
103
+ import { SSR } from 'foldkit-ssr/client'
98
104
 
99
- // Which part of the Model the browser owns. The rest starts from the
100
- // baseline, by default the application's initial Model.
101
105
  export const Post = SSR.plan(App, {
102
106
  id: 'post',
103
107
  state: Projection.pick(App.model.route, App.model.draft),
104
108
  })
109
+ ```
110
+
111
+ ```ts
112
+ // server.ts, per request.
113
+ import { Effect } from 'effect'
114
+ import { SSR } from 'foldkit-ssr'
105
115
 
106
- // On the server, per request.
107
116
  const result = await Effect.runPromise(SSR.render(config, Post, { buildId, url: request.url }))
108
117
  const html = SSR.page(template, result)
118
+ ```
119
+
120
+ ```ts
121
+ // client.ts, the page's script, instead of Runtime.hydrate.
122
+ import { SSR } from 'foldkit-ssr/client'
109
123
 
110
- // In the browser, instead of Runtime.hydrate.
111
124
  SSR.hydrate(config, Post, { buildId })
112
125
  ```
113
126
 
127
+ `foldkit-ssr/client` is the browser's part: `SSR.plan`, `SSR.resume`,
128
+ `SSR.hydrate`, `SSR.static`, `SSR.serving`, `Resume`, and the attribute names,
129
+ Foldkit's root stamp (`FOLDKIT_APP_ATTRIBUTE`) among them. It imports nothing
130
+ of `foldkit/experimental/server`, whose renderer and HTML parser `foldkit-ssr`
131
+ brings along: about 200 kB minified (60 kB gzipped) off a page's script in the
132
+ [SSR example](../../examples/foldkit-ssr). `foldkit-ssr` has all of it and the
133
+ server's calls, the same functions, so a plan made from either works with
134
+ both. Import `foldkit-ssr/client` in every module the page loads, the plan and
135
+ the view included, and `foldkit-ssr` only where the server alone runs.
136
+
114
137
  What each call does:
115
138
 
116
139
  - **`SSR.plan`** is a declaration. It does no I/O and holds no state. It
117
140
  throws only for a plan that could never work, such as two parts with one id.
118
141
  - **`SSR.render`** is an Effect. It runs `init` once, renders the view twice,
119
- checks the plan, and returns the rendered application and the envelope
120
- script. It fails with `ResumeUnsafe` when the browser could not start where
142
+ checks the plan, and returns the rendered application and the envelope it
143
+ carries on the stamped root. It fails with `ResumeUnsafe` when the browser could not start where
121
144
  the server did; [the refusals](#when-a-page-is-refused) say why and how to
122
145
  fix each.
123
- - **`SSR.page`** is pure: the template with the application and the envelope in
124
- it. The envelope goes before the template's last `</body>`, and a template
125
- without one is refused, by `SSR.page` and by `SSR.entry` when it is made.
146
+ - **`SSR.page`** is pure: the rendered application in the template, through
147
+ Foldkit's `injectIntoTemplate`. The envelope rides on the rendered root, so
148
+ the template needs no place for it. An optional `head` adds markup before
149
+ `</head>`, given what was rendered.
126
150
  - **`SSR.hydrate`** reads the envelope, starts Foldkit's runtime from the
127
151
  resumed Model, and runs the plan's `boot` Commands. `init` does not run. A
128
152
  page with no server render at all starts on the client as usual.
@@ -151,6 +175,35 @@ Commands, which is where a `Mirror.kv` restores what the user saved:
151
175
  boot: model => assembly.init(model).commands ?? []
152
176
  ```
153
177
 
178
+ ### Styles in the first paint
179
+
180
+ A generated page styled with `foldkit-mixins` can ship the CSS its markup uses
181
+ in the head, so it is styled before any script runs. `head` is given the rendered
182
+ application; `Style.usedIn` returns the CSS of every compiled class the markup
183
+ carries. In the browser, Styles bring their rules as they draw and skip what
184
+ this sheet already carries, so nothing is added twice.
185
+
186
+ ```ts
187
+ import { Style } from 'foldkit-mixins'
188
+
189
+ const html = SSR.page(template, result, {
190
+ head: rendered => `<style>${Style.usedIn(rendered.html)}</style>`,
191
+ })
192
+ ```
193
+
194
+ A served page has no template head to write to, so `SSR.render`, `SSR.entry`
195
+ and `SSR.handle` take the same function as `styles` instead, carried as the
196
+ rendered root's last child. Keep it to `<style>`: hydration adopts the nodes
197
+ around it and drops it on its first patch, and the browser's Styles skip what
198
+ it already carries. A void root holds no children, so styles for one are
199
+ refused with `VoidRootWithStyles`, naming the tag. Anything a head owns
200
+ (`meta`, links) stays with `SSR.generate`.
201
+
202
+ `SSR.generate` takes the same `head`, and answers a `head` that throws `500`,
203
+ as it does a render that fails. `SSR.entry` takes no `head`: the host owns
204
+ the template in dynamic serving, so a served page carries no per-page head
205
+ markup, and the script brings what the first paint needs.
206
+
154
207
  ### The head is part of the view
155
208
 
156
209
  `title`, `lang`, `dir`, `canonical` and `ogUrl` are checked like the body.
@@ -158,19 +211,56 @@ Since Foldkit 0.163 nothing gives `canonical` a default from the URL, so a page
158
211
  that wants one derives it from the route in its Model, as it does its `title`,
159
212
  and sends the route in `state`.
160
213
 
214
+ Foldkit fills `canonical` and `og:url` only into tags the template already has
215
+ and adds none, so a render that sets either into a template without
216
+ `<link rel="canonical" href="">` or `<meta property="og:url" content="">` is
217
+ refused, naming the tag.
218
+
219
+ ### What a page says of itself: `meta`
220
+
221
+ A search result and a link preview read more than Foldkit's `Document`: a
222
+ description, an image, Open Graph, a post's dates and structured data. The
223
+ plan's `meta` gives them from the Model:
224
+
225
+ ```ts
226
+ const Post = SSR.plan(App, {
227
+ id: 'post',
228
+ state: Projection.pick(App.model.route, App.model.post),
229
+ meta: model => ({
230
+ description: model.post.excerpt,
231
+ type: 'article',
232
+ article: { published: model.post.publishedAt },
233
+ jsonLd: [{ '@context': 'https://schema.org', '@type': 'BlogPosting', headline: model.post.title }],
234
+ }),
235
+ })
236
+ ```
237
+
238
+ `SSR.page` and `SSR.generate` write the tags (`description`, `og:*`,
239
+ `twitter:card`, `article:*`, `robots`, `link rel="alternate"`, and one JSON-LD
240
+ script per entry) before `</head>`, every value escaped, and `SSR.render`
241
+ checks them like the view: a `meta` that reads a field `state` does not send
242
+ is `ViewDependsOnUnsentState`. `SSR.hydrate` keeps them in step with the Model,
243
+ so a move to another post replaces the description too. Each carries
244
+ `data-foldkit-meta` (`META_ATTRIBUTE`), which is how the browser finds the
245
+ ones to replace; leave such tags out of the template.
246
+
161
247
  ## Serving pages
162
248
 
163
249
  ### Through Foldkit's fetch handler
164
250
 
165
251
  Foldkit's server entry is one function, `renderPage(request)`, which
166
252
  `handleRequest` calls for every request that is not a static file, on Node and
167
- on Workers alike. `SSR.entry` is that function for a plan:
253
+ on Workers alike. `SSR.entry` is that function for a plan. The host owns the
254
+ template: the entry answers `Rendered`, with the envelope on the rendered
255
+ root, and the host injects it into its own template, in development through
256
+ the `foldkit` Vite plugin and in production through the fetch handler a
257
+ `vite build` emits.
168
258
 
169
259
  ```ts
170
260
  import { handleRequest } from 'foldkit/experimental/server'
171
261
 
172
262
  // The server entry.
173
- export const { renderPage } = SSR.entry(config, Post, { buildId, template })
263
+ export const { renderPage } = SSR.entry(config, Post, { buildId })
174
264
 
175
265
  // A Worker, or any host that hands you a Web Request.
176
266
  export default {
@@ -178,19 +268,52 @@ export default {
178
268
  }
179
269
  ```
180
270
 
271
+ ```ts
272
+ // vite.config.ts, for the dev server and the build id both entries compile in.
273
+ import { foldkit } from '@foldkit/vite-plugin'
274
+
275
+ export default defineConfig({
276
+ plugins: [foldkit({ ssr: { serverEntry: '/src/entry.server.ts' } })],
277
+ })
278
+ ```
279
+
280
+ ```ts
281
+ // entry.server.ts and the browser's entry.ts alike.
282
+ buildId: import.meta.env.FOLDKIT_BUILD_ID,
283
+ ```
284
+
285
+ `FOLDKIT_BUILD_ID` names the deployment, from the environment: a commit or a
286
+ release tag, public and unique per deployment. The plugin compiles it into
287
+ both bundles; a script outside Vite, such as a prerender, reads
288
+ `process.env.FOLDKIT_BUILD_ID`, the same value the build saw.
289
+
181
290
  `GET` and `HEAD` render the page for the request's URL; an application with
182
291
  Flags passes `flags: request => ...`. `POST` is handled only for a plan with a
183
- [server fallback](#forms-that-work-without-scripts), and any other method is
184
- answered `405`. A render that fails or throws, `flags` that reject, and a plan
185
- the render refuses are answered `500` with the reason logged, never with a page
292
+ [server fallback](#forms-that-work-without-scripts). `OPTIONS` is answered
293
+ `204` and any other method `405`, each with the methods the entry answers in
294
+ `allow`. A render that fails or throws, `flags` that reject, and a plan the
295
+ render refuses are answered `500` with the reason logged, never with a page
186
296
  the browser could not resume.
187
297
 
188
- The page comes back whole, as Foldkit's `Responded`, built by Foldkit's own
189
- `toResponse`. A `Rendered` result has no room for the envelope, which is why
190
- the entry takes the template itself, and why Foldkit's built-in `prerender`
191
- cannot generate these pages; `SSR.generate` below does.
298
+ `headers: request => ...` rides on the `Rendered` result, set over the host's
299
+ own: a cache policy for a page that is one visitor's, or the CORS answer to a
300
+ preflight, which reaches the entry and not the host.
301
+
302
+ ```ts
303
+ SSR.entry(config, Post, {
304
+ buildId,
305
+ headers: () => ({ 'cache-control': 'private, no-store', vary: 'cookie' }),
306
+ })
307
+ ```
308
+
309
+ A `headers` that throws is answered `500`, as a failed render is.
310
+
311
+ What the page says of itself (`meta`) and per-page `head` markup are written
312
+ into a template's head, which the host owns here: a plan with `meta` is
313
+ refused when the entry is made, and served with `SSR.generate` below, which
314
+ owns its template.
192
315
  [foldkit#1448](https://github.com/foldkit/foldkit/issues/1448) asks Foldkit
193
- for that room.
316
+ for a per-request head channel beside the envelope.
194
317
 
195
318
  ### At build time
196
319
 
@@ -223,6 +346,26 @@ alike, so a generated page records its path alone: `/about?ref=mail` resumes
223
346
  the page generated for `/about`, and `/other` is refused. A server-rendered page
224
347
  records its path and query, and resumes only there.
225
348
 
349
+ A generated site also wants a sitemap and a `robots.txt` that names it.
350
+ `SSR.sitemap` takes the pages, with a `modified` date where one is known, and
351
+ `SSR.robots` the origin:
352
+
353
+ ```ts
354
+ await writeFile(
355
+ 'dist/sitemap.xml',
356
+ SSR.sitemap(
357
+ pages.map(page => ({ path: page.path, modified: '2026-09-27' })),
358
+ { origin: 'https://example.com' },
359
+ ),
360
+ )
361
+ await writeFile('dist/robots.txt', SSR.robots({ origin: 'https://example.com' }))
362
+ ```
363
+
364
+ `modified` is any date `Date` reads, written as its UTC day. A path listed
365
+ twice, one not starting with `/`, or a date `Date` cannot read is refused
366
+ rather than written into a sitemap a search engine would reject. `robots`
367
+ takes `disallow` paths and a `sitemap` path other than `/sitemap.xml`.
368
+
226
369
  ## Checking what the browser will read
227
370
 
228
371
  The view check sees what the first render shows. A Surface can read a field the
@@ -307,6 +450,15 @@ content a Message should change belongs in a Surface. A region the browser
307
450
  needs that is not in the page, say after a Message shows one, is logged and
308
451
  rendered in the browser.
309
452
 
453
+ ### Markup the browser adopts: `SSR.serving`
454
+
455
+ `SSR.serving()` is true while the view call in progress is the server rendering a page (both
456
+ of `render`'s passes), and false while the browser resumes and outside any render. It is for
457
+ a view whose element hydration leaves alone, such as a custom element's light DOM, and which
458
+ sends markup there that the browser's own code then takes over. The rich-text editor's host is
459
+ one: pass `serverRendered: SSR.serving` to `foldkit-richtext-dom`'s `editorAt`, and the page
460
+ carries the document instead of an empty editor until the script runs.
461
+
310
462
  ## Resumable pages: answering before the runtime boots
311
463
 
312
464
  Everything above boots Foldkit's runtime as soon as the page loads. A resumable
@@ -318,7 +470,7 @@ code to start.
318
470
  server each handler ──▶ its Message, encoded ──▶ a marker on the element + an entry in the envelope
319
471
 
320
472
  browser event ──▶ the markers name its Messages ──▶ queued ──▶ the runtime boots
321
- ──▶ the queue replays through update
473
+ ──▶ update runs the queue first
322
474
  ```
323
475
 
324
476
  It rests on the fact that a Foldkit handler is already a Message value.
@@ -351,6 +503,7 @@ it leaves open. The types check it where it is written: the member must be one
351
503
  of the view's Messages, and leave exactly one string field, or exactly `key`
352
504
  and `modifiers`. A closure still works. It is not data, so the page cannot
353
505
  answer that event itself and boots on it instead, letting the live page answer.
506
+ `SSR.render` names each such element and event in its result's `unnamed`.
354
507
  So does a hole form whose field has checks the empty placeholder fails, such
355
508
  as `Schema.isMinLength(1)`: it cannot be written into the page as data, so it
356
509
  is treated as a closure.
@@ -377,10 +530,12 @@ const Post = SSR.plan(App, {
377
530
  })
378
531
  ```
379
532
 
380
- The event that boots the page is not lost and does not count twice. Messages
381
- answered before boot replay in order through the same `update`, so the Model
382
- ends where an eager boot would have taken it, and the input typed into is
383
- adopted, not rebuilt.
533
+ The event that boots the page is not lost and does not count twice. The
534
+ runtime starts from the resumed Model, so its first render is the served
535
+ markup and every node is adopted, the input typed into included. The Messages
536
+ answered before boot then go through the same `update`, in order, ahead of
537
+ anything the live page answers, even an event dispatched in the task that
538
+ boots it, so the Model ends where an eager boot would have taken it.
384
539
 
385
540
  ### What a resumable page must declare
386
541
 
@@ -496,14 +651,16 @@ of:
496
651
  | `UndeclaredSurfaces` | The page has bindings and the plan no `surfaces` | Name the Surfaces the page may activate |
497
652
  | `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 |
498
653
  | `EagerStartRequired` | A deferred plan would start a Subscription or Managed Resource late | Declare it in `deferrable`, or start `'now'` |
654
+ | `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 |
499
655
  | `UngeneratablePath` | `SSR.generate` was given a path no file can be served at | Leave out the query and fragment; keep paths to distinct files |
500
656
 
501
657
  In the browser, `SSR.hydrate` checks in Foldkit's order: the build id first,
502
- then the envelope. `SSR.resume` returns the envelope's refusal as
503
- `ResumeRefused`: `Missing` or `Duplicate` envelope, `Unreadable` JSON, another
504
- `Protocol` version or `Plan`, state, parts or bindings that are `Invalid`, or a
505
- `Route` other than the one the page was rendered for. A page is resumed whole or
506
- not at all.
658
+ then the envelope. `SSR.resume` reads the envelope off the stamped root and
659
+ returns its refusal as `ResumeRefused`: a page with no stamped root or more
660
+ than one, a root with no envelope (`Missing`, also for a second root as
661
+ `Duplicate`), `Unreadable` JSON, another `Protocol` version or `Plan`, state,
662
+ parts or bindings that are `Invalid`, or a `Route` other than the one the page
663
+ was rendered for. A page is resumed whole or not at all.
507
664
 
508
665
  ## Costs and limits
509
666
 
@@ -515,32 +672,43 @@ not at all.
515
672
  fail the day Foldkit changes.
516
673
  [foldkit#1449](https://github.com/foldkit/foldkit/issues/1449) asks whether
517
674
  Foldkit would support this directly.
518
- - **A resumable page leans on three Foldkit behaviours,** each pinned by a test
519
- here and two by Foldkit's own: the first patch removes attributes the
520
- browser's view does not assert, a control's value is re-asserted to the
521
- Model's, and `Runtime.hydrate` renders its first frame before it returns.
675
+ - **A resumable page leans on two Foldkit behaviours,** each pinned by a test
676
+ here and by Foldkit's own: the first patch removes attributes the browser's
677
+ view does not assert, and a control's value is re-asserted to the Model's.
678
+ It does not depend on `Runtime.hydrate` rendering its first frame before
679
+ it returns, which Foldkit does today without promising it: until that
680
+ frame commits (`Render.afterCommit`), the page keeps answering from its
681
+ markers and sends the live page what only it can answer.
522
682
  - **Development is not production.** Under Vite's dev server, Foldkit's model
523
683
  preservation restores the previous Model after a reload and skips adoption.
524
- - **A closure handler makes its event wait for boot,** with no warning yet
525
- naming the element.
684
+ - **A closure handler makes its event wait for boot.** `SSR.render`'s result
685
+ lists each under `unnamed` (`{ element: 'button#point', event:
686
+ 'pointerdown' }`), and on a page that waits to boot `SSR.entry` and
687
+ `SSR.generate` warn about each once per process, naming the fix.
526
688
 
527
689
  ## Lower-level API
528
690
 
529
691
  `SSR.render` and `SSR.hydrate` are built from pieces usable on their own:
530
692
 
531
- - **`SSR.envelope(plan, model, { route? })`** returns the envelope script for a
532
- Model, and **`SSR.resume(plan, document, { route? })`** reads it back as a
533
- `Result`. The envelope escapes `<` as Foldkit escapes its Flags, and U+2028
534
- and U+2029, so no string in the Model can close the script.
693
+ - **`SSR.envelope(plan, model, { route? })`** returns the envelope for a
694
+ Model, as JSON, and **`SSR.resume(plan, document, { route? })`** reads it back
695
+ as a `Result`. `SSR.render` carries it on the stamped root, beside Foldkit's
696
+ own stamps; the JSON escapes `<` as Foldkit escapes its Flags, and U+2028
697
+ and U+2029, and the attribute escapes `&` and `"` besides, so no string in
698
+ the Model can break out of the value. Hydration drops the attribute on its
699
+ first patch, so the browser reads it before it boots.
535
700
  - **`SSR.inspect(plan, model)`**: the plan's coverage as data.
536
701
  - **`Resume.bindings(plan, document, root, model)`** decodes and checks a
537
- page's bindings, and **`Resume.listen(root, { bindings, onAnswer })`**
702
+ page's bindings, and **`Resume.listen(root, { bindings, onAnswer, events? })`**
538
703
  answers events from the markers, one `{ event, messages, unnamed? }` per
539
- event. `SSR.hydrate` uses both; they are there for a custom boot.
704
+ event. `events` is the envelope's list of every event the markers name;
705
+ without it `listen` reads every element's attributes to find them.
706
+ `SSR.hydrate` uses both, passing the list; they are there for a custom
707
+ boot.
540
708
  - **Attribute names**, for tools and tests: `RESUME_ATTRIBUTE` (the envelope
541
- script), `STATIC_ATTRIBUTE`, `BINDING_ATTRIBUTE` (a prefix, followed by the
542
- event), `SLOT_ATTRIBUTE` (a placement's root while the server renders) and
543
- `FALLBACK_FIELD` (the posted Message).
709
+ on the stamped root), `STATIC_ATTRIBUTE`, `BINDING_ATTRIBUTE` (a prefix,
710
+ followed by the event), `SLOT_ATTRIBUTE` (a placement's root while the server
711
+ renders) and `FALLBACK_FIELD` (the posted Message).
544
712
 
545
713
  ## The application in these examples
546
714