foldkit-ssr 0.12.0 → 0.13.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
@@ -76,13 +76,13 @@ and the checks that the browser can start from it.
76
76
 
77
77
  ## The mental model
78
78
 
79
- ```text
80
- server init ──▶ Model ──┬── plan.state ──▶ slice ──▶ envelope (JSON on the stamped root)
81
- └── view ──▶ HTML (checked, see below)
79
+ On the server, `init` makes the Model. The plan's `state` turns it into a slice,
80
+ which goes into an envelope as JSON on the stamped root, and the view turns the
81
+ same Model into HTML, which is checked (see below).
82
82
 
83
- browser envelope ──▶ baseline with the slice set on it ──▶ Model
84
- Model + the server's HTML ──▶ Runtime.hydrate adopts ──▶ plan.boot Commands
85
- ```
83
+ In the browser, the envelope sets the slice onto the baseline Model, and that is
84
+ the first Model. `Runtime.hydrate` adopts the server's HTML with that Model, and
85
+ then the plan's `boot` Commands run.
86
86
 
87
87
  The one rule everything else serves: **the browser's first Model renders the
88
88
  same page the server sent.** The browser's Model is the plan's baseline, by
@@ -846,7 +846,12 @@ Model is prepared per page returns its own); `paths` may be a thunk that seeds
846
846
  and lists; `head` is the same `head`; and `sitemap`/`robots` write their files
847
847
  from the generated pages. `files` is the host's layout — `'directory'`
848
848
  (`/about` as `about/index.html`, the default) or `'flat'` (`about.html`, for a
849
- host with clean addresses and no directory indexes):
849
+ host with clean addresses and no directory indexes). `plan` is one plan, or a
850
+ function of the path for a site of more than one application: a path then
851
+ resumes with the plan of the application `config` returns for it, so a site's
852
+ guides and its interactive pages can have Models of their own. A plan function
853
+ that throws fails the build and names the path; the sitemap and robots text
854
+ still list every path:
850
855
 
851
856
  <!-- docs-check standalone use ssr-app
852
857
  import { Resume, SSR } from 'foldkit-ssr'
@@ -872,6 +877,13 @@ export const site = {
872
877
  } satisfies SiteModule
873
878
  ```
874
879
 
880
+ `staticSite({ site, plugins })` loads the site module with `plugins`: the build
881
+ renders the pages from a Vite server of its own, which has none of the
882
+ application's, so a plugin that changes what a view draws must be passed here
883
+ too. Foldkit's view-identity branding is one: the browser compares the identity
884
+ markers it computes with the page's, and a page drawn without them is rebuilt
885
+ element by element rather than adopted, silently in a production build.
886
+
875
887
  `emit` adds files made from the generated pages, written beside them: what the
876
888
  pages reference and the build must also serve, such as the image variants
877
889
  their `srcset`s name (`foldkit-media`'s `materialize`). It takes the pages and
@@ -1141,8 +1153,8 @@ rule above still holds, so the first client view is the served page, and
1141
1153
  such state is split by whether the view draws it:
1142
1154
 
1143
1155
  ```text
1144
- envelope ──▶ resumed Model ──▶ prepare: what the view does not draw ──▶ Runtime.hydrate adopts the served page
1145
- └─▶ a Subscription reads the store ──▶ Message ──▶ update ──▶ drawn
1156
+ envelope ──► resumed Model ──► prepare: what the view does not draw ──► Runtime.hydrate adopts the served page
1157
+ └─► a Subscription reads the store ──► Message ──► update ──► drawn
1146
1158
  ```
1147
1159
 
1148
1160
  `prepare: model => Effect` runs once, on the Model a page resumes, before
@@ -1228,10 +1240,10 @@ only when it must, so the first interaction does not wait for the application's
1228
1240
  code to start.
1229
1241
 
1230
1242
  ```text
1231
- server each handler ──▶ its Message, encoded ──▶ a marker on the element + an entry in the envelope
1243
+ server each handler ──► its Message, encoded ──► a marker on the element + an entry in the envelope
1232
1244
 
1233
- browser event ──▶ the markers name its Messages ──▶ queued ──▶ the runtime boots
1234
- ──▶ update runs the queue first
1245
+ browser event ──► the markers name its Messages ──► queued ──► the runtime boots
1246
+ ──► update runs the queue first
1235
1247
  ```
1236
1248
 
1237
1249
  It rests on the fact that a Foldkit handler is already a Message value.
@@ -1367,7 +1379,22 @@ const config = {
1367
1379
 
1368
1380
  The server loads the code before it renders, so the page carries the real
1369
1381
  view. The browser loads it before it boots and answers from the markers
1370
- meanwhile, whatever `start` says. A binding inside a placement dispatches the
1382
+ meanwhile, whatever `start` says.
1383
+
1384
+ A list loads whole on every page. When each route has code of its own, give
1385
+ `lazy` as a function of the Model instead, and only what the page draws loads:
1386
+
1387
+ ```ts sketch
1388
+ lazy: model => Routing.codeFor(model.route), // Routing = Site.routing({ pages, … })
1389
+ ```
1390
+
1391
+ The server asks it with the Model the page is drawn from (`init`'s, after
1392
+ `SSR.entry`'s `prepare`), and runs `init` once for it; the browser asks it
1393
+ with the resumed Model. The two must name the same bundles, or the render
1394
+ fails with `LazyDependsOnUnsentState`: send in the plan's `state` what `lazy`
1395
+ reads. A page on another route fetches none of this route's code, and
1396
+ `Site.routing`'s `preload` fetches it when the reader points at a link there
1397
+ (`foldkit-site`'s README, "Code split by route"). A binding inside a placement dispatches the
1371
1398
  parent's Message, as Foldkit's own handlers do, so the plan's Surface lists the
1372
1399
  wrapper variant, `Message.GotUploadMessage`.
1373
1400
 
@@ -1389,9 +1416,9 @@ rh.input([rh.Value(model.draft), rh.OnInput(Message.ChangedDraft), rh.KeepTyped(
1389
1416
  ```
1390
1417
 
1391
1418
  ```text
1392
- parse ──▶ typing (the field holds it) ──▶ script: SSR.hydrate reads the marked fields
1393
- ──▶ each changed one becomes its OnInput Message, first in the queue
1394
- ──▶ first render adopts the served page ──▶ value and caret put back ──▶ update
1419
+ parse ──► typing (the field holds it) ──► script: SSR.hydrate reads the marked fields
1420
+ ──► each changed one becomes its OnInput Message, first in the queue
1421
+ ──► first render adopts the served page ──► value and caret put back ──► update
1395
1422
  ```
1396
1423
 
1397
1424
  There is no inline script: the field itself holds what was typed, and an
@@ -1464,12 +1491,12 @@ load({ runtime: () => import('./entry.js') }) // entry.ts calls SSR.hydrate
1464
1491
  ```
1465
1492
 
1466
1493
  ```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
1494
+ load ──► read start from the envelope
1495
+ 'now' ──► run the chunk
1496
+ 'idle' ──► fetch the chunk now ──► idle after load, chunk here: run it
1497
+ 'on-interaction' ──► fetch the chunk now ──► first intent: run it
1498
+ until SSR.hydrate takes over: a marked event ──► held (a submission prevented)
1499
+ SSR.hydrate ──► starts now ──► answers each held event from the markers, once
1473
1500
  ```
1474
1501
 
1475
1502
  - **`start` stays the plan's.** The server writes it into the envelope, and
@@ -1588,9 +1615,9 @@ and one given `Method('post')` posts no Message, which the entry answers
1588
1615
  `400`.
1589
1616
 
1590
1617
  ```text
1591
- POST ──▶ decode the Message ──▶ set the posted fields into it (the typed `title`)
1592
- ──▶ init, prepare, then boot and its Commands ──▶ update, and every Command after it
1593
- ──▶ the page, rendered
1618
+ POST ──► decode the Message ──► set the posted fields into it (the typed `title`)
1619
+ ──► init, prepare, then boot and its Commands ──► update, and every Command after it
1620
+ ──► the page, rendered
1594
1621
  ```
1595
1622
 
1596
1623
  The Message must be one the page's active Surfaces list. Commands run under the
@@ -1636,8 +1663,8 @@ one that orders or sends something. `answerPost: 'redirect'` answers the post
1636
1663
  (Post/Redirect/Get):
1637
1664
 
1638
1665
  ```text
1639
- POST /todos ──▶ update, and its Commands ──▶ 303, Location: /todos, headers(request, some(model))
1640
- GET /todos ──▶ init, prepare ──▶ the page, rendered
1666
+ POST /todos ──► update, and its Commands ──► 303, Location: /todos, headers(request, some(model))
1667
+ GET /todos ──► init, prepare ──► the page, rendered
1641
1668
  ```
1642
1669
 
1643
1670
  ```ts
@@ -1703,7 +1730,7 @@ the first frame shows whatever the server knew when it rendered.
1703
1730
  [example's](../../examples/foldkit/ssr) count, by the same route:
1704
1731
 
1705
1732
  ```text
1706
- request cookie ─▶ flags ─▶ init ─▶ Model.theme ─┬─ view draws it
1733
+ request cookie ─► flags ─► init ─► Model.theme ─┬─ view draws it
1707
1734
  └─ plan.state carries it, so the browser resumes with it
1708
1735
  ```
1709
1736
 
@@ -1768,6 +1795,7 @@ of:
1768
1795
  | `reason` | What it means | The fix |
1769
1796
  | -------------------------- | ----------------------------------------------------------------------------- | ------------------------------------------------------------------- |
1770
1797
  | `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 |
1798
+ | `LazyDependsOnUnsentState` | `lazy`, a function of the Model, names other bundles for the browser's Model than for the server's | Add the field it reads to `state`, or stop `lazy` reading it |
1771
1799
  | `UndeclaredStartup` | `init` returned Commands and the plan has no `boot` | Name them in `boot` |
1772
1800
  | `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 |
1773
1801
  | `UnrestorablePart` | A part cannot restore its own capture | A bug in that part |
@@ -1,6 +1,6 @@
1
1
  import { o as listen } from "./listen-7HzKBhqU.js";
2
2
  import { m as view, p as builder } from "./resumable-BV9_OKxr.js";
3
- import { A as resume, D as plan, F as staticRegion, L as unbound, N as serving, b as bindings, d as ResumePlan, l as ResumableConfig } from "./shared-mQ8CXr-r.js";
3
+ import { I as staticRegion, O as plan, P as serving, R as unbound, b as bindings, d as ResumePlan, j as resume, l as ResumableConfig } from "./shared-BuCOwm57.js";
4
4
  import { Effect, Schema } from "effect";
5
5
  import { Diagnostic as Diagnostic$1, Diagnostics as Diagnostics$1, ReportDiagnostic, ReportDiagnostic as ReportDiagnostic$1 } from "foldkit-surface";
6
6
  /**
@@ -85,4 +85,4 @@ declare const SSR: {
85
85
  serving: typeof serving;
86
86
  };
87
87
  export { SSR as a, Resume as i, Diagnostics$1 as n, ReportDiagnostic$1 as r, Diagnostic$1 as t };
88
- //# sourceMappingURL=client-BEHlUHBv.d.ts.map
88
+ //# sourceMappingURL=client-cumvT9XN.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-BEHlUHBv.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cA0FM,UAAW,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAa,QAChE,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;WAEpB;;;;;;;WAOA,SAAS,MAAM;;;;;;;WAOf;;;;;;;;WAQA,UAAU,OAAO;;;;;;;;WAQjB,UAAU;;;;;;;;;;WAUV,YAAY,OAAO,UAAU,OAAO,OAAO;;;;;;;;WAQ3C,cAAc;;;cAmad;;;;;;;cAGA"}
1
+ {"version":3,"file":"client-cumvT9XN.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;;;;;;;;;;;;;;;cA2FM,UAAW,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAa,QAChE,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;WAEpB;;;;;;;WAOA,SAAS,MAAM;;;;;;;WAOf;;;;;;;;WAQA,UAAU,OAAO;;;;;;;;WAQjB,UAAU;;;;;;;;;;WAUV,YAAY,OAAO,UAAU,OAAO,OAAO;;;;;;;;WAQ3C,cAAc;;;cAqad;;;;;;;cAGA"}
package/dist/client.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { a as UNTIL_LIMIT_MS, i as RESUME_ATTRIBUTE, n as FOLDKIT_APP_ATTRIBUTE, r as KEEP_ATTRIBUTE, t as BINDING_ATTRIBUTE } from "./marks-CX15BwOw.js";
2
2
  import { n as DecodedBinding } from "./listen-7HzKBhqU.js";
3
3
  import { c as ResumableBuilder, i as FALLBACK_FIELD, l as SLOT_ATTRIBUTE } from "./resumable-BV9_OKxr.js";
4
- import { G as BundleUnloaded, J as HeadNotMoved, K as CachedPageDiffers, Q as StaticRegionMissing, V as UnnamedHandler, X as PageFailed, Y as PageContained, Z as SsrDiagnostic, a as Meta, d as ResumePlan, f as ResumeRefused, g as Start, i as META_ATTRIBUTE, l as ResumableConfig, m as STATIC_ATTRIBUTE, q as HandlerUnnamed, r as Loadable, s as PlanSurface, u as ResumePart, w as metaMarkup } from "./shared-mQ8CXr-r.js";
5
- import { a as SSR, i as Resume, n as Diagnostics, r as ReportDiagnostic, t as Diagnostic } from "./client-BEHlUHBv.js";
4
+ import { $ as StaticRegionMissing, H as UnnamedHandler, J as HandlerUnnamed, K as BundleUnloaded, Q as SsrDiagnostic, T as metaMarkup, X as PageContained, Y as HeadNotMoved, Z as PageFailed, a as Meta, d as ResumePlan, f as ResumeRefused, g as Start, i as META_ATTRIBUTE, l as ResumableConfig, m as STATIC_ATTRIBUTE, q as CachedPageDiffers, r as Loadable, s as PlanSurface, u as ResumePart } from "./shared-BuCOwm57.js";
5
+ import { a as SSR, i as Resume, n as Diagnostics, r as ReportDiagnostic, t as Diagnostic } from "./client-cumvT9XN.js";
6
6
  export { BINDING_ATTRIBUTE, type BundleUnloaded, type CachedPageDiffers, type DecodedBinding, type Diagnostic, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type HandlerUnnamed, type HeadNotMoved, KEEP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, type PageContained, type PageFailed, type PlanSurface, RESUME_ATTRIBUTE, type ReportDiagnostic, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, type SsrDiagnostic, type Start, type StaticRegionMissing, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
package/dist/client.js CHANGED
@@ -5,7 +5,7 @@ import { BINDING_ATTRIBUTE, FOLDKIT_APP_ATTRIBUTE, KEEP_ATTRIBUTE, RESUME_ATTRIB
5
5
  import { FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, SLOT_ATTRIBUTE, builder, view } from "./resumable.js";
6
6
  import { listen, listening } from "./listen.js";
7
7
  import { hold, keptFields, restore, typedMessages } from "./keep.js";
8
- import { HEAD_MARKER, META_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, arrival, bindings, bindingsAndEvents, metaEntry, metaMarkup, plan, resume, routeOf, serving, startingFrom, staticRegion, unbound } from "./shared.js";
8
+ import { HEAD_MARKER, META_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, arrival, bindings, bindingsAndEvents, lazyFor, metaEntry, metaMarkup, plan, resume, routeOf, serving, startingFrom, staticRegion, unbound } from "./shared.js";
9
9
  import { Effect, Option, Result, Schema, Stream } from "effect";
10
10
  import { hydrate, makeApplication, run } from "foldkit/runtime";
11
11
  import * as Render from "foldkit/render";
@@ -155,7 +155,7 @@ const hydrate$1 = (config, plan, options) => {
155
155
  }
156
156
  }), { buildId: options.buildId });
157
157
  };
158
- const pending = (config.lazy ?? []).filter((bundle) => !bundle.isLoaded());
158
+ const pending = lazyFor(config, model).filter((bundle) => !bundle.isLoaded());
159
159
  const start = Option.isSome(arrived) || Option.isSome(loader) ? "now" : plan.start;
160
160
  const eager = start === "now" && pending.length === 0;
161
161
  if (eager && Option.isNone(loader) && root.querySelector(`[data-foldkit-plus-keep]`) === null) {
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["hydrate","Diagnostics","adopt"],"sources":["../src/client.ts"],"sourcesContent":["/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Option, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { Diagnostics, type ReportDiagnostic } from 'foldkit-surface'\nimport { withContext, type RenderContext } from './context.js'\nimport {\n bundleUnloaded,\n headNotMoved,\n noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { claim, type HeldEvent } from './handoff.js'\nimport { UNTIL_LIMIT_MS } from './marks.js'\nimport { hold, keptFields, restore, typedMessages, type Held, type KeptField } from './keep.js'\nimport { listen, listening, type DecodedBinding } from './listen.js'\nimport {\n BINDING_ATTRIBUTE,\n FALLBACK_DEPTH_FIELD,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n builder,\n view,\n} from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n HEAD_END_MARKER,\n HEAD_MARKER,\n STYLES_MARKER,\n arrival,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n unbound,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is reported (`options.diagnostics`). A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n *\n * Run by `foldkit-ssr/loader`, it starts now, whatever the plan's `start`\n * (the loader followed it), and answers each event the loader held from the\n * markers, once. A page that does not resume releases them to the browser.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * With `otherwise: 'render'`, when the fresh application is ready to be\n * seen: until a Model it has drawn satisfies this, it draws out of view\n * and the served page stays, so a page is not swapped for its loading\n * state and back. Omitted, the fresh application replaces the page at\n * once. The served page stays no longer than `UNTIL_LIMIT_MS`.\n */\n readonly until?: ((model: Model) => boolean) | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n /**\n * What only this browser adds to the resumed Model before it is adopted,\n * and the view does not draw: a session minted for this page load (an\n * outbox's `session`). Run once, for a page that resumes; the runtime\n * starts when it succeeds. What the view draws, such as a queue read from\n * storage, arrives after, as a Message: here it would make the first\n * client view differ from the served page. Must not fail, as `when` must\n * not throw.\n */\n readonly prepare?: ((model: Model) => Effect.Effect<Model>) | undefined\n /**\n * Where what the page met goes: a page contained rather than resumed, a\n * static region the server's page lacked, a lazy bundle that did not\n * load. Each is reported before or apart from the runtime, so its\n * resources' reporter is not in effect. Omitted, Effect's log: the\n * browser's console.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): void => {\n const report = (diagnostic: SsrDiagnostic): void => {\n Effect.runFork(reportingTo(options.diagnostics)(Diagnostics.report(diagnostic)))\n }\n const loader = Option.fromNullishOr(claim())\n // Every path below that does not resume the page lets the browser have what\n // the loader held: a held submission posts.\n const release = (): void => Option.match(loader, { onNone: () => {}, onSome: it => it.release() })\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (root !== null) {\n if (dropUnmovedHead(root)) report(headNotMoved)\n keepStyles(root)\n }\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n release()\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n release()\n if (options.otherwise !== 'render') contain()\n else if (options.until === undefined)\n run(makeApplication({ ...config, container: root } as never))\n else renderBeside(config, root, options.until)\n return\n }\n // The type says a string, but `import.meta.env` is `any`: with the variable\n // unset the id arrives undefined, and Foldkit, given none, takes its own\n // compiled id, which matches the page, so the baseline was adopted in silence.\n if (typeof options.buildId !== 'string') {\n report(noBuildId)\n release()\n contain()\n return\n }\n const served = root.getAttribute(BUILD_ATTRIBUTE)\n if (served !== options.buildId) {\n report(otherBuild(Option.fromNullOr(served), options.buildId))\n release()\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n report(pageContained(resumed.failure.reason, resumed.failure.message))\n release()\n contain()\n return\n }\n const adoptFrom = (model: Model): void => {\n // A page recorded for its path, opened at a query: the application learns\n // the URL, as from a navigation, and the page starts now, since what it\n // shows is not yet the address.\n const arrived = arrival(config, document, window.location.href)\n const bootCommands = (started: Model): ReadonlyArray<unknown> =>\n (plan.boot?.(started) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n report,\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n // The URL goes into the Model the runtime starts from, not into `answered`:\n // Subscriptions start from that Model before any Message lands, and a URL\n // mirror among them would write the served address back over the real one.\n // The first render then differs from the served page where the URL does, and\n // Foldkit rebuilds that part, as a navigation would redraw it. Applied at\n // boot, once any lazy bundle's `update` has loaded. The boot Commands are\n // planned from the Model the runtime actually starts with, so one derived\n // from the route or query sees the address the page arrived at.\n const startOf = () =>\n Option.match(arrived, {\n onNone: () => ({ model, commands: bootCommands(model) }),\n onSome: message => {\n const step = apply(model, message) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n return {\n model: step.model,\n commands: [...bootCommands(step.model), ...(step.commands ?? [])],\n }\n },\n })\n const boot = (entries: Readonly<Record<string, unknown>> = {}) => {\n unmark(root)\n return adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, startOf()), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n }\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n // A loader ran this chunk when the plan's `start` said to.\n const start = Option.isSome(arrived) || Option.isSome(loader) ? 'now' : plan.start\n const eager = start === 'now' && pending.length === 0\n // With a loader, the page reads its bindings first: the loader may hold\n // events for them.\n if (eager && Option.isNone(loader) && root.querySelector(`[${KEEP_ATTRIBUTE}]`) === null) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n report(pageContained(decoded.failure.reason, decoded.failure.message))\n release()\n contain()\n return\n }\n const kept = keptFields(root, decoded.success.bindings)\n if (Result.isFailure(kept)) {\n report(pageContained('Invalid', kept.failure))\n release()\n contain()\n return\n }\n // What was typed before this script ran, first in the queue: everything the\n // page answers from here on happened after it.\n answered.push(...typedMessages(kept.success))\n const held = Option.match(loader, { onNone: () => [], onSome: it => it.take() })\n if (eager && answered.length === 0 && held.length === 0) {\n boot()\n return\n }\n // Typing is an interaction, whenever it happened: a page that waits for\n // one starts now, so what was typed is answered as soon as the script runs.\n const typed = answered.length > 0 ? 'now' : start\n deferBoot(root, decoded.success, typed, { boot, answered }, pending, report, kept.success, held)\n }\n const prepare = options.prepare\n let startingModel: Model\n try {\n startingModel = plan.restore === undefined ? resumed.success : plan.restore(resumed.success)\n } catch (error) {\n report(pageContained('Invalid', error instanceof Error ? error.message : String(error)))\n release()\n contain()\n return\n }\n if (prepare === undefined) adoptFrom(startingModel)\n else void Effect.runPromise(prepare(startingModel)).then(adoptFrom)\n}\n\n/**\n * Takes out of the served page what the server wrote for this script to read\n * and no view draws: the envelope, each binding's and kept field's marker,\n * each placement's slot, and each form's fallback (its `method` and hidden\n * fields). Left in, each is in what Foldkit records of the served page and\n * gone after its first patch, so Foldkit reconciles every such element, and\n * a development build reports that the server's markup and the view\n * disagree. Run as the page boots, so a form submitted before then still\n * posts.\n */\nconst unmark = (root: Element): void => {\n root.removeAttribute(RESUME_ATTRIBUTE)\n for (const element of [root, ...root.querySelectorAll('*')]) {\n for (const name of element.getAttributeNames()) {\n if (name.startsWith(BINDING_ATTRIBUTE) || name === KEEP_ATTRIBUTE || name === SLOT_ATTRIBUTE)\n element.removeAttribute(name)\n }\n }\n for (const field of root.querySelectorAll(`input[type=\"hidden\"][name=\"${FALLBACK_FIELD}\"]`)) {\n const form = field.parentElement\n form?.removeAttribute('method')\n form?.querySelector(`:scope > input[type=\"hidden\"][name=\"${FALLBACK_DEPTH_FIELD}\"]`)?.remove()\n field.remove()\n }\n}\n\n/**\n * Removes head markup `SSR.headed` should have moved out of the root (a plan's\n * `meta`), saying whether there was any: the view does not draw it, and the\n * plan's meta entry writes the head once the page runs.\n */\nconst dropUnmovedHead = (root: Element): boolean => {\n const nodes = Array.from(root.childNodes)\n const marks = (value: string) => (node: ChildNode) =>\n node.nodeType === Node.COMMENT_NODE && node.nodeValue === value\n const open = nodes.findIndex(marks(HEAD_MARKER))\n if (open === -1) return false\n const close = nodes.findIndex((node, at) => at > open && marks(HEAD_END_MARKER)(node))\n for (const node of nodes.slice(open, close === -1 ? undefined : close + 1)) node.remove()\n return true\n}\n\n/**\n * Moves what a render's `styles` put in the root into the head, before\n * anything adopts the page: the view does not draw it, so hydration would\n * remove it, and a page that never renders again would lose the rules its\n * classes need. Whatever adopts the page next finds them in the head.\n */\nconst keepStyles = (root: Element): void => {\n const marker = Array.from(root.childNodes).find(\n node => node.nodeType === Node.COMMENT_NODE && node.nodeValue === STYLES_MARKER,\n )\n if (marker === undefined) return\n for (let next = marker.nextSibling; next !== null; next = marker.nextSibling) {\n if (next instanceof Element) document.head.append(next)\n else next.remove()\n }\n marker.remove()\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport { UNTIL_LIMIT_MS }\n\n/**\n * Runs the application afresh out of view, beside the served page, and puts\n * it in the page's place once a Model it drew satisfies `until`, or after\n * `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its\n * Mounts start in the document as they would in place.\n */\nconst renderBeside = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n served: HTMLElement,\n until: (model: Model) => boolean,\n): void => {\n const holder = document.createElement('div')\n holder.hidden = true\n const container = document.createElement('div')\n // The runtime refuses a container without an id; the served page gives its own up.\n container.id = served.id === '' ? 'foldkit-ssr-app' : served.id\n served.removeAttribute('id')\n // Nor does it boot beside a page stamped as a server render, which this one,\n // never adopted, no longer is.\n served.removeAttribute(FOLDKIT_APP_ATTRIBUTE)\n holder.append(container)\n served.after(holder)\n let shown = false\n const show = () => {\n if (shown) return\n shown = true\n clearTimeout(limit)\n holder.replaceWith(...holder.childNodes)\n served.remove()\n }\n const limit = setTimeout(show, UNTIL_LIMIT_MS)\n const view: ResumableConfig<Model, Message>['view'] = (model, h) => {\n const drawn = config.view(model, h)\n // Shown once the drawing this view returns is patched in, which the\n // runtime does in the same task.\n if (!shown && until(model)) queueMicrotask(show)\n return drawn\n }\n run(makeApplication({ ...config, view, container } as never))\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n * Each kept field the person changed is put back, value and selection, as\n * the first render commits, since that render re-asserts the served value.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n report: (diagnostic: SsrDiagnostic) => void,\n kept: ReadonlyArray<KeptField>,\n loaded: ReadonlyArray<HeldEvent>,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n // The kept fields as the person left them, which the first render resets.\n let held: ReadonlyArray<Held> = []\n const { stop, answer } = listening(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n // Before the queue runs, so its Messages find the fields holding their values.\n restore(held)\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n held = hold(kept)\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n report(bundleUnloaded(error))\n commit()\n })\n }\n // What the loader held, answered as if the page had listened then.\n for (const { event, path } of loaded) answer(event, path)\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, unbound, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n/** The diagnostics channel `hydrate` reports into, re-exported so a page needs no other import. */\nexport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nexport type {\n BundleUnloaded,\n CachedPageDiffers,\n HandlerUnnamed,\n HeadNotMoved,\n PageContained,\n PageFailed,\n SsrDiagnostic,\n StaticRegionMissing,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AA6DA,MAAM,eAAe,SACnB,IAAI,IACF,MAAM,KAAK,KAAK,iBAAiB,IAAI,iBAAiB,EAAE,IAAG,YAAW,CACpE,QAAQ,aAAA,0BAA6B,KAAK,IAC1C,QAAQ,SACV,CAAC,CACH;;;;;;AAOF,MAAM,kBAAkB;;;;;;;;;;;;;;;AAgBxB,MAAMA,aACJ,QACA,MACA,YAmDS;CACT,MAAM,UAAU,eAAoC;EAClD,OA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O,cAAc,OAAO,MACvE,OAAO,KAAK,QAAQ,CACtB,GACA,QACF,CACF;EACJ,EACF,CAAC;EACD,IAAI,CAAC,KAAK,aAAA,kBAAkC,GAAG,SAAS;CAC1D;CACA,MAAM,iBAAiB;EACrB,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,IAAI,QAAQ,WAAW,GAAG;GACxB,OAAO;GACP;EACF;EACA,QAAa,IAAI,QAAQ,KAAI,WAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,UAAmB;GACtF,OAAO,eAAe,KAAK,CAAC;GAC5B,OAAO;EACT,CAAC;CACH;CAEA,KAAK,MAAM,EAAE,OAAO,UAAU,QAAQ,OAAO,OAAO,IAAI;CACxD,IAAI,UAAU,OAAO,SAAS;MACzB,IAAI,UAAU,QAAQ;EACzB,IAAI,OAAO,OAAO,wBAAwB,YAAY,OAAO,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;CAAS;AAAQ"}
1
+ {"version":3,"file":"client.js","names":["hydrate","Diagnostics","adopt"],"sources":["../src/client.ts"],"sourcesContent":["/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Option, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { Diagnostics, type ReportDiagnostic } from 'foldkit-surface'\nimport { withContext, type RenderContext } from './context.js'\nimport {\n bundleUnloaded,\n headNotMoved,\n noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { claim, type HeldEvent } from './handoff.js'\nimport { UNTIL_LIMIT_MS } from './marks.js'\nimport { hold, keptFields, restore, typedMessages, type Held, type KeptField } from './keep.js'\nimport { listen, listening, type DecodedBinding } from './listen.js'\nimport {\n BINDING_ATTRIBUTE,\n FALLBACK_DEPTH_FIELD,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n builder,\n view,\n} from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n HEAD_END_MARKER,\n HEAD_MARKER,\n STYLES_MARKER,\n arrival,\n bindings,\n bindingsAndEvents,\n lazyFor,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n unbound,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is reported (`options.diagnostics`). A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n *\n * Run by `foldkit-ssr/loader`, it starts now, whatever the plan's `start`\n * (the loader followed it), and answers each event the loader held from the\n * markers, once. A page that does not resume releases them to the browser.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * With `otherwise: 'render'`, when the fresh application is ready to be\n * seen: until a Model it has drawn satisfies this, it draws out of view\n * and the served page stays, so a page is not swapped for its loading\n * state and back. Omitted, the fresh application replaces the page at\n * once. The served page stays no longer than `UNTIL_LIMIT_MS`.\n */\n readonly until?: ((model: Model) => boolean) | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n /**\n * What only this browser adds to the resumed Model before it is adopted,\n * and the view does not draw: a session minted for this page load (an\n * outbox's `session`). Run once, for a page that resumes; the runtime\n * starts when it succeeds. What the view draws, such as a queue read from\n * storage, arrives after, as a Message: here it would make the first\n * client view differ from the served page. Must not fail, as `when` must\n * not throw.\n */\n readonly prepare?: ((model: Model) => Effect.Effect<Model>) | undefined\n /**\n * Where what the page met goes: a page contained rather than resumed, a\n * static region the server's page lacked, a lazy bundle that did not\n * load. Each is reported before or apart from the runtime, so its\n * resources' reporter is not in effect. Omitted, Effect's log: the\n * browser's console.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): void => {\n const report = (diagnostic: SsrDiagnostic): void => {\n Effect.runFork(reportingTo(options.diagnostics)(Diagnostics.report(diagnostic)))\n }\n const loader = Option.fromNullishOr(claim())\n // Every path below that does not resume the page lets the browser have what\n // the loader held: a held submission posts.\n const release = (): void => Option.match(loader, { onNone: () => {}, onSome: it => it.release() })\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (root !== null) {\n if (dropUnmovedHead(root)) report(headNotMoved)\n keepStyles(root)\n }\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n release()\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n release()\n if (options.otherwise !== 'render') contain()\n else if (options.until === undefined)\n run(makeApplication({ ...config, container: root } as never))\n else renderBeside(config, root, options.until)\n return\n }\n // The type says a string, but `import.meta.env` is `any`: with the variable\n // unset the id arrives undefined, and Foldkit, given none, takes its own\n // compiled id, which matches the page, so the baseline was adopted in silence.\n if (typeof options.buildId !== 'string') {\n report(noBuildId)\n release()\n contain()\n return\n }\n const served = root.getAttribute(BUILD_ATTRIBUTE)\n if (served !== options.buildId) {\n report(otherBuild(Option.fromNullOr(served), options.buildId))\n release()\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n report(pageContained(resumed.failure.reason, resumed.failure.message))\n release()\n contain()\n return\n }\n const adoptFrom = (model: Model): void => {\n // A page recorded for its path, opened at a query: the application learns\n // the URL, as from a navigation, and the page starts now, since what it\n // shows is not yet the address.\n const arrived = arrival(config, document, window.location.href)\n const bootCommands = (started: Model): ReadonlyArray<unknown> =>\n (plan.boot?.(started) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n report,\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n // The URL goes into the Model the runtime starts from, not into `answered`:\n // Subscriptions start from that Model before any Message lands, and a URL\n // mirror among them would write the served address back over the real one.\n // The first render then differs from the served page where the URL does, and\n // Foldkit rebuilds that part, as a navigation would redraw it. Applied at\n // boot, once any lazy bundle's `update` has loaded. The boot Commands are\n // planned from the Model the runtime actually starts with, so one derived\n // from the route or query sees the address the page arrived at.\n const startOf = () =>\n Option.match(arrived, {\n onNone: () => ({ model, commands: bootCommands(model) }),\n onSome: message => {\n const step = apply(model, message) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n return {\n model: step.model,\n commands: [...bootCommands(step.model), ...(step.commands ?? [])],\n }\n },\n })\n const boot = (entries: Readonly<Record<string, unknown>> = {}) => {\n unmark(root)\n return adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, startOf()), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n }\n // What the served page draws: a function of the Model is asked with the\n // resumed one, so another route's code is not fetched to boot this page.\n const pending = lazyFor(config, model).filter(bundle => !bundle.isLoaded())\n // A loader ran this chunk when the plan's `start` said to.\n const start = Option.isSome(arrived) || Option.isSome(loader) ? 'now' : plan.start\n const eager = start === 'now' && pending.length === 0\n // With a loader, the page reads its bindings first: the loader may hold\n // events for them.\n if (eager && Option.isNone(loader) && root.querySelector(`[${KEEP_ATTRIBUTE}]`) === null) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n report(pageContained(decoded.failure.reason, decoded.failure.message))\n release()\n contain()\n return\n }\n const kept = keptFields(root, decoded.success.bindings)\n if (Result.isFailure(kept)) {\n report(pageContained('Invalid', kept.failure))\n release()\n contain()\n return\n }\n // What was typed before this script ran, first in the queue: everything the\n // page answers from here on happened after it.\n answered.push(...typedMessages(kept.success))\n const held = Option.match(loader, { onNone: () => [], onSome: it => it.take() })\n if (eager && answered.length === 0 && held.length === 0) {\n boot()\n return\n }\n // Typing is an interaction, whenever it happened: a page that waits for\n // one starts now, so what was typed is answered as soon as the script runs.\n const typed = answered.length > 0 ? 'now' : start\n deferBoot(root, decoded.success, typed, { boot, answered }, pending, report, kept.success, held)\n }\n const prepare = options.prepare\n let startingModel: Model\n try {\n startingModel = plan.restore === undefined ? resumed.success : plan.restore(resumed.success)\n } catch (error) {\n report(pageContained('Invalid', error instanceof Error ? error.message : String(error)))\n release()\n contain()\n return\n }\n if (prepare === undefined) adoptFrom(startingModel)\n else void Effect.runPromise(prepare(startingModel)).then(adoptFrom)\n}\n\n/**\n * Takes out of the served page what the server wrote for this script to read\n * and no view draws: the envelope, each binding's and kept field's marker,\n * each placement's slot, and each form's fallback (its `method` and hidden\n * fields). Left in, each is in what Foldkit records of the served page and\n * gone after its first patch, so Foldkit reconciles every such element, and\n * a development build reports that the server's markup and the view\n * disagree. Run as the page boots, so a form submitted before then still\n * posts.\n */\nconst unmark = (root: Element): void => {\n root.removeAttribute(RESUME_ATTRIBUTE)\n for (const element of [root, ...root.querySelectorAll('*')]) {\n for (const name of element.getAttributeNames()) {\n if (name.startsWith(BINDING_ATTRIBUTE) || name === KEEP_ATTRIBUTE || name === SLOT_ATTRIBUTE)\n element.removeAttribute(name)\n }\n }\n for (const field of root.querySelectorAll(`input[type=\"hidden\"][name=\"${FALLBACK_FIELD}\"]`)) {\n const form = field.parentElement\n form?.removeAttribute('method')\n form?.querySelector(`:scope > input[type=\"hidden\"][name=\"${FALLBACK_DEPTH_FIELD}\"]`)?.remove()\n field.remove()\n }\n}\n\n/**\n * Removes head markup `SSR.headed` should have moved out of the root (a plan's\n * `meta`), saying whether there was any: the view does not draw it, and the\n * plan's meta entry writes the head once the page runs.\n */\nconst dropUnmovedHead = (root: Element): boolean => {\n const nodes = Array.from(root.childNodes)\n const marks = (value: string) => (node: ChildNode) =>\n node.nodeType === Node.COMMENT_NODE && node.nodeValue === value\n const open = nodes.findIndex(marks(HEAD_MARKER))\n if (open === -1) return false\n const close = nodes.findIndex((node, at) => at > open && marks(HEAD_END_MARKER)(node))\n for (const node of nodes.slice(open, close === -1 ? undefined : close + 1)) node.remove()\n return true\n}\n\n/**\n * Moves what a render's `styles` put in the root into the head, before\n * anything adopts the page: the view does not draw it, so hydration would\n * remove it, and a page that never renders again would lose the rules its\n * classes need. Whatever adopts the page next finds them in the head.\n */\nconst keepStyles = (root: Element): void => {\n const marker = Array.from(root.childNodes).find(\n node => node.nodeType === Node.COMMENT_NODE && node.nodeValue === STYLES_MARKER,\n )\n if (marker === undefined) return\n for (let next = marker.nextSibling; next !== null; next = marker.nextSibling) {\n if (next instanceof Element) document.head.append(next)\n else next.remove()\n }\n marker.remove()\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport { UNTIL_LIMIT_MS }\n\n/**\n * Runs the application afresh out of view, beside the served page, and puts\n * it in the page's place once a Model it drew satisfies `until`, or after\n * `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its\n * Mounts start in the document as they would in place.\n */\nconst renderBeside = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n served: HTMLElement,\n until: (model: Model) => boolean,\n): void => {\n const holder = document.createElement('div')\n holder.hidden = true\n const container = document.createElement('div')\n // The runtime refuses a container without an id; the served page gives its own up.\n container.id = served.id === '' ? 'foldkit-ssr-app' : served.id\n served.removeAttribute('id')\n // Nor does it boot beside a page stamped as a server render, which this one,\n // never adopted, no longer is.\n served.removeAttribute(FOLDKIT_APP_ATTRIBUTE)\n holder.append(container)\n served.after(holder)\n let shown = false\n const show = () => {\n if (shown) return\n shown = true\n clearTimeout(limit)\n holder.replaceWith(...holder.childNodes)\n served.remove()\n }\n const limit = setTimeout(show, UNTIL_LIMIT_MS)\n const view: ResumableConfig<Model, Message>['view'] = (model, h) => {\n const drawn = config.view(model, h)\n // Shown once the drawing this view returns is patched in, which the\n // runtime does in the same task.\n if (!shown && until(model)) queueMicrotask(show)\n return drawn\n }\n run(makeApplication({ ...config, view, container } as never))\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n * Each kept field the person changed is put back, value and selection, as\n * the first render commits, since that render re-asserts the served value.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n report: (diagnostic: SsrDiagnostic) => void,\n kept: ReadonlyArray<KeptField>,\n loaded: ReadonlyArray<HeldEvent>,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n // The kept fields as the person left them, which the first render resets.\n let held: ReadonlyArray<Held> = []\n const { stop, answer } = listening(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n // Before the queue runs, so its Messages find the fields holding their values.\n restore(held)\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n held = hold(kept)\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n report(bundleUnloaded(error))\n commit()\n })\n }\n // What the loader held, answered as if the page had listened then.\n for (const { event, path } of loaded) answer(event, path)\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, unbound, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n/** The diagnostics channel `hydrate` reports into, re-exported so a page needs no other import. */\nexport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nexport type {\n BundleUnloaded,\n CachedPageDiffers,\n HandlerUnnamed,\n HeadNotMoved,\n PageContained,\n PageFailed,\n SsrDiagnostic,\n StaticRegionMissing,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;;;;;;;;;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AAM,OAAO,MAAM;GACnB,QAAQ,cAAc,IAAI,KAAK,MAAM,MAAM,KAAK,CAAC;EACnD;CACF;CACA,MAAM,eAAe;EACnB,QAAQ;EACR,OAAO,KAAK,IAAI;EAChB,QAAQ,KAAK,EACX,wBAAwB;GACtB,oBAAoB,OAAO;GAC3B,2BAA2B;GAG3B,4BACE,OAAO,WACL,OAAO,GACL,OAAO,QACL,KAAK,aAAA,kBAAkC,IAAI,OAAO,cAAc,OAAO,MACvE,OAAO,KAAK,QAAQ,CACtB,GACA,QACF,CACF;EACJ,EACF,CAAC;EACD,IAAI,CAAC,KAAK,aAAA,kBAAkC,GAAG,SAAS;CAC1D;CACA,MAAM,iBAAiB;EACrB,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,IAAI,QAAQ,WAAW,GAAG;GACxB,OAAO;GACP;EACF;EACA,QAAa,IAAI,QAAQ,KAAI,WAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,UAAmB;GACtF,OAAO,eAAe,KAAK,CAAC;GAC5B,OAAO;EACT,CAAC;CACH;CAEA,KAAK,MAAM,EAAE,OAAO,UAAU,QAAQ,OAAO,OAAO,IAAI;CACxD,IAAI,UAAU,OAAO,SAAS;MACzB,IAAI,UAAU,QAAQ;EACzB,IAAI,OAAO,OAAO,wBAAwB,YAAY,OAAO,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;CAAS;AAAQ"}
package/dist/context.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { B as RenderContext, H as current, R as Binding, U as withContext, V as UnnamedHandler, W as within, z as Region } from "./shared-mQ8CXr-r.js";
1
+ import { B as Region, G as within, H as UnnamedHandler, U as current, V as RenderContext, W as withContext, z as Binding } from "./shared-BuCOwm57.js";
2
2
  export { Binding, Region, RenderContext, UnnamedHandler, current, withContext, within };
@@ -1,2 +1,2 @@
1
- import { $ as bundleUnloaded, G as BundleUnloaded, J as HeadNotMoved, K as CachedPageDiffers, Q as StaticRegionMissing, X as PageFailed, Y as PageContained, Z as SsrDiagnostic, at as pageContained, ct as staticRegionMissing, et as cachedPageDiffers, it as otherBuild, nt as headNotMoved, ot as pageFailed, q as HandlerUnnamed, rt as noBuildId, st as reportingTo, tt as handlerUnnamed } from "./shared-mQ8CXr-r.js";
1
+ import { $ as StaticRegionMissing, J as HandlerUnnamed, K as BundleUnloaded, Q as SsrDiagnostic, X as PageContained, Y as HeadNotMoved, Z as PageFailed, at as otherBuild, ct as reportingTo, et as bundleUnloaded, it as noBuildId, lt as staticRegionMissing, nt as handlerUnnamed, ot as pageContained, q as CachedPageDiffers, rt as headNotMoved, st as pageFailed, tt as cachedPageDiffers } from "./shared-BuCOwm57.js";
2
2
  export { BundleUnloaded, CachedPageDiffers, HandlerUnnamed, HeadNotMoved, PageContained, PageFailed, SsrDiagnostic, StaticRegionMissing, bundleUnloaded, cachedPageDiffers, handlerUnnamed, headNotMoved, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
package/dist/index.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { a as UNTIL_LIMIT_MS, i as RESUME_ATTRIBUTE, n as FOLDKIT_APP_ATTRIBUTE, r as KEEP_ATTRIBUTE, t as BINDING_ATTRIBUTE } from "./marks-CX15BwOw.js";
2
2
  import { n as DecodedBinding, r as EncodedBinding } from "./listen-7HzKBhqU.js";
3
3
  import { c as ResumableBuilder, i as FALLBACK_FIELD, l as SLOT_ATTRIBUTE } from "./resumable-BV9_OKxr.js";
4
- import { A as resume, D as plan, F as staticRegion, G as BundleUnloaded, J as HeadNotMoved, K as CachedPageDiffers, L as unbound, M as serializeJsonScript, N as serving, Q as StaticRegionMissing, V as UnnamedHandler, X as PageFailed, Y as PageContained, Z as SsrDiagnostic, a as Meta, d as ResumePlan, f as ResumeRefused, g as Start, i as META_ATTRIBUTE, l as ResumableConfig, m as STATIC_ATTRIBUTE, p as RouteMatch, q as HandlerUnnamed, r as Loadable, s as PlanSurface, u as ResumePart, w as metaMarkup } from "./shared-mQ8CXr-r.js";
5
- import { i as Resume, n as Diagnostics, r as ReportDiagnostic, t as Diagnostic } from "./client-BEHlUHBv.js";
4
+ import { $ as StaticRegionMissing, H as UnnamedHandler, I as staticRegion, J as HandlerUnnamed, K as BundleUnloaded, N as serializeJsonScript, O as plan, P as serving, Q as SsrDiagnostic, R as unbound, T as metaMarkup, X as PageContained, Y as HeadNotMoved, Z as PageFailed, a as Meta, d as ResumePlan, f as ResumeRefused, g as Start, i as META_ATTRIBUTE, j as resume, l as ResumableConfig, m as STATIC_ATTRIBUTE, p as RouteMatch, q as CachedPageDiffers, r as Loadable, s as PlanSurface, u as ResumePart } from "./shared-BuCOwm57.js";
5
+ import { i as Resume, n as Diagnostics, r as ReportDiagnostic, t as Diagnostic } from "./client-cumvT9XN.js";
6
6
  import { s as keptDocuments } from "./pageCache-DO0pOgnc.js";
7
7
  import { n as requestContext, t as RequestContext } from "./requestContext-DmwmQeci.js";
8
8
  import { Cause, Effect, Layer, Option, Schema } from "effect";
@@ -79,7 +79,7 @@ export interface PlanInspection {
79
79
  */
80
80
  declare const inspect: <Model, Fields extends Schema.Struct.Fields>(plan: ResumePlan<Model, Fields>, model: Model) => PlanInspection;
81
81
  declare const ResumeUnsafe_base: Schema.Class<ResumeUnsafe, Schema.TaggedStruct<"ResumeUnsafe", {
82
- readonly reason: Schema.Literals<readonly ["UndeclaredStartup", "Uncovered", "ViewDependsOnUnsentState", "DuplicateStaticRegion", "UngeneratablePath", "UnrestorablePart", "UnencodableBinding", "EagerStartRequired", "UndeclaredSurfaces", "BindingInStaticRegion", "VoidRootWithStyles", "RootRefusesHead", "UnkeepableField", "UnkeptField"]>;
82
+ readonly reason: Schema.Literals<readonly ["UndeclaredStartup", "Uncovered", "ViewDependsOnUnsentState", "LazyDependsOnUnsentState", "DuplicateStaticRegion", "UngeneratablePath", "UnrestorablePart", "UnencodableBinding", "EagerStartRequired", "UndeclaredSurfaces", "BindingInStaticRegion", "VoidRootWithStyles", "RootRefusesHead", "UnkeepableField", "UnkeptField"]>;
83
83
  readonly message: Schema.String;
84
84
  }>, Cause.YieldableError>;
85
85
  /** Why a server refused to render a page against its plan. */
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["Diagnostic"],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;UAgIU;WACC;WACA,QAAQ;WACR,WAAW,cAAc;;WAEzB,SAAS;;;;;;;;;cAUd,WAAY,OAAO,eAAe,OAAO,OAAO,QAAM,QAClD,WAAW,OAAO,SAAO,OAC1B,OAAK,UACH;;YAiNC;;iBAGK;WACN;;WAEA;;WAEA;;;;;WAKA;aAEM;aACA;eAAwB;eAAuB,OAAO;;;;WAI5D;aAAwB;aAAuB,OAAO;;;WAEtD,OAAO;aAAyB;aAAuB,OAAO;;;;;;WAK9D,WAAW,cAAc;;WAEzB;;;iBAIM;WACN;WACA,OAAO;WACP,OAAO;;WAEP,UAAU;;WAEV,OAAO;WACP,UAAU,cAAc;;;;;;;cA8C7B,UAAW,OAAO,eAAe,OAAO,OAAO,QAAM,MACnD,WAAW,OAAO,SAAO,OACxB,UACN;;;;;;qBA0KU,qBAAqB;;iBA6KjB;;;;;;WAMN,UAAU;;WAEV;;WAEA;;WAEA,OAAO;;;;;WAKP,SAAS,cAAc;;;;;;;;;;;;;;;cAgB5B,SAAU,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAa,QAC/D,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;WAEpB;WACA;WACA;;;;;;;WAOA,SAAS;MAEnB,OAAO,OAAO,cAAc,cAAc;;;;;;;;YAiNjC,QAAQ,UAAU,qBAAqB,OAAO;;;;;;;cA+DpD,OAAI,kBACQ;WAEL,UAAU;WACV;WACA,OAAO;GACjB;WACmB,OAAO;;;;;;;;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BAAe,OAAO;MACrD,aAAW,UACP,oBAAoB,aAC7B;;;;;;qBAwGU,wBAAwB;;YA4GzB,QAAQ,UAAU,OAAO,OAAO,SAAS,YAAY,OAAO,OAAO;;;;;;;;;;cA+BzE,SAAU,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAa,SAC9D,SAAO,QACR,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO,SACtB,cAAc,WACtB,OAAO,OAAO,cAAc,cAAc,eAAe;UAGlD,cAAc;WACb;WACA;WACA,SAAS;;WAET;;WAEA,UAAU,QAAQ;;;;;;WAMlB,YAAY,MAAM;;qBAwGhB"}
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@ import { withContext } from "./context.js";
2
2
  import { cachedPageDiffers, handlerUnnamed, pageFailed, reportingTo } from "./diagnostics.js";
3
3
  import { BINDING_ATTRIBUTE, FOLDKIT_APP_ATTRIBUTE, KEEP_ATTRIBUTE, RESUME_ATTRIBUTE, UNTIL_LIMIT_MS } from "./marks.js";
4
4
  import { FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, SLOT_ATTRIBUTE } from "./resumable.js";
5
- import { HEAD_END_MARKER, HEAD_MARKER, META_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, STYLES_MARKER, allowedTags, attributeOf, codecOf, metaMarkup, modelFrom, pathKey, plan, projectionsOf, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf, unbound } from "./shared.js";
5
+ import { HEAD_END_MARKER, HEAD_MARKER, META_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, STYLES_MARKER, allowedTags, attributeOf, codecOf, lazyFor, metaMarkup, modelFrom, pathKey, plan, projectionsOf, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf, unbound } from "./shared.js";
6
6
  import { Diagnostics, Resume, SSR as SSR$1 } from "./client.js";
7
7
  import { requestContext } from "./requestContext.js";
8
8
  import { decodeKept, fits, headerOf, keptApplications, keptDocuments, pageKey, samePage, tracked } from "./pageCache.js";
@@ -304,6 +304,7 @@ var ResumeUnsafe = class extends Schema.TaggedError()("ResumeUnsafe", {
304
304
  "UndeclaredStartup",
305
305
  "Uncovered",
306
306
  "ViewDependsOnUnsentState",
307
+ "LazyDependsOnUnsentState",
307
308
  "DuplicateStaticRegion",
308
309
  "UngeneratablePath",
309
310
  "UnrestorablePart",
@@ -362,8 +363,30 @@ const unplacedKeeps = (html) => {
362
363
  }
363
364
  return found;
364
365
  };
365
- /** Loads every lazy bundle's bodies, so the view renders whole. */
366
- const loadLazy = (config) => Effect.promise(() => Promise.all((config.lazy ?? []).map((bundle) => bundle.load())));
366
+ /**
367
+ * Loads the lazy bundles the page draws, so the view renders whole, and
368
+ * returns the config the render starts from. A list loads whole; a function
369
+ * of the Model is asked with the Model `init` starts this page from, so the
370
+ * render starts from that start rather than running `init` a second time.
371
+ * `known` is that Model when the config already starts from it (`prepare`'s,
372
+ * a post's), which no render need work out again.
373
+ */
374
+ const loadLazy = (config, options, known) => Effect.gen(function* () {
375
+ const { lazy } = config;
376
+ if (typeof lazy !== "function") {
377
+ yield* Effect.promise(() => Promise.all((lazy ?? []).map((each) => each.load())));
378
+ return config;
379
+ }
380
+ if (Option.isSome(known)) {
381
+ yield* Effect.promise(() => Promise.all(lazy(known.value).map((each) => each.load())));
382
+ return config;
383
+ }
384
+ const started = yield* startOf(config, options);
385
+ yield* Effect.promise(() => Promise.all(lazy(started.model).map((each) => each.load())));
386
+ return startingFrom(config, started);
387
+ });
388
+ /** A lazy list by its bundles' names, in a stable order, to compare two. */
389
+ const codeNames = (code) => code.map((each) => each.name).sort().join(", ");
367
390
  /** Foldkit's own Flags script, which a resumed page never carries. */
368
391
  const FLAGS_SCRIPT = new RegExp(`<script[^>]*${FOLDKIT_FLAGS_ATTRIBUTE}[^>]*>[\\s\\S]*?<\/script>`, "g");
369
392
  /**
@@ -433,8 +456,8 @@ const eagerEntries = (config, plan, model) => {
433
456
  * place it shows.
434
457
  */
435
458
  const render = (config, plan, options) => Effect.map(renderMatching(config, plan, options, "full"), (served) => served.page);
436
- const renderMatching = (config, plan, options, match) => Effect.gen(function* () {
437
- yield* loadLazy(config);
459
+ const renderMatching = (config, plan, options, match, known = Option.none()) => Effect.gen(function* () {
460
+ config = yield* loadLazy(config, options, known);
438
461
  let served;
439
462
  const regions = /* @__PURE__ */ new Map();
440
463
  const duplicates = /* @__PURE__ */ new Set();
@@ -493,6 +516,12 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
493
516
  message: resumed.failure
494
517
  });
495
518
  const browser = resumed.success;
519
+ const drawnCode = codeNames(lazyFor(config, started.model));
520
+ const bootedCode = codeNames(lazyFor(config, browser));
521
+ if (drawnCode !== bootedCode) return yield* new ResumeUnsafe({
522
+ reason: "LazyDependsOnUnsentState",
523
+ message: `lazy names [${drawnCode}] for the Model the server draws and [${bootedCode}] for the one the browser resumes: send what it reads in the plan's state`
524
+ });
496
525
  const eager = eagerEntries(config, plan, started.model);
497
526
  if (eager.length > 0) return yield* new ResumeUnsafe({
498
527
  reason: "EagerStartRequired",
@@ -671,10 +700,10 @@ const reportedUnnamed = /* @__PURE__ */ new Set();
671
700
  /**
672
701
  * Reports, once per process, each handler that keeps a page from answering
673
702
  * before boot. Only a page that waits to boot is held up: one started
674
- * `'now'`, with no lazy bundle to load, boots before any event.
703
+ * `'now'`, with no lazy bundle to load for the Model it shows, boots before any event.
675
704
  */
676
- const reportUnnamed = (config, plan, unnamed) => Effect.suspend(() => {
677
- if (plan.start === "now" && (config.lazy ?? []).length === 0) return Effect.void;
705
+ const reportUnnamed = (config, plan, { model, page: { unnamed } }) => Effect.suspend(() => {
706
+ if (plan.start === "now" && lazyFor(config, model).length === 0) return Effect.void;
678
707
  const first = unnamed.filter(({ element, event }) => {
679
708
  const key = JSON.stringify([
680
709
  plan.id,
@@ -716,7 +745,7 @@ const generate = (config, plan, options) => Effect.gen(function* () {
716
745
  buildId: options.buildId,
717
746
  url: new URL(path, options.origin).href,
718
747
  ...options.flags === void 0 ? {} : { flags: options.flags(path) }
719
- }, "path").pipe(Effect.map((served) => served.page), Effect.tap((result) => reportUnnamed(config, plan, result.unnamed)), Effect.map((result) => ({
748
+ }, "path").pipe(Effect.tap((served) => reportUnnamed(config, plan, served)), Effect.map(({ page: result }) => ({
720
749
  path,
721
750
  file: fileOf(path),
722
751
  html: page(options.template, result, { head: options.head })
@@ -860,12 +889,12 @@ const entry = (config, plan, options) => {
860
889
  buildId: options.buildId,
861
890
  ...start,
862
891
  ...styled
863
- }, matchOf(request.url));
892
+ }, matchOf(request.url), Option.map(started, ({ model }) => model));
864
893
  const extra = yield* Effect.sync(() => headersOf(request, Option.some(served.model)));
865
894
  const status = Option.map(Option.fromUndefinedOr(statusOf), (of) => of(served.model, request));
866
895
  const unanswerable = Option.filter(status, (given) => !Number.isInteger(given) || given < 200 || given > 599 || given === 204 || given === 205 || given === 304);
867
896
  if (Option.isSome(unanswerable)) return yield* Effect.die(/* @__PURE__ */ new Error(`status gave ${unanswerable.value} for the page, which is no status for a page with a body`));
868
- yield* reportUnnamed(config, plan, served.page.unnamed);
897
+ yield* reportUnnamed(config, plan, served);
869
898
  return Rendered(served.page.rendered, {
870
899
  ...extra === void 0 ? {} : { headers: extra },
871
900
  ...Option.match(status, {
@@ -1197,7 +1226,7 @@ const handleServed = (request, config, plan, options) => Effect.flatMap(postedMo
1197
1226
  url: request.url,
1198
1227
  ...options.styles === void 0 ? {} : { styles: options.styles },
1199
1228
  ...options.metaInRoot === true ? { metaInRoot: true } : {}
1200
- }, "full"));
1229
+ }, "full", Option.some(model)));
1201
1230
  /** The Model a posted form reaches: its Message decoded and checked, then `update` and its Commands. */
1202
1231
  const postedModel = (request, config, plan, options) => Effect.scoped(Effect.gen(function* () {
1203
1232
  if (plan.fallback !== "server" || plan.Message === void 0) return yield* refuseFallback("NoFallback", `plan "${plan.id}" has no server fallback`);