foldkit-ssr 0.10.0 → 0.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/README.md +693 -61
  2. package/dist/{client-XnpTQZHw.d.ts → client-BEHlUHBv.d.ts} +10 -7
  3. package/dist/client-BEHlUHBv.d.ts.map +1 -0
  4. package/dist/client.d.ts +6 -5
  5. package/dist/client.js +66 -18
  6. package/dist/client.js.map +1 -1
  7. package/dist/context.d.ts +1 -1
  8. package/dist/context.js.map +1 -1
  9. package/dist/diagnostics.d.ts +2 -2
  10. package/dist/diagnostics.js +14 -1
  11. package/dist/diagnostics.js.map +1 -1
  12. package/dist/handoff.d.ts +23 -0
  13. package/dist/handoff.d.ts.map +1 -0
  14. package/dist/handoff.js +15 -0
  15. package/dist/handoff.js.map +1 -0
  16. package/dist/index.d.ts +108 -26
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js +386 -51
  19. package/dist/index.js.map +1 -1
  20. package/dist/keep.d.ts +5 -1
  21. package/dist/keep.d.ts.map +1 -1
  22. package/dist/keep.js +55 -11
  23. package/dist/keep.js.map +1 -1
  24. package/dist/{listen-DaUPRKVR.d.ts → listen-7HzKBhqU.d.ts} +11 -2
  25. package/dist/{listen-DaUPRKVR.d.ts.map → listen-7HzKBhqU.d.ts.map} +1 -1
  26. package/dist/listen.d.ts +2 -2
  27. package/dist/listen.js +17 -7
  28. package/dist/listen.js.map +1 -1
  29. package/dist/loader.d.ts +13 -0
  30. package/dist/loader.d.ts.map +1 -0
  31. package/dist/loader.js +156 -0
  32. package/dist/loader.js.map +1 -0
  33. package/dist/marks-CX15BwOw.d.ts +39 -0
  34. package/dist/marks-CX15BwOw.d.ts.map +1 -0
  35. package/dist/marks.d.ts +2 -0
  36. package/dist/marks.js +41 -0
  37. package/dist/marks.js.map +1 -0
  38. package/dist/pageCache-DO0pOgnc.d.ts +80 -0
  39. package/dist/pageCache-DO0pOgnc.d.ts.map +1 -0
  40. package/dist/pageCache.d.ts +2 -0
  41. package/dist/pageCache.js +112 -0
  42. package/dist/pageCache.js.map +1 -0
  43. package/dist/{requestContext-D9nsbGSJ.d.ts → requestContext-DmwmQeci.d.ts} +12 -2
  44. package/dist/requestContext-DmwmQeci.d.ts.map +1 -0
  45. package/dist/requestContext.d.ts +2 -2
  46. package/dist/requestContext.js +30 -13
  47. package/dist/requestContext.js.map +1 -1
  48. package/dist/{resumable-BPN_qQHU.d.ts → resumable-BV9_OKxr.d.ts} +7 -10
  49. package/dist/resumable-BV9_OKxr.d.ts.map +1 -0
  50. package/dist/resumable.d.ts +2 -1
  51. package/dist/resumable.js +16 -19
  52. package/dist/resumable.js.map +1 -1
  53. package/dist/runtimeChunk.d.ts +13 -0
  54. package/dist/runtimeChunk.d.ts.map +1 -0
  55. package/dist/runtimeChunk.js +36 -0
  56. package/dist/runtimeChunk.js.map +1 -0
  57. package/dist/runtimeUrl.d.ts +10 -0
  58. package/dist/runtimeUrl.d.ts.map +1 -0
  59. package/dist/runtimeUrl.js +13 -0
  60. package/dist/runtimeUrl.js.map +1 -0
  61. package/dist/{shared-DbupL3vO.d.ts → shared-mQ8CXr-r.d.ts} +69 -22
  62. package/dist/shared-mQ8CXr-r.d.ts.map +1 -0
  63. package/dist/shared.d.ts +3 -2
  64. package/dist/shared.js +40 -18
  65. package/dist/shared.js.map +1 -1
  66. package/dist/vite.d.ts +3 -2
  67. package/dist/vite.d.ts.map +1 -1
  68. package/dist/vite.js +2 -1
  69. package/dist/vite.js.map +1 -1
  70. package/package.json +11 -6
  71. package/dist/client-XnpTQZHw.d.ts.map +0 -1
  72. package/dist/requestContext-D9nsbGSJ.d.ts.map +0 -1
  73. package/dist/resumable-BPN_qQHU.d.ts.map +0 -1
  74. package/dist/shared-DbupL3vO.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,11 +1,13 @@
1
1
  import { withContext } from "./context.js";
2
- import { 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";
2
+ import { cachedPageDiffers, handlerUnnamed, pageFailed, reportingTo } from "./diagnostics.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, 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";
8
+ import { decodeKept, fits, headerOf, keptApplications, keptDocuments, pageKey, samePage, tracked } from "./pageCache.js";
7
9
  import { Cause, Context, Effect, Exit, Layer, Option, Result, Schema } from "effect";
8
- import { Diagnostics as Diagnostics$1, Metadata } from "foldkit-surface";
10
+ import { CacheStore, Diagnostics as Diagnostics$1, Metadata, PageReads, cachePolicy, maxAgeSeconds, shorterPolicy } from "foldkit-surface";
9
11
  import { FOLDKIT_FLAGS_ATTRIBUTE, Rendered, Responded, injectIntoTemplate, renderToString } from "foldkit/experimental/server";
10
12
  // src/index.ts
11
13
  /**
@@ -23,6 +25,8 @@ import { FOLDKIT_FLAGS_ATTRIBUTE, Rendered, Responded, injectIntoTemplate, rende
23
25
  * handover. This module is the server's side and the browser's
24
26
  * (`foldkit-ssr/client`) together.
25
27
  */
28
+ /** The set `foldkit-mixins` collects drawn classes in, under the same registered symbol. */
29
+ const DRAWN_CLASSES = Symbol.for("foldkit-plus.drawnClasses");
26
30
  /** The projections of the plan's entries that are active for `model`. */
27
31
  const activeProjections = (plan, model) => plan.surfaces.flatMap((source) => projectionsOf(source, model));
28
32
  /**
@@ -56,7 +60,8 @@ const envelopeOf = (resume, payload, options) => serializeJsonScript({
56
60
  ...options.route === void 0 ? {} : { route: options.route },
57
61
  ...options.match === "path" ? { match: "path" } : {},
58
62
  ...options.bindings === void 0 || options.bindings.length === 0 ? {} : { bindings: options.bindings },
59
- ...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 }
60
65
  });
61
66
  /**
62
67
  * The rendered application with the envelope on its stamped root, beside
@@ -96,36 +101,107 @@ const isInRootTag = (html, at) => {
96
101
  return true;
97
102
  };
98
103
  /**
99
- * The rendered markup with `extra` as the root's last children, after the
100
- * styles marker, so the first paint is styled before any script runs where no
101
- * template head can take it; `SSR.hydrate` moves them into the head. A void
102
- * root holds no children: styles for one are refused, naming the tag, rather
103
- * 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.
104
107
  */
105
- const withInRoot = (html, extra) => {
108
+ const beforeRootEnd = (html, insert, refused) => {
106
109
  const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1];
107
110
  const at = tag === void 0 ? -1 : html.search(new RegExp(`</${tag}>\\s*$`));
108
- if (tag === void 0 || at === -1) return Result.fail(new ResumeUnsafe({
109
- reason: "VoidRootWithStyles",
110
- 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`
111
- }));
112
- 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
+ });
113
184
  };
114
185
  /**
115
186
  * The Model the browser will start from when the server's Model is `model`:
116
187
  * the payload taken through the page as the envelope carries it, as JSON, and
117
- * resumed exactly as `SSR.resume` resumes it. A part that cannot restore its
118
- * 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.
119
191
  */
120
- 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
+ };
121
196
  const pathOf = (path) => path.length === 0 ? "(the whole Model)" : path.join(".");
122
197
  /**
123
- * A path is covered by a sent or local path equal to it or containing it. An
124
- * 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.
125
200
  */
126
201
  const coverOf = (path, plan) => {
127
202
  const contains = (outer) => outer.length > 0 && outer.length <= path.length && outer.every((key, index) => path[index] === key);
128
203
  if (plan.state.dependencies.some(contains)) return "state";
204
+ if (plan.restored.some(({ path: outer }) => contains(outer))) return "restored";
129
205
  if (plan.local.some(contains)) return "local";
130
206
  return "missing";
131
207
  };
@@ -137,7 +213,7 @@ const readsKey = (projection) => projection === void 0 ? "inactive" : JSON.strin
137
213
  * worked out for a Model, not for the plan alone.
138
214
  */
139
215
  const inspect = (plan, model) => {
140
- const resumed = browserModelOf(plan, payloadOf(plan, model));
216
+ const resumed = browserModelOf(plan, payloadOf(plan, model), model);
141
217
  if (Result.isFailure(resumed)) throw new Error(`SSR.inspect: ${resumed.failure}`);
142
218
  return coverage(plan, model, resumed.success);
143
219
  };
@@ -155,6 +231,7 @@ const coverage = (plan, model, browser) => {
155
231
  id: plan.id,
156
232
  state: plan.state.dependencies.map(pathOf),
157
233
  local: plan.local.map(pathOf),
234
+ restored: plan.restored.map(({ path }) => pathOf(path)),
158
235
  parts: plan.parts.map((part) => part.id),
159
236
  surfaces: plan.surfaces.flatMap((source) => {
160
237
  const surface = Option.match(familyOf(source), {
@@ -235,7 +312,9 @@ var ResumeUnsafe = class extends Schema.TaggedError()("ResumeUnsafe", {
235
312
  "UndeclaredSurfaces",
236
313
  "BindingInStaticRegion",
237
314
  "VoidRootWithStyles",
238
- "UnkeepableField"
315
+ "RootRefusesHead",
316
+ "UnkeepableField",
317
+ "UnkeptField"
239
318
  ]),
240
319
  message: Schema.String
241
320
  }) {};
@@ -245,16 +324,37 @@ const unlistedBindings = (plan, model, bindings) => {
245
324
  return bindings.filter((binding) => !allowed.has(tagOf(binding.message))).map((binding) => `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`);
246
325
  };
247
326
  /**
327
+ * Whether `at` starts an attribute inside the start tag opened before it.
328
+ * A marker in a text node follows that tag's `>`, and one inside another
329
+ * attribute's value has its quotes escaped (`&quot;`), so only a marker
330
+ * between a tag's `<` and a `>` outside a quoted value is an attribute.
331
+ */
332
+ const opensAttribute = (html, at) => {
333
+ if (at === 0 || !/[ \t\r\n]/.test(html[at - 1])) return false;
334
+ const open = html.lastIndexOf("<", at);
335
+ if (open === -1 || html.startsWith("<!--", open)) return false;
336
+ let quote;
337
+ for (let index = open + 1; index < at; index++) {
338
+ const char = html[index];
339
+ if (quote !== void 0) {
340
+ if (char === quote) quote = void 0;
341
+ } else if (char === "\"" || char === "'") quote = char;
342
+ else if (char === ">") return false;
343
+ }
344
+ return quote === void 0;
345
+ };
346
+ /**
248
347
  * A line for each `KeepTyped` the render drew on an element the resumable
249
348
  * builder did not build, whose marker still holds its server-render value:
250
349
  * nothing marks which binding replays such a field, so every browser would
251
- * refuse the page. Foldkit escapes `<` in text and attribute values, so the
252
- * last `<` before the marker opens its element.
350
+ * refuse the page. Only a marker that is an attribute counts: ordinary text
351
+ * can spell the same characters.
253
352
  */
254
353
  const unplacedKeeps = (html) => {
255
354
  const marker = `${KEEP_ATTRIBUTE}="?"`;
256
355
  const found = [];
257
356
  for (let at = html.indexOf(marker); at !== -1; at = html.indexOf(marker, at + 1)) {
357
+ if (!opensAttribute(html, at)) continue;
258
358
  const open = html.lastIndexOf("<", at);
259
359
  const tag = /^<([A-Za-z][A-Za-z0-9._-]*)/.exec(html.slice(open))?.[1] ?? "an element";
260
360
  const id = /\sid="([^"]*)"/.exec(html.slice(open, html.indexOf(">", at)))?.[1];
@@ -343,6 +443,7 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
343
443
  const inStatic = [];
344
444
  const unnamed = [];
345
445
  const unkeepable = [];
446
+ const unkept = [];
346
447
  const fallback = fallbackEncoder(plan);
347
448
  const capturing = withContext({
348
449
  ...config,
@@ -358,7 +459,8 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
358
459
  region: void 0,
359
460
  inStatic,
360
461
  unnamed,
361
- unkeepable
462
+ unkeepable,
463
+ unkept
362
464
  });
363
465
  const full = yield* renderToString(capturing, options);
364
466
  unkeepable.push(...unplacedKeeps(full.html));
@@ -374,6 +476,10 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
374
476
  reason: "UnkeepableField",
375
477
  message: `the page cannot keep what is typed into these fields before it boots:\n- ${unkeepable.join("\n- ")}`
376
478
  });
479
+ if (plan.start !== "now" && unkept.length > 0) return yield* new ResumeUnsafe({
480
+ reason: "UnkeptField",
481
+ 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- ")}`
482
+ });
377
483
  const started = served;
378
484
  const commands = started.commands ?? [];
379
485
  if (commands.length > 0 && plan.boot === void 0) return yield* new ResumeUnsafe({
@@ -381,7 +487,7 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
381
487
  message: `init returned ${commands.map((command) => command.name).join(", ")}, which no browser would run: name them in the plan's boot`
382
488
  });
383
489
  const payload = payloadOf(plan, started.model);
384
- const resumed = browserModelOf(plan, payload);
490
+ const resumed = browserModelOf(plan, payload, started.model);
385
491
  if (Result.isFailure(resumed)) return yield* new ResumeUnsafe({
386
492
  reason: "UnrestorablePart",
387
493
  message: resumed.failure
@@ -401,6 +507,9 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
401
507
  reason: "Uncovered",
402
508
  message: `the plan does not cover what the browser reads:\n- ${uncovered.join("\n- ")}`
403
509
  });
510
+ const drawn = /* @__PURE__ */ new Set();
511
+ const global = globalThis;
512
+ global[DRAWN_CLASSES] = drawn;
404
513
  const rendered = yield* renderToString(withContext(startingFrom(config, { model: browser }), {
405
514
  mode: "replay",
406
515
  regions,
@@ -408,7 +517,9 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
408
517
  fallback,
409
518
  wrap: (message) => message,
410
519
  depth: 0
411
- }), options);
520
+ }), options).pipe(Effect.ensuring(Effect.sync(() => {
521
+ if (global[DRAWN_CLASSES] === drawn) delete global[DRAWN_CLASSES];
522
+ })));
412
523
  const encoded = encodeBindings(plan, servedBindings);
413
524
  const reencoded = encodeBindings(plan, browserBindings);
414
525
  if (Result.isFailure(encoded)) return yield* new ResumeUnsafe({
@@ -432,7 +543,9 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
432
543
  bindings: encoded.success,
433
544
  events: [.../* @__PURE__ */ new Set([...servedBindings.map((binding) => binding.event), ...unnamed.map((handler) => handler.event)])].sort()
434
545
  });
435
- const styled = options.styles === void 0 ? Result.succeed(rendered.html) : withInRoot(rendered.html, options.styles(rendered));
546
+ const headed = options.metaInRoot === true ? withHeadInRoot(rendered.html, meta) : Result.succeed(rendered.html);
547
+ if (Result.isFailure(headed)) return yield* headed.failure;
548
+ const styled = options.styles === void 0 ? Result.succeed(headed.success) : withInRoot(headed.success, options.styles(rendered, drawn));
436
549
  if (Result.isFailure(styled)) return yield* styled.failure;
437
550
  return {
438
551
  page: {
@@ -441,6 +554,7 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
441
554
  html: withEnvelopeAttribute(styled.success, envelope)
442
555
  },
443
556
  meta,
557
+ drawn,
444
558
  envelope,
445
559
  unnamed
446
560
  },
@@ -478,7 +592,7 @@ const withFilledTags = (template, rendered) => {
478
592
  return template;
479
593
  };
480
594
  /** The plan's `meta`, then what `head` adds, one line apart. */
481
- const headOf = (result, head) => [result.meta, head?.(result.rendered) ?? ""].filter((markup) => markup !== "").join("\n");
595
+ const headOf = (result, head) => [result.meta, head?.(result.rendered, result.drawn) ?? ""].filter((markup) => markup !== "").join("\n");
482
596
  /**
483
597
  * The page to serve: the rendered application in the template, with the
484
598
  * plan's `meta` and `head`'s markup, if any, before `</head>`. The envelope
@@ -486,6 +600,28 @@ const headOf = (result, head) => [result.meta, head?.(result.rendered) ?? ""].fi
486
600
  * with a head, and nothing else.
487
601
  */
488
602
  const page = (template, result, options = {}) => injectIntoTemplate(withHead(withFilledTags(template, result.rendered), headOf(result, options.head)), result.rendered);
603
+ /**
604
+ * `render`, the host's document renderer, with the head markup `SSR.entry`
605
+ * carries in the rendered root (a plan's `meta`) moved before the document's
606
+ * `</head>`, where link previews and crawlers read it. Wrap whatever draws the
607
+ * document: `SSR.headed(renderDocument)`, or, for a host that hands Foldkit a
608
+ * template, `SSR.headed(application => injectIntoTemplate(template,
609
+ * application))`. The markup is taken from the rendered root alone, where the
610
+ * entry put it, so nothing a view draws elsewhere is moved. Without it the
611
+ * markup stays in the body, and `SSR.hydrate` reports `HeadNotMoved`.
612
+ */
613
+ const headed = (render) => (application, ...args) => Option.match(pageHeadOf(application.html), {
614
+ onNone: () => render(application, ...args),
615
+ onSome: ({ head, html }) => {
616
+ const document = render({
617
+ ...application,
618
+ html
619
+ }, ...args);
620
+ const at = document.search(/<\/head>/i);
621
+ if (at === -1) throw new Error("foldkit-ssr: the document has no </head> to put the head in");
622
+ return `${document.slice(0, at)}${head}${document.slice(at)}`;
623
+ }
624
+ });
489
625
  /** The file a static host serves for a path: `/about` is `about/index.html`. */
490
626
  const fileOf = (path) => {
491
627
  const trimmed = path.replace(/^\/+/, "").replace(/\/+$/, "");
@@ -613,12 +749,15 @@ const generate = (config, plan, options) => Effect.gen(function* () {
613
749
  * `handleRequest` still classifies static misses and answers `HEAD` without
614
750
  * a body.
615
751
  *
616
- * What the page says of itself (`meta`) and per-page `head` markup are
617
- * written into a template's head, which the host owns here: a plan with
618
- * `meta` is refused when the entry is made, and served with `SSR.generate`.
752
+ * What the page says of itself (`meta`) belongs in the head, which the host
753
+ * owns here: the entry carries it in the rendered root, and the host's
754
+ * document renderer, wrapped in `SSR.headed`, moves it before `</head>`.
619
755
  */
620
756
  const entry = (config, plan, options) => {
621
- 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`);
757
+ const cache = Option.map(Option.fromUndefinedOr(options.cache), (given) => ({
758
+ ...given,
759
+ policy: cachePolicy(given)
760
+ }));
622
761
  const listed = options.origins === "same-origin" ? [] : options.origins ?? [];
623
762
  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`);
624
763
  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)`);
@@ -643,11 +782,17 @@ const entry = (config, plan, options) => {
643
782
  for (const name of headers.keys()) if (ENTRY_HEADERS.has(name)) throw new Error(`headers set ${name}, which the entry writes and an application may not`);
644
783
  return headers;
645
784
  };
646
- const answer = async (request) => {
785
+ /**
786
+ * One request answered. `watched`, for a render that may be kept, records
787
+ * what the render read of the request's headers and through `pageReader`.
788
+ */
789
+ const answer = async (given, watched) => {
790
+ const request = watched === void 0 ? given : tracked(given, watched.read);
647
791
  const method = request.method.toUpperCase();
648
792
  const posting = method === "POST" && plan.fallback === "server";
649
793
  const { diagnostics } = options;
650
- const reporting = reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request));
794
+ const reported = reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, given));
795
+ const reporting = (effect) => reported(watched === void 0 ? effect : Effect.provideService(effect, PageReads, Option.some((read) => watched.reads.push(read))));
651
796
  const responded = async (response, { reported = false } = {}) => {
652
797
  let extra;
653
798
  try {
@@ -669,8 +814,12 @@ const entry = (config, plan, options) => {
669
814
  if (posting && !postedFrom(request, originsOf(request))) return responded(plainText(403, "The form was not posted from this site."));
670
815
  const flagsOf = options.flags;
671
816
  const statusOf = options.status;
817
+ const redirectOf = options.redirect;
672
818
  const { prepare } = options;
673
- const styled = options.styles === void 0 ? {} : { styles: options.styles };
819
+ const styled = {
820
+ ...options.styles === void 0 ? {} : { styles: options.styles },
821
+ metaInRoot: true
822
+ };
674
823
  const exit = await Effect.runPromiseExit(Effect.gen(function* () {
675
824
  const flags = flagsOf === void 0 ? void 0 : yield* Effect.tryPromise(async () => flagsOf(request));
676
825
  const flagged = flagsOf === void 0 ? {} : { flags };
@@ -691,19 +840,31 @@ const entry = (config, plan, options) => {
691
840
  });
692
841
  return Responded(extra === void 0 ? redirect : merge(redirect, extra));
693
842
  }
694
- const served = posting ? yield* handleServed(request, config, plan, post()) : yield* renderMatching(prepare === void 0 ? config : yield* preparedStart(request, config, {
843
+ const start = {
695
844
  url: request.url,
696
845
  ...flagged
697
- }, prepare), plan, {
846
+ };
847
+ const started = posting || prepare === void 0 && redirectOf === void 0 ? Option.none() : Option.some(yield* preparedStart(request, config, start, prepare));
848
+ const sentTo = Option.flatMap(started, ({ model }) => redirectOf === void 0 ? Option.none() : Option.map(redirectOf(model, request), (path) => ({
849
+ path,
850
+ model
851
+ })));
852
+ if (Option.isSome(sentTo)) {
853
+ const { path, model } = sentTo.value;
854
+ return yield* Effect.sync(() => Responded(redirected(path, request.url, headersOf(request, Option.some(model)))));
855
+ }
856
+ const served = posting ? yield* handleServed(request, config, plan, post()) : yield* renderMatching(Option.match(started, {
857
+ onNone: () => config,
858
+ onSome: ({ config }) => config
859
+ }), plan, {
698
860
  buildId: options.buildId,
699
- url: request.url,
700
- ...flagged,
861
+ ...start,
701
862
  ...styled
702
863
  }, matchOf(request.url));
703
864
  const extra = yield* Effect.sync(() => headersOf(request, Option.some(served.model)));
704
865
  const status = Option.map(Option.fromUndefinedOr(statusOf), (of) => of(served.model, request));
705
- const unanswerable = Option.filter(status, (given) => !Number.isInteger(given) || given < 200 || given > 599);
706
- if (Option.isSome(unanswerable)) return yield* Effect.die(/* @__PURE__ */ new Error(`status gave ${unanswerable.value} for the page, which is no status between 200 and 599`));
866
+ const unanswerable = Option.filter(status, (given) => !Number.isInteger(given) || given < 200 || given > 599 || given === 204 || given === 205 || given === 304);
867
+ 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`));
707
868
  yield* reportUnnamed(config, plan, served.page.unnamed);
708
869
  return Rendered(served.page.rendered, {
709
870
  ...extra === void 0 ? {} : { headers: extra },
@@ -721,7 +882,152 @@ const entry = (config, plan, options) => {
721
882
  }
722
883
  return exit.value;
723
884
  };
724
- return { renderPage: answer };
885
+ /**
886
+ * A prerendered page, as the file every visitor is given: refused, by
887
+ * rejecting, unless it was drawn from its URL alone and sets nothing a
888
+ * file cannot carry.
889
+ */
890
+ const prerender = async (request) => {
891
+ const watched = {
892
+ read: {
893
+ names: /* @__PURE__ */ new Set(),
894
+ all: false
895
+ },
896
+ reads: []
897
+ };
898
+ const result = await answer(request, watched);
899
+ 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)`);
900
+ if (result._tag !== "Rendered") throw refuse(`it was answered ${result.response.status}`);
901
+ const set = [...new Headers(result.headers).keys()];
902
+ 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)}`)));
903
+ if (Option.isSome(refused)) throw refuse(refused.value);
904
+ return Rendered(result.application);
905
+ };
906
+ const prerendering = (request) => {
907
+ const method = request.method.toUpperCase();
908
+ return (method === "GET" || method === "HEAD") && matchOf(request.url) === "path";
909
+ };
910
+ if (Option.isNone(cache)) return { renderPage: (request) => prerendering(request) ? prerender(request) : answer(request) };
911
+ const { store, check, policy } = cache.value;
912
+ const reportTo = (request) => {
913
+ const { diagnostics } = options;
914
+ return reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request));
915
+ };
916
+ /** A page no store may keep for another request: its own `cache-control` stands. */
917
+ const unkept = (result) => {
918
+ if (result._tag !== "Rendered" || Option.isSome(headerOf(result.headers, "cache-control"))) return result;
919
+ const headers = new Headers(result.headers);
920
+ headers.set("cache-control", "private, no-store");
921
+ return Rendered(result.application, {
922
+ ...result,
923
+ headers
924
+ });
925
+ };
926
+ /** The page as a store keeps it, when nothing it was drawn from was the request's own. */
927
+ const keepable = (request, result, watched) => {
928
+ if (result._tag !== "Rendered" || Option.isSome(notPublic(result.status ?? 200, watched))) return Option.none();
929
+ if (![...watched.read.names].every((name) => !request.headers.has(name))) return Option.none();
930
+ if (Option.isSome(headerOf(result.headers, "set-cookie")) || Option.isSome(headerOf(result.headers, "cache-control"))) return Option.none();
931
+ let shortest = policy;
932
+ const tags = /* @__PURE__ */ new Set();
933
+ for (const read of watched.reads) {
934
+ if (read._tag === "Private") continue;
935
+ shortest = shorterPolicy(shortest, read.policy);
936
+ for (const tag of read.tags) tags.add(tag);
937
+ }
938
+ const vary = [...watched.read.names].sort();
939
+ const headers = new Headers(result.headers);
940
+ headers.set("cache-control", `public, max-age=${maxAgeSeconds(shortest)}`);
941
+ if (vary.length > 0) headers.set("vary", vary.join(", "));
942
+ return Option.some({
943
+ page: {
944
+ application: result.application,
945
+ ...result.status === void 0 ? {} : { status: result.status },
946
+ headers: [...headers],
947
+ vary
948
+ },
949
+ maxAge: shortest,
950
+ tags: [...tags]
951
+ });
952
+ };
953
+ const served = (page) => {
954
+ keptApplications.add(page.application);
955
+ return Rendered(page.application, {
956
+ ...page.status === void 0 ? {} : { status: page.status },
957
+ headers: page.headers.map(([name, value]) => [name, value])
958
+ });
959
+ };
960
+ const renderPage = async (request) => {
961
+ if (prerendering(request)) return prerender(request);
962
+ const method = request.method.toUpperCase();
963
+ if (method !== "GET" && method !== "HEAD") return unkept(await answer(request));
964
+ const key = await Effect.runPromise(pageKey(options.buildId, request.url));
965
+ const kept = Option.filter(Option.flatMap(await Effect.runPromise(store.match(key)), decodeKept), (page) => fits(request, page.vary));
966
+ if (Option.isSome(kept)) {
967
+ if (check !== true) return served(kept.value);
968
+ const again = await answer(request);
969
+ if (again._tag === "Rendered" && samePage(again, kept.value, Date.now())) return served(kept.value);
970
+ await Effect.runPromise(reportTo(request)(Diagnostics$1.report(cachedPageDiffers(request.url))));
971
+ return unkept(again);
972
+ }
973
+ const watched = {
974
+ read: {
975
+ names: /* @__PURE__ */ new Set(),
976
+ all: false
977
+ },
978
+ reads: []
979
+ };
980
+ const result = await answer(request, watched);
981
+ return Option.match(keepable(request, result, watched), {
982
+ onNone: () => unkept(result),
983
+ onSome: ({ page, maxAge, tags }) => Effect.runPromise(Effect.as(store.put(key, JSON.stringify(page), {
984
+ maxAge: maxAge.maxAge,
985
+ tags
986
+ }), served(page)))
987
+ });
988
+ };
989
+ return { renderPage };
990
+ };
991
+ /**
992
+ * Why a render drew a page from more than its URL, so it is no page every
993
+ * visitor may be given: one not answered `200`, one that read every header,
994
+ * or one that made a private read. None when it drew it from the URL alone,
995
+ * the headers it read by name aside, which `cache` varies by and a
996
+ * prerendered file cannot.
997
+ */
998
+ const notPublic = (status, watched) => {
999
+ if (status !== 200) return Option.some(`it was answered ${status}`);
1000
+ 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)");
1001
+ 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)`);
1002
+ return Option.none();
1003
+ };
1004
+ /** Names in a sentence: `a`, `a and b`, `a, b and c`. */
1005
+ const inWords = (names) => names.length < 2 ? names.join("") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`;
1006
+ /**
1007
+ * The page cache's checker, for a test: builds the entry with `make`, given a
1008
+ * store in memory and `check`, and answers each request twice, so a page
1009
+ * kept for one request is drawn again for every later one it serves.
1010
+ * Rejects naming each page drawn otherwise for a request it served, and
1011
+ * when no page was kept, which would check nothing. Give requests that
1012
+ * differ in who asks (a visitor's, and one with someone's cookie); each is a
1013
+ * function, since a request is read once.
1014
+ */
1015
+ const checkCache = async (make, requests) => {
1016
+ const store = CacheStore.memory();
1017
+ const differs = [];
1018
+ const entry = make({
1019
+ cache: {
1020
+ store,
1021
+ maxAge: "1 hour",
1022
+ check: true
1023
+ },
1024
+ diagnostics: (diagnostic) => Effect.sync(() => {
1025
+ if (diagnostic._tag === "CachedPageDiffers") differs.push(diagnostic.message);
1026
+ })
1027
+ });
1028
+ for (const _round of [1, 2]) for (const request of requests) await entry.renderPage(request());
1029
+ if (differs.length > 0) throw new Error(differs.join("\n"));
1030
+ if (store.size() === 0) throw new Error("SSR.checkCache: no page was kept, so nothing was checked");
725
1031
  };
726
1032
  /**
727
1033
  * Where a post's answer sends the browser: the address it posted to, its path
@@ -734,6 +1040,27 @@ const sameAddress = (url) => {
734
1040
  return `${pathname.replace(/^\/+/, "/")}${search}`;
735
1041
  };
736
1042
  /**
1043
+ * `SSR.entry`'s answer to a page `redirect` sends elsewhere: a `303` to `path`
1044
+ * with the entry's `headers`, said `private, no-store` over theirs, since it
1045
+ * was decided for one reader. Throws for a path that is not one on the
1046
+ * request's own origin: resolved there, it must keep that origin and start
1047
+ * with a single `/`, so `//elsewhere.test`, `/\elsewhere.test` (which a
1048
+ * browser reads as `//`), a scheme, or a path whose dot segments resolve to
1049
+ * `//` are refused. The location written is the path as resolved.
1050
+ */
1051
+ const redirected = (path, url, headers) => {
1052
+ const origin = new URL(url).origin;
1053
+ const resolved = path.startsWith("/") ? new URL(path, origin) : void 0;
1054
+ 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 /`);
1055
+ const response = new Response(null, {
1056
+ status: 303,
1057
+ headers: { location: `${resolved.pathname}${resolved.search}${resolved.hash}` }
1058
+ });
1059
+ headers?.forEach((value, name) => response.headers.append(name, value));
1060
+ response.headers.set("cache-control", "private, no-store");
1061
+ return response;
1062
+ };
1063
+ /**
737
1064
  * What `headers` may not set: what frames the response, which the host's
738
1065
  * server writes, and `location`, which only the entry writes.
739
1066
  */
@@ -846,11 +1173,14 @@ const startOf = (config, options) => Effect.gen(function* () {
846
1173
  */
847
1174
  const preparedStart = (request, config, options, prepare) => Effect.gen(function* () {
848
1175
  const started = yield* startOf(config, options);
849
- const model = yield* Effect.orDie(prepare(started.model, request));
850
- return startingFrom(config, {
851
- ...started,
852
- model
853
- });
1176
+ const model = prepare === void 0 ? started.model : yield* Effect.orDie(prepare(started.model, request));
1177
+ return {
1178
+ model,
1179
+ config: startingFrom(config, {
1180
+ ...started,
1181
+ model
1182
+ })
1183
+ };
854
1184
  });
855
1185
  /**
856
1186
  * Answers a form posted by a page rendered with `fallback: 'server'`: the
@@ -865,7 +1195,8 @@ const handle = (request, config, plan, options) => Effect.map(handleServed(reque
865
1195
  const handleServed = (request, config, plan, options) => Effect.flatMap(postedModel(request, config, plan, options), (model) => renderMatching(startingFrom(config, { model }), plan, {
866
1196
  buildId: options.buildId,
867
1197
  url: request.url,
868
- ...options.styles === void 0 ? {} : { styles: options.styles }
1198
+ ...options.styles === void 0 ? {} : { styles: options.styles },
1199
+ ...options.metaInRoot === true ? { metaInRoot: true } : {}
869
1200
  }, "full"));
870
1201
  /** The Model a posted form reaches: its Message decoded and checked, then `update` and its Commands. */
871
1202
  const postedModel = (request, config, plan, options) => Effect.scoped(Effect.gen(function* () {
@@ -927,9 +1258,13 @@ const SSR = {
927
1258
  hydrate: SSR$1.hydrate,
928
1259
  inspect,
929
1260
  static: staticRegion,
1261
+ unbound,
930
1262
  serving,
931
1263
  generate,
932
1264
  entry,
1265
+ checkCache,
1266
+ keptDocuments,
1267
+ headed,
933
1268
  handle,
934
1269
  serializeJsonScript,
935
1270
  sitemap,