foldkit-ssr 0.11.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.
Files changed (63) hide show
  1. package/README.md +656 -83
  2. package/dist/{client-qmdYY-Eb.d.ts → client-cumvT9XN.d.ts} +10 -7
  3. package/dist/client-cumvT9XN.d.ts.map +1 -0
  4. package/dist/client.d.ts +6 -5
  5. package/dist/client.js +64 -16
  6. package/dist/client.js.map +1 -1
  7. package/dist/context.d.ts +1 -1
  8. package/dist/context.js.map +1 -1
  9. package/dist/diagnostics.d.ts +2 -2
  10. package/dist/diagnostics.js +7 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/handoff.d.ts +23 -0
  13. package/dist/handoff.d.ts.map +1 -0
  14. package/dist/handoff.js +15 -0
  15. package/dist/handoff.js.map +1 -0
  16. package/dist/index.d.ts +66 -26
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +282 -56
  19. package/dist/index.js.map +1 -1
  20. package/dist/keep.d.ts +3 -1
  21. package/dist/keep.d.ts.map +1 -1
  22. package/dist/keep.js +21 -6
  23. package/dist/keep.js.map +1 -1
  24. package/dist/{listen-DaUPRKVR.d.ts → listen-7HzKBhqU.d.ts} +11 -2
  25. package/dist/{listen-DaUPRKVR.d.ts.map → listen-7HzKBhqU.d.ts.map} +1 -1
  26. package/dist/listen.d.ts +2 -2
  27. package/dist/listen.js +17 -7
  28. package/dist/listen.js.map +1 -1
  29. package/dist/loader.d.ts +13 -0
  30. package/dist/loader.d.ts.map +1 -0
  31. package/dist/loader.js +156 -0
  32. package/dist/loader.js.map +1 -0
  33. package/dist/marks-CX15BwOw.d.ts +39 -0
  34. package/dist/marks-CX15BwOw.d.ts.map +1 -0
  35. package/dist/marks.d.ts +2 -0
  36. package/dist/marks.js +41 -0
  37. package/dist/marks.js.map +1 -0
  38. package/dist/{resumable-BPN_qQHU.d.ts → resumable-BV9_OKxr.d.ts} +7 -10
  39. package/dist/resumable-BV9_OKxr.d.ts.map +1 -0
  40. package/dist/resumable.d.ts +2 -1
  41. package/dist/resumable.js +16 -19
  42. package/dist/resumable.js.map +1 -1
  43. package/dist/runtimeChunk.d.ts +13 -0
  44. package/dist/runtimeChunk.d.ts.map +1 -0
  45. package/dist/runtimeChunk.js +36 -0
  46. package/dist/runtimeChunk.js.map +1 -0
  47. package/dist/runtimeUrl.d.ts +10 -0
  48. package/dist/runtimeUrl.d.ts.map +1 -0
  49. package/dist/runtimeUrl.js +13 -0
  50. package/dist/runtimeUrl.js.map +1 -0
  51. package/dist/{shared-CJN-m58Z.d.ts → shared-BuCOwm57.d.ts} +62 -20
  52. package/dist/shared-BuCOwm57.d.ts.map +1 -0
  53. package/dist/shared.d.ts +3 -2
  54. package/dist/shared.js +36 -13
  55. package/dist/shared.js.map +1 -1
  56. package/dist/vite.d.ts +19 -5
  57. package/dist/vite.d.ts.map +1 -1
  58. package/dist/vite.js +9 -2
  59. package/dist/vite.js.map +1 -1
  60. package/package.json +13 -8
  61. package/dist/client-qmdYY-Eb.d.ts.map +0 -1
  62. package/dist/resumable-BPN_qQHU.d.ts.map +0 -1
  63. package/dist/shared-CJN-m58Z.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { withContext } from "./context.js";
2
2
  import { cachedPageDiffers, handlerUnnamed, pageFailed, reportingTo } from "./diagnostics.js";
3
- import { BINDING_ATTRIBUTE, FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, KEEP_ATTRIBUTE, SLOT_ATTRIBUTE } from "./resumable.js";
4
- import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, STYLES_MARKER, allowedTags, attributeOf, codecOf, metaMarkup, modelFrom, pathKey, plan, projectionsOf, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf } from "./shared.js";
5
- import { Diagnostics, Resume, SSR as SSR$1, UNTIL_LIMIT_MS } from "./client.js";
3
+ import { BINDING_ATTRIBUTE, FOLDKIT_APP_ATTRIBUTE, KEEP_ATTRIBUTE, RESUME_ATTRIBUTE, UNTIL_LIMIT_MS } from "./marks.js";
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, lazyFor, metaMarkup, modelFrom, pathKey, plan, projectionsOf, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf, unbound } from "./shared.js";
6
+ import { Diagnostics, Resume, SSR as SSR$1 } from "./client.js";
6
7
  import { requestContext } from "./requestContext.js";
7
8
  import { decodeKept, fits, headerOf, keptApplications, keptDocuments, pageKey, samePage, tracked } from "./pageCache.js";
8
9
  import { Cause, Context, Effect, Exit, Layer, Option, Result, Schema } from "effect";
@@ -24,6 +25,8 @@ import { FOLDKIT_FLAGS_ATTRIBUTE, Rendered, Responded, injectIntoTemplate, rende
24
25
  * handover. This module is the server's side and the browser's
25
26
  * (`foldkit-ssr/client`) together.
26
27
  */
28
+ /** The set `foldkit-mixins` collects drawn classes in, under the same registered symbol. */
29
+ const DRAWN_CLASSES = Symbol.for("foldkit-plus.drawnClasses");
27
30
  /** The projections of the plan's entries that are active for `model`. */
28
31
  const activeProjections = (plan, model) => plan.surfaces.flatMap((source) => projectionsOf(source, model));
29
32
  /**
@@ -57,7 +60,8 @@ const envelopeOf = (resume, payload, options) => serializeJsonScript({
57
60
  ...options.route === void 0 ? {} : { route: options.route },
58
61
  ...options.match === "path" ? { match: "path" } : {},
59
62
  ...options.bindings === void 0 || options.bindings.length === 0 ? {} : { bindings: options.bindings },
60
- ...options.events === void 0 || options.events.length === 0 ? {} : { events: options.events }
63
+ ...options.events === void 0 || options.events.length === 0 ? {} : { events: options.events },
64
+ ...resume.start === "now" ? {} : { start: resume.start }
61
65
  });
62
66
  /**
63
67
  * The rendered application with the envelope on its stamped root, beside
@@ -97,36 +101,107 @@ const isInRootTag = (html, at) => {
97
101
  return true;
98
102
  };
99
103
  /**
100
- * The rendered markup with `extra` as the root's last children, after the
101
- * styles marker, so the first paint is styled before any script runs where no
102
- * template head can take it; `SSR.hydrate` moves them into the head. A void
103
- * root holds no children: styles for one are refused, naming the tag, rather
104
- * than served where no browser could keep them.
104
+ * The rendered markup with `insert` as the root's last children. A void root
105
+ * holds no children: what it would carry is refused, naming the tag, rather
106
+ * than served where no browser could keep it.
105
107
  */
106
- const withInRoot = (html, extra) => {
108
+ const beforeRootEnd = (html, insert, refused) => {
107
109
  const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1];
108
110
  const at = tag === void 0 ? -1 : html.search(new RegExp(`</${tag}>\\s*$`));
109
- if (tag === void 0 || at === -1) return Result.fail(new ResumeUnsafe({
110
- reason: "VoidRootWithStyles",
111
- message: `styles need a root element that can hold them, but the view returned <${tag ?? "?"}>: put the styles in the template's head with SSR.generate, or return an element root`
112
- }));
113
- return Result.succeed(`${html.slice(0, at)}<!--${STYLES_MARKER}-->${extra}${html.slice(at)}`);
111
+ if (tag === void 0 || at === -1) return Result.fail(refused(tag ?? "?"));
112
+ return Result.succeed(`${html.slice(0, at)}${insert}${html.slice(at)}`);
113
+ };
114
+ /**
115
+ * The rendered markup with `extra` after the styles marker, so the first
116
+ * paint is styled before any script runs where no template head can take
117
+ * it; `SSR.hydrate` moves them into the head.
118
+ */
119
+ const withInRoot = (html, extra) => beforeRootEnd(html, `<!--${STYLES_MARKER}-->${extra}`, (tag) => new ResumeUnsafe({
120
+ reason: "VoidRootWithStyles",
121
+ message: `styles need a root element that can hold them, but the view returned <${tag}>: put the styles in the template's head with SSR.generate, or return an element root`
122
+ }));
123
+ const HEAD_OPEN = `<!--${HEAD_MARKER}-->`;
124
+ const HEAD_CLOSE = `<!--${HEAD_END_MARKER}-->`;
125
+ /**
126
+ * Roots a parser does not keep `<meta>` inside: a table's (it is moved out),
127
+ * foreign content (it breaks out), and raw text, where the markers are text.
128
+ */
129
+ const HEADLESS_ROOTS = /* @__PURE__ */ new Set([
130
+ "table",
131
+ "thead",
132
+ "tbody",
133
+ "tfoot",
134
+ "tr",
135
+ "colgroup",
136
+ "svg",
137
+ "math",
138
+ "textarea",
139
+ "title",
140
+ "style",
141
+ "script",
142
+ "xmp",
143
+ "iframe",
144
+ "noembed",
145
+ "noframes",
146
+ "noscript",
147
+ "plaintext"
148
+ ]);
149
+ const rootTagOf = (html) => /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1]?.toLowerCase();
150
+ /**
151
+ * The rendered markup with the plan's `meta` between the head markers at the
152
+ * root's end, where `SSR.headed` takes it from. A root that cannot carry it
153
+ * to the host intact is refused, naming the tag.
154
+ */
155
+ const withHeadInRoot = (html, markup) => {
156
+ if (markup === "") return Result.succeed(html);
157
+ const refused = (tag) => new ResumeUnsafe({
158
+ reason: "RootRefusesHead",
159
+ message: `the plan's meta needs a root that keeps it until SSR.headed moves it, but the view returned <${tag}>: serve the page with SSR.generate, or return another element root`
160
+ });
161
+ const tag = rootTagOf(html);
162
+ if (tag !== void 0 && HEADLESS_ROOTS.has(tag)) return Result.fail(refused(tag));
163
+ return beforeRootEnd(html, `${HEAD_OPEN}${markup}${HEAD_CLOSE}`, refused);
164
+ };
165
+ /**
166
+ * The head block `withHeadInRoot` put in a rendered root, and the root
167
+ * without it: the last close marker, followed only by the styles or the
168
+ * root's end, and the last open marker before it, between which is only
169
+ * escaped `meta`. Markers anywhere else (text a view drew in a `<style>`) are
170
+ * not a block, and stay where they are.
171
+ */
172
+ const pageHeadOf = (html) => {
173
+ const tag = rootTagOf(html);
174
+ const end = html.lastIndexOf(HEAD_CLOSE);
175
+ if (tag === void 0 || HEADLESS_ROOTS.has(tag) || end === -1) return Option.none();
176
+ const after = html.slice(end + HEAD_CLOSE.length);
177
+ if (!after.startsWith(`<!--foldkit-plus-styles-->`) && !new RegExp(`^</${tag}>\\s*$`, "i").test(after)) return Option.none();
178
+ const start = html.lastIndexOf(HEAD_OPEN, end);
179
+ if (start === -1) return Option.none();
180
+ return Option.some({
181
+ head: html.slice(start + HEAD_OPEN.length, end),
182
+ html: `${html.slice(0, start)}${after}`
183
+ });
114
184
  };
115
185
  /**
116
186
  * The Model the browser will start from when the server's Model is `model`:
117
187
  * the payload taken through the page as the envelope carries it, as JSON, and
118
- * resumed exactly as `SSR.resume` resumes it. A part that cannot restore its
119
- * own capture fails here, on the server.
188
+ * resumed exactly as `SSR.resume` resumes it, with each restored path taking
189
+ * the server's value (the browser reads the same address and cookie). A part
190
+ * that cannot restore its own capture fails here, on the server.
120
191
  */
121
- const browserModelOf = (plan, payload) => modelFrom(plan, JSON.parse(serializeJsonScript(payload)));
192
+ const browserModelOf = (plan, payload, model) => {
193
+ const resumed = modelFrom(plan, JSON.parse(serializeJsonScript(payload)));
194
+ return Result.isFailure(resumed) ? resumed : Result.succeed(plan.restored.reduce((browser, place) => place.copy(browser, model), resumed.success));
195
+ };
122
196
  const pathOf = (path) => path.length === 0 ? "(the whole Model)" : path.join(".");
123
197
  /**
124
- * A path is covered by a sent or local path equal to it or containing it. An
125
- * empty path is the whole Model, which no pick covers.
198
+ * A path is covered by a sent, restored or local path equal to it or
199
+ * containing it. An empty path is the whole Model, which no pick covers.
126
200
  */
127
201
  const coverOf = (path, plan) => {
128
202
  const contains = (outer) => outer.length > 0 && outer.length <= path.length && outer.every((key, index) => path[index] === key);
129
203
  if (plan.state.dependencies.some(contains)) return "state";
204
+ if (plan.restored.some(({ path: outer }) => contains(outer))) return "restored";
130
205
  if (plan.local.some(contains)) return "local";
131
206
  return "missing";
132
207
  };
@@ -138,7 +213,7 @@ const readsKey = (projection) => projection === void 0 ? "inactive" : JSON.strin
138
213
  * worked out for a Model, not for the plan alone.
139
214
  */
140
215
  const inspect = (plan, model) => {
141
- const resumed = browserModelOf(plan, payloadOf(plan, model));
216
+ const resumed = browserModelOf(plan, payloadOf(plan, model), model);
142
217
  if (Result.isFailure(resumed)) throw new Error(`SSR.inspect: ${resumed.failure}`);
143
218
  return coverage(plan, model, resumed.success);
144
219
  };
@@ -156,6 +231,7 @@ const coverage = (plan, model, browser) => {
156
231
  id: plan.id,
157
232
  state: plan.state.dependencies.map(pathOf),
158
233
  local: plan.local.map(pathOf),
234
+ restored: plan.restored.map(({ path }) => pathOf(path)),
159
235
  parts: plan.parts.map((part) => part.id),
160
236
  surfaces: plan.surfaces.flatMap((source) => {
161
237
  const surface = Option.match(familyOf(source), {
@@ -228,6 +304,7 @@ var ResumeUnsafe = class extends Schema.TaggedError()("ResumeUnsafe", {
228
304
  "UndeclaredStartup",
229
305
  "Uncovered",
230
306
  "ViewDependsOnUnsentState",
307
+ "LazyDependsOnUnsentState",
231
308
  "DuplicateStaticRegion",
232
309
  "UngeneratablePath",
233
310
  "UnrestorablePart",
@@ -236,7 +313,9 @@ var ResumeUnsafe = class extends Schema.TaggedError()("ResumeUnsafe", {
236
313
  "UndeclaredSurfaces",
237
314
  "BindingInStaticRegion",
238
315
  "VoidRootWithStyles",
239
- "UnkeepableField"
316
+ "RootRefusesHead",
317
+ "UnkeepableField",
318
+ "UnkeptField"
240
319
  ]),
241
320
  message: Schema.String
242
321
  }) {};
@@ -284,8 +363,30 @@ const unplacedKeeps = (html) => {
284
363
  }
285
364
  return found;
286
365
  };
287
- /** Loads every lazy bundle's bodies, so the view renders whole. */
288
- 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(", ");
289
390
  /** Foldkit's own Flags script, which a resumed page never carries. */
290
391
  const FLAGS_SCRIPT = new RegExp(`<script[^>]*${FOLDKIT_FLAGS_ATTRIBUTE}[^>]*>[\\s\\S]*?<\/script>`, "g");
291
392
  /**
@@ -355,8 +456,8 @@ const eagerEntries = (config, plan, model) => {
355
456
  * place it shows.
356
457
  */
357
458
  const render = (config, plan, options) => Effect.map(renderMatching(config, plan, options, "full"), (served) => served.page);
358
- const renderMatching = (config, plan, options, match) => Effect.gen(function* () {
359
- yield* loadLazy(config);
459
+ const renderMatching = (config, plan, options, match, known = Option.none()) => Effect.gen(function* () {
460
+ config = yield* loadLazy(config, options, known);
360
461
  let served;
361
462
  const regions = /* @__PURE__ */ new Map();
362
463
  const duplicates = /* @__PURE__ */ new Set();
@@ -365,6 +466,7 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
365
466
  const inStatic = [];
366
467
  const unnamed = [];
367
468
  const unkeepable = [];
469
+ const unkept = [];
368
470
  const fallback = fallbackEncoder(plan);
369
471
  const capturing = withContext({
370
472
  ...config,
@@ -380,7 +482,8 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
380
482
  region: void 0,
381
483
  inStatic,
382
484
  unnamed,
383
- unkeepable
485
+ unkeepable,
486
+ unkept
384
487
  });
385
488
  const full = yield* renderToString(capturing, options);
386
489
  unkeepable.push(...unplacedKeeps(full.html));
@@ -396,6 +499,10 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
396
499
  reason: "UnkeepableField",
397
500
  message: `the page cannot keep what is typed into these fields before it boots:\n- ${unkeepable.join("\n- ")}`
398
501
  });
502
+ if (plan.start !== "now" && unkept.length > 0) return yield* new ResumeUnsafe({
503
+ reason: "UnkeptField",
504
+ message: `the plan starts ${plan.start}, and what is typed into these fields before it boots would be lost at its first render: give each KeepTyped, or start now:\n- ${unkept.join("\n- ")}`
505
+ });
399
506
  const started = served;
400
507
  const commands = started.commands ?? [];
401
508
  if (commands.length > 0 && plan.boot === void 0) return yield* new ResumeUnsafe({
@@ -403,12 +510,18 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
403
510
  message: `init returned ${commands.map((command) => command.name).join(", ")}, which no browser would run: name them in the plan's boot`
404
511
  });
405
512
  const payload = payloadOf(plan, started.model);
406
- const resumed = browserModelOf(plan, payload);
513
+ const resumed = browserModelOf(plan, payload, started.model);
407
514
  if (Result.isFailure(resumed)) return yield* new ResumeUnsafe({
408
515
  reason: "UnrestorablePart",
409
516
  message: resumed.failure
410
517
  });
411
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
+ });
412
525
  const eager = eagerEntries(config, plan, started.model);
413
526
  if (eager.length > 0) return yield* new ResumeUnsafe({
414
527
  reason: "EagerStartRequired",
@@ -423,6 +536,9 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
423
536
  reason: "Uncovered",
424
537
  message: `the plan does not cover what the browser reads:\n- ${uncovered.join("\n- ")}`
425
538
  });
539
+ const drawn = /* @__PURE__ */ new Set();
540
+ const global = globalThis;
541
+ global[DRAWN_CLASSES] = drawn;
426
542
  const rendered = yield* renderToString(withContext(startingFrom(config, { model: browser }), {
427
543
  mode: "replay",
428
544
  regions,
@@ -430,7 +546,9 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
430
546
  fallback,
431
547
  wrap: (message) => message,
432
548
  depth: 0
433
- }), options);
549
+ }), options).pipe(Effect.ensuring(Effect.sync(() => {
550
+ if (global[DRAWN_CLASSES] === drawn) delete global[DRAWN_CLASSES];
551
+ })));
434
552
  const encoded = encodeBindings(plan, servedBindings);
435
553
  const reencoded = encodeBindings(plan, browserBindings);
436
554
  if (Result.isFailure(encoded)) return yield* new ResumeUnsafe({
@@ -454,7 +572,9 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
454
572
  bindings: encoded.success,
455
573
  events: [.../* @__PURE__ */ new Set([...servedBindings.map((binding) => binding.event), ...unnamed.map((handler) => handler.event)])].sort()
456
574
  });
457
- const styled = options.styles === void 0 ? Result.succeed(rendered.html) : withInRoot(rendered.html, options.styles(rendered));
575
+ const headed = options.metaInRoot === true ? withHeadInRoot(rendered.html, meta) : Result.succeed(rendered.html);
576
+ if (Result.isFailure(headed)) return yield* headed.failure;
577
+ const styled = options.styles === void 0 ? Result.succeed(headed.success) : withInRoot(headed.success, options.styles(rendered, drawn));
458
578
  if (Result.isFailure(styled)) return yield* styled.failure;
459
579
  return {
460
580
  page: {
@@ -463,6 +583,7 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
463
583
  html: withEnvelopeAttribute(styled.success, envelope)
464
584
  },
465
585
  meta,
586
+ drawn,
466
587
  envelope,
467
588
  unnamed
468
589
  },
@@ -500,7 +621,7 @@ const withFilledTags = (template, rendered) => {
500
621
  return template;
501
622
  };
502
623
  /** The plan's `meta`, then what `head` adds, one line apart. */
503
- const headOf = (result, head) => [result.meta, head?.(result.rendered) ?? ""].filter((markup) => markup !== "").join("\n");
624
+ const headOf = (result, head) => [result.meta, head?.(result.rendered, result.drawn) ?? ""].filter((markup) => markup !== "").join("\n");
504
625
  /**
505
626
  * The page to serve: the rendered application in the template, with the
506
627
  * plan's `meta` and `head`'s markup, if any, before `</head>`. The envelope
@@ -508,6 +629,28 @@ const headOf = (result, head) => [result.meta, head?.(result.rendered) ?? ""].fi
508
629
  * with a head, and nothing else.
509
630
  */
510
631
  const page = (template, result, options = {}) => injectIntoTemplate(withHead(withFilledTags(template, result.rendered), headOf(result, options.head)), result.rendered);
632
+ /**
633
+ * `render`, the host's document renderer, with the head markup `SSR.entry`
634
+ * carries in the rendered root (a plan's `meta`) moved before the document's
635
+ * `</head>`, where link previews and crawlers read it. Wrap whatever draws the
636
+ * document: `SSR.headed(renderDocument)`, or, for a host that hands Foldkit a
637
+ * template, `SSR.headed(application => injectIntoTemplate(template,
638
+ * application))`. The markup is taken from the rendered root alone, where the
639
+ * entry put it, so nothing a view draws elsewhere is moved. Without it the
640
+ * markup stays in the body, and `SSR.hydrate` reports `HeadNotMoved`.
641
+ */
642
+ const headed = (render) => (application, ...args) => Option.match(pageHeadOf(application.html), {
643
+ onNone: () => render(application, ...args),
644
+ onSome: ({ head, html }) => {
645
+ const document = render({
646
+ ...application,
647
+ html
648
+ }, ...args);
649
+ const at = document.search(/<\/head>/i);
650
+ if (at === -1) throw new Error("foldkit-ssr: the document has no </head> to put the head in");
651
+ return `${document.slice(0, at)}${head}${document.slice(at)}`;
652
+ }
653
+ });
511
654
  /** The file a static host serves for a path: `/about` is `about/index.html`. */
512
655
  const fileOf = (path) => {
513
656
  const trimmed = path.replace(/^\/+/, "").replace(/\/+$/, "");
@@ -557,10 +700,10 @@ const reportedUnnamed = /* @__PURE__ */ new Set();
557
700
  /**
558
701
  * Reports, once per process, each handler that keeps a page from answering
559
702
  * before boot. Only a page that waits to boot is held up: one started
560
- * `'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.
561
704
  */
562
- const reportUnnamed = (config, plan, unnamed) => Effect.suspend(() => {
563
- 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;
564
707
  const first = unnamed.filter(({ element, event }) => {
565
708
  const key = JSON.stringify([
566
709
  plan.id,
@@ -602,7 +745,7 @@ const generate = (config, plan, options) => Effect.gen(function* () {
602
745
  buildId: options.buildId,
603
746
  url: new URL(path, options.origin).href,
604
747
  ...options.flags === void 0 ? {} : { flags: options.flags(path) }
605
- }, "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 }) => ({
606
749
  path,
607
750
  file: fileOf(path),
608
751
  html: page(options.template, result, { head: options.head })
@@ -635,16 +778,15 @@ const generate = (config, plan, options) => Effect.gen(function* () {
635
778
  * `handleRequest` still classifies static misses and answers `HEAD` without
636
779
  * a body.
637
780
  *
638
- * What the page says of itself (`meta`) and per-page `head` markup are
639
- * written into a template's head, which the host owns here: a plan with
640
- * `meta` is refused when the entry is made, and served with `SSR.generate`.
781
+ * What the page says of itself (`meta`) belongs in the head, which the host
782
+ * owns here: the entry carries it in the rendered root, and the host's
783
+ * document renderer, wrapped in `SSR.headed`, moves it before `</head>`.
641
784
  */
642
785
  const entry = (config, plan, options) => {
643
786
  const cache = Option.map(Option.fromUndefinedOr(options.cache), (given) => ({
644
787
  ...given,
645
788
  policy: cachePolicy(given)
646
789
  }));
647
- if (plan.meta !== void 0) throw new Error(`foldkit-ssr: plan "${plan.id}" says what the page says of itself (meta), which is written into the template's head, and the template is the host's: serve it with SSR.generate, not SSR.entry`);
648
790
  const listed = options.origins === "same-origin" ? [] : options.origins ?? [];
649
791
  for (const origin of listed) if (!URL.canParse(origin) || new URL(origin).origin !== origin) throw new Error(`foldkit-ssr: ${JSON.stringify(origin)} in origins is not an origin`);
650
792
  if (options.answerPost !== void 0 && plan.fallback !== "server") throw new Error(`foldkit-ssr: plan "${plan.id}" has no server fallback, so no form is posted to answer (answerPost)`);
@@ -701,8 +843,12 @@ const entry = (config, plan, options) => {
701
843
  if (posting && !postedFrom(request, originsOf(request))) return responded(plainText(403, "The form was not posted from this site."));
702
844
  const flagsOf = options.flags;
703
845
  const statusOf = options.status;
846
+ const redirectOf = options.redirect;
704
847
  const { prepare } = options;
705
- const styled = options.styles === void 0 ? {} : { styles: options.styles };
848
+ const styled = {
849
+ ...options.styles === void 0 ? {} : { styles: options.styles },
850
+ metaInRoot: true
851
+ };
706
852
  const exit = await Effect.runPromiseExit(Effect.gen(function* () {
707
853
  const flags = flagsOf === void 0 ? void 0 : yield* Effect.tryPromise(async () => flagsOf(request));
708
854
  const flagged = flagsOf === void 0 ? {} : { flags };
@@ -723,20 +869,32 @@ const entry = (config, plan, options) => {
723
869
  });
724
870
  return Responded(extra === void 0 ? redirect : merge(redirect, extra));
725
871
  }
726
- const served = posting ? yield* handleServed(request, config, plan, post()) : yield* renderMatching(prepare === void 0 ? config : yield* preparedStart(request, config, {
872
+ const start = {
727
873
  url: request.url,
728
874
  ...flagged
729
- }, prepare), plan, {
875
+ };
876
+ const started = posting || prepare === void 0 && redirectOf === void 0 ? Option.none() : Option.some(yield* preparedStart(request, config, start, prepare));
877
+ const sentTo = Option.flatMap(started, ({ model }) => redirectOf === void 0 ? Option.none() : Option.map(redirectOf(model, request), (path) => ({
878
+ path,
879
+ model
880
+ })));
881
+ if (Option.isSome(sentTo)) {
882
+ const { path, model } = sentTo.value;
883
+ return yield* Effect.sync(() => Responded(redirected(path, request.url, headersOf(request, Option.some(model)))));
884
+ }
885
+ const served = posting ? yield* handleServed(request, config, plan, post()) : yield* renderMatching(Option.match(started, {
886
+ onNone: () => config,
887
+ onSome: ({ config }) => config
888
+ }), plan, {
730
889
  buildId: options.buildId,
731
- url: request.url,
732
- ...flagged,
890
+ ...start,
733
891
  ...styled
734
- }, matchOf(request.url));
892
+ }, matchOf(request.url), Option.map(started, ({ model }) => model));
735
893
  const extra = yield* Effect.sync(() => headersOf(request, Option.some(served.model)));
736
894
  const status = Option.map(Option.fromUndefinedOr(statusOf), (of) => of(served.model, request));
737
895
  const unanswerable = Option.filter(status, (given) => !Number.isInteger(given) || given < 200 || given > 599 || given === 204 || given === 205 || given === 304);
738
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`));
739
- yield* reportUnnamed(config, plan, served.page.unnamed);
897
+ yield* reportUnnamed(config, plan, served);
740
898
  return Rendered(served.page.rendered, {
741
899
  ...extra === void 0 ? {} : { headers: extra },
742
900
  ...Option.match(status, {
@@ -753,7 +911,32 @@ const entry = (config, plan, options) => {
753
911
  }
754
912
  return exit.value;
755
913
  };
756
- if (Option.isNone(cache)) return { renderPage: (request) => answer(request) };
914
+ /**
915
+ * A prerendered page, as the file every visitor is given: refused, by
916
+ * rejecting, unless it was drawn from its URL alone and sets nothing a
917
+ * file cannot carry.
918
+ */
919
+ const prerender = async (request) => {
920
+ const watched = {
921
+ read: {
922
+ names: /* @__PURE__ */ new Set(),
923
+ all: false
924
+ },
925
+ reads: []
926
+ };
927
+ const result = await answer(request, watched);
928
+ const refuse = (reason) => /* @__PURE__ */ new Error(`foldkit-ssr: ${routeOf(request.url)} is prerendered, a file every visitor is given, but ${reason}; render it per request instead (leave it out of prerendered)`);
929
+ if (result._tag !== "Rendered") throw refuse(`it was answered ${result.response.status}`);
930
+ const set = [...new Headers(result.headers).keys()];
931
+ const refused = notPublic(result.status ?? 200, watched).pipe(Option.orElse(() => watched.read.names.size === 0 ? Option.none() : Option.some(`it read the request's ${inWords([...watched.read.names])} header${watched.read.names.size > 1 ? "s" : ""}`)), Option.orElse(() => set.length === 0 ? Option.none() : Option.some(`its headers set ${inWords(set)}`)));
932
+ if (Option.isSome(refused)) throw refuse(refused.value);
933
+ return Rendered(result.application);
934
+ };
935
+ const prerendering = (request) => {
936
+ const method = request.method.toUpperCase();
937
+ return (method === "GET" || method === "HEAD") && matchOf(request.url) === "path";
938
+ };
939
+ if (Option.isNone(cache)) return { renderPage: (request) => prerendering(request) ? prerender(request) : answer(request) };
757
940
  const { store, check, policy } = cache.value;
758
941
  const reportTo = (request) => {
759
942
  const { diagnostics } = options;
@@ -771,13 +954,13 @@ const entry = (config, plan, options) => {
771
954
  };
772
955
  /** The page as a store keeps it, when nothing it was drawn from was the request's own. */
773
956
  const keepable = (request, result, watched) => {
774
- if (result._tag !== "Rendered" || (result.status ?? 200) !== 200 || watched.read.all) return Option.none();
957
+ if (result._tag !== "Rendered" || Option.isSome(notPublic(result.status ?? 200, watched))) return Option.none();
775
958
  if (![...watched.read.names].every((name) => !request.headers.has(name))) return Option.none();
776
959
  if (Option.isSome(headerOf(result.headers, "set-cookie")) || Option.isSome(headerOf(result.headers, "cache-control"))) return Option.none();
777
960
  let shortest = policy;
778
961
  const tags = /* @__PURE__ */ new Set();
779
962
  for (const read of watched.reads) {
780
- if (read._tag === "Private") return Option.none();
963
+ if (read._tag === "Private") continue;
781
964
  shortest = shorterPolicy(shortest, read.policy);
782
965
  for (const tag of read.tags) tags.add(tag);
783
966
  }
@@ -804,6 +987,7 @@ const entry = (config, plan, options) => {
804
987
  });
805
988
  };
806
989
  const renderPage = async (request) => {
990
+ if (prerendering(request)) return prerender(request);
807
991
  const method = request.method.toUpperCase();
808
992
  if (method !== "GET" && method !== "HEAD") return unkept(await answer(request));
809
993
  const key = await Effect.runPromise(pageKey(options.buildId, request.url));
@@ -834,6 +1018,21 @@ const entry = (config, plan, options) => {
834
1018
  return { renderPage };
835
1019
  };
836
1020
  /**
1021
+ * Why a render drew a page from more than its URL, so it is no page every
1022
+ * visitor may be given: one not answered `200`, one that read every header,
1023
+ * or one that made a private read. None when it drew it from the URL alone,
1024
+ * the headers it read by name aside, which `cache` varies by and a
1025
+ * prerendered file cannot.
1026
+ */
1027
+ const notPublic = (status, watched) => {
1028
+ if (status !== 200) return Option.some(`it was answered ${status}`);
1029
+ if (watched.read.all) return Option.some("it read every header of its request (it listed them, cloned the request or read a request context)");
1030
+ for (const read of watched.reads) if (read._tag === "Private") return Option.some(`it read ${read.read}, which is not public (a source with authorize, filter, visible or a per-viewer member, one with no cache, or a read that failed)`);
1031
+ return Option.none();
1032
+ };
1033
+ /** Names in a sentence: `a`, `a and b`, `a, b and c`. */
1034
+ const inWords = (names) => names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
1035
+ /**
837
1036
  * The page cache's checker, for a test: builds the entry with `make`, given a
838
1037
  * store in memory and `check`, and answers each request twice, so a page
839
1038
  * kept for one request is drawn again for every later one it serves.
@@ -870,6 +1069,27 @@ const sameAddress = (url) => {
870
1069
  return `${pathname.replace(/^\/+/, "/")}${search}`;
871
1070
  };
872
1071
  /**
1072
+ * `SSR.entry`'s answer to a page `redirect` sends elsewhere: a `303` to `path`
1073
+ * with the entry's `headers`, said `private, no-store` over theirs, since it
1074
+ * was decided for one reader. Throws for a path that is not one on the
1075
+ * request's own origin: resolved there, it must keep that origin and start
1076
+ * with a single `/`, so `//elsewhere.test`, `/\elsewhere.test` (which a
1077
+ * browser reads as `//`), a scheme, or a path whose dot segments resolve to
1078
+ * `//` are refused. The location written is the path as resolved.
1079
+ */
1080
+ const redirected = (path, url, headers) => {
1081
+ const origin = new URL(url).origin;
1082
+ const resolved = path.startsWith("/") ? new URL(path, origin) : void 0;
1083
+ if (resolved === void 0 || resolved.origin !== origin || resolved.pathname.startsWith("//")) throw new Error(`redirect gave ${JSON.stringify(path)}, which is no path on this origin: give one starting with a single /`);
1084
+ const response = new Response(null, {
1085
+ status: 303,
1086
+ headers: { location: `${resolved.pathname}${resolved.search}${resolved.hash}` }
1087
+ });
1088
+ headers?.forEach((value, name) => response.headers.append(name, value));
1089
+ response.headers.set("cache-control", "private, no-store");
1090
+ return response;
1091
+ };
1092
+ /**
873
1093
  * What `headers` may not set: what frames the response, which the host's
874
1094
  * server writes, and `location`, which only the entry writes.
875
1095
  */
@@ -982,11 +1202,14 @@ const startOf = (config, options) => Effect.gen(function* () {
982
1202
  */
983
1203
  const preparedStart = (request, config, options, prepare) => Effect.gen(function* () {
984
1204
  const started = yield* startOf(config, options);
985
- const model = yield* Effect.orDie(prepare(started.model, request));
986
- return startingFrom(config, {
987
- ...started,
988
- model
989
- });
1205
+ const model = prepare === void 0 ? started.model : yield* Effect.orDie(prepare(started.model, request));
1206
+ return {
1207
+ model,
1208
+ config: startingFrom(config, {
1209
+ ...started,
1210
+ model
1211
+ })
1212
+ };
990
1213
  });
991
1214
  /**
992
1215
  * Answers a form posted by a page rendered with `fallback: 'server'`: the
@@ -1001,8 +1224,9 @@ const handle = (request, config, plan, options) => Effect.map(handleServed(reque
1001
1224
  const handleServed = (request, config, plan, options) => Effect.flatMap(postedModel(request, config, plan, options), (model) => renderMatching(startingFrom(config, { model }), plan, {
1002
1225
  buildId: options.buildId,
1003
1226
  url: request.url,
1004
- ...options.styles === void 0 ? {} : { styles: options.styles }
1005
- }, "full"));
1227
+ ...options.styles === void 0 ? {} : { styles: options.styles },
1228
+ ...options.metaInRoot === true ? { metaInRoot: true } : {}
1229
+ }, "full", Option.some(model)));
1006
1230
  /** The Model a posted form reaches: its Message decoded and checked, then `update` and its Commands. */
1007
1231
  const postedModel = (request, config, plan, options) => Effect.scoped(Effect.gen(function* () {
1008
1232
  if (plan.fallback !== "server" || plan.Message === void 0) return yield* refuseFallback("NoFallback", `plan "${plan.id}" has no server fallback`);
@@ -1063,11 +1287,13 @@ const SSR = {
1063
1287
  hydrate: SSR$1.hydrate,
1064
1288
  inspect,
1065
1289
  static: staticRegion,
1290
+ unbound,
1066
1291
  serving,
1067
1292
  generate,
1068
1293
  entry,
1069
1294
  checkCache,
1070
1295
  keptDocuments,
1296
+ headed,
1071
1297
  handle,
1072
1298
  serializeJsonScript,
1073
1299
  sitemap,