foldkit-ssr 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/README.md +315 -36
  2. package/dist/{client-F16QT0sc.d.ts → client-XnpTQZHw.d.ts} +15 -5
  3. package/dist/client-XnpTQZHw.d.ts.map +1 -0
  4. package/dist/client.d.ts +5 -5
  5. package/dist/client.js +126 -54
  6. package/dist/client.js.map +1 -1
  7. package/dist/context.d.ts +1 -1
  8. package/dist/context.js +12 -0
  9. package/dist/context.js.map +1 -1
  10. package/dist/diagnostics.d.ts +1 -1
  11. package/dist/index.d.ts +83 -23
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +174 -54
  14. package/dist/index.js.map +1 -1
  15. package/dist/keep.d.ts +34 -0
  16. package/dist/keep.d.ts.map +1 -0
  17. package/dist/keep.js +80 -0
  18. package/dist/keep.js.map +1 -0
  19. package/dist/{listen-zNd0IIAT.d.ts → listen-DaUPRKVR.d.ts} +4 -2
  20. package/dist/listen-DaUPRKVR.d.ts.map +1 -0
  21. package/dist/listen.d.ts +2 -2
  22. package/dist/listen.js +31 -23
  23. package/dist/listen.js.map +1 -1
  24. package/dist/{resumable-BWItJsxF.d.ts → resumable-BPN_qQHU.d.ts} +33 -12
  25. package/dist/resumable-BPN_qQHU.d.ts.map +1 -0
  26. package/dist/resumable.d.ts +2 -2
  27. package/dist/resumable.js +51 -8
  28. package/dist/resumable.js.map +1 -1
  29. package/dist/{shared-v1u-OEQI.d.ts → shared-DbupL3vO.d.ts} +20 -5
  30. package/dist/shared-DbupL3vO.d.ts.map +1 -0
  31. package/dist/shared.d.ts +2 -2
  32. package/dist/shared.js +25 -2
  33. package/dist/shared.js.map +1 -1
  34. package/dist/vite.d.ts +1 -1
  35. package/package.json +9 -9
  36. package/dist/client-F16QT0sc.d.ts.map +0 -1
  37. package/dist/listen-zNd0IIAT.d.ts.map +0 -1
  38. package/dist/resumable-BWItJsxF.d.ts.map +0 -1
  39. package/dist/shared-v1u-OEQI.d.ts.map +0 -1
package/dist/client.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { withContext } from "./context.js";
2
2
  import { bundleUnloaded, noBuildId, otherBuild, pageContained, reportingTo } from "./diagnostics.js";
3
- import { BINDING_ATTRIBUTE, FALLBACK_FIELD, SLOT_ATTRIBUTE, builder, view } from "./resumable.js";
3
+ import { BINDING_ATTRIBUTE, FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, KEEP_ATTRIBUTE, SLOT_ATTRIBUTE, builder, view } from "./resumable.js";
4
4
  import { listen } from "./listen.js";
5
- import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, bindings, bindingsAndEvents, metaEntry, metaMarkup, plan, resume, routeOf, serving, startingFrom, staticRegion } from "./shared.js";
5
+ import { hold, keptFields, restore, typedMessages } from "./keep.js";
6
+ import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, arrival, bindings, bindingsAndEvents, metaEntry, metaMarkup, plan, resume, routeOf, serving, startingFrom, staticRegion } from "./shared.js";
6
7
  import { Effect, Option, Result, Schema, Stream } from "effect";
7
8
  import { hydrate, makeApplication, run } from "foldkit/runtime";
8
9
  import * as Render from "foldkit/render";
@@ -45,6 +46,7 @@ const hydrate$1 = (config, plan, options) => {
45
46
  }
46
47
  };
47
48
  const root = document.querySelector(`[${FOLDKIT_APP_ATTRIBUTE}]`);
49
+ if (root !== null) keepStyles(root);
48
50
  const declined = options.when !== void 0 && !options.when(document);
49
51
  const stale = options.fresh !== void 0 && !options.fresh(plan.version);
50
52
  if (root === null) {
@@ -82,59 +84,124 @@ const hydrate$1 = (config, plan, options) => {
82
84
  contain();
83
85
  return;
84
86
  }
85
- const model = resumed.success;
86
- const commands = plan.boot?.(model) ?? [];
87
- const resuming = {
88
- mode: "resume",
89
- snapshots: snapshotsOf(root),
90
- reported: /* @__PURE__ */ new Set(),
91
- report
92
- };
93
- const answered = [];
94
- const apply = config.update;
95
- const update = (current, message) => {
96
- const handingOver = message === HANDOVER;
97
- if (answered.length === 0) return handingOver ? { model: current } : apply(current, message);
98
- const returned = [];
99
- for (const next of [...answered.splice(0), ...handingOver ? [] : [message]]) {
100
- const step = apply(current, next);
101
- current = step.model;
102
- returned.push(...step.commands ?? []);
103
- }
104
- return {
105
- model: current,
106
- commands: returned
87
+ const adoptFrom = (model) => {
88
+ const arrived = arrival(config, document, window.location.href);
89
+ const commands = plan.boot?.(model) ?? [];
90
+ const resuming = {
91
+ mode: "resume",
92
+ snapshots: snapshotsOf(root),
93
+ reported: /* @__PURE__ */ new Set(),
94
+ report
107
95
  };
108
- };
109
- const boot = (entries = {}) => hydrate(makeApplication({
110
- ...withContext(startingFrom({
111
- ...config,
112
- update
113
- }, {
114
- model,
115
- commands
116
- }), resuming),
117
- container: root,
118
- subscriptions: {
119
- ...config.subscriptions,
120
- ...entries
96
+ const answered = [];
97
+ const apply = config.update;
98
+ const update = (current, message) => {
99
+ const handingOver = message === HANDOVER;
100
+ if (answered.length === 0) return handingOver ? { model: current } : apply(current, message);
101
+ const returned = [];
102
+ for (const next of [...answered.splice(0), ...handingOver ? [] : [message]]) {
103
+ const step = apply(current, next);
104
+ current = step.model;
105
+ returned.push(...step.commands ?? []);
106
+ }
107
+ return {
108
+ model: current,
109
+ commands: returned
110
+ };
111
+ };
112
+ const startOf = () => Option.match(arrived, {
113
+ onNone: () => ({
114
+ model,
115
+ commands
116
+ }),
117
+ onSome: (message) => {
118
+ const step = apply(model, message);
119
+ return {
120
+ model: step.model,
121
+ commands: [...commands, ...step.commands ?? []]
122
+ };
123
+ }
124
+ });
125
+ const boot = (entries = {}) => {
126
+ unmark(root);
127
+ return hydrate(makeApplication({
128
+ ...withContext(startingFrom({
129
+ ...config,
130
+ update
131
+ }, startOf()), resuming),
132
+ container: root,
133
+ subscriptions: {
134
+ ...config.subscriptions,
135
+ ...entries
136
+ }
137
+ }), { buildId: options.buildId });
138
+ };
139
+ const pending = (config.lazy ?? []).filter((bundle) => !bundle.isLoaded());
140
+ const start = Option.isSome(arrived) ? "now" : plan.start;
141
+ const eager = start === "now" && pending.length === 0;
142
+ if (eager && root.querySelector(`[data-foldkit-plus-keep]`) === null) {
143
+ boot();
144
+ return;
121
145
  }
122
- }), { buildId: options.buildId });
123
- const pending = (config.lazy ?? []).filter((bundle) => !bundle.isLoaded());
124
- if (plan.start === "now" && pending.length === 0) {
125
- boot();
126
- return;
127
- }
128
- const decoded = bindingsAndEvents(plan, document, root, model);
129
- if (Result.isFailure(decoded)) {
130
- report(pageContained(decoded.failure.reason, decoded.failure.message));
131
- contain();
132
- return;
146
+ const decoded = bindingsAndEvents(plan, document, root, model);
147
+ if (Result.isFailure(decoded)) {
148
+ report(pageContained(decoded.failure.reason, decoded.failure.message));
149
+ contain();
150
+ return;
151
+ }
152
+ const kept = keptFields(root, decoded.success.bindings);
153
+ if (Result.isFailure(kept)) {
154
+ report(pageContained("Invalid", kept.failure));
155
+ contain();
156
+ return;
157
+ }
158
+ answered.push(...typedMessages(kept.success));
159
+ if (eager && answered.length === 0) {
160
+ boot();
161
+ return;
162
+ }
163
+ const typed = answered.length > 0 ? "now" : start;
164
+ deferBoot(root, decoded.success, typed, {
165
+ boot,
166
+ answered
167
+ }, pending, report, kept.success);
168
+ };
169
+ const prepare = options.prepare;
170
+ if (prepare === void 0) adoptFrom(resumed.success);
171
+ else Effect.runPromise(prepare(resumed.success)).then(adoptFrom);
172
+ };
173
+ /**
174
+ * Takes out of the served page what the server wrote for this script to read
175
+ * and no view draws: the envelope, each binding's and kept field's marker,
176
+ * each placement's slot, and each form's fallback (its `method` and hidden
177
+ * fields). Left in, each is in what Foldkit records of the served page and
178
+ * gone after its first patch, so Foldkit reconciles every such element, and
179
+ * a development build reports that the server's markup and the view
180
+ * disagree. Run as the page boots, so a form submitted before then still
181
+ * posts.
182
+ */
183
+ const unmark = (root) => {
184
+ root.removeAttribute(RESUME_ATTRIBUTE);
185
+ for (const element of [root, ...root.querySelectorAll("*")]) for (const name of element.getAttributeNames()) if (name.startsWith("data-foldkit-plus-on-") || name === "data-foldkit-plus-keep" || name === "data-foldkit-plus-slot") element.removeAttribute(name);
186
+ for (const field of root.querySelectorAll(`input[type="hidden"][name="${FALLBACK_FIELD}"]`)) {
187
+ const form = field.parentElement;
188
+ form?.removeAttribute("method");
189
+ form?.querySelector(`:scope > input[type="hidden"][name="${FALLBACK_DEPTH_FIELD}"]`)?.remove();
190
+ field.remove();
133
191
  }
134
- deferBoot(root, decoded.success, plan.start, {
135
- boot,
136
- answered
137
- }, pending, report);
192
+ };
193
+ /**
194
+ * Moves what a render's `styles` put in the root into the head, before
195
+ * anything adopts the page: the view does not draw it, so hydration would
196
+ * remove it, and a page that never renders again would lose the rules its
197
+ * classes need. Whatever adopts the page next finds them in the head.
198
+ */
199
+ const keepStyles = (root) => {
200
+ const marker = Array.from(root.childNodes).find((node) => node.nodeType === Node.COMMENT_NODE && node.nodeValue === "foldkit-plus-styles");
201
+ if (marker === void 0) return;
202
+ for (let next = marker.nextSibling; next !== null; next = marker.nextSibling) if (next instanceof Element) document.head.append(next);
203
+ else next.remove();
204
+ marker.remove();
138
205
  };
139
206
  /** The longest a served page stays in view while a fresh application waits for `until`. */
140
207
  const UNTIL_LIMIT_MS = 3e3;
@@ -190,10 +257,13 @@ const HANDOVER = Object.freeze({ _tag: "foldkit-ssr/Handover" });
190
257
  * `hydrate` returns, which Foldkit does today, or else when a handover
191
258
  * Subscription entry starts, after `Render.afterCommit`. When lazy bundles
192
259
  * must load first, the boot waits for them and the page keeps answering.
260
+ * Each kept field the person changed is put back, value and selection, as
261
+ * the first render commits, since that render re-asserts the served value.
193
262
  */
194
- const deferBoot = (root, decoded, start, runtime, pending, report) => {
263
+ const deferBoot = (root, decoded, start, runtime, pending, report, kept) => {
195
264
  const unanswered = [];
196
265
  let phase = "waiting";
266
+ let held = [];
197
267
  const stop = listen(root, {
198
268
  bindings: decoded.bindings,
199
269
  ...decoded.events === void 0 ? {} : { events: decoded.events },
@@ -218,6 +288,7 @@ const deferBoot = (root, decoded, start, runtime, pending, report) => {
218
288
  const handOver = () => {
219
289
  if (phase === "live") return;
220
290
  phase = "live";
291
+ restore(held);
221
292
  stop();
222
293
  for (const { event, element } of unanswered.splice(0)) {
223
294
  const Ctor = event.constructor;
@@ -226,6 +297,7 @@ const deferBoot = (root, decoded, start, runtime, pending, report) => {
226
297
  };
227
298
  const commit = () => {
228
299
  phase = "starting";
300
+ held = hold(kept);
229
301
  runtime.boot({ "foldkit-ssr.handover": {
230
302
  dependenciesSchema: Schema.Null,
231
303
  modelToDependencies: () => null,
@@ -266,6 +338,6 @@ const SSR = {
266
338
  static: staticRegion,
267
339
  serving
268
340
  };
269
- export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
341
+ export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, KEEP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
270
342
 
271
343
  //# sourceMappingURL=client.js.map
@@ -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 noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { listen, type DecodedBinding } from './listen.js'\nimport { builder, view } from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\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 */\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 * 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 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 // 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 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 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 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 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 contain()\n return\n }\n const model = resumed.success\n const commands = (plan.boot?.(model) 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 const boot = (entries: Readonly<Record<string, unknown>> = {}) =>\n adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, { model, commands }), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n if (plan.start === 'now' && pending.length === 0) {\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 contain()\n return\n }\n deferBoot(root, decoded.success, plan.start, { boot, answered }, pending, report)\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport const UNTIL_LIMIT_MS = 3000\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 */\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): 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 const stop = listen(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 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 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 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, 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 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 'foldk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I,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;CACA,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;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 noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { hold, keptFields, restore, typedMessages, type Held, type KeptField } from './keep.js'\nimport { listen, 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 STYLES_MARKER,\n arrival,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\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 */\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 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) keepStyles(root)\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 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 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 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 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 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 commands = (plan.boot?.(model) 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.\n const startOf = () =>\n Option.match(arrived, {\n onNone: () => ({ model, commands }),\n onSome: message => {\n const step = apply(model, message) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n return { model: step.model, commands: [...commands, ...(step.commands ?? [])] }\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 const start = Option.isSome(arrived) ? 'now' : plan.start\n const eager = start === 'now' && pending.length === 0\n if (eager && 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 contain()\n return\n }\n const kept = keptFields(root, decoded.success.bindings)\n if (Result.isFailure(kept)) {\n report(pageContained('Invalid', kept.failure))\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 if (eager && answered.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)\n }\n const prepare = options.prepare\n if (prepare === undefined) adoptFrom(resumed.success)\n else void Effect.runPromise(prepare(resumed.success)).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 * 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 const UNTIL_LIMIT_MS = 3000\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): 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 = listen(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 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, 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 HandlerUnnamed,\n PageContained,\n PageFailed,\n SsrDiagnostic,\n StaticRegionMissing,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuDA,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;;;;;;;;;;;AAYxB,MAAMA,aACJ,QACA,MACA,YAmDS;CACT,MAAM,UAA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BAAoB,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;CACA,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;AAAQ"}
package/dist/context.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { B as within, F as Region, I as RenderContext, L as UnnamedHandler, P as Binding, R as current, z as withContext } from "./shared-v1u-OEQI.js";
1
+ import { B as current, H as within, I as Binding, L as Region, R as RenderContext, V as withContext, z as UnnamedHandler } from "./shared-DbupL3vO.js";
2
2
  export { Binding, Region, RenderContext, UnnamedHandler, current, withContext, within };
package/dist/context.js CHANGED
@@ -2,13 +2,25 @@
2
2
  let context;
3
3
  /** The context of the view call in progress, if any. */
4
4
  const current = () => context;
5
+ /**
6
+ * Set on `globalThis` while the server renders a page, under a registered
7
+ * symbol so a view's packages find it from another bundle: a memoized
8
+ * drawing (`foldkit-mixins`' SlotView) is drawn afresh then, since one kept
9
+ * from another pass or request carries that render's markers and none of
10
+ * this one's bindings.
11
+ */
12
+ const SERVER_RENDER = Symbol.for("foldkit-plus.serverRender");
5
13
  const within = (next, run) => {
6
14
  const previous = context;
15
+ const global = globalThis;
16
+ const rendering = global[SERVER_RENDER];
7
17
  context = next;
18
+ global[SERVER_RENDER] = next.mode === "collect" || next.mode === "replay";
8
19
  try {
9
20
  return run();
10
21
  } finally {
11
22
  context = previous;
23
+ global[SERVER_RENDER] = rendering;
12
24
  }
13
25
  };
14
26
  /** The config whose view runs inside `next`. */
@@ -1 +1 @@
1
- {"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["/**\n * The render context: what the page's server-owned parts do, set around one\n * synchronous call of the view. `SSR.static` reads it to decide whether a\n * region renders, replays, or adopts the server's markup, and the resumable\n * builder reads it to decide whether to mark the bindings it builds. With no\n * context, as in a client-only render, both behave as ordinary view code.\n *\n * - `collect`: the server's render. Each region runs once and is kept, and\n * each binding is recorded in render order.\n * - `replay`: the server's second render, from the browser's Model. Each\n * region is the one already rendered, so it never reads the browser's Model;\n * bindings are recorded again, to be compared with the first render's.\n * - `resume`: the browser. Each region is the markup the server left in the\n * page, and its render never runs; no binding is marked.\n */\nimport type { Html } from 'foldkit/html'\nimport type { StaticRegionMissing } from './diagnostics.js'\n\nexport type Region = ReadonlyArray<Html | string>\n\n/** An element whose handler for `event` is a function, which the page cannot describe. */\nexport interface UnnamedHandler {\n readonly element: string\n readonly event: string\n}\n\n/**\n * An element's binding as the server's render records it, before encoding:\n * the Foldkit attribute and its DOM event, the element for diagnostics, and\n * the Message it causes. For a Message with a hole, `message` is the Message\n * with the hole filled by a placeholder, and `hole` names the fields the event\n * fills.\n */\nexport interface Binding {\n /** Foldkit's attribute, whose tag says what the handler does beside dispatching. */\n readonly attribute: string\n readonly event: string\n readonly element: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n /** How many placement wrappers enclose the hole's fields: `message` is entered that many times. */\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\nexport type RenderContext =\n | {\n readonly mode: 'collect'\n readonly regions: Map<string, Region>\n readonly duplicates: Set<string>\n readonly bindings: Array<Binding>\n /** Encodes a form's Message for its no-script fallback; absent when the plan has none. */\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n /** Lifts a Message of the view in progress to the application's, through each enclosing placement. */\n wrap: (message: unknown) => unknown\n /** How many placements enclose the view in progress. */\n depth: number\n /** The static region whose render is in progress, if any. */\n region: string | undefined\n /** Handlers met inside a static region, which the server alone renders. */\n readonly inStatic: Array<{\n readonly region: string\n readonly element: string\n readonly event: string\n }>\n /** Each element and event marked `*`: a handler the page cannot name. */\n readonly unnamed: Array<UnnamedHandler>\n }\n | {\n readonly mode: 'replay'\n readonly regions: ReadonlyMap<string, Region>\n readonly bindings: Array<Binding>\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n wrap: (message: unknown) => unknown\n depth: number\n }\n | {\n readonly mode: 'resume'\n readonly snapshots: ReadonlyMap<string, string>\n /** The regions already reported missing, so each is reported once. */\n readonly reported: Set<string>\n readonly report: (diagnostic: StaticRegionMissing) => void\n }\n\nlet context: RenderContext | undefined\n\n/** The context of the view call in progress, if any. */\nexport const current = (): RenderContext | undefined => context\n\nexport const within = <A>(next: RenderContext, run: () => A): A => {\n const previous = context\n context = next\n try {\n return run()\n } finally {\n context = previous\n }\n}\n\n/** The config whose view runs inside `next`. */\nexport const withContext = <Config extends { readonly view: (model: any, h: any) => unknown }>(\n config: Config,\n next: RenderContext,\n): Config => ({\n ...config,\n view: (model: unknown, h: unknown) => within(next, () => config.view(model, h)),\n})\n"],"mappings":";AAoFA,IAAI;;AAGJ,MAAa,gBAA2C;AAExD,MAAa,UAAa,MAAqB,QAAoB;CACjE,MAAM,WAAW;CACjB,UAAU;CACV,IAAI;EACF,OAAO,IAAI;CACb,UAAU;EACR,UAAU;CACZ;AACF;;AAGA,MAAa,eACX,QACA,UACY;CACZ,GAAG;CACH,OAAO,OAAgB,MAAe,OAAO,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC;AAChF"}
1
+ {"version":3,"file":"context.js","names":[],"sources":["../src/context.ts"],"sourcesContent":["/**\n * The render context: what the page's server-owned parts do, set around one\n * synchronous call of the view. `SSR.static` reads it to decide whether a\n * region renders, replays, or adopts the server's markup, and the resumable\n * builder reads it to decide whether to mark the bindings it builds. With no\n * context, as in a client-only render, both behave as ordinary view code.\n *\n * - `collect`: the server's render. Each region runs once and is kept, and\n * each binding is recorded in render order.\n * - `replay`: the server's second render, from the browser's Model. Each\n * region is the one already rendered, so it never reads the browser's Model;\n * bindings are recorded again, to be compared with the first render's.\n * - `resume`: the browser. Each region is the markup the server left in the\n * page, and its render never runs; no binding is marked.\n */\nimport type { Html } from 'foldkit/html'\nimport type { StaticRegionMissing } from './diagnostics.js'\n\nexport type Region = ReadonlyArray<Html | string>\n\n/** An element whose handler for `event` is a function, which the page cannot describe. */\nexport interface UnnamedHandler {\n readonly element: string\n readonly event: string\n}\n\n/**\n * An element's binding as the server's render records it, before encoding:\n * the Foldkit attribute and its DOM event, the element for diagnostics, and\n * the Message it causes. For a Message with a hole, `message` is the Message\n * with the hole filled by a placeholder, and `hole` names the fields the event\n * fills.\n */\nexport interface Binding {\n /** Foldkit's attribute, whose tag says what the handler does beside dispatching. */\n readonly attribute: string\n readonly event: string\n readonly element: string\n readonly message: unknown\n readonly hole?: ReadonlyArray<string> | undefined\n /** How many placement wrappers enclose the hole's fields: `message` is entered that many times. */\n readonly depth?: number | undefined\n readonly options?: unknown\n}\n\nexport type RenderContext =\n | {\n readonly mode: 'collect'\n readonly regions: Map<string, Region>\n readonly duplicates: Set<string>\n readonly bindings: Array<Binding>\n /** Encodes a form's Message for its no-script fallback; absent when the plan has none. */\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n /** Lifts a Message of the view in progress to the application's, through each enclosing placement. */\n wrap: (message: unknown) => unknown\n /** How many placements enclose the view in progress. */\n depth: number\n /** The static region whose render is in progress, if any. */\n region: string | undefined\n /** Handlers met inside a static region, which the server alone renders. */\n readonly inStatic: Array<{\n readonly region: string\n readonly element: string\n readonly event: string\n }>\n /** Each element and event marked `*`: a handler the page cannot name. */\n readonly unnamed: Array<UnnamedHandler>\n /** Why each `KeepTyped` field met cannot be replayed, one line each. */\n readonly unkeepable: Array<string>\n }\n | {\n readonly mode: 'replay'\n readonly regions: ReadonlyMap<string, Region>\n readonly bindings: Array<Binding>\n readonly fallback: ((message: unknown) => string | undefined) | undefined\n wrap: (message: unknown) => unknown\n depth: number\n }\n | {\n readonly mode: 'resume'\n readonly snapshots: ReadonlyMap<string, string>\n /** The regions already reported missing, so each is reported once. */\n readonly reported: Set<string>\n readonly report: (diagnostic: StaticRegionMissing) => void\n }\n\nlet context: RenderContext | undefined\n\n/** The context of the view call in progress, if any. */\nexport const current = (): RenderContext | undefined => context\n\n/**\n * Set on `globalThis` while the server renders a page, under a registered\n * symbol so a view's packages find it from another bundle: a memoized\n * drawing (`foldkit-mixins`' SlotView) is drawn afresh then, since one kept\n * from another pass or request carries that render's markers and none of\n * this one's bindings.\n */\nconst SERVER_RENDER = Symbol.for('foldkit-plus.serverRender')\n\nexport const within = <A>(next: RenderContext, run: () => A): A => {\n const previous = context\n const global = globalThis as Record<symbol, unknown>\n const rendering = global[SERVER_RENDER]\n context = next\n global[SERVER_RENDER] = next.mode === 'collect' || next.mode === 'replay'\n try {\n return run()\n } finally {\n context = previous\n global[SERVER_RENDER] = rendering\n }\n}\n\n/** The config whose view runs inside `next`. */\nexport const withContext = <Config extends { readonly view: (model: any, h: any) => unknown }>(\n config: Config,\n next: RenderContext,\n): Config => ({\n ...config,\n view: (model: unknown, h: unknown) => within(next, () => config.view(model, h)),\n})\n"],"mappings":";AAsFA,IAAI;;AAGJ,MAAa,gBAA2C;;;;;;;;AASxD,MAAM,gBAAgB,OAAO,IAAI,2BAA2B;AAE5D,MAAa,UAAa,MAAqB,QAAoB;CACjE,MAAM,WAAW;CACjB,MAAM,SAAS;CACf,MAAM,YAAY,OAAO;CACzB,UAAU;CACV,OAAO,iBAAiB,KAAK,SAAS,aAAa,KAAK,SAAS;CACjE,IAAI;EACF,OAAO,IAAI;CACb,UAAU;EACR,UAAU;EACV,OAAO,iBAAiB;CAC1B;AACF;;AAGA,MAAa,eACX,QACA,UACY;CACZ,GAAG;CACH,OAAO,OAAgB,MAAe,OAAO,YAAY,OAAO,KAAK,OAAO,CAAC,CAAC;AAChF"}
@@ -1,2 +1,2 @@
1
- import { $ as reportingTo, G as SsrDiagnostic, H as HandlerUnnamed, J as handlerUnnamed, K as StaticRegionMissing, Q as pageFailed, U as PageContained, V as BundleUnloaded, W as PageFailed, X as otherBuild, Y as noBuildId, Z as pageContained, et as staticRegionMissing, q as bundleUnloaded } from "./shared-v1u-OEQI.js";
1
+ import { $ as pageContained, G as PageContained, J as StaticRegionMissing, K as PageFailed, Q as otherBuild, U as BundleUnloaded, W as HandlerUnnamed, X as handlerUnnamed, Y as bundleUnloaded, Z as noBuildId, et as pageFailed, nt as staticRegionMissing, q as SsrDiagnostic, tt as reportingTo } from "./shared-DbupL3vO.js";
2
2
  export { BundleUnloaded, HandlerUnnamed, PageContained, PageFailed, SsrDiagnostic, StaticRegionMissing, bundleUnloaded, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
package/dist/index.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { n as DecodedBinding, r as EncodedBinding } from "./listen-zNd0IIAT.js";
2
- import { a as FALLBACK_FIELD, l as ResumableBuilder, n as BINDING_ATTRIBUTE, u as SLOT_ATTRIBUTE } from "./resumable-BWItJsxF.js";
3
- import { A as serving, D as resume, G as SsrDiagnostic, H as HandlerUnnamed, K as StaticRegionMissing, L as UnnamedHandler, M as staticRegion, U as PageContained, V as BundleUnloaded, W as PageFailed, c as ResumableConfig, d as ResumeRefused, f as RouteMatch, i as Meta, k as serializeJsonScript, l as ResumePart, m as Start, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, w as plan, x as metaMarkup } from "./shared-v1u-OEQI.js";
4
- import { i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-F16QT0sc.js";
1
+ import { n as DecodedBinding, r as EncodedBinding } from "./listen-DaUPRKVR.js";
2
+ import { a as FALLBACK_FIELD, d as SLOT_ATTRIBUTE, n as BINDING_ATTRIBUTE, s as KEEP_ATTRIBUTE, u as ResumableBuilder } from "./resumable-BPN_qQHU.js";
3
+ import { C as metaMarkup, E as plan, G as PageContained, J as StaticRegionMissing, K as PageFailed, M as serving, P as staticRegion, U as BundleUnloaded, W as HandlerUnnamed, c as ResumableConfig, d as ResumeRefused, f as RouteMatch, h as Start, i as Meta, j as serializeJsonScript, k as resume, l as ResumePart, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, q as SsrDiagnostic, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, z as UnnamedHandler } from "./shared-DbupL3vO.js";
4
+ import { i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-XnpTQZHw.js";
5
5
  import { n as requestContext, t as RequestContext } from "./requestContext-D9nsbGSJ.js";
6
- import { Cause, Effect, Layer, Schema } from "effect";
6
+ import { Cause, Effect, Layer, Option, Schema } from "effect";
7
7
  import { Diagnostic as Diagnostic$1, MetadataSummary } from "foldkit-surface";
8
8
  import { EntryModule, RenderError, RenderedApplication } from "foldkit/experimental/server";
9
9
  interface EnvelopeOptions {
@@ -75,7 +75,7 @@ export interface PlanInspection {
75
75
  */
76
76
  declare const inspect: <Model, Fields extends Schema.Struct.Fields>(plan: ResumePlan<Model, Fields>, model: Model) => PlanInspection;
77
77
  declare const ResumeUnsafe_base: Schema.Class<ResumeUnsafe, Schema.TaggedStruct<"ResumeUnsafe", {
78
- readonly reason: Schema.Literals<readonly ["UndeclaredStartup", "Uncovered", "ViewDependsOnUnsentState", "DuplicateStaticRegion", "UngeneratablePath", "UnrestorablePart", "UnencodableBinding", "EagerStartRequired", "UndeclaredSurfaces", "BindingInStaticRegion", "VoidRootWithStyles"]>;
78
+ readonly reason: Schema.Literals<readonly ["UndeclaredStartup", "Uncovered", "ViewDependsOnUnsentState", "DuplicateStaticRegion", "UngeneratablePath", "UnrestorablePart", "UnencodableBinding", "EagerStartRequired", "UndeclaredSurfaces", "BindingInStaticRegion", "VoidRootWithStyles", "UnkeepableField"]>;
79
79
  readonly message: Schema.String;
80
80
  }>, Cause.YieldableError>;
81
81
  /** Why a server refused to render a page against its plan. */
@@ -117,9 +117,9 @@ declare const render: <Model, Fields extends Schema.Struct.Fields, Message = any
117
117
  readonly flags?: unknown;
118
118
  /**
119
119
  * Markup for the first paint, given what was rendered, carried as the
120
- * root's last child: keep it to `<style>`, which the browser drops on
121
- * hydration. Anything a head owns (`meta`, links) stays with `SSR.page`
122
- * and `SSR.generate`.
120
+ * root's last children: `<style>` (or a stylesheet `<link>`), which
121
+ * `SSR.hydrate` moves into the head before adopting the page. Anything
122
+ * else a head owns (`meta`) stays with `SSR.page` and `SSR.generate`.
123
123
  */
124
124
  readonly styles?: Head | undefined;
125
125
  }) => Effect.Effect<RenderedPage, RenderError | ResumeUnsafe>;
@@ -201,15 +201,18 @@ declare const generate: <Model, Fields extends Schema.Struct.Fields, const Paths
201
201
  * served by Node and Workers alike.
202
202
  *
203
203
  * `GET` and `HEAD` render the page against the plan, with the request's URL
204
- * and, when the application has Flags, `flags(request)`. `POST` goes to
204
+ * and, when the application has Flags, `flags(request)`; `prepare(model,
205
+ * request)` turns the Model `init` gave into the one rendered, a read made
206
+ * before the render (`Data.satisfy`). `POST` goes to
205
207
  * `SSR.handle` when the plan has a server fallback, and is answered `400` when
206
208
  * the post is unusable. `OPTIONS` is answered `204`, and any other method
207
209
  * `405`, each with the methods the entry answers in `allow` (`handleRequest`
208
210
  * passes every method through). A render that fails, or a plan the render
209
211
  * refuses, is answered `500` with the reason reported (`diagnostics`), never with a page the
210
- * browser cannot resume. `headers(request)` rides on the `Rendered` result, so
211
- * Foldkit's `toResponse` sets it over its own on the page: a cache policy, or
212
- * a CORS answer to a preflight.
212
+ * browser cannot resume. `headers(request, model)` is set over Foldkit's own
213
+ * on every answer: a cache policy, a CORS answer to a preflight, or a cookie
214
+ * written from the Model a post reached. `status(model, request)` gives a page
215
+ * its status from that Model, `404` for a route not found.
213
216
  *
214
217
  * The page is answered as `Rendered`: the rendered application carries the
215
218
  * envelope in its root, so the host injects it into its own template with
@@ -225,7 +228,26 @@ declare const generate: <Model, Fields extends Schema.Struct.Fields, const Paths
225
228
  declare const entry: <Model, Fields extends Schema.Struct.Fields, Message = any>(config: ResumableConfig<Model, Message>, plan: ResumePlan<Model, Fields>, options: {
226
229
  readonly buildId: string;
227
230
  readonly flags?: ((request: Request) => unknown | PromiseLike<unknown>) | undefined;
228
- readonly headers?: ((request: Request) => HeadersInit) | undefined;
231
+ /**
232
+ * The Model a request starts from, from the one `init` gave: what the page
233
+ * shows read first (`Data.satisfy`), or what the request carries (a
234
+ * cookie). Run for `GET`, `HEAD` and a posted form, before the post's
235
+ * Message is checked or `update` runs, so the entry is made once. A
236
+ * failure is answered `500` and reported; to draw the page unread
237
+ * instead, recover inside the Effect.
238
+ */
239
+ readonly prepare?: Prepare<Model> | undefined;
240
+ /**
241
+ * Headers set over the entry's own on every answer. `model` is the Model
242
+ * the server reached for a rendered page, a posted form's after `update`;
243
+ * it is `none` for an answer that rendered nothing (`OPTIONS`, `405`, a
244
+ * refused post, a `500`). So a cookie kept from the Model is written here.
245
+ * A name or value no `Headers` takes (a CR or LF in a value), a header that
246
+ * frames the response (`content-length`, `transfer-encoding`, `connection`
247
+ * and the like) or `location`, which only the entry writes, is answered
248
+ * `500` and reported, as `headers` that throw are.
249
+ */
250
+ readonly headers?: ((request: Request, model: Option.Option<Model>) => HeadersInit) | undefined;
229
251
  /**
230
252
  * A posted form's own services, from its request (who is asking, a
231
253
  * client bound to them), for the Commands the fallback runs; where one is
@@ -243,15 +265,47 @@ declare const entry: <Model, Fields extends Schema.Struct.Fields, Message = any>
243
265
  * form cannot carry a CSRF header; this is its check. A post with no
244
266
  * `Origin` or `Origin: null` (a page served with `Referrer-Policy:
245
267
  * no-referrer`) is taken when `Sec-Fetch-Site` says `same-origin`. Each must be an origin exactly as
246
- * a browser sends it (`https://example.com`).
268
+ * a browser sends it (`https://example.com`). `'same-origin'` takes a
269
+ * post from the origin the request was addressed to and no other, for a
270
+ * site served at addresses not known when the entry is made (a dev
271
+ * server's port). It compares with the request's own URL, so behind a
272
+ * proxy that terminates TLS (the server sees `http://`, the browser
273
+ * sends `Origin: https://`) or rewrites the host, every post is refused
274
+ * 403: there, name the public origin (`['https://example.com']`).
247
275
  */
248
- readonly origins?: ReadonlyArray<string> | undefined;
276
+ readonly origins?: ReadonlyArray<string> | 'same-origin' | undefined;
249
277
  /**
250
- * Markup for the first paint, carried as the rendered root's last child.
251
- * The host owns the template in dynamic serving, so this is where
252
- * per-page styles go; anything a head owns stays with `SSR.generate`.
278
+ * Markup for the first paint, carried as the rendered root's last
279
+ * children, which `SSR.hydrate` moves into the head. The host owns the
280
+ * template in dynamic serving, so this is where per-page styles go;
281
+ * anything else a head owns stays with `SSR.generate`.
253
282
  */
254
283
  readonly styles?: Head | undefined;
284
+ /**
285
+ * The status a rendered page is answered with, from the Model the server
286
+ * reached and the request: `404` for a route the Model says is not found.
287
+ * Omitted, every page is `200`. One outside `200`–`599`, or a `status`
288
+ * that throws, is answered `500` and reported, as a failed render is.
289
+ */
290
+ readonly status?: ((model: Model, request: Request) => number) | undefined;
291
+ /**
292
+ * How a posted form is answered. `'page'`, the default, is the page
293
+ * `update` reached, at the address the form posted to, so a reload posts
294
+ * again. `'redirect'` is a `303` to that address, which the browser then
295
+ * asks for with a `GET` (Post/Redirect/Get): what the post changed must
296
+ * outlive it where the next request reads it, a cookie `headers` writes
297
+ * from the Model the post reached. A refused post is still a `400`.
298
+ */
299
+ readonly answerPost?: 'page' | 'redirect' | undefined;
300
+ /**
301
+ * The paths a build prerenders through this entry (Foldkit's plugin,
302
+ * `ssr.build.prerender`), whose files a static host serves for every
303
+ * query. A request for one of them with no query records its path alone,
304
+ * as `SSR.generate` does, so the file resumes at `/?q=…` and the
305
+ * application starts from that URL. Export the same list as the entry
306
+ * module's `prerenderPaths`, which the plugin reads.
307
+ */
308
+ readonly prerendered?: ReadonlyArray<string> | undefined;
255
309
  /**
256
310
  * Where this request's diagnostics go, with the request: a request
257
311
  * answered 500 (`PageFailed`), a handler the page cannot name, and what
@@ -266,26 +320,31 @@ declare const FallbackRefused_base: Schema.Class<FallbackRefused, Schema.TaggedS
266
320
  }>, Cause.YieldableError>;
267
321
  /** Why a posted form was not handled: the request, not the page or the plan, is at fault. */
268
322
  export declare class FallbackRefused extends FallbackRefused_base {}
323
+ /** Turns the Model `init` gave into the one a request starts from. */
324
+ export type Prepare<Model> = (model: Model, request: Request) => Effect.Effect<Model, unknown>;
269
325
  /**
270
326
  * Answers a form posted by a page rendered with `fallback: 'server'`: the
271
327
  * posted Message is decoded through the plan's Message Schema, with posted
272
328
  * fields of the same names as its own overriding them, and must be one the
273
329
  * Surfaces active for the request's Model may send. The server then rebuilds
274
- * the Model the browser had, `init` and then the plan's `boot` with every
330
+ * the Model the browser had, `init`, `prepare` and then the plan's `boot` with every
275
331
  * Command it leads to, runs `update` with the Message and every Command that
276
332
  * follows, and renders the result as a fresh page.
277
333
  */
278
- declare const handle: <Model, Fields extends Schema.Struct.Fields, Message = any>(request: Request, config: ResumableConfig<Model, Message>, plan: ResumePlan<Model, Fields>, options: {
334
+ declare const handle: <Model, Fields extends Schema.Struct.Fields, Message = any>(request: Request, config: ResumableConfig<Model, Message>, plan: ResumePlan<Model, Fields>, options: HandleOptions<Model>) => Effect.Effect<RenderedPage, RenderError | ResumeUnsafe | FallbackRefused>;
335
+ interface HandleOptions<Model> {
279
336
  readonly buildId: string;
280
337
  readonly flags?: unknown;
281
338
  readonly styles?: Head | undefined;
339
+ /** The Model the post starts from, from `init`'s, as `SSR.entry`'s `prepare`. */
340
+ readonly prepare?: Prepare<Model> | undefined;
282
341
  /**
283
342
  * This post's own services, beside the config's `resources`: who is
284
343
  * asking, a client bound to them. Built once for the post; where both
285
344
  * provide a service, the post's is the one its Commands get.
286
345
  */
287
346
  readonly resources?: Layer.Layer<never, never, never> | undefined;
288
- }) => Effect.Effect<RenderedPage, RenderError | ResumeUnsafe | FallbackRefused>;
347
+ }
289
348
  export declare const SSR: {
290
349
  plan: typeof plan;
291
350
  envelope: typeof envelope;
@@ -298,6 +357,7 @@ export declare const SSR: {
298
357
  readonly otherwise?: 'render' | undefined;
299
358
  readonly until?: ((model: Model) => boolean) | undefined;
300
359
  readonly fresh?: ((version: unknown) => boolean) | undefined;
360
+ readonly prepare?: ((model: Model) => Effect.Effect<Model>) | undefined;
301
361
  readonly diagnostics?: import("foldkit-surface").ReportDiagnostic | undefined;
302
362
  }) => void;
303
363
  inspect: typeof inspect;
@@ -311,5 +371,5 @@ export declare const SSR: {
311
371
  robots: typeof robots;
312
372
  requestContext: typeof requestContext;
313
373
  };
314
- export { BINDING_ATTRIBUTE, type BundleUnloaded, type DecodedBinding, type Diagnostic, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type HandlerUnnamed, type Loadable, META_ATTRIBUTE, type Meta, type PageContained, type PageFailed, type PlanSurface, RESUME_ATTRIBUTE, type ReportDiagnostic, type RequestContext, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, STATIC_ATTRIBUTE, type SsrDiagnostic, type Start, type StaticRegionMissing, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
374
+ export { BINDING_ATTRIBUTE, type BundleUnloaded, type DecodedBinding, type Diagnostic, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type HandlerUnnamed, KEEP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, type PageContained, type PageFailed, type PlanSurface, RESUME_ATTRIBUTE, type ReportDiagnostic, type RequestContext, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, STATIC_ATTRIBUTE, type SsrDiagnostic, type Start, type StaticRegionMissing, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
315
375
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["Diagnostic"],"sources":["../src/index.ts"],"mappings":";;;;;;;;UA8FU;WACC;WACA,QAAQ;WACR,WAAW,cAAc;;WAEzB,SAAS;;;;;;;;;cAUd,WAAY,OAAO,eAAe,OAAO,OAAO,QAAM,QAClD,WAAW,OAAO,SAAO,OAC1B,OAAK,UACH;;YAgHC;;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,OAAO;WACP,UAAU,cAAc;;;;;;;cA4C7B,UAAW,OAAO,eAAe,OAAO,OAAO,QAAM,MACnD,WAAW,OAAO,SAAO,OACxB,UACN;;;;;;qBAyKU,qBAAqB;;iBA+HjB;;;;;;WAMN,UAAU;;WAEV;;WAEA;;;;;WAKA,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;;;;;;;YAmKjC,QAAQ,UAAU;;;;;;;cAwDxB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