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.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["Diagnostics","Client"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-ssr`: what crosses from the server to the browser when a page is\n * rendered on one and resumed on the other.\n *\n * Built from the plan in `docs/design/ssr-PLAN.md`. A resume plan names the\n * slice of the Model the browser owns. The server writes that slice onto the\n * stamped root as a JSON attribute, beside Foldkit's own stamps; the browser\n * reads it back and sets it onto a baseline\n * Model. Nothing outside the slice crosses, and a payload that cannot be read\n * back exactly is refused, never half-restored.\n *\n * Rendering and hydrating stay Foldkit's own: this package adds only the\n * handover. This module is the server's side and the browser's\n * (`foldkit-ssr/client`) together.\n */\nimport { Cause, Context, Effect, Exit, Layer, Option, Result, Schema } from 'effect'\nimport {\n FOLDKIT_FLAGS_ATTRIBUTE,\n Rendered,\n Responded,\n injectIntoTemplate,\n renderToString,\n type EntryModule,\n type EntryResult,\n type RenderError,\n type RenderedApplication,\n} from 'foldkit/experimental/server'\nimport { Diagnostics, Metadata, type Diagnostic, type MetadataSummary } from 'foldkit-surface'\nimport type { HtmlBuilder } from 'foldkit/html'\nimport type {\n Activation,\n ActiveSurface,\n Projection,\n SurfaceFamily,\n SurfaceSource,\n} from 'foldkit-surface'\nimport { withContext, type Binding, type Region, type UnnamedHandler } from './context.js'\nimport { handlerUnnamed, pageFailed, reportingTo } from './diagnostics.js'\nimport { type EncodedBinding } from './listen.js'\nimport { FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, KEEP_ATTRIBUTE, UNPLACED_KEEP } from './resumable.js'\nimport { requestContext } from './requestContext.js'\nimport { SSR as Client } from './client.js'\nimport {\n PROTOCOL,\n allowedTags,\n attributeOf,\n codecOf,\n modelFrom,\n metaMarkup,\n pathKey,\n plan,\n projectionsOf,\n resume,\n routeOf,\n serializeJsonScript,\n serving,\n startingFrom,\n staticRegion,\n STYLES_MARKER,\n tagOf,\n type Loadable,\n type PlanSurface,\n type ResumableConfig,\n type ResumePlan,\n type RouteMatch,\n} from './shared.js'\n\n/** The projections of the plan's entries that are active for `model`. */\nconst activeProjections = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n) => plan.surfaces.flatMap(source => projectionsOf(source, model))\n\n/** What the envelope carries of a Model: the encoded slice, and each part's capture. */\ninterface Payload {\n readonly state: unknown\n readonly parts?: Readonly<Record<string, unknown>>\n}\n\n/**\n * What the envelope carries of `model`: the plan's slice, encoded through its\n * own Schema, and each part's capture.\n */\nconst payloadOf = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): Payload => {\n const state = Schema.encodeSync(codecOf(plan.state.schema))(plan.state.get(model))\n if (plan.parts.length === 0) return { state }\n const projections = activeProjections(plan, model)\n return {\n state,\n parts: Object.fromEntries(plan.parts.map(part => [part.id, part.capture(model, projections)])),\n }\n}\n\ninterface EnvelopeOptions {\n readonly route?: string | undefined\n readonly match?: RouteMatch | undefined\n readonly bindings?: ReadonlyArray<EncodedBinding> | undefined\n /** Every event the page's markers name, so the browser listens without scanning for them. */\n readonly events?: ReadonlyArray<string> | undefined\n}\n\n/**\n * The envelope for `model`: the plan's slice, each part's capture, and\n * the route it was rendered for, if it was rendered for one. `SSR.render`\n * carries it on the stamped root, beside Foldkit's own stamps, escaped for\n * the attribute; this is the same JSON unescaped, for tests and hosts that\n * place the page themselves.\n */\nconst envelope = <Model, Fields extends Schema.Struct.Fields>(\n resume: ResumePlan<Model, Fields>,\n model: Model,\n options: EnvelopeOptions = {},\n): string => envelopeOf(resume, payloadOf(resume, model), options)\n\n/**\n * The envelope for a payload already built: the JSON the stamped root carries.\n */\nconst envelopeOf = <Model, Fields extends Schema.Struct.Fields>(\n resume: ResumePlan<Model, Fields>,\n payload: Payload,\n options: EnvelopeOptions,\n): string =>\n serializeJsonScript({\n v: PROTOCOL,\n plan: resume.id,\n ...payload,\n ...(options.route === undefined ? {} : { route: options.route }),\n ...(options.match === 'path' ? { match: 'path' } : {}),\n ...(options.bindings === undefined || options.bindings.length === 0\n ? {}\n : { bindings: options.bindings }),\n ...(options.events === undefined || options.events.length === 0\n ? {}\n : { events: options.events }),\n })\n\n/**\n * The rendered application with the envelope on its stamped root, beside\n * Foldkit's own app and build stamps. `injectIntoTemplate` accepts the\n * envelope there, as part of the root, and refuses it beside the root, so a\n * page the host injects carries the handover without the entry owning the\n * template. The browser reads the envelope, then takes the attribute off\n * as the page boots, before Foldkit adopts the server's nodes around it.\n */\nconst withEnvelopeAttribute = (html: string, json: string): string => {\n const stamp = 'data-foldkit-app=\"'\n // The stamp names the root's open tag: it opens the markup, and no quoted\n // attribute value before it may hold a `>` of its own, which would end a\n // naive scan early, or the stamp string itself. A stamp past the tag's end,\n // or in text, is not the root.\n let from = 0\n for (;;) {\n const at = html.indexOf(stamp, from)\n if (at === -1) {\n throw new Error(\n 'foldkit-ssr: the rendered application has no stamped root to carry the resume envelope',\n )\n }\n if (isInRootTag(html, at)) {\n const end = html.indexOf('\"', at + stamp.length)\n if (end === -1) {\n throw new Error(\n 'foldkit-ssr: the rendered application has no stamped root to carry the resume envelope',\n )\n }\n return `${html.slice(0, end + 1)}${attributeOf(json)}${html.slice(end + 1)}`\n }\n from = at + stamp.length\n }\n}\n\n/** Whether `at` sits inside the markup's first tag: quoted values skipped whole. */\nconst isInRootTag = (html: string, at: number): boolean => {\n if (!html.startsWith('<')) return false\n let index = 1\n while (index < at) {\n const char = html[index]\n if (char === '\"' || char === \"'\") {\n const close = html.indexOf(char, index + 1)\n if (close === -1 || close >= at) return false\n index = close + 1\n } else if (char === '>') {\n return false\n } else {\n index++\n }\n }\n return true\n}\n\n/**\n * The rendered markup with `extra` as the root's last children, after the\n * styles marker, so the first paint is styled before any script runs where no\n * template head can take it; `SSR.hydrate` moves them into the head. A void\n * root holds no children: styles for one are refused, naming the tag, rather\n * than served where no browser could keep them.\n */\nconst withInRoot = (html: string, extra: string): Result.Result<string, ResumeUnsafe> => {\n const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1]\n const at = tag === undefined ? -1 : html.search(new RegExp(`</${tag}>\\\\s*$`))\n if (tag === undefined || at === -1) {\n return Result.fail(\n new ResumeUnsafe({\n reason: 'VoidRootWithStyles',\n 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`,\n }),\n )\n }\n return Result.succeed(`${html.slice(0, at)}<!--${STYLES_MARKER}-->${extra}${html.slice(at)}`)\n}\n\n/**\n * The Model the browser will start from when the server's Model is `model`:\n * the payload taken through the page as the envelope carries it, as JSON, and\n * resumed exactly as `SSR.resume` resumes it. A part that cannot restore its\n * own capture fails here, on the server.\n */\nconst browserModelOf = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: Payload,\n): Result.Result<Model, string> => modelFrom(plan, JSON.parse(serializeJsonScript(payload)))\n\n/** Where the browser gets a Model path's value: the envelope, the baseline, or nowhere it may. */\nexport type Cover = 'state' | 'local' | 'missing'\n\n/** One Surface as a plan covers it, for the server's Model. */\nexport interface SurfaceCoverage {\n readonly name: string\n /** Whether the Surface is active for the server's Model. */\n readonly active: boolean\n /** The instance key, for one instance of a `Surface.each` family. */\n readonly key?: string | undefined\n /**\n * The parent a family instance resolves through: the Surface whose Model\n * reveals it, and the place that activates the parent, when readable.\n */\n readonly via?:\n | {\n readonly surface: string\n readonly activation?: { readonly path: string; readonly cover: Cover } | undefined\n }\n | undefined\n /** The place a `Surface.when` activation reads; absent for `Surface.at`. */\n readonly activation?: { readonly path: string; readonly cover: Cover } | undefined\n /** The Model paths the active Surface reads. */\n readonly reads: ReadonlyArray<{ readonly path: string; readonly cover: Cover }>\n /**\n * What the active Surface reads that no Model path names, such as Remote\n * data, by its metadata. The slice cannot carry it.\n */\n readonly unresumed: ReadonlyArray<MetadataSummary>\n /** Whether the browser's Model activates it the same way, with the same reads. */\n readonly sameInBrowser: boolean\n}\n\n/** What a plan sends, what it leaves local, and how it covers each Surface. */\nexport interface PlanInspection {\n readonly id: string\n readonly state: ReadonlyArray<string>\n readonly local: ReadonlyArray<string>\n /** The ids of the parts that resume state the slice cannot carry. */\n readonly parts: ReadonlyArray<string>\n readonly surfaces: ReadonlyArray<SurfaceCoverage>\n}\n\nconst pathOf = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? '(the whole Model)' : path.join('.')\n\n/**\n * A path is covered by a sent or local path equal to it or containing it. An\n * empty path is the whole Model, which no pick covers.\n */\nconst coverOf = (\n path: ReadonlyArray<string>,\n plan: {\n readonly state: { readonly dependencies: ReadonlyArray<ReadonlyArray<string>> }\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n },\n): Cover => {\n const contains = (outer: ReadonlyArray<string>) =>\n outer.length > 0 &&\n outer.length <= path.length &&\n outer.every((key, index) => path[index] === key)\n if (plan.state.dependencies.some(contains)) return 'state'\n if (plan.local.some(contains)) return 'local'\n return 'missing'\n}\n\n/** A projection's reads as one comparable string, or `inactive`. */\nconst readsKey = (\n projection:\n | {\n readonly dependencies: ReadonlyArray<ReadonlyArray<string>>\n readonly metadata: Metadata\n }\n | undefined,\n): string =>\n projection === undefined\n ? 'inactive'\n : JSON.stringify([projection.dependencies, Metadata.summarize(projection.metadata)])\n\n/**\n * How a plan covers each of its Surfaces when the server's Model is `model`.\n * A Surface's reads depend on the Model, through its params, so coverage is\n * worked out for a Model, not for the plan alone.\n */\nconst inspect = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): PlanInspection => {\n const resumed = browserModelOf(plan, payloadOf(plan, model))\n if (Result.isFailure(resumed)) throw new Error(`SSR.inspect: ${resumed.failure}`)\n return coverage(plan, model, resumed.success)\n}\n\n/** How a plan covers its Surfaces, given the server's Model and the browser's. */\nconst coverage = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n browser: Model,\n): PlanInspection => {\n const covered = new Set(plan.parts.flatMap(part => part.covers))\n const families = new Map<ActiveSurface<Model>, Array<Family<Model>>>()\n for (const family of plan.surfaces.flatMap(source => Option.toArray(familyOf(source)))) {\n const siblings = families.get(family.from)\n if (siblings === undefined) families.set(family.from, [family])\n else siblings.push(family)\n }\n // A row is a Surface's identity, not a plan entry: families sharing a\n // parent, or a parent also listed alone, show that parent once.\n const shown = new Set<ActiveSurface<Model>>()\n return {\n id: plan.id,\n state: plan.state.dependencies.map(pathOf),\n local: plan.local.map(pathOf),\n parts: plan.parts.map(part => part.id),\n surfaces: plan.surfaces.flatMap(source => {\n const surface = Option.match(familyOf(source), {\n onNone: () => source as ActiveSurface<Model>,\n onSome: family => family.from,\n })\n if (shown.has(surface)) return []\n shown.add(surface)\n return coverSurface(plan, covered, surface, families.get(surface) ?? [], model, browser)\n }),\n }\n}\n\ntype Family<Model> = SurfaceFamily<Model, unknown, unknown, unknown, unknown>\n\n/** The plan entry as a family with a parent; none for a lone Surface. */\nconst familyOf = <Model>(source: PlanSurface<Model>): Option.Option<Family<Model>> =>\n (source as { readonly from?: ActiveSurface<Model> }).from !== undefined &&\n typeof (source as Partial<SurfaceSource<Model>>).instancesOf === 'function'\n ? Option.some(source as Family<Model>)\n : Option.none()\n\n/** One coverage row: a lone Surface, a family's parent, or one family instance. */\nconst coverRow = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n covered: ReadonlySet<string>,\n entry: {\n readonly name: string\n readonly key?: string | undefined\n readonly via?: SurfaceCoverage['via']\n readonly activation?: Activation | undefined\n },\n served: Projection<Model, unknown> | undefined,\n browserServed: Projection<Model, unknown> | undefined,\n): SurfaceCoverage => ({\n name: entry.name,\n active: served !== undefined,\n ...(entry.key === undefined ? {} : { key: entry.key }),\n ...(entry.via === undefined ? {} : { via: entry.via }),\n ...(entry.activation === undefined\n ? {}\n : {\n activation: {\n path: pathOf(entry.activation.path),\n cover: coverOf(entry.activation.path, plan),\n },\n }),\n reads: (served?.dependencies ?? []).map(path => ({\n path: pathOf(path),\n cover: coverOf(path, plan),\n })),\n unresumed:\n served === undefined\n ? []\n : Metadata.summarize(served.metadata).filter(summary => !covered.has(summary.name)),\n sameInBrowser: readsKey(served) === readsKey(browserServed),\n})\n\n/**\n * A Surface's coverage rows: its own row, then, while it is active, one row\n * per instance of each family it is the parent of. The parent row keeps the\n * parent's reads covered; each instance row says which key it is and which\n * parent reveals it, so a gap names the instance (`Member[u1]`), not just the\n * Surface.\n */\nconst coverSurface = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n covered: ReadonlySet<string>,\n surface: ActiveSurface<Model>,\n families: ReadonlyArray<Family<Model>>,\n model: Model,\n browser: Model,\n): ReadonlyArray<SurfaceCoverage> => {\n const own = coverRow(\n plan,\n covered,\n surface,\n Option.getOrUndefined(surface.projectionOf(model)),\n Option.getOrUndefined(surface.projectionOf(browser)),\n )\n if (!own.active) return [own]\n const via: SurfaceCoverage['via'] = {\n surface: surface.name,\n ...(surface.activation === undefined\n ? {}\n : {\n activation: {\n path: pathOf(surface.activation.path),\n cover: coverOf(surface.activation.path, plan),\n },\n }),\n }\n return [\n own,\n ...families.flatMap(family => {\n const browserInstances = new Map(\n family.instancesOf(browser).map(instance => [instance.key, instance.projection]),\n )\n return family\n .instancesOf(model)\n .map(instance =>\n coverRow(\n plan,\n covered,\n { name: family.name, key: instance.key, via },\n instance.projection,\n browserInstances.get(instance.key),\n ),\n )\n }),\n ]\n}\n\n/** A coverage row as a shortfall names it: `Member[u1]` for an instance, the name alone otherwise. */\nconst displayOf = (surface: SurfaceCoverage): string =>\n surface.key === undefined ? surface.name : `${surface.name}[${surface.key}]`\n\n/** Each way an inspection shows the plan falls short, one line each. */\nconst shortfalls = (inspection: PlanInspection): ReadonlyArray<string> =>\n inspection.surfaces.flatMap(surface => [\n ...(surface.activation?.cover === 'missing'\n ? [\n `Surface \"${displayOf(surface)}\" is activated by ${surface.activation.path}, which is neither in the plan's state nor local`,\n ]\n : []),\n ...surface.reads\n .filter(read => read.cover === 'missing')\n .map(\n read =>\n `Surface \"${displayOf(surface)}\" reads ${read.path}, which is neither in the plan's state nor local`,\n ),\n ...surface.unresumed.map(\n summary =>\n `Surface \"${displayOf(surface)}\" reads ${summary.name} data (${summary.entries.join(', ')}), which no part of the plan resumes`,\n ),\n ...(surface.sameInBrowser\n ? []\n : [\n `Surface \"${displayOf(surface)}\" is ${surface.active ? 'active' : 'inactive'} on the server and activates differently from the Model the browser starts from`,\n ]),\n ])\n\n/** Why a server refused to render a page against its plan. */\nexport class ResumeUnsafe extends Schema.TaggedError<ResumeUnsafe>()('ResumeUnsafe', {\n reason: Schema.Literals([\n 'UndeclaredStartup',\n 'Uncovered',\n 'ViewDependsOnUnsentState',\n 'DuplicateStaticRegion',\n 'UngeneratablePath',\n 'UnrestorablePart',\n 'UnencodableBinding',\n 'EagerStartRequired',\n 'UndeclaredSurfaces',\n 'BindingInStaticRegion',\n 'VoidRootWithStyles',\n 'UnkeepableField',\n ]),\n message: Schema.String,\n}) {}\n\n/** Each binding whose Message no active Surface lists, one line each. */\nconst unlistedBindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n bindings: ReadonlyArray<Binding>,\n): ReadonlyArray<string> => {\n const allowed = allowedTags(plan, model)\n return bindings\n .filter(binding => !allowed.has(tagOf(binding.message)))\n .map(\n binding =>\n `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`,\n )\n}\n\n/**\n * A line for each `KeepTyped` the render drew on an element the resumable\n * builder did not build, whose marker still holds its server-render value:\n * nothing marks which binding replays such a field, so every browser would\n * refuse the page. Foldkit escapes `<` in text and attribute values, so the\n * last `<` before the marker opens its element.\n */\nconst unplacedKeeps = (html: string): ReadonlyArray<string> => {\n const marker = `${KEEP_ATTRIBUTE}=\"${UNPLACED_KEEP}\"`\n const found: Array<string> = []\n for (let at = html.indexOf(marker); at !== -1; at = html.indexOf(marker, at + 1)) {\n const open = html.lastIndexOf('<', at)\n const tag = /^<([A-Za-z][A-Za-z0-9._-]*)/.exec(html.slice(open))?.[1] ?? 'an element'\n const id = /\\sid=\"([^\"]*)\"/.exec(html.slice(open, html.indexOf('>', at)))?.[1]\n found.push(\n `KeepTyped on ${id === undefined ? tag : `${tag}#${id}`}, which Resume.builder did not build, so nothing marks the binding its typing replays as: build the element with the resumable builder (rh.input), not h`,\n )\n }\n return found\n}\n\n/** Loads every lazy bundle's bodies, so the view renders whole. */\nconst loadLazy = (config: { readonly lazy?: ReadonlyArray<Loadable> | undefined }) =>\n Effect.promise(() => Promise.all((config.lazy ?? []).map(bundle => bundle.load())))\n\n/** Foldkit's own Flags script, which a resumed page never carries. */\nconst FLAGS_SCRIPT = new RegExp(\n `<script[^>]*${FOLDKIT_FLAGS_ATTRIBUTE}[^>]*>[\\\\s\\\\S]*?</script>`,\n 'g',\n)\n\n/**\n * The head fields a render returns beside the body. Each is read by the view,\n * so each must come out the same from the browser's Model; since Foldkit 0.163\n * none has a default from the URL.\n */\nconst HEAD_FIELDS = ['title', 'lang', 'dir', 'canonical', 'ogUrl'] as const\n\n/** A render's bindings, encoded, or why one cannot be. */\nconst encodeBindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n bindings: ReadonlyArray<Binding>,\n): Result.Result<ReadonlyArray<EncodedBinding>, string> => {\n if (bindings.length === 0) return Result.succeed([])\n if (plan.Message === undefined) {\n return Result.fail(\n 'the page has bindings, and the plan has no Message Schema to encode them with: make the plan from the application',\n )\n }\n const encode = Schema.encodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n const out: Array<EncodedBinding> = []\n for (const binding of bindings) {\n const message = encode(binding.message)\n if (Result.isFailure(message)) {\n return Result.fail(\n `the ${binding.event} binding on ${binding.element} does not encode as a Message: ${message.failure.message}`,\n )\n }\n out.push({\n attribute: binding.attribute,\n message: message.success,\n ...(binding.hole === undefined ? {} : { hole: binding.hole }),\n ...(binding.depth === undefined ? {} : { depth: binding.depth }),\n ...(binding.options === undefined ? {} : { options: binding.options }),\n })\n }\n return Result.succeed(out)\n}\n\n/**\n * The bindings that differ between the server's render and the browser's, by\n * element: a Message built from a field the plan does not send would dispatch\n * one Message before boot and another after.\n */\nconst changedBindings = (\n served: ReadonlyArray<Binding>,\n encoded: ReadonlyArray<EncodedBinding>,\n reencoded: ReadonlyArray<EncodedBinding>,\n): ReadonlyArray<string> =>\n served.flatMap((binding, index) =>\n JSON.stringify(encoded[index]) === JSON.stringify(reencoded[index])\n ? []\n : [`${binding.event} binding on ${binding.element}`],\n )\n\n/**\n * The Subscription and Managed Resource entries that would start late under a\n * deferred boot and are not declared deferrable, by the plan or by a part.\n * Foldkit starts every Subscription's stream at boot, so every entry counts; a\n * Managed Resource counts when the Model asks for it.\n */\nconst eagerEntries = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlyArray<string> => {\n if (plan.start === 'now') return []\n const declared = (key: string, entry: unknown) =>\n plan.deferrable.includes(key) || plan.parts.some(part => part.deferrable?.(key, entry) === true)\n const subscriptions = Object.entries(config.subscriptions ?? {}).filter(\n ([key, entry]) => !declared(key, entry),\n )\n const resources = Object.entries(config.managedResources ?? {}).filter(([key, entry]) => {\n const asks = (\n entry as { modelToMaybeRequirements?: (model: Model) => unknown }\n ).modelToMaybeRequirements?.(model)\n const active = Option.isOption(asks) ? Option.isSome(asks) : asks !== undefined\n return active && !declared(key, entry)\n })\n return [\n ...subscriptions.map(([key]) => `subscription \"${key}\"`),\n ...resources.map(([key]) => `resource \"${key}\"`),\n ]\n}\n\n/** A page the server rendered against a plan, with its envelope. */\nexport interface RenderedPage {\n /**\n * The rendered application with the envelope on its stamped root, so\n * Foldkit's `injectIntoTemplate` places the page whole: the host owns the\n * template, and the entry never splices markup into it.\n */\n readonly rendered: RenderedApplication\n /** The envelope, as carried on the root, for tests and custom hosts. */\n readonly envelope: string\n /** The head markup of the plan's `meta`, empty without one. */\n readonly meta: string\n /**\n * Each element whose handler for an event is a function, marked `*`: the\n * page cannot answer that event before the live runtime boots.\n */\n readonly unnamed: ReadonlyArray<UnnamedHandler>\n}\n\n/**\n * Renders a page on the server against a resume plan.\n *\n * The application's `init` runs once. Its Model's slice is round-tripped\n * through the plan's Schema and set onto the baseline, which is the Model the\n * browser will start from, and the page is rendered from that Model. Every\n * way the browser could start somewhere else is a `ResumeUnsafe`, whose\n * `reason` names it; the README lists them. The one that matters most: the\n * view rendered from the browser's Model differs from the one rendered from\n * the server's, because it reads a field the plan leaves out. In production\n * Foldkit would rebuild that part of the page silently, so this is the one\n * place it shows.\n */\nconst render = <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 readonly url?: string | undefined\n readonly flags?: unknown\n /**\n * Markup for the first paint, given what was rendered, carried as the\n * root's last children: `<style>` (or a stylesheet `<link>`), which\n * `SSR.hydrate` moves into the head before adopting the page. Anything\n * else a head owns (`meta`) stays with `SSR.page` and `SSR.generate`.\n */\n readonly styles?: Head | undefined\n },\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe> =>\n Effect.map(renderMatching(config, plan, options, 'full'), served => served.page)\n\n/** A rendered page, with the Model the server's `init` (or a post) reached. */\ninterface Served<Model> {\n readonly page: RenderedPage\n readonly model: Model\n}\n\nconst renderMatching = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly url?: string | undefined\n readonly flags?: unknown\n readonly styles?: Head | undefined\n },\n match: RouteMatch,\n): Effect.Effect<Served<Model>, RenderError | ResumeUnsafe> =>\n Effect.gen(function* () {\n yield* loadLazy(config)\n let served: ReturnType<ResumableConfig<Model>['init']> | undefined\n const regions = new Map<string, Region>()\n const duplicates = new Set<string>()\n const servedBindings: Array<Binding> = []\n const browserBindings: Array<Binding> = []\n const inStatic: Array<{ region: string; element: string; event: string }> = []\n const unnamed: Array<UnnamedHandler> = []\n const unkeepable: Array<string> = []\n const fallback = fallbackEncoder(plan)\n const capturing = withContext(\n { ...config, init: (...args: ReadonlyArray<unknown>) => (served = config.init(...args)) },\n {\n mode: 'collect',\n regions,\n duplicates,\n bindings: servedBindings,\n fallback,\n wrap: message => message,\n depth: 0,\n region: undefined,\n inStatic,\n unnamed,\n unkeepable,\n },\n )\n const full = yield* renderToString(capturing as never, options as never)\n unkeepable.push(...unplacedKeeps(full.html))\n if (duplicates.size > 0) {\n return yield* new ResumeUnsafe({\n reason: 'DuplicateStaticRegion',\n message: `two static regions share the id ${[...duplicates].map(id => `\"${id}\"`).join(', ')}: the browser could adopt only one`,\n })\n }\n if (inStatic.length > 0) {\n const found = inStatic.map(\n ({ region, element, event }) => `a ${event} handler on ${element} in \"${region}\"`,\n )\n return yield* new ResumeUnsafe({\n reason: 'BindingInStaticRegion',\n message: `a static region is the server's alone, and these would never run: ${found.join(', ')}. What a Message changes belongs in a Surface`,\n })\n }\n if (unkeepable.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'UnkeepableField',\n message: `the page cannot keep what is typed into these fields before it boots:\\n- ${unkeepable.join('\\n- ')}`,\n })\n }\n const started = served!\n const commands = started.commands ?? []\n if (commands.length > 0 && plan.boot === undefined) {\n return yield* new ResumeUnsafe({\n reason: 'UndeclaredStartup',\n message: `init returned ${commands.map(command => command.name).join(', ')}, which no browser would run: name them in the plan's boot`,\n })\n }\n\n // Built once: each part's capture reads the whole store it owns.\n const payload = payloadOf(plan, started.model)\n const resumed = browserModelOf(plan, payload)\n if (Result.isFailure(resumed)) {\n return yield* new ResumeUnsafe({ reason: 'UnrestorablePart', message: resumed.failure })\n }\n const browser = resumed.success\n\n const eager = eagerEntries(config, plan, started.model)\n if (eager.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'EagerStartRequired',\n message: `the plan starts ${plan.start}, and these would start late: ${eager.join(', ')}. Name each in the plan's deferrable, or start now`,\n })\n }\n\n if (servedBindings.length > 0 && plan.surfaces.length === 0) {\n return yield* new ResumeUnsafe({\n reason: 'UndeclaredSurfaces',\n message: `the page has ${servedBindings.length} binding${servedBindings.length === 1 ? '' : 's'} and the plan declares no surfaces, so nothing says which Messages it may dispatch: name them in the plan's surfaces`,\n })\n }\n const uncovered = [\n ...shortfalls(coverage(plan, started.model, browser)),\n ...unlistedBindings(plan, started.model, servedBindings),\n ]\n if (uncovered.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'Uncovered',\n message: `the plan does not cover what the browser reads:\\n- ${uncovered.join('\\n- ')}`,\n })\n }\n\n // With no `Flags` key in the config, Foldkit writes no Flags script.\n const rendered = yield* renderToString(\n withContext(startingFrom(config, { model: browser }), {\n mode: 'replay',\n regions,\n bindings: browserBindings,\n fallback,\n wrap: message => message,\n depth: 0,\n }) as never,\n options as never,\n )\n const encoded = encodeBindings(plan, servedBindings)\n const reencoded = encodeBindings(plan, browserBindings)\n if (Result.isFailure(encoded)) {\n return yield* new ResumeUnsafe({ reason: 'UnencodableBinding', message: encoded.failure })\n }\n const meta = plan.meta === undefined ? '' : metaMarkup(plan.meta(started.model))\n const differing = [\n ...(full.html.replace(FLAGS_SCRIPT, '') === rendered.html ? [] : ['body']),\n ...HEAD_FIELDS.filter(field => full[field] !== rendered[field]),\n ...(plan.meta === undefined || metaMarkup(plan.meta(browser)) === meta ? [] : ['meta']),\n ...changedBindings(\n servedBindings,\n encoded.success,\n Result.isFailure(reencoded) ? [] : reencoded.success,\n ),\n ]\n if (differing.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'ViewDependsOnUnsentState',\n message: `the view differs in its ${differing.join(', ')} when rendered from the Model the browser will start from: it reads a field the plan leaves out`,\n })\n }\n const envelope = envelopeOf(plan, payload, {\n ...(options.url === undefined\n ? {}\n : { route: match === 'path' ? pathKey(routeOf(options.url)) : routeOf(options.url) }),\n match,\n bindings: encoded.success,\n events: [\n ...new Set([\n ...servedBindings.map(binding => binding.event),\n ...unnamed.map(handler => handler.event),\n ]),\n ].sort(),\n })\n const styled =\n options.styles === undefined\n ? Result.succeed(rendered.html)\n : withInRoot(rendered.html, options.styles(rendered))\n if (Result.isFailure(styled)) return yield* styled.failure\n return {\n page: {\n rendered: { ...rendered, html: withEnvelopeAttribute(styled.success, envelope) },\n meta,\n envelope,\n unnamed,\n },\n model: started.model,\n }\n })\n\n/**\n * What a page adds to its head, given what it rendered: such as a stylesheet\n * of the classes the markup uses (`Style.usedIn` in `foldkit-mixins`). The\n * same shape describes `styles`, which rides in the rendered root instead,\n * for pages whose template the host owns.\n */\nexport type Head = (rendered: RenderedApplication) => string\n\n/**\n * The template with `extra` before its last `</head>`, as a slice for the same\n * reason as the envelope. Nothing to add leaves it as it is; something to add\n * and no `</head>` is refused, rather than dropped.\n */\nconst withHead = (template: string, extra: string): string => {\n if (extra === '') return template\n const at = template.search(/<\\/head>(?![\\s\\S]*<\\/head>)/i)\n if (at === -1) throw new Error('foldkit-ssr: the template has no </head> to put the head in')\n return `${template.slice(0, at)}${extra}${template.slice(at)}`\n}\n\n/**\n * Foldkit fills `canonical` and `og:url` only into a tag the template already\n * has, and leaves the page without one otherwise. A render that sets either\n * and a template without its tag is refused, naming the tag.\n */\nconst FILLED_TAGS = [\n {\n field: 'canonical',\n tag: '<link rel=\"canonical\" href=\"\">',\n at: /<link\\b[^>]*\\brel\\s*=\\s*[\"']?canonical[\"'\\s>]/i,\n },\n {\n field: 'ogUrl',\n tag: '<meta property=\"og:url\" content=\"\">',\n at: /<meta\\b[^>]*\\bproperty\\s*=\\s*[\"']?og:url[\"'\\s>]/i,\n },\n] as const\n\nconst withFilledTags = (template: string, rendered: RenderedApplication): string => {\n const missing = FILLED_TAGS.filter(\n ({ field, at }) => rendered[field] !== undefined && !at.test(template),\n )\n if (missing.length > 0) {\n throw new Error(\n `foldkit-ssr: the view sets ${missing.map(({ field }) => field).join(' and ')}, and the template has no ${missing.map(({ tag }) => tag).join(' or ')} for Foldkit to fill: add it to the template's head`,\n )\n }\n return template\n}\n\n/** The plan's `meta`, then what `head` adds, one line apart. */\nconst headOf = (\n result: { readonly rendered: RenderedApplication; readonly meta: string },\n head: Head | undefined,\n): string => [result.meta, head?.(result.rendered) ?? ''].filter(markup => markup !== '').join('\\n')\n\n/**\n * The page to serve: the rendered application in the template, with the\n * plan's `meta` and `head`'s markup, if any, before `</head>`. The envelope\n * is already in the rendered root, so this is Foldkit's `injectIntoTemplate`\n * with a head, and nothing else.\n */\nconst page = (\n template: string,\n result: { readonly rendered: RenderedApplication; readonly meta: string },\n options: { readonly head?: Head | undefined } = {},\n): string =>\n injectIntoTemplate(\n withHead(withFilledTags(template, result.rendered), headOf(result, options.head)),\n result.rendered,\n )\n\n/** A page generated at build time, and the file a static host serves it from. */\nexport interface GeneratedPage {\n readonly path: string\n readonly file: string\n readonly html: string\n}\n\n/**\n * One generated page per path, in the paths' order: a tuple when the paths\n * are written out, so `const [home, about] = pages` needs no check.\n */\nexport type GeneratedPages<Paths extends ReadonlyArray<string>> = {\n readonly [K in keyof Paths]: GeneratedPage\n}\n\n/** The file a static host serves for a path: `/about` is `about/index.html`. */\nconst fileOf = (path: string): string => {\n const trimmed = path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n if (trimmed === '') return 'index.html'\n return trimmed.endsWith('.html') ? trimmed : `${trimmed}/index.html`\n}\n\nconst xmlText = (text: string): string =>\n text\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll(\"'\", '&apos;')\n\n/**\n * A sitemap of the pages a build generated, each at its full address under\n * `origin`, in the order given. `modified`, when a page has it, is any date\n * `Date` reads, written as the UTC day. A path that does not start with `/`,\n * a path given twice, and a date `Date` cannot read are refused: each would\n * make a sitemap a search engine rejects or misreads.\n */\nconst sitemap = (\n pages: ReadonlyArray<{ readonly path: string; readonly modified?: string | undefined }>,\n options: { readonly origin: string },\n): string => {\n const seen = new Set<string>()\n const urls = pages.map(({ path, modified }) => {\n if (!path.startsWith('/')) throw new Error(`SSR.sitemap: \"${path}\" does not start with /`)\n if (seen.has(path)) throw new Error(`SSR.sitemap: \"${path}\" is listed twice`)\n seen.add(path)\n const loc = `<loc>${xmlText(new URL(path, options.origin).href)}</loc>`\n if (modified === undefined) return ` <url>${loc}</url>`\n const at = new Date(modified)\n if (Number.isNaN(at.getTime())) {\n throw new Error(`SSR.sitemap: \"${modified}\", the date of \"${path}\", is not a date`)\n }\n return ` <url>${loc}<lastmod>${at.toISOString().slice(0, 10)}</lastmod></url>`\n })\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">',\n ...urls,\n '</urlset>',\n '',\n ].join('\\n')\n}\n\n/**\n * A `robots.txt` that lets every crawler in, except under `disallow`, and\n * names the sitemap at `sitemap` (default `/sitemap.xml`) under `origin`.\n */\nconst robots = (options: {\n readonly origin: string\n readonly sitemap?: string | undefined\n readonly disallow?: ReadonlyArray<string> | undefined\n}): string =>\n [\n 'User-agent: *',\n 'Allow: /',\n ...(options.disallow ?? []).map(path => `Disallow: ${path}`),\n '',\n `Sitemap: ${new URL(options.sitemap ?? '/sitemap.xml', options.origin).href}`,\n '',\n ].join('\\n')\n\n// Keyed by plan, element and event: a server renders the same page for every\n// request, so one report each is enough to learn which handler to name.\nconst reportedUnnamed = new Set<string>()\n\n/**\n * Reports, once per process, each handler that keeps a page from answering\n * before boot. Only a page that waits to boot is held up: one started\n * `'now'`, with no lazy bundle to load, boots before any event.\n */\nconst reportUnnamed = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n unnamed: ReadonlyArray<UnnamedHandler>,\n): Effect.Effect<void> =>\n Effect.suspend(() => {\n if (plan.start === 'now' && (config.lazy ?? []).length === 0) return Effect.void\n const first = unnamed.filter(({ element, event }) => {\n const key = JSON.stringify([plan.id, element, event])\n if (reportedUnnamed.has(key)) return false\n reportedUnnamed.add(key)\n return true\n })\n return Effect.forEach(\n first,\n ({ element, event }) => Diagnostics.report(handlerUnnamed(plan.id, element, event)),\n { discard: true },\n )\n })\n\n/**\n * Renders pages at build time, one per path, each as `SSR.render` and\n * `SSR.page` would, to be written as files. `origin` makes each path the full\n * URL a routing application parses. `flags`, when the application has them,\n * gives each path its own.\n *\n * A generated page records its path alone: a static host serves the same file\n * whatever the query, so the browser checks the path and ignores the query. A\n * path with a query or fragment, or two paths that would be one file, are\n * refused.\n */\nconst generate = <\n Model,\n Fields extends Schema.Struct.Fields,\n const Paths extends ReadonlyArray<string>,\n Message = any,\n>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly template: string\n readonly origin: string\n readonly paths: Paths\n readonly flags?: ((path: string) => unknown) | undefined\n readonly head?: Head | undefined\n },\n): Effect.Effect<GeneratedPages<Paths>, RenderError | ResumeUnsafe> =>\n Effect.gen(function* () {\n const files = new Map<string, string>()\n for (const path of options.paths) {\n if (!path.startsWith('/') || /[?#]/.test(path)) {\n return yield* new ResumeUnsafe({\n reason: 'UngeneratablePath',\n message: `\"${path}\" is not a path a file can be served at: start it with / and leave out any query or fragment`,\n })\n }\n const other = files.get(fileOf(path))\n if (other !== undefined) {\n return yield* new ResumeUnsafe({\n reason: 'UngeneratablePath',\n message: `\"${other}\" and \"${path}\" would both be written to ${fileOf(path)}`,\n })\n }\n files.set(fileOf(path), path)\n }\n const pages = yield* Effect.forEach(options.paths, path =>\n renderMatching(\n config,\n plan,\n {\n buildId: options.buildId,\n url: new URL(path, options.origin).href,\n ...(options.flags === undefined ? {} : { flags: options.flags(path) }),\n },\n 'path',\n ).pipe(\n Effect.map(served => served.page),\n Effect.tap(result => reportUnnamed(config, plan, result.unnamed)),\n Effect.map(result => ({\n path,\n file: fileOf(path),\n html: page(options.template, result, { head: options.head }),\n })),\n ),\n )\n // One page per path, in order, so the array is the tuple the paths describe.\n return pages as unknown as GeneratedPages<Paths>\n })\n\n/**\n * The server entry for Foldkit's pipeline: the `renderPage` a dev server,\n * a fetch handler, or `handleRequest` calls, and that the `fetch.js` a Foldkit\n * build emits imports from the server entry module, so a resumed page is\n * served by Node and Workers alike.\n *\n * `GET` and `HEAD` render the page against the plan, with the request's URL\n * and, when the application has Flags, `flags(request)`; `prepare(model,\n * request)` turns the Model `init` gave into the one rendered, a read made\n * before the render (`Data.satisfy`). `POST` goes to\n * `SSR.handle` when the plan has a server fallback, and is answered `400` when\n * the post is unusable. `OPTIONS` is answered `204`, and any other method\n * `405`, each with the methods the entry answers in `allow` (`handleRequest`\n * passes every method through). A render that fails, or a plan the render\n * refuses, is answered `500` with the reason reported (`diagnostics`), never with a page the\n * browser cannot resume. `headers(request, model)` is set over Foldkit's own\n * on every answer: a cache policy, a CORS answer to a preflight, or a cookie\n * written from the Model a post reached. `status(model, request)` gives a page\n * its status from that Model, `404` for a route not found.\n *\n * The page is answered as `Rendered`: the rendered application carries the\n * envelope in its root, so the host injects it into its own template with\n * Foldkit's `injectIntoTemplate`, and a build can generate it with Foldkit's\n * `prerender`. The template, and the container it fills, are the host's:\n * `handleRequest` still classifies static misses and answers `HEAD` without\n * a body.\n *\n * What the page says of itself (`meta`) and per-page `head` markup are\n * written into a template's head, which the host owns here: a plan with\n * `meta` is refused when the entry is made, and served with `SSR.generate`.\n */\nconst entry = <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 readonly flags?: ((request: Request) => unknown | PromiseLike<unknown>) | undefined\n /**\n * The Model a request starts from, from the one `init` gave: what the page\n * shows read first (`Data.satisfy`), or what the request carries (a\n * cookie). Run for `GET`, `HEAD` and a posted form, before the post's\n * Message is checked or `update` runs, so the entry is made once. A\n * failure is answered `500` and reported; to draw the page unread\n * instead, recover inside the Effect.\n */\n readonly prepare?: Prepare<Model> | undefined\n /**\n * Headers set over the entry's own on every answer. `model` is the Model\n * the server reached for a rendered page, a posted form's after `update`;\n * it is `none` for an answer that rendered nothing (`OPTIONS`, `405`, a\n * refused post, a `500`). So a cookie kept from the Model is written here.\n * A name or value no `Headers` takes (a CR or LF in a value), a header that\n * frames the response (`content-length`, `transfer-encoding`, `connection`\n * and the like) or `location`, which only the entry writes, is answered\n * `500` and reported, as `headers` that throw are.\n */\n readonly headers?: ((request: Request, model: Option.Option<Model>) => HeadersInit) | undefined\n /**\n * A posted form's own services, from its request (who is asking, a\n * client bound to them), for the Commands the fallback runs; where one is\n * also the config's, the request's is used. A render runs no Command, so\n * it reads the request through `flags`. The Layer may neither fail nor\n * need a service: one that refuses who is asking (a session that ended)\n * decides before this, in the host, or dies here into a 500.\n */\n readonly resources?: ((request: Request) => Layer.Layer<never, never, never>) | undefined\n /**\n * The origins a form may be posted from, required by a plan with a server\n * fallback: a post whose `Origin` (which\n * every browser sends on one) is not among them is a 403 before its body\n * is read, so a page elsewhere cannot post as someone signed in here. A\n * form cannot carry a CSRF header; this is its check. A post with no\n * `Origin` or `Origin: null` (a page served with `Referrer-Policy:\n * no-referrer`) is taken when `Sec-Fetch-Site` says `same-origin`. Each must be an origin exactly as\n * a browser sends it (`https://example.com`). `'same-origin'` takes a\n * post from the origin the request was addressed to and no other, for a\n * site served at addresses not known when the entry is made (a dev\n * server's port). It compares with the request's own URL, so behind a\n * proxy that terminates TLS (the server sees `http://`, the browser\n * sends `Origin: https://`) or rewrites the host, every post is refused\n * 403: there, name the public origin (`['https://example.com']`).\n */\n readonly origins?: ReadonlyArray<string> | 'same-origin' | undefined\n /**\n * Markup for the first paint, carried as the rendered root's last\n * children, which `SSR.hydrate` moves into the head. The host owns the\n * template in dynamic serving, so this is where per-page styles go;\n * anything else a head owns stays with `SSR.generate`.\n */\n readonly styles?: Head | undefined\n /**\n * The status a rendered page is answered with, from the Model the server\n * reached and the request: `404` for a route the Model says is not found.\n * Omitted, every page is `200`. One outside `200`–`599`, or a `status`\n * that throws, is answered `500` and reported, as a failed render is.\n */\n readonly status?: ((model: Model, request: Request) => number) | undefined\n /**\n * How a posted form is answered. `'page'`, the default, is the page\n * `update` reached, at the address the form posted to, so a reload posts\n * again. `'redirect'` is a `303` to that address, which the browser then\n * asks for with a `GET` (Post/Redirect/Get): what the post changed must\n * outlive it where the next request reads it, a cookie `headers` writes\n * from the Model the post reached. A refused post is still a `400`.\n */\n readonly answerPost?: 'page' | 'redirect' | undefined\n /**\n * The paths a build prerenders through this entry (Foldkit's plugin,\n * `ssr.build.prerender`), whose files a static host serves for every\n * query. A request for one of them with no query records its path alone,\n * as `SSR.generate` does, so the file resumes at `/?q=…` and the\n * application starts from that URL. Export the same list as the entry\n * module's `prerenderPaths`, which the plugin reads.\n */\n readonly prerendered?: ReadonlyArray<string> | undefined\n /**\n * Where this request's diagnostics go, with the request: a request\n * answered 500 (`PageFailed`), a handler the page cannot name, and what\n * a posted form's Commands report. The reporter in the Effect context\n * (`Diagnostics.Reporter`) when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n },\n): EntryModule => {\n if (plan.meta !== undefined) {\n throw new Error(\n `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`,\n )\n }\n const listed = options.origins === 'same-origin' ? [] : (options.origins ?? [])\n for (const origin of listed) {\n if (!URL.canParse(origin) || new URL(origin).origin !== origin)\n throw new Error(`foldkit-ssr: ${JSON.stringify(origin)} in origins is not an origin`)\n }\n // A post runs `flags`, the config's resources and the post's own, any of\n // which may act as whoever the cookie says posted.\n if (options.answerPost !== undefined && plan.fallback !== 'server') {\n throw new Error(\n `foldkit-ssr: plan \"${plan.id}\" has no server fallback, so no form is posted to answer (answerPost)`,\n )\n }\n if (plan.fallback === 'server' && options.origins === undefined) {\n throw new Error(\n `foldkit-ssr: plan \"${plan.id}\" handles posted forms, which run as whoever posted; name the origins a form may be posted from (origins)`,\n )\n }\n for (const path of options.prerendered ?? []) {\n if (!path.startsWith('/') || /[?#]/.test(path)) {\n throw new Error(\n `foldkit-ssr: \"${path}\" in prerendered is not a path a file can be served at: start it with / and leave out any query or fragment`,\n )\n }\n }\n const prerendered = new Set((options.prerendered ?? []).map(pathKey))\n // A file a static host serves whatever the query, read for no query.\n const matchOf = (url: string): RouteMatch => {\n const route = routeOf(url)\n return !route.includes('?') && prerendered.has(pathKey(route)) ? 'path' : 'full'\n }\n // Required above for every plan that takes a post, the only reader of it.\n const origins = new Set(listed)\n const originsOf = (request: Request): ReadonlySet<string> =>\n options.origins === 'same-origin' ? new Set([new URL(request.url).origin]) : origins\n const allow = plan.fallback === 'server' ? 'GET, HEAD, POST, OPTIONS' : 'GET, HEAD, OPTIONS'\n // Deleted and appended rather than set, which would keep one `set-cookie` of several.\n const merge = (response: Response, extra: Headers): Response => {\n for (const name of new Set(extra.keys())) response.headers.delete(name)\n extra.forEach((value, name) => response.headers.append(name, value))\n return response\n }\n // `Headers` refuses a name that is no token and a value holding CR, LF or NUL.\n const headersOf = (request: Request, model: Option.Option<Model>): Headers | undefined => {\n if (options.headers === undefined) return undefined\n const headers = new Headers(options.headers(request, model))\n for (const name of headers.keys()) {\n if (ENTRY_HEADERS.has(name)) {\n throw new Error(`headers set ${name}, which the entry writes and an application may not`)\n }\n }\n return headers\n }\n const answer = async (request: Request): Promise<EntryResult> => {\n const method = request.method.toUpperCase()\n const posting = method === 'POST' && plan.fallback === 'server'\n const { diagnostics } = options\n const reporting = reportingTo(\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request),\n )\n // An answer that rendered nothing, with the headers given no Model. A 500\n // is reported already, so `headers` failing again for it is not.\n const responded = async (\n response: Response,\n { reported = false } = {},\n ): Promise<EntryResult> => {\n let extra: Headers | undefined\n try {\n extra = headersOf(request, Option.none())\n } catch (error) {\n if (!reported) {\n await Effect.runPromise(\n reporting(Diagnostics.report(pageFailed(request.url, Cause.die(error)))),\n )\n }\n return Responded(plainText(500, 'The page could not be rendered.'))\n }\n return Responded(extra === undefined ? response : merge(response, extra))\n }\n if (method === 'OPTIONS')\n return responded(new Response(null, { status: 204, headers: { allow } }))\n if (method !== 'GET' && method !== 'HEAD' && !posting) {\n return responded(new Response(null, { status: 405, headers: { allow } }))\n }\n if (posting && !postedFrom(request, originsOf(request))) {\n return responded(plainText(403, 'The form was not posted from this site.'))\n }\n const flagsOf = options.flags\n const statusOf = options.status\n const { prepare } = options\n const styled = options.styles === undefined ? {} : { styles: options.styles }\n // `Effect.result` would miss a defect, such as a view that throws, and a\n // `flags` that throws or rejects is not in the Effect at all: both would\n // reject `renderPage` instead of answering it.\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n const flags =\n flagsOf === undefined ? undefined : yield* Effect.tryPromise(async () => flagsOf(request))\n const flagged = flagsOf === undefined ? {} : { flags }\n const prepared = prepare === undefined ? {} : { prepare }\n // Built for a post alone: a GET runs no Command, and no `resources`.\n const post = () => ({\n buildId: options.buildId,\n ...flagged,\n ...styled,\n ...prepared,\n ...(options.resources === undefined ? {} : { resources: options.resources(request) }),\n })\n if (posting && options.answerPost === 'redirect') {\n const model = yield* postedModel(request, config, plan, post())\n const extra = yield* Effect.sync(() => headersOf(request, Option.some(model)))\n const redirect = new Response(null, {\n status: 303,\n headers: { location: sameAddress(request.url) },\n })\n return Responded(extra === undefined ? redirect : merge(redirect, extra))\n }\n const served = posting\n ? yield* handleServed(request, config, plan, post())\n : yield* renderMatching(\n prepare === undefined\n ? config\n : yield* preparedStart(request, config, { url: request.url, ...flagged }, prepare),\n plan,\n { buildId: options.buildId, url: request.url, ...flagged, ...styled },\n matchOf(request.url),\n )\n // `headers` or `status` that throws is a defect, answered 500 and reported.\n const extra = yield* Effect.sync(() => headersOf(request, Option.some(served.model)))\n const status = Option.map(Option.fromUndefinedOr(statusOf), of => of(served.model, request))\n const unanswerable = Option.filter(\n status,\n given => !Number.isInteger(given) || given < 200 || given > 599,\n )\n if (Option.isSome(unanswerable)) {\n return yield* Effect.die(\n new Error(\n `status gave ${unanswerable.value} for the page, which is no status between 200 and 599`,\n ),\n )\n }\n yield* reportUnnamed(config, plan, served.page.unnamed)\n // No `headers` or `status` key unless given: a `Rendered` that carries\n // neither stays generatable as a static file.\n return Rendered(served.page.rendered, {\n ...(extra === undefined ? {} : { headers: extra }),\n ...Option.match(status, { onNone: () => ({}), onSome: status => ({ status }) }),\n })\n }).pipe(reporting),\n )\n if (Exit.isFailure(exit)) {\n const refused = Cause.findErrorOption(exit.cause).pipe(\n Option.filter(error => error instanceof FallbackRefused),\n )\n if (Option.isSome(refused)) {\n return responded(plainText(400, `The form could not be handled: ${refused.value.message}`))\n }\n await Effect.runPromise(reporting(Diagnostics.report(pageFailed(request.url, exit.cause))))\n return responded(plainText(500, 'The page could not be rendered.'), { reported: true })\n }\n return exit.value\n }\n return { renderPage: answer }\n}\n\n/**\n * Where a post's answer sends the browser: the address it posted to, its path\n * and query alone. Relative, so the browser resolves it against that address\n * and it names no other origin, whatever `Host` the request claimed; leading\n * slashes collapse to one, since `//elsewhere.test/` would name another host.\n */\nconst sameAddress = (url: string): string => {\n const { pathname, search } = new URL(url)\n return `${pathname.replace(/^\\/+/, '/')}${search}`\n}\n\n/**\n * What `headers` may not set: what frames the response, which the host's\n * server writes, and `location`, which only the entry writes.\n */\nconst ENTRY_HEADERS: ReadonlySet<string> = new Set([\n 'connection',\n 'content-length',\n 'keep-alive',\n 'location',\n 'proxy-connection',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n])\n\n/**\n * Whether a post came from one of `origins`, by what the browser sends and no\n * page or form can set: its `Origin`, or, where that is missing or opaque\n * (`Origin: null`, which a page served with `Referrer-Policy: no-referrer`\n * sends on its own forms), its Fetch Metadata `Sec-Fetch-Site`. A post with\n * neither header is refused. `foldkit-auth`'s resolver decides the same way.\n */\nconst postedFrom = (request: Request, origins: ReadonlySet<string>): boolean => {\n const origin = request.headers.get('origin')\n return origin === null || origin === 'null'\n ? request.headers.get('sec-fetch-site') === 'same-origin'\n : origins.has(origin)\n}\n\nconst plainText = (status: number, body: string): Response =>\n new Response(body, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n\n/** How a form's Message is written into the page for the fallback, when the plan has one. */\nconst fallbackEncoder = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n): ((message: unknown) => string | undefined) | undefined => {\n if (plan.fallback !== 'server' || plan.Message === undefined) return undefined\n const encode = Schema.encodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n return message => {\n const encoded = encode(message)\n return Result.isFailure(encoded) ? undefined : JSON.stringify(encoded.success)\n }\n}\n\n/** Why a posted form was not handled: the request, not the page or the plan, is at fault. */\nexport class FallbackRefused extends Schema.TaggedError<FallbackRefused>()('FallbackRefused', {\n reason: Schema.Literals(['Missing', 'Unreadable', 'Invalid', 'Unlisted', 'NoFallback']),\n message: Schema.String,\n}) {}\n\nconst refuseFallback = (reason: FallbackRefused['reason'], message: string) =>\n Effect.fail(new FallbackRefused({ reason, message }))\n\n/** A Command as Foldkit runs it: named, with the Effect that yields its Message. */\ninterface RunnableCommand {\n readonly name: string\n readonly effect: Effect.Effect<unknown, unknown, any>\n}\n\nconst isRunnable = (command: unknown): command is RunnableCommand =>\n typeof command === 'object' &&\n command !== null &&\n 'effect' in command &&\n Effect.isEffect(command.effect)\n\n/**\n * The most Messages and Commands one post may run. The browser's loop runs\n * for the life of the page, so a Command that schedules itself again, a tick\n * or a poll, is ordinary there; on the server it would hold the request open\n * for ever.\n */\nconst MAX_STEPS = 100\n\n/**\n * Foldkit's loop, once, on the server: `update` for each Message, then each\n * returned Command run under the config's `resources`, its Message folded\n * back through `update`, until no Command remains.\n */\nconst fold = <Model>(\n config: ResumableConfig<Model>,\n post: Context.Context<never>,\n model: Model,\n messages: ReadonlyArray<unknown>,\n commands: ReadonlyArray<unknown>,\n): Effect.Effect<Model> =>\n Effect.gen(function* () {\n let current = model\n const pending = [...messages]\n const queue = [...commands]\n let steps = 0\n let last = ''\n while (pending.length > 0 || queue.length > 0) {\n if (++steps > MAX_STEPS) {\n return yield* Effect.die(\n new Error(\n `SSR.handle: the post did not settle within ${MAX_STEPS} Messages and Commands; the last Command run was \"${last}\". A Command that schedules itself again cannot run on the server`,\n ),\n )\n }\n if (pending.length > 0) {\n const next = config.update(current, pending.shift()) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = next.model\n queue.push(...(next.commands ?? []))\n continue\n }\n const command = queue.shift()\n if (!isRunnable(command)) {\n return yield* Effect.die(\n new Error(`SSR.handle: a Command has no Effect to run: ${JSON.stringify(command)}`),\n )\n }\n // A Command that fails would crash Foldkit's runtime; here it is a defect\n // the entry answers with 500, since the config declares its requirements.\n // The post's own services first, so one it shares with the config's is its own.\n const own = Effect.provide(command.effect, post)\n const provided: Effect.Effect<unknown, unknown, never> =\n config.resources === undefined\n ? (own as Effect.Effect<unknown, unknown, never>)\n : (Effect.provide(own, config.resources) as Effect.Effect<unknown, unknown, never>)\n last = command.name\n const result = yield* Effect.orDie(provided)\n // A Command fired and forgotten yields no Message, and folds nothing in.\n if (result !== undefined && result !== null) pending.push(result)\n }\n return current\n })\n\n/** The Model `init` gives this request, as the server's render would start from. */\nconst startOf = <Model>(\n config: ResumableConfig<Model>,\n options: { readonly url?: string | undefined; readonly flags?: unknown },\n): Effect.Effect<ReturnType<ResumableConfig<Model>['init']>, RenderError> =>\n Effect.gen(function* () {\n let started: ReturnType<ResumableConfig<Model>['init']> | undefined\n yield* renderToString(\n {\n ...config,\n init: (...args: ReadonlyArray<unknown>) => (started = config.init(...args)),\n // Only `init`'s answer is wanted. The application's view drawn here\n // would also fill its memoized drawings (`createLazy`) outside any\n // render the plan records, and the post's own render, from a Model\n // holding the same values, would reuse them without their markers.\n view: (_model: unknown, h: HtmlBuilder<unknown>) => ({ title: '', body: h.div([], []) }),\n } as never,\n { buildId: 'x', ...options } as never,\n )\n return started!\n })\n\n/** Turns the Model `init` gave into the one a request starts from. */\nexport type Prepare<Model> = (model: Model, request: Request) => Effect.Effect<Model, unknown>\n\n/**\n * The config a request starts from: `init`'s answer, its Model prepared. A\n * failed `prepare` is a defect, answered 500 and reported as a failed render.\n */\nconst preparedStart = <Model>(\n request: Request,\n config: ResumableConfig<Model>,\n options: { readonly url: string; readonly flags?: unknown },\n prepare: Prepare<Model>,\n): Effect.Effect<ResumableConfig<Model>, RenderError> =>\n Effect.gen(function* () {\n const started = yield* startOf(config, options)\n const model = yield* Effect.orDie(prepare(started.model, request))\n return startingFrom(config, { ...started, model }) as ResumableConfig<Model>\n })\n\n/**\n * Answers a form posted by a page rendered with `fallback: 'server'`: the\n * posted Message is decoded through the plan's Message Schema, with posted\n * fields of the same names as its own overriding them, and must be one the\n * Surfaces active for the request's Model may send. The server then rebuilds\n * the Model the browser had, `init`, `prepare` and then the plan's `boot` with every\n * Command it leads to, runs `update` with the Message and every Command that\n * follows, and renders the result as a fresh page.\n */\nconst handle = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n request: Request,\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: HandleOptions<Model>,\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe | FallbackRefused> =>\n Effect.map(handleServed(request, config, plan, options), served => served.page)\n\ninterface HandleOptions<Model> {\n readonly buildId: string\n readonly flags?: unknown\n readonly styles?: Head | undefined\n /** The Model the post starts from, from `init`'s, as `SSR.entry`'s `prepare`. */\n readonly prepare?: Prepare<Model> | undefined\n /**\n * This post's own services, beside the config's `resources`: who is\n * asking, a client bound to them. Built once for the post; where both\n * provide a service, the post's is the one its Commands get.\n */\n readonly resources?: Layer.Layer<never, never, never> | undefined\n}\n\nconst handleServed = <Model, Fields extends Schema.Struct.Fields>(\n request: Request,\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n options: HandleOptions<Model>,\n): Effect.Effect<Served<Model>, RenderError | ResumeUnsafe | FallbackRefused> =>\n Effect.flatMap(postedModel(request, config, plan, options), model =>\n renderMatching(\n startingFrom(config, { model }) as ResumableConfig<Model>,\n plan,\n {\n buildId: options.buildId,\n url: request.url,\n ...(options.styles === undefined ? {} : { styles: options.styles }),\n },\n 'full',\n ),\n )\n\n/** The Model a posted form reaches: its Message decoded and checked, then `update` and its Commands. */\nconst postedModel = <Model, Fields extends Schema.Struct.Fields>(\n request: Request,\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n options: HandleOptions<Model>,\n): Effect.Effect<Model, RenderError | FallbackRefused> =>\n // The post's resources live as long as the post.\n Effect.scoped(\n Effect.gen(function* () {\n if (plan.fallback !== 'server' || plan.Message === undefined) {\n return yield* refuseFallback('NoFallback', `plan \"${plan.id}\" has no server fallback`)\n }\n const form = yield* Effect.tryPromise({\n try: () => request.formData(),\n catch: () =>\n new FallbackRefused({ reason: 'Unreadable', message: 'the body is not a form' }),\n })\n const posted = form.get(FALLBACK_FIELD)\n if (typeof posted !== 'string') {\n return yield* refuseFallback('Missing', `the form carries no ${FALLBACK_FIELD} field`)\n }\n let raw: unknown\n try {\n raw = JSON.parse(posted)\n } catch {\n return yield* refuseFallback('Unreadable', `${FALLBACK_FIELD} is not JSON`)\n }\n const decode = Schema.decodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n const invalid = (failure: { readonly message: string }) =>\n refuseFallback('Invalid', `the posted Message does not decode: ${failure.message}`)\n // The posted Message is decoded before anything reads it.\n const written = decode(raw)\n if (Result.isFailure(written)) return yield* invalid(written.failure)\n // A form inside a placement posts the parent's Message; the fields it\n // names sit `depth` wrappers down.\n const postedDepth = form.get(FALLBACK_DEPTH_FIELD) ?? '0'\n if (typeof postedDepth !== 'string' || !/^\\d{1,2}$/.test(postedDepth)) {\n return yield* refuseFallback('Unreadable', `${FALLBACK_DEPTH_FIELD} is not a depth`)\n }\n const override = (value: unknown, down: number): unknown => {\n if (typeof value !== 'object' || value === null) return value\n const copy: Record<string, unknown> = { ...value }\n if (down > 0) {\n copy.message = override(copy.message, down - 1)\n return copy\n }\n form.forEach((field, name) => {\n if (name !== FALLBACK_FIELD && Object.hasOwn(copy, name) && typeof field === 'string') {\n copy[name] = field\n }\n })\n return copy\n }\n // The fields typed into the form, set into the Message and decoded again.\n const decoded = decode(override(raw, Number(postedDepth)))\n if (Result.isFailure(decoded)) return yield* invalid(decoded.failure)\n const message = decoded.success\n const started = yield* startOf(config, { url: request.url, ...options })\n const { prepare } = options\n const start =\n prepare === undefined ? started.model : yield* Effect.orDie(prepare(started.model, request))\n const allowed = allowedTags(plan, start)\n if (!allowed.has(tagOf(message))) {\n return yield* refuseFallback(\n 'Unlisted',\n `the posted ${tagOf(message)} is not one an active Surface lists in its messages`,\n )\n }\n // As the browser got here: `init` on the server, then the plan's `boot`\n // at hydration, and only then the user's Message. `init`'s own Commands\n // never run in the browser, so they do not run here.\n const boot = (plan.boot?.(start) as ReadonlyArray<unknown> | undefined) ?? []\n const post =\n options.resources === undefined ? Context.empty() : yield* Layer.build(options.resources)\n const booted = yield* fold(config, post, start, [], boot)\n return yield* fold(config, post, booted, [message], [])\n }),\n )\n\nexport const SSR = {\n plan,\n envelope,\n resume,\n render,\n page,\n hydrate: Client.hydrate,\n inspect,\n static: staticRegion,\n serving,\n generate,\n entry,\n handle,\n serializeJsonScript,\n sitemap,\n robots,\n requestContext,\n}\n\nexport type { RequestContext } from './requestContext.js'\n\nexport {\n FOLDKIT_APP_ATTRIBUTE,\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n Resume,\n ResumeRefused,\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n UNTIL_LIMIT_MS,\n metaMarkup,\n type DecodedBinding,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableBuilder,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n type UnnamedHandler,\n type BundleUnloaded,\n type HandlerUnnamed,\n type PageContained,\n type PageFailed,\n type SsrDiagnostic,\n type StaticRegionMissing,\n Diagnostics,\n type Diag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AACF"}
1
+ {"version":3,"file":"index.js","names":["Diagnostics","Client"],"sources":["../src/index.ts"],"sourcesContent":["/**\n * `foldkit-ssr`: what crosses from the server to the browser when a page is\n * rendered on one and resumed on the other.\n *\n * Built from the plan in `docs/design/ssr-PLAN.md`. A resume plan names the\n * slice of the Model the browser owns. The server writes that slice onto the\n * stamped root as a JSON attribute, beside Foldkit's own stamps; the browser\n * reads it back and sets it onto a baseline\n * Model. Nothing outside the slice crosses, and a payload that cannot be read\n * back exactly is refused, never half-restored.\n *\n * Rendering and hydrating stay Foldkit's own: this package adds only the\n * handover. This module is the server's side and the browser's\n * (`foldkit-ssr/client`) together.\n */\nimport { Cause, Context, Effect, Exit, Layer, Option, Result, Schema } from 'effect'\nimport {\n FOLDKIT_FLAGS_ATTRIBUTE,\n Rendered,\n Responded,\n injectIntoTemplate,\n renderToString,\n type EntryModule,\n type EntryResult,\n type RenderError,\n type RenderedApplication,\n} from 'foldkit/experimental/server'\nimport {\n CacheStore,\n CachedRead,\n Diagnostics,\n Metadata,\n PageReads,\n cachePolicy,\n maxAgeSeconds,\n shorterPolicy,\n type CacheOptions,\n type CachePolicy,\n type Diagnostic,\n type MetadataSummary,\n type PageCacheStore,\n} from 'foldkit-surface'\nimport type { HtmlBuilder } from 'foldkit/html'\nimport type {\n Activation,\n ActiveSurface,\n Projection,\n SurfaceFamily,\n SurfaceSource,\n} from 'foldkit-surface'\nimport { withContext, type Binding, type Region, type UnnamedHandler } from './context.js'\nimport { cachedPageDiffers, handlerUnnamed, pageFailed, reportingTo } from './diagnostics.js'\nimport {\n decodeKept,\n fits,\n headerOf,\n keptApplications,\n keptDocuments,\n pageKey,\n samePage,\n tracked,\n type HeadersRead,\n type KeptPage,\n} from './pageCache.js'\nimport { type EncodedBinding } from './listen.js'\nimport { FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, KEEP_ATTRIBUTE, UNPLACED_KEEP } from './resumable.js'\nimport { requestContext } from './requestContext.js'\nimport { SSR as Client } from './client.js'\nimport {\n PROTOCOL,\n allowedTags,\n attributeOf,\n codecOf,\n modelFrom,\n metaMarkup,\n pathKey,\n plan,\n projectionsOf,\n resume,\n routeOf,\n serializeJsonScript,\n serving,\n startingFrom,\n staticRegion,\n unbound,\n STYLES_MARKER,\n HEAD_END_MARKER,\n HEAD_MARKER,\n tagOf,\n type Loadable,\n type PlanSurface,\n type ResumableConfig,\n type ResumePlan,\n type RouteMatch,\n} from './shared.js'\n\n/** The set `foldkit-mixins` collects drawn classes in, under the same registered symbol. */\nconst DRAWN_CLASSES = Symbol.for('foldkit-plus.drawnClasses')\n\n/** The projections of the plan's entries that are active for `model`. */\nconst activeProjections = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n) => plan.surfaces.flatMap(source => projectionsOf(source, model))\n\n/** What the envelope carries of a Model: the encoded slice, and each part's capture. */\ninterface Payload {\n readonly state: unknown\n readonly parts?: Readonly<Record<string, unknown>>\n}\n\n/**\n * What the envelope carries of `model`: the plan's slice, encoded through its\n * own Schema, and each part's capture.\n */\nconst payloadOf = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): Payload => {\n const state = Schema.encodeSync(codecOf(plan.state.schema))(plan.state.get(model))\n if (plan.parts.length === 0) return { state }\n const projections = activeProjections(plan, model)\n return {\n state,\n parts: Object.fromEntries(plan.parts.map(part => [part.id, part.capture(model, projections)])),\n }\n}\n\ninterface EnvelopeOptions {\n readonly route?: string | undefined\n readonly match?: RouteMatch | undefined\n readonly bindings?: ReadonlyArray<EncodedBinding> | undefined\n /** Every event the page's markers name, so the browser listens without scanning for them. */\n readonly events?: ReadonlyArray<string> | undefined\n}\n\n/**\n * The envelope for `model`: the plan's slice, each part's capture, and\n * the route it was rendered for, if it was rendered for one. `SSR.render`\n * carries it on the stamped root, beside Foldkit's own stamps, escaped for\n * the attribute; this is the same JSON unescaped, for tests and hosts that\n * place the page themselves.\n */\nconst envelope = <Model, Fields extends Schema.Struct.Fields>(\n resume: ResumePlan<Model, Fields>,\n model: Model,\n options: EnvelopeOptions = {},\n): string => envelopeOf(resume, payloadOf(resume, model), options)\n\n/**\n * The envelope for a payload already built: the JSON the stamped root carries.\n */\nconst envelopeOf = <Model, Fields extends Schema.Struct.Fields>(\n resume: ResumePlan<Model, Fields>,\n payload: Payload,\n options: EnvelopeOptions,\n): string =>\n serializeJsonScript({\n v: PROTOCOL,\n plan: resume.id,\n ...payload,\n ...(options.route === undefined ? {} : { route: options.route }),\n ...(options.match === 'path' ? { match: 'path' } : {}),\n ...(options.bindings === undefined || options.bindings.length === 0\n ? {}\n : { bindings: options.bindings }),\n ...(options.events === undefined || options.events.length === 0\n ? {}\n : { events: options.events }),\n // For `foldkit-ssr/loader`, which cannot import the plan.\n ...(resume.start === 'now' ? {} : { start: resume.start }),\n })\n\n/**\n * The rendered application with the envelope on its stamped root, beside\n * Foldkit's own app and build stamps. `injectIntoTemplate` accepts the\n * envelope there, as part of the root, and refuses it beside the root, so a\n * page the host injects carries the handover without the entry owning the\n * template. The browser reads the envelope, then takes the attribute off\n * as the page boots, before Foldkit adopts the server's nodes around it.\n */\nconst withEnvelopeAttribute = (html: string, json: string): string => {\n const stamp = 'data-foldkit-app=\"'\n // The stamp names the root's open tag: it opens the markup, and no quoted\n // attribute value before it may hold a `>` of its own, which would end a\n // naive scan early, or the stamp string itself. A stamp past the tag's end,\n // or in text, is not the root.\n let from = 0\n for (;;) {\n const at = html.indexOf(stamp, from)\n if (at === -1) {\n throw new Error(\n 'foldkit-ssr: the rendered application has no stamped root to carry the resume envelope',\n )\n }\n if (isInRootTag(html, at)) {\n const end = html.indexOf('\"', at + stamp.length)\n if (end === -1) {\n throw new Error(\n 'foldkit-ssr: the rendered application has no stamped root to carry the resume envelope',\n )\n }\n return `${html.slice(0, end + 1)}${attributeOf(json)}${html.slice(end + 1)}`\n }\n from = at + stamp.length\n }\n}\n\n/** Whether `at` sits inside the markup's first tag: quoted values skipped whole. */\nconst isInRootTag = (html: string, at: number): boolean => {\n if (!html.startsWith('<')) return false\n let index = 1\n while (index < at) {\n const char = html[index]\n if (char === '\"' || char === \"'\") {\n const close = html.indexOf(char, index + 1)\n if (close === -1 || close >= at) return false\n index = close + 1\n } else if (char === '>') {\n return false\n } else {\n index++\n }\n }\n return true\n}\n\n/**\n * The rendered markup with `insert` as the root's last children. A void root\n * holds no children: what it would carry is refused, naming the tag, rather\n * than served where no browser could keep it.\n */\nconst beforeRootEnd = (\n html: string,\n insert: string,\n refused: (tag: string) => ResumeUnsafe,\n): Result.Result<string, ResumeUnsafe> => {\n const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1]\n const at = tag === undefined ? -1 : html.search(new RegExp(`</${tag}>\\\\s*$`))\n if (tag === undefined || at === -1) return Result.fail(refused(tag ?? '?'))\n return Result.succeed(`${html.slice(0, at)}${insert}${html.slice(at)}`)\n}\n\n/**\n * The rendered markup with `extra` after the styles marker, so the first\n * paint is styled before any script runs where no template head can take\n * it; `SSR.hydrate` moves them into the head.\n */\nconst withInRoot = (html: string, extra: string): Result.Result<string, ResumeUnsafe> =>\n beforeRootEnd(\n html,\n `<!--${STYLES_MARKER}-->${extra}`,\n tag =>\n new ResumeUnsafe({\n reason: 'VoidRootWithStyles',\n 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`,\n }),\n )\n\nconst HEAD_OPEN = `<!--${HEAD_MARKER}-->`\nconst HEAD_CLOSE = `<!--${HEAD_END_MARKER}-->`\n\n/**\n * Roots a parser does not keep `<meta>` inside: a table's (it is moved out),\n * foreign content (it breaks out), and raw text, where the markers are text.\n */\nconst HEADLESS_ROOTS = new Set([\n 'table',\n 'thead',\n 'tbody',\n 'tfoot',\n 'tr',\n 'colgroup',\n 'svg',\n 'math',\n 'textarea',\n 'title',\n 'style',\n 'script',\n 'xmp',\n 'iframe',\n 'noembed',\n 'noframes',\n 'noscript',\n 'plaintext',\n])\n\nconst rootTagOf = (html: string): string | undefined =>\n /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1]?.toLowerCase()\n\n/**\n * The rendered markup with the plan's `meta` between the head markers at the\n * root's end, where `SSR.headed` takes it from. A root that cannot carry it\n * to the host intact is refused, naming the tag.\n */\nconst withHeadInRoot = (html: string, markup: string): Result.Result<string, ResumeUnsafe> => {\n if (markup === '') return Result.succeed(html)\n const refused = (tag: string) =>\n new ResumeUnsafe({\n reason: 'RootRefusesHead',\n 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`,\n })\n const tag = rootTagOf(html)\n if (tag !== undefined && HEADLESS_ROOTS.has(tag)) return Result.fail(refused(tag))\n return beforeRootEnd(html, `${HEAD_OPEN}${markup}${HEAD_CLOSE}`, refused)\n}\n\n/**\n * The head block `withHeadInRoot` put in a rendered root, and the root\n * without it: the last close marker, followed only by the styles or the\n * root's end, and the last open marker before it, between which is only\n * escaped `meta`. Markers anywhere else (text a view drew in a `<style>`) are\n * not a block, and stay where they are.\n */\nconst pageHeadOf = (\n html: string,\n): Option.Option<{ readonly head: string; readonly html: string }> => {\n const tag = rootTagOf(html)\n const end = html.lastIndexOf(HEAD_CLOSE)\n if (tag === undefined || HEADLESS_ROOTS.has(tag) || end === -1) return Option.none()\n const after = html.slice(end + HEAD_CLOSE.length)\n if (\n !after.startsWith(`<!--${STYLES_MARKER}-->`) &&\n !new RegExp(`^</${tag}>\\\\s*$`, 'i').test(after)\n )\n return Option.none()\n const start = html.lastIndexOf(HEAD_OPEN, end)\n if (start === -1) return Option.none()\n return Option.some({\n head: html.slice(start + HEAD_OPEN.length, end),\n html: `${html.slice(0, start)}${after}`,\n })\n}\n\n/**\n * The Model the browser will start from when the server's Model is `model`:\n * the payload taken through the page as the envelope carries it, as JSON, and\n * resumed exactly as `SSR.resume` resumes it, with each restored path taking\n * the server's value (the browser reads the same address and cookie). A part\n * that cannot restore its own capture fails here, on the server.\n */\nconst browserModelOf = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: Payload,\n model: Model,\n): Result.Result<Model, string> => {\n const resumed = modelFrom(plan, JSON.parse(serializeJsonScript(payload)))\n return Result.isFailure(resumed)\n ? resumed\n : Result.succeed(\n plan.restored.reduce((browser, place) => place.copy(browser, model), resumed.success),\n )\n}\n\n/** Where the browser gets a Model path's value: the envelope, itself, or nowhere it may. */\nexport type Cover = 'state' | 'restored' | 'local' | 'missing'\n\n/** One Surface as a plan covers it, for the server's Model. */\nexport interface SurfaceCoverage {\n readonly name: string\n /** Whether the Surface is active for the server's Model. */\n readonly active: boolean\n /** The instance key, for one instance of a `Surface.each` family. */\n readonly key?: string | undefined\n /**\n * The parent a family instance resolves through: the Surface whose Model\n * reveals it, and the place that activates the parent, when readable.\n */\n readonly via?:\n | {\n readonly surface: string\n readonly activation?: { readonly path: string; readonly cover: Cover } | undefined\n }\n | undefined\n /** The place a `Surface.when` activation reads; absent for `Surface.at`. */\n readonly activation?: { readonly path: string; readonly cover: Cover } | undefined\n /** The Model paths the active Surface reads. */\n readonly reads: ReadonlyArray<{ readonly path: string; readonly cover: Cover }>\n /**\n * What the active Surface reads that no Model path names, such as Remote\n * data, by its metadata. The slice cannot carry it.\n */\n readonly unresumed: ReadonlyArray<MetadataSummary>\n /** Whether the browser's Model activates it the same way, with the same reads. */\n readonly sameInBrowser: boolean\n}\n\n/** What a plan sends, what it leaves local or restored, and how it covers each Surface. */\nexport interface PlanInspection {\n readonly id: string\n readonly state: ReadonlyArray<string>\n readonly local: ReadonlyArray<string>\n /** Model paths the browser reads again before the first render. */\n readonly restored: ReadonlyArray<string>\n /** The ids of the parts that resume state the slice cannot carry. */\n readonly parts: ReadonlyArray<string>\n readonly surfaces: ReadonlyArray<SurfaceCoverage>\n}\n\nconst pathOf = (path: ReadonlyArray<string>): string =>\n path.length === 0 ? '(the whole Model)' : path.join('.')\n\n/**\n * A path is covered by a sent, restored or local path equal to it or\n * containing it. An empty path is the whole Model, which no pick covers.\n */\nconst coverOf = (\n path: ReadonlyArray<string>,\n plan: {\n readonly state: { readonly dependencies: ReadonlyArray<ReadonlyArray<string>> }\n readonly restored: ReadonlyArray<{ readonly path: ReadonlyArray<string> }>\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n },\n): Cover => {\n const contains = (outer: ReadonlyArray<string>) =>\n outer.length > 0 &&\n outer.length <= path.length &&\n outer.every((key, index) => path[index] === key)\n if (plan.state.dependencies.some(contains)) return 'state'\n if (plan.restored.some(({ path: outer }) => contains(outer))) return 'restored'\n if (plan.local.some(contains)) return 'local'\n return 'missing'\n}\n\n/** A projection's reads as one comparable string, or `inactive`. */\nconst readsKey = (\n projection:\n | {\n readonly dependencies: ReadonlyArray<ReadonlyArray<string>>\n readonly metadata: Metadata\n }\n | undefined,\n): string =>\n projection === undefined\n ? 'inactive'\n : JSON.stringify([projection.dependencies, Metadata.summarize(projection.metadata)])\n\n/**\n * How a plan covers each of its Surfaces when the server's Model is `model`.\n * A Surface's reads depend on the Model, through its params, so coverage is\n * worked out for a Model, not for the plan alone.\n */\nconst inspect = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): PlanInspection => {\n const resumed = browserModelOf(plan, payloadOf(plan, model), model)\n if (Result.isFailure(resumed)) throw new Error(`SSR.inspect: ${resumed.failure}`)\n return coverage(plan, model, resumed.success)\n}\n\n/** How a plan covers its Surfaces, given the server's Model and the browser's. */\nconst coverage = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n browser: Model,\n): PlanInspection => {\n const covered = new Set(plan.parts.flatMap(part => part.covers))\n const families = new Map<ActiveSurface<Model>, Array<Family<Model>>>()\n for (const family of plan.surfaces.flatMap(source => Option.toArray(familyOf(source)))) {\n const siblings = families.get(family.from)\n if (siblings === undefined) families.set(family.from, [family])\n else siblings.push(family)\n }\n // A row is a Surface's identity, not a plan entry: families sharing a\n // parent, or a parent also listed alone, show that parent once.\n const shown = new Set<ActiveSurface<Model>>()\n return {\n id: plan.id,\n state: plan.state.dependencies.map(pathOf),\n local: plan.local.map(pathOf),\n restored: plan.restored.map(({ path }) => pathOf(path)),\n parts: plan.parts.map(part => part.id),\n surfaces: plan.surfaces.flatMap(source => {\n const surface = Option.match(familyOf(source), {\n onNone: () => source as ActiveSurface<Model>,\n onSome: family => family.from,\n })\n if (shown.has(surface)) return []\n shown.add(surface)\n return coverSurface(plan, covered, surface, families.get(surface) ?? [], model, browser)\n }),\n }\n}\n\ntype Family<Model> = SurfaceFamily<Model, unknown, unknown, unknown, unknown>\n\n/** The plan entry as a family with a parent; none for a lone Surface. */\nconst familyOf = <Model>(source: PlanSurface<Model>): Option.Option<Family<Model>> =>\n (source as { readonly from?: ActiveSurface<Model> }).from !== undefined &&\n typeof (source as Partial<SurfaceSource<Model>>).instancesOf === 'function'\n ? Option.some(source as Family<Model>)\n : Option.none()\n\n/** One coverage row: a lone Surface, a family's parent, or one family instance. */\nconst coverRow = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n covered: ReadonlySet<string>,\n entry: {\n readonly name: string\n readonly key?: string | undefined\n readonly via?: SurfaceCoverage['via']\n readonly activation?: Activation | undefined\n },\n served: Projection<Model, unknown> | undefined,\n browserServed: Projection<Model, unknown> | undefined,\n): SurfaceCoverage => ({\n name: entry.name,\n active: served !== undefined,\n ...(entry.key === undefined ? {} : { key: entry.key }),\n ...(entry.via === undefined ? {} : { via: entry.via }),\n ...(entry.activation === undefined\n ? {}\n : {\n activation: {\n path: pathOf(entry.activation.path),\n cover: coverOf(entry.activation.path, plan),\n },\n }),\n reads: (served?.dependencies ?? []).map(path => ({\n path: pathOf(path),\n cover: coverOf(path, plan),\n })),\n unresumed:\n served === undefined\n ? []\n : Metadata.summarize(served.metadata).filter(summary => !covered.has(summary.name)),\n sameInBrowser: readsKey(served) === readsKey(browserServed),\n})\n\n/**\n * A Surface's coverage rows: its own row, then, while it is active, one row\n * per instance of each family it is the parent of. The parent row keeps the\n * parent's reads covered; each instance row says which key it is and which\n * parent reveals it, so a gap names the instance (`Member[u1]`), not just the\n * Surface.\n */\nconst coverSurface = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n covered: ReadonlySet<string>,\n surface: ActiveSurface<Model>,\n families: ReadonlyArray<Family<Model>>,\n model: Model,\n browser: Model,\n): ReadonlyArray<SurfaceCoverage> => {\n const own = coverRow(\n plan,\n covered,\n surface,\n Option.getOrUndefined(surface.projectionOf(model)),\n Option.getOrUndefined(surface.projectionOf(browser)),\n )\n if (!own.active) return [own]\n const via: SurfaceCoverage['via'] = {\n surface: surface.name,\n ...(surface.activation === undefined\n ? {}\n : {\n activation: {\n path: pathOf(surface.activation.path),\n cover: coverOf(surface.activation.path, plan),\n },\n }),\n }\n return [\n own,\n ...families.flatMap(family => {\n const browserInstances = new Map(\n family.instancesOf(browser).map(instance => [instance.key, instance.projection]),\n )\n return family\n .instancesOf(model)\n .map(instance =>\n coverRow(\n plan,\n covered,\n { name: family.name, key: instance.key, via },\n instance.projection,\n browserInstances.get(instance.key),\n ),\n )\n }),\n ]\n}\n\n/** A coverage row as a shortfall names it: `Member[u1]` for an instance, the name alone otherwise. */\nconst displayOf = (surface: SurfaceCoverage): string =>\n surface.key === undefined ? surface.name : `${surface.name}[${surface.key}]`\n\n/** Each way an inspection shows the plan falls short, one line each. */\nconst shortfalls = (inspection: PlanInspection): ReadonlyArray<string> =>\n inspection.surfaces.flatMap(surface => [\n ...(surface.activation?.cover === 'missing'\n ? [\n `Surface \"${displayOf(surface)}\" is activated by ${surface.activation.path}, which is neither in the plan's state nor local`,\n ]\n : []),\n ...surface.reads\n .filter(read => read.cover === 'missing')\n .map(\n read =>\n `Surface \"${displayOf(surface)}\" reads ${read.path}, which is neither in the plan's state nor local`,\n ),\n ...surface.unresumed.map(\n summary =>\n `Surface \"${displayOf(surface)}\" reads ${summary.name} data (${summary.entries.join(', ')}), which no part of the plan resumes`,\n ),\n ...(surface.sameInBrowser\n ? []\n : [\n `Surface \"${displayOf(surface)}\" is ${surface.active ? 'active' : 'inactive'} on the server and activates differently from the Model the browser starts from`,\n ]),\n ])\n\n/** Why a server refused to render a page against its plan. */\nexport class ResumeUnsafe extends Schema.TaggedError<ResumeUnsafe>()('ResumeUnsafe', {\n reason: Schema.Literals([\n 'UndeclaredStartup',\n 'Uncovered',\n 'ViewDependsOnUnsentState',\n 'DuplicateStaticRegion',\n 'UngeneratablePath',\n 'UnrestorablePart',\n 'UnencodableBinding',\n 'EagerStartRequired',\n 'UndeclaredSurfaces',\n 'BindingInStaticRegion',\n 'VoidRootWithStyles',\n 'RootRefusesHead',\n 'UnkeepableField',\n 'UnkeptField',\n ]),\n message: Schema.String,\n}) {}\n\n/** Each binding whose Message no active Surface lists, one line each. */\nconst unlistedBindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n bindings: ReadonlyArray<Binding>,\n): ReadonlyArray<string> => {\n const allowed = allowedTags(plan, model)\n return bindings\n .filter(binding => !allowed.has(tagOf(binding.message)))\n .map(\n binding =>\n `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`,\n )\n}\n\n/**\n * Whether `at` starts an attribute inside the start tag opened before it.\n * A marker in a text node follows that tag's `>`, and one inside another\n * attribute's value has its quotes escaped (`&quot;`), so only a marker\n * between a tag's `<` and a `>` outside a quoted value is an attribute.\n */\nconst opensAttribute = (html: string, at: number): boolean => {\n if (at === 0 || !/[ \\t\\r\\n]/.test(html[at - 1]!)) return false\n const open = html.lastIndexOf('<', at)\n if (open === -1 || html.startsWith('<!--', open)) return false\n let quote: string | undefined\n for (let index = open + 1; index < at; index++) {\n const char = html[index]\n if (quote !== undefined) {\n if (char === quote) quote = undefined\n } else if (char === '\"' || char === \"'\") quote = char\n else if (char === '>') return false\n }\n return quote === undefined\n}\n\n/**\n * A line for each `KeepTyped` the render drew on an element the resumable\n * builder did not build, whose marker still holds its server-render value:\n * nothing marks which binding replays such a field, so every browser would\n * refuse the page. Only a marker that is an attribute counts: ordinary text\n * can spell the same characters.\n */\nconst unplacedKeeps = (html: string): ReadonlyArray<string> => {\n const marker = `${KEEP_ATTRIBUTE}=\"${UNPLACED_KEEP}\"`\n const found: Array<string> = []\n for (let at = html.indexOf(marker); at !== -1; at = html.indexOf(marker, at + 1)) {\n if (!opensAttribute(html, at)) continue\n const open = html.lastIndexOf('<', at)\n const tag = /^<([A-Za-z][A-Za-z0-9._-]*)/.exec(html.slice(open))?.[1] ?? 'an element'\n const id = /\\sid=\"([^\"]*)\"/.exec(html.slice(open, html.indexOf('>', at)))?.[1]\n found.push(\n `KeepTyped on ${id === undefined ? tag : `${tag}#${id}`}, which Resume.builder did not build, so nothing marks the binding its typing replays as: build the element with the resumable builder (rh.input), not h`,\n )\n }\n return found\n}\n\n/** Loads every lazy bundle's bodies, so the view renders whole. */\nconst loadLazy = (config: { readonly lazy?: ReadonlyArray<Loadable> | undefined }) =>\n Effect.promise(() => Promise.all((config.lazy ?? []).map(bundle => bundle.load())))\n\n/** Foldkit's own Flags script, which a resumed page never carries. */\nconst FLAGS_SCRIPT = new RegExp(\n `<script[^>]*${FOLDKIT_FLAGS_ATTRIBUTE}[^>]*>[\\\\s\\\\S]*?</script>`,\n 'g',\n)\n\n/**\n * The head fields a render returns beside the body. Each is read by the view,\n * so each must come out the same from the browser's Model; since Foldkit 0.163\n * none has a default from the URL.\n */\nconst HEAD_FIELDS = ['title', 'lang', 'dir', 'canonical', 'ogUrl'] as const\n\n/** A render's bindings, encoded, or why one cannot be. */\nconst encodeBindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n bindings: ReadonlyArray<Binding>,\n): Result.Result<ReadonlyArray<EncodedBinding>, string> => {\n if (bindings.length === 0) return Result.succeed([])\n if (plan.Message === undefined) {\n return Result.fail(\n 'the page has bindings, and the plan has no Message Schema to encode them with: make the plan from the application',\n )\n }\n const encode = Schema.encodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n const out: Array<EncodedBinding> = []\n for (const binding of bindings) {\n const message = encode(binding.message)\n if (Result.isFailure(message)) {\n return Result.fail(\n `the ${binding.event} binding on ${binding.element} does not encode as a Message: ${message.failure.message}`,\n )\n }\n out.push({\n attribute: binding.attribute,\n message: message.success,\n ...(binding.hole === undefined ? {} : { hole: binding.hole }),\n ...(binding.depth === undefined ? {} : { depth: binding.depth }),\n ...(binding.options === undefined ? {} : { options: binding.options }),\n })\n }\n return Result.succeed(out)\n}\n\n/**\n * The bindings that differ between the server's render and the browser's, by\n * element: a Message built from a field the plan does not send would dispatch\n * one Message before boot and another after.\n */\nconst changedBindings = (\n served: ReadonlyArray<Binding>,\n encoded: ReadonlyArray<EncodedBinding>,\n reencoded: ReadonlyArray<EncodedBinding>,\n): ReadonlyArray<string> =>\n served.flatMap((binding, index) =>\n JSON.stringify(encoded[index]) === JSON.stringify(reencoded[index])\n ? []\n : [`${binding.event} binding on ${binding.element}`],\n )\n\n/**\n * The Subscription and Managed Resource entries that would start late under a\n * deferred boot and are not declared deferrable, by the plan or by a part.\n * Foldkit starts every Subscription's stream at boot, so every entry counts; a\n * Managed Resource counts when the Model asks for it.\n */\nconst eagerEntries = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlyArray<string> => {\n if (plan.start === 'now') return []\n const declared = (key: string, entry: unknown) =>\n plan.deferrable.includes(key) || plan.parts.some(part => part.deferrable?.(key, entry) === true)\n const subscriptions = Object.entries(config.subscriptions ?? {}).filter(\n ([key, entry]) => !declared(key, entry),\n )\n const resources = Object.entries(config.managedResources ?? {}).filter(([key, entry]) => {\n const asks = (\n entry as { modelToMaybeRequirements?: (model: Model) => unknown }\n ).modelToMaybeRequirements?.(model)\n const active = Option.isOption(asks) ? Option.isSome(asks) : asks !== undefined\n return active && !declared(key, entry)\n })\n return [\n ...subscriptions.map(([key]) => `subscription \"${key}\"`),\n ...resources.map(([key]) => `resource \"${key}\"`),\n ]\n}\n\n/** A page the server rendered against a plan, with its envelope. */\nexport interface RenderedPage {\n /**\n * The rendered application with the envelope on its stamped root, so\n * Foldkit's `injectIntoTemplate` places the page whole: the host owns the\n * template, and the entry never splices markup into it.\n */\n readonly rendered: RenderedApplication\n /** The envelope, as carried on the root, for tests and custom hosts. */\n readonly envelope: string\n /** The head markup of the plan's `meta`, empty without one. */\n readonly meta: string\n /** The compiled classes the render drew, for a stylesheet without an HTML scan. */\n readonly drawn: ReadonlySet<string>\n /**\n * Each element whose handler for an event is a function, marked `*`: the\n * page cannot answer that event before the live runtime boots.\n */\n readonly unnamed: ReadonlyArray<UnnamedHandler>\n}\n\n/**\n * Renders a page on the server against a resume plan.\n *\n * The application's `init` runs once. Its Model's slice is round-tripped\n * through the plan's Schema and set onto the baseline, which is the Model the\n * browser will start from, and the page is rendered from that Model. Every\n * way the browser could start somewhere else is a `ResumeUnsafe`, whose\n * `reason` names it; the README lists them. The one that matters most: the\n * view rendered from the browser's Model differs from the one rendered from\n * the server's, because it reads a field the plan leaves out. In production\n * Foldkit would rebuild that part of the page silently, so this is the one\n * place it shows.\n */\nconst render = <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 readonly url?: string | undefined\n readonly flags?: unknown\n /**\n * Markup for the first paint, given what was rendered, carried as the\n * root's last children: `<style>` (or a stylesheet `<link>`), which\n * `SSR.hydrate` moves into the head before adopting the page. Anything\n * else a head owns (`meta`) stays with `SSR.page` and `SSR.generate`.\n */\n readonly styles?: Head | undefined\n },\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe> =>\n Effect.map(renderMatching(config, plan, options, 'full'), served => served.page)\n\n/** A rendered page, with the Model the server's `init` (or a post) reached. */\ninterface Served<Model> {\n readonly page: RenderedPage\n readonly model: Model\n}\n\nconst renderMatching = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly url?: string | undefined\n readonly flags?: unknown\n readonly styles?: Head | undefined\n /** Carry the plan's `meta` in the root for `SSR.headed`, as `SSR.entry` serves it. */\n readonly metaInRoot?: boolean | undefined\n },\n match: RouteMatch,\n): Effect.Effect<Served<Model>, RenderError | ResumeUnsafe> =>\n Effect.gen(function* () {\n yield* loadLazy(config)\n let served: ReturnType<ResumableConfig<Model>['init']> | undefined\n const regions = new Map<string, Region>()\n const duplicates = new Set<string>()\n const servedBindings: Array<Binding> = []\n const browserBindings: Array<Binding> = []\n const inStatic: Array<{ region: string; element: string; event: string }> = []\n const unnamed: Array<UnnamedHandler> = []\n const unkeepable: Array<string> = []\n const unkept: Array<string> = []\n const fallback = fallbackEncoder(plan)\n const capturing = withContext(\n { ...config, init: (...args: ReadonlyArray<unknown>) => (served = config.init(...args)) },\n {\n mode: 'collect',\n regions,\n duplicates,\n bindings: servedBindings,\n fallback,\n wrap: message => message,\n depth: 0,\n region: undefined,\n inStatic,\n unnamed,\n unkeepable,\n unkept,\n },\n )\n const full = yield* renderToString(capturing as never, options as never)\n unkeepable.push(...unplacedKeeps(full.html))\n if (duplicates.size > 0) {\n return yield* new ResumeUnsafe({\n reason: 'DuplicateStaticRegion',\n message: `two static regions share the id ${[...duplicates].map(id => `\"${id}\"`).join(', ')}: the browser could adopt only one`,\n })\n }\n if (inStatic.length > 0) {\n const found = inStatic.map(\n ({ region, element, event }) => `a ${event} handler on ${element} in \"${region}\"`,\n )\n return yield* new ResumeUnsafe({\n reason: 'BindingInStaticRegion',\n message: `a static region is the server's alone, and these would never run: ${found.join(', ')}. What a Message changes belongs in a Surface`,\n })\n }\n if (unkeepable.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'UnkeepableField',\n message: `the page cannot keep what is typed into these fields before it boots:\\n- ${unkeepable.join('\\n- ')}`,\n })\n }\n if (plan.start !== 'now' && unkept.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'UnkeptField',\n 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- ')}`,\n })\n }\n const started = served!\n const commands = started.commands ?? []\n if (commands.length > 0 && plan.boot === undefined) {\n return yield* new ResumeUnsafe({\n reason: 'UndeclaredStartup',\n message: `init returned ${commands.map(command => command.name).join(', ')}, which no browser would run: name them in the plan's boot`,\n })\n }\n\n // Built once: each part's capture reads the whole store it owns.\n const payload = payloadOf(plan, started.model)\n const resumed = browserModelOf(plan, payload, started.model)\n if (Result.isFailure(resumed)) {\n return yield* new ResumeUnsafe({ reason: 'UnrestorablePart', message: resumed.failure })\n }\n const browser = resumed.success\n\n const eager = eagerEntries(config, plan, started.model)\n if (eager.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'EagerStartRequired',\n message: `the plan starts ${plan.start}, and these would start late: ${eager.join(', ')}. Name each in the plan's deferrable, or start now`,\n })\n }\n\n if (servedBindings.length > 0 && plan.surfaces.length === 0) {\n return yield* new ResumeUnsafe({\n reason: 'UndeclaredSurfaces',\n message: `the page has ${servedBindings.length} binding${servedBindings.length === 1 ? '' : 's'} and the plan declares no surfaces, so nothing says which Messages it may dispatch: name them in the plan's surfaces`,\n })\n }\n const uncovered = [\n ...shortfalls(coverage(plan, started.model, browser)),\n ...unlistedBindings(plan, started.model, servedBindings),\n ]\n if (uncovered.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'Uncovered',\n message: `the plan does not cover what the browser reads:\\n- ${uncovered.join('\\n- ')}`,\n })\n }\n\n // With no `Flags` key in the config, Foldkit writes no Flags script.\n // The Mixins resolver records every compiled class this pass draws, so a\n // stylesheet needs no scan of the HTML it produces.\n const drawn = new Set<string>()\n const global = globalThis as Record<symbol, unknown>\n global[DRAWN_CLASSES] = drawn\n const rendered = yield* renderToString(\n withContext(startingFrom(config, { model: browser }), {\n mode: 'replay',\n regions,\n bindings: browserBindings,\n fallback,\n wrap: message => message,\n depth: 0,\n }) as never,\n options as never,\n ).pipe(\n Effect.ensuring(\n Effect.sync(() => {\n if (global[DRAWN_CLASSES] === drawn) delete global[DRAWN_CLASSES]\n }),\n ),\n )\n const encoded = encodeBindings(plan, servedBindings)\n const reencoded = encodeBindings(plan, browserBindings)\n if (Result.isFailure(encoded)) {\n return yield* new ResumeUnsafe({ reason: 'UnencodableBinding', message: encoded.failure })\n }\n const meta = plan.meta === undefined ? '' : metaMarkup(plan.meta(started.model))\n const differing = [\n ...(full.html.replace(FLAGS_SCRIPT, '') === rendered.html ? [] : ['body']),\n ...HEAD_FIELDS.filter(field => full[field] !== rendered[field]),\n ...(plan.meta === undefined || metaMarkup(plan.meta(browser)) === meta ? [] : ['meta']),\n ...changedBindings(\n servedBindings,\n encoded.success,\n Result.isFailure(reencoded) ? [] : reencoded.success,\n ),\n ]\n if (differing.length > 0) {\n return yield* new ResumeUnsafe({\n reason: 'ViewDependsOnUnsentState',\n message: `the view differs in its ${differing.join(', ')} when rendered from the Model the browser will start from: it reads a field the plan leaves out`,\n })\n }\n const envelope = envelopeOf(plan, payload, {\n ...(options.url === undefined\n ? {}\n : { route: match === 'path' ? pathKey(routeOf(options.url)) : routeOf(options.url) }),\n match,\n bindings: encoded.success,\n events: [\n ...new Set([\n ...servedBindings.map(binding => binding.event),\n ...unnamed.map(handler => handler.event),\n ]),\n ].sort(),\n })\n const headed =\n options.metaInRoot === true\n ? withHeadInRoot(rendered.html, meta)\n : Result.succeed(rendered.html)\n if (Result.isFailure(headed)) return yield* headed.failure\n const styled =\n options.styles === undefined\n ? Result.succeed(headed.success)\n : withInRoot(headed.success, options.styles(rendered, drawn))\n if (Result.isFailure(styled)) return yield* styled.failure\n return {\n page: {\n rendered: { ...rendered, html: withEnvelopeAttribute(styled.success, envelope) },\n meta,\n drawn,\n envelope,\n unnamed,\n },\n model: started.model,\n }\n })\n\n/**\n * What a page adds to its head, given what it rendered and the compiled\n * classes it drew: such as a stylesheet of those classes (`Style.usedDrawn`\n * in `foldkit-mixins`, with no scan of the HTML). The same shape describes\n * `styles`, which rides in the rendered root instead, for pages whose\n * template the host owns.\n */\nexport type Head = (rendered: RenderedApplication, drawn: ReadonlySet<string>) => string\n\n/**\n * The template with `extra` before its last `</head>`, as a slice for the same\n * reason as the envelope. Nothing to add leaves it as it is; something to add\n * and no `</head>` is refused, rather than dropped.\n */\nconst withHead = (template: string, extra: string): string => {\n if (extra === '') return template\n const at = template.search(/<\\/head>(?![\\s\\S]*<\\/head>)/i)\n if (at === -1) throw new Error('foldkit-ssr: the template has no </head> to put the head in')\n return `${template.slice(0, at)}${extra}${template.slice(at)}`\n}\n\n/**\n * Foldkit fills `canonical` and `og:url` only into a tag the template already\n * has, and leaves the page without one otherwise. A render that sets either\n * and a template without its tag is refused, naming the tag.\n */\nconst FILLED_TAGS = [\n {\n field: 'canonical',\n tag: '<link rel=\"canonical\" href=\"\">',\n at: /<link\\b[^>]*\\brel\\s*=\\s*[\"']?canonical[\"'\\s>]/i,\n },\n {\n field: 'ogUrl',\n tag: '<meta property=\"og:url\" content=\"\">',\n at: /<meta\\b[^>]*\\bproperty\\s*=\\s*[\"']?og:url[\"'\\s>]/i,\n },\n] as const\n\nconst withFilledTags = (template: string, rendered: RenderedApplication): string => {\n const missing = FILLED_TAGS.filter(\n ({ field, at }) => rendered[field] !== undefined && !at.test(template),\n )\n if (missing.length > 0) {\n throw new Error(\n `foldkit-ssr: the view sets ${missing.map(({ field }) => field).join(' and ')}, and the template has no ${missing.map(({ tag }) => tag).join(' or ')} for Foldkit to fill: add it to the template's head`,\n )\n }\n return template\n}\n\n/** The plan's `meta`, then what `head` adds, one line apart. */\nconst headOf = (\n result: {\n readonly rendered: RenderedApplication\n readonly meta: string\n readonly drawn: ReadonlySet<string>\n },\n head: Head | undefined,\n): string =>\n [result.meta, head?.(result.rendered, result.drawn) ?? '']\n .filter(markup => markup !== '')\n .join('\\n')\n\n/**\n * The page to serve: the rendered application in the template, with the\n * plan's `meta` and `head`'s markup, if any, before `</head>`. The envelope\n * is already in the rendered root, so this is Foldkit's `injectIntoTemplate`\n * with a head, and nothing else.\n */\nconst page = (\n template: string,\n result: {\n readonly rendered: RenderedApplication\n readonly meta: string\n readonly drawn: ReadonlySet<string>\n },\n options: { readonly head?: Head | undefined } = {},\n): string =>\n injectIntoTemplate(\n withHead(withFilledTags(template, result.rendered), headOf(result, options.head)),\n result.rendered,\n )\n\n/**\n * `render`, the host's document renderer, with the head markup `SSR.entry`\n * carries in the rendered root (a plan's `meta`) moved before the document's\n * `</head>`, where link previews and crawlers read it. Wrap whatever draws the\n * document: `SSR.headed(renderDocument)`, or, for a host that hands Foldkit a\n * template, `SSR.headed(application => injectIntoTemplate(template,\n * application))`. The markup is taken from the rendered root alone, where the\n * entry put it, so nothing a view draws elsewhere is moved. Without it the\n * markup stays in the body, and `SSR.hydrate` reports `HeadNotMoved`.\n */\nconst headed =\n <Args extends ReadonlyArray<unknown>>(\n render: (application: RenderedApplication, ...args: Args) => string,\n ) =>\n (application: RenderedApplication, ...args: Args): string =>\n Option.match(pageHeadOf(application.html), {\n onNone: () => render(application, ...args),\n onSome: ({ head, html }) => {\n const document = render({ ...application, html }, ...args)\n // The template's own `</head>` comes first; a later one is text in the body.\n const at = document.search(/<\\/head>/i)\n if (at === -1)\n throw new Error('foldkit-ssr: the document has no </head> to put the head in')\n return `${document.slice(0, at)}${head}${document.slice(at)}`\n },\n })\n\n/** A page generated at build time, and the file a static host serves it from. */\nexport interface GeneratedPage {\n readonly path: string\n readonly file: string\n readonly html: string\n}\n\n/**\n * One generated page per path, in the paths' order: a tuple when the paths\n * are written out, so `const [home, about] = pages` needs no check.\n */\nexport type GeneratedPages<Paths extends ReadonlyArray<string>> = {\n readonly [K in keyof Paths]: GeneratedPage\n}\n\n/** The file a static host serves for a path: `/about` is `about/index.html`. */\nconst fileOf = (path: string): string => {\n const trimmed = path.replace(/^\\/+/, '').replace(/\\/+$/, '')\n if (trimmed === '') return 'index.html'\n return trimmed.endsWith('.html') ? trimmed : `${trimmed}/index.html`\n}\n\nconst xmlText = (text: string): string =>\n text\n .replaceAll('&', '&amp;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n .replaceAll('\"', '&quot;')\n .replaceAll(\"'\", '&apos;')\n\n/**\n * A sitemap of the pages a build generated, each at its full address under\n * `origin`, in the order given. `modified`, when a page has it, is any date\n * `Date` reads, written as the UTC day. A path that does not start with `/`,\n * a path given twice, and a date `Date` cannot read are refused: each would\n * make a sitemap a search engine rejects or misreads.\n */\nconst sitemap = (\n pages: ReadonlyArray<{ readonly path: string; readonly modified?: string | undefined }>,\n options: { readonly origin: string },\n): string => {\n const seen = new Set<string>()\n const urls = pages.map(({ path, modified }) => {\n if (!path.startsWith('/')) throw new Error(`SSR.sitemap: \"${path}\" does not start with /`)\n if (seen.has(path)) throw new Error(`SSR.sitemap: \"${path}\" is listed twice`)\n seen.add(path)\n const loc = `<loc>${xmlText(new URL(path, options.origin).href)}</loc>`\n if (modified === undefined) return ` <url>${loc}</url>`\n const at = new Date(modified)\n if (Number.isNaN(at.getTime())) {\n throw new Error(`SSR.sitemap: \"${modified}\", the date of \"${path}\", is not a date`)\n }\n return ` <url>${loc}<lastmod>${at.toISOString().slice(0, 10)}</lastmod></url>`\n })\n return [\n '<?xml version=\"1.0\" encoding=\"UTF-8\"?>',\n '<urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap/0.9\">',\n ...urls,\n '</urlset>',\n '',\n ].join('\\n')\n}\n\n/**\n * A `robots.txt` that lets every crawler in, except under `disallow`, and\n * names the sitemap at `sitemap` (default `/sitemap.xml`) under `origin`.\n */\nconst robots = (options: {\n readonly origin: string\n readonly sitemap?: string | undefined\n readonly disallow?: ReadonlyArray<string> | undefined\n}): string =>\n [\n 'User-agent: *',\n 'Allow: /',\n ...(options.disallow ?? []).map(path => `Disallow: ${path}`),\n '',\n `Sitemap: ${new URL(options.sitemap ?? '/sitemap.xml', options.origin).href}`,\n '',\n ].join('\\n')\n\n// Keyed by plan, element and event: a server renders the same page for every\n// request, so one report each is enough to learn which handler to name.\nconst reportedUnnamed = new Set<string>()\n\n/**\n * Reports, once per process, each handler that keeps a page from answering\n * before boot. Only a page that waits to boot is held up: one started\n * `'now'`, with no lazy bundle to load, boots before any event.\n */\nconst reportUnnamed = <Model, Fields extends Schema.Struct.Fields>(\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n unnamed: ReadonlyArray<UnnamedHandler>,\n): Effect.Effect<void> =>\n Effect.suspend(() => {\n if (plan.start === 'now' && (config.lazy ?? []).length === 0) return Effect.void\n const first = unnamed.filter(({ element, event }) => {\n const key = JSON.stringify([plan.id, element, event])\n if (reportedUnnamed.has(key)) return false\n reportedUnnamed.add(key)\n return true\n })\n return Effect.forEach(\n first,\n ({ element, event }) => Diagnostics.report(handlerUnnamed(plan.id, element, event)),\n { discard: true },\n )\n })\n\n/**\n * Renders pages at build time, one per path, each as `SSR.render` and\n * `SSR.page` would, to be written as files. `origin` makes each path the full\n * URL a routing application parses. `flags`, when the application has them,\n * gives each path its own.\n *\n * A generated page records its path alone: a static host serves the same file\n * whatever the query, so the browser checks the path and ignores the query. A\n * path with a query or fragment, or two paths that would be one file, are\n * refused.\n */\nconst generate = <\n Model,\n Fields extends Schema.Struct.Fields,\n const Paths extends ReadonlyArray<string>,\n Message = any,\n>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n readonly template: string\n readonly origin: string\n readonly paths: Paths\n readonly flags?: ((path: string) => unknown) | undefined\n readonly head?: Head | undefined\n },\n): Effect.Effect<GeneratedPages<Paths>, RenderError | ResumeUnsafe> =>\n Effect.gen(function* () {\n const files = new Map<string, string>()\n for (const path of options.paths) {\n if (!path.startsWith('/') || /[?#]/.test(path)) {\n return yield* new ResumeUnsafe({\n reason: 'UngeneratablePath',\n message: `\"${path}\" is not a path a file can be served at: start it with / and leave out any query or fragment`,\n })\n }\n const other = files.get(fileOf(path))\n if (other !== undefined) {\n return yield* new ResumeUnsafe({\n reason: 'UngeneratablePath',\n message: `\"${other}\" and \"${path}\" would both be written to ${fileOf(path)}`,\n })\n }\n files.set(fileOf(path), path)\n }\n const pages = yield* Effect.forEach(options.paths, path =>\n renderMatching(\n config,\n plan,\n {\n buildId: options.buildId,\n url: new URL(path, options.origin).href,\n ...(options.flags === undefined ? {} : { flags: options.flags(path) }),\n },\n 'path',\n ).pipe(\n Effect.map(served => served.page),\n Effect.tap(result => reportUnnamed(config, plan, result.unnamed)),\n Effect.map(result => ({\n path,\n file: fileOf(path),\n html: page(options.template, result, { head: options.head }),\n })),\n ),\n )\n // One page per path, in order, so the array is the tuple the paths describe.\n return pages as unknown as GeneratedPages<Paths>\n })\n\n/**\n * The server entry for Foldkit's pipeline: the `renderPage` a dev server,\n * a fetch handler, or `handleRequest` calls, and that the `fetch.js` a Foldkit\n * build emits imports from the server entry module, so a resumed page is\n * served by Node and Workers alike.\n *\n * `GET` and `HEAD` render the page against the plan, with the request's URL\n * and, when the application has Flags, `flags(request)`; `prepare(model,\n * request)` turns the Model `init` gave into the one rendered, a read made\n * before the render (`Data.satisfy`). `POST` goes to\n * `SSR.handle` when the plan has a server fallback, and is answered `400` when\n * the post is unusable. `OPTIONS` is answered `204`, and any other method\n * `405`, each with the methods the entry answers in `allow` (`handleRequest`\n * passes every method through). A render that fails, or a plan the render\n * refuses, is answered `500` with the reason reported (`diagnostics`), never with a page the\n * browser cannot resume. `headers(request, model)` is set over Foldkit's own\n * on every answer: a cache policy, a CORS answer to a preflight, or a cookie\n * written from the Model a post reached. `status(model, request)` gives a page\n * its status from that Model, `404` for a route not found.\n *\n * The page is answered as `Rendered`: the rendered application carries the\n * envelope in its root, so the host injects it into its own template with\n * Foldkit's `injectIntoTemplate`, and a build can generate it with Foldkit's\n * `prerender`. The template, and the container it fills, are the host's:\n * `handleRequest` still classifies static misses and answers `HEAD` without\n * a body.\n *\n * What the page says of itself (`meta`) belongs in the head, which the host\n * owns here: the entry carries it in the rendered root, and the host's\n * document renderer, wrapped in `SSR.headed`, moves it before `</head>`.\n */\nconst entry = <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 readonly flags?: ((request: Request) => unknown | PromiseLike<unknown>) | undefined\n /**\n * The Model a request starts from, from the one `init` gave: what the page\n * shows read first (`Data.satisfy`), or what the request carries (a\n * cookie). Run for `GET`, `HEAD` and a posted form, before the post's\n * Message is checked or `update` runs, so the entry is made once. A\n * failure is answered `500` and reported; to draw the page unread\n * instead, recover inside the Effect.\n */\n readonly prepare?: Prepare<Model> | undefined\n /**\n * Headers set over the entry's own on every answer. `model` is the Model\n * the server reached for a rendered page, a posted form's after `update`;\n * it is `none` for an answer that rendered nothing (`OPTIONS`, `405`, a\n * refused post, a `500`). So a cookie kept from the Model is written here.\n * A name or value no `Headers` takes (a CR or LF in a value), a header that\n * frames the response (`content-length`, `transfer-encoding`, `connection`\n * and the like) or `location`, which only the entry writes, is answered\n * `500` and reported, as `headers` that throw are.\n */\n readonly headers?: ((request: Request, model: Option.Option<Model>) => HeadersInit) | undefined\n /**\n * A posted form's own services, from its request (who is asking, a\n * client bound to them), for the Commands the fallback runs; where one is\n * also the config's, the request's is used. A render runs no Command, so\n * it reads the request through `flags`. The Layer may neither fail nor\n * need a service: one that refuses who is asking (a session that ended)\n * decides before this, in the host, or dies here into a 500.\n */\n readonly resources?: ((request: Request) => Layer.Layer<never, never, never>) | undefined\n /**\n * The origins a form may be posted from, required by a plan with a server\n * fallback: a post whose `Origin` (which\n * every browser sends on one) is not among them is a 403 before its body\n * is read, so a page elsewhere cannot post as someone signed in here. A\n * form cannot carry a CSRF header; this is its check. A post with no\n * `Origin` or `Origin: null` (a page served with `Referrer-Policy:\n * no-referrer`) is taken when `Sec-Fetch-Site` says `same-origin`. Each must be an origin exactly as\n * a browser sends it (`https://example.com`). `'same-origin'` takes a\n * post from the origin the request was addressed to and no other, for a\n * site served at addresses not known when the entry is made (a dev\n * server's port). It compares with the request's own URL, so behind a\n * proxy that terminates TLS (the server sees `http://`, the browser\n * sends `Origin: https://`) or rewrites the host, every post is refused\n * 403: there, name the public origin (`['https://example.com']`).\n */\n readonly origins?: ReadonlyArray<string> | 'same-origin' | undefined\n /**\n * Markup for the first paint, carried as the rendered root's last\n * children, which `SSR.hydrate` moves into the head. The host owns the\n * template in dynamic serving, so this is where per-page styles go;\n * anything else a head owns stays with `SSR.generate`.\n */\n readonly styles?: Head | undefined\n /**\n * The status a rendered page is answered with, from the Model the server\n * reached and the request: `404` for a route the Model says is not found.\n * Omitted, every page is `200`. One outside `200`–`599`, a `204`, `205`\n * or `304` that carries no body, or a `status` that throws, is answered\n * `500` and reported, as a failed render is.\n */\n readonly status?: ((model: Model, request: Request) => number) | undefined\n /**\n * Where a `GET` or `HEAD` is sent instead of drawn, from the Model\n * `prepare` made: `some(path)` answers `303` to it and the page is never\n * rendered, `none` renders it. The answer carries the `headers` given that\n * Model, and says `cache-control: private, no-store` over any they set: a\n * redirect is decided for one reader, and no cache keeps or shares it. The\n * path must start with one `/` and stay on this origin\n * (`/sign-in?next=%2Fnotes`); anything else, or a `redirect` that throws,\n * is answered `500` and reported. A posted form is answered by `answerPost`.\n */\n readonly redirect?: ((model: Model, request: Request) => Option.Option<string>) | undefined\n /**\n * How a posted form is answered. `'page'`, the default, is the page\n * `update` reached, at the address the form posted to, so a reload posts\n * again. `'redirect'` is a `303` to that address, which the browser then\n * asks for with a `GET` (Post/Redirect/Get): what the post changed must\n * outlive it where the next request reads it, a cookie `headers` writes\n * from the Model the post reached. A refused post is still a `400`.\n */\n readonly answerPost?: 'page' | 'redirect' | undefined\n /**\n * The paths a build prerenders through this entry (Foldkit's plugin,\n * `ssr.build.prerender`), each one file a static host serves to every\n * visitor, at every query. A request for one of them with no query records\n * its path alone, as `SSR.generate` does, so the file resumes at `/?q=…`\n * and the application starts from that URL. Export the same list as the\n * entry module's `prerenderPaths`, which the plugin reads.\n *\n * Such a page must be one `cache` would keep for every visitor: every\n * read through `pageReader` public, no request header read (not even an\n * absent one, which a file cannot vary by), nothing set by `headers`,\n * and status `200`. Otherwise `renderPage` rejects naming the read, the\n * header or the status, so the build fails. The page answers with no\n * headers of its own, and the cache is not consulted for it.\n */\n readonly prerendered?: ReadonlyArray<string> | undefined\n /**\n * Where this request's diagnostics go, with the request: a request\n * answered 500 (`PageFailed`), a handler the page cannot name, and what\n * a posted form's Commands report. The reporter in the Effect context\n * (`Diagnostics.Reporter`) when not given, by default the log.\n */\n readonly diagnostics?:\n | ((diagnostic: Diagnostic, request: Request) => Effect.Effect<void>)\n | undefined\n /**\n * Keeps rendered `GET` and `HEAD` pages in `store` by build and URL\n * (#428). A page is kept only when every read the render made through\n * `foldkit-remote-server`'s `pageReader` was public, every request\n * header `flags`, `prepare`, `redirect`, `headers` or `status` read was\n * absent (the request's `cookie` included), `headers` set no `cookie` or\n * `cache-control` of its own, and the status is `200`: drawn from the\n * URL alone. It is kept for `maxAge` or its reads' shortest, and serves\n * each later request that also lacks the headers it read; it says\n * `cache-control: public, max-age=…` and `vary` with those names. Every\n * other page says `private, no-store`. A read made other than through\n * `pageReader` is not seen, so `maxAge` is all that bounds it.\n *\n * The render reads a request that records its headers: one handed to\n * `fetch` or `new Request` fails the render. With `check`, for\n * development and tests, a kept page is drawn again for the request it\n * serves, and a difference is reported (`CachedPageDiffers`) and\n * answered with the page drawn again.\n */\n readonly cache?: PageCache | undefined\n },\n): EntryModule => {\n const cache = Option.map(Option.fromUndefinedOr(options.cache), given => ({\n ...given,\n policy: cachePolicy(given),\n }))\n const listed = options.origins === 'same-origin' ? [] : (options.origins ?? [])\n for (const origin of listed) {\n if (!URL.canParse(origin) || new URL(origin).origin !== origin)\n throw new Error(`foldkit-ssr: ${JSON.stringify(origin)} in origins is not an origin`)\n }\n // A post runs `flags`, the config's resources and the post's own, any of\n // which may act as whoever the cookie says posted.\n if (options.answerPost !== undefined && plan.fallback !== 'server') {\n throw new Error(\n `foldkit-ssr: plan \"${plan.id}\" has no server fallback, so no form is posted to answer (answerPost)`,\n )\n }\n if (plan.fallback === 'server' && options.origins === undefined) {\n throw new Error(\n `foldkit-ssr: plan \"${plan.id}\" handles posted forms, which run as whoever posted; name the origins a form may be posted from (origins)`,\n )\n }\n for (const path of options.prerendered ?? []) {\n if (!path.startsWith('/') || /[?#]/.test(path)) {\n throw new Error(\n `foldkit-ssr: \"${path}\" in prerendered is not a path a file can be served at: start it with / and leave out any query or fragment`,\n )\n }\n }\n const prerendered = new Set((options.prerendered ?? []).map(pathKey))\n // A file a static host serves whatever the query, read for no query.\n const matchOf = (url: string): RouteMatch => {\n const route = routeOf(url)\n return !route.includes('?') && prerendered.has(pathKey(route)) ? 'path' : 'full'\n }\n // Required above for every plan that takes a post, the only reader of it.\n const origins = new Set(listed)\n const originsOf = (request: Request): ReadonlySet<string> =>\n options.origins === 'same-origin' ? new Set([new URL(request.url).origin]) : origins\n const allow = plan.fallback === 'server' ? 'GET, HEAD, POST, OPTIONS' : 'GET, HEAD, OPTIONS'\n // Deleted and appended rather than set, which would keep one `set-cookie` of several.\n const merge = (response: Response, extra: Headers): Response => {\n for (const name of new Set(extra.keys())) response.headers.delete(name)\n extra.forEach((value, name) => response.headers.append(name, value))\n return response\n }\n // `Headers` refuses a name that is no token and a value holding CR, LF or NUL.\n const headersOf = (request: Request, model: Option.Option<Model>): Headers | undefined => {\n if (options.headers === undefined) return undefined\n const headers = new Headers(options.headers(request, model))\n for (const name of headers.keys()) {\n if (ENTRY_HEADERS.has(name)) {\n throw new Error(`headers set ${name}, which the entry writes and an application may not`)\n }\n }\n return headers\n }\n /**\n * One request answered. `watched`, for a render that may be kept, records\n * what the render read of the request's headers and through `pageReader`.\n */\n const answer = async (given: Request, watched?: Watched): Promise<EntryResult> => {\n const request = watched === undefined ? given : tracked(given, watched.read)\n const method = request.method.toUpperCase()\n const posting = method === 'POST' && plan.fallback === 'server'\n const { diagnostics } = options\n const reported = reportingTo(\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, given),\n )\n const reporting = <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n reported(\n watched === undefined\n ? effect\n : Effect.provideService(\n effect,\n PageReads,\n Option.some(read => watched.reads.push(read)),\n ),\n )\n // An answer that rendered nothing, with the headers given no Model. A 500\n // is reported already, so `headers` failing again for it is not.\n const responded = async (\n response: Response,\n { reported = false } = {},\n ): Promise<EntryResult> => {\n let extra: Headers | undefined\n try {\n extra = headersOf(request, Option.none())\n } catch (error) {\n if (!reported) {\n await Effect.runPromise(\n reporting(Diagnostics.report(pageFailed(request.url, Cause.die(error)))),\n )\n }\n return Responded(plainText(500, 'The page could not be rendered.'))\n }\n return Responded(extra === undefined ? response : merge(response, extra))\n }\n if (method === 'OPTIONS')\n return responded(new Response(null, { status: 204, headers: { allow } }))\n if (method !== 'GET' && method !== 'HEAD' && !posting) {\n return responded(new Response(null, { status: 405, headers: { allow } }))\n }\n if (posting && !postedFrom(request, originsOf(request))) {\n return responded(plainText(403, 'The form was not posted from this site.'))\n }\n const flagsOf = options.flags\n const statusOf = options.status\n const redirectOf = options.redirect\n const { prepare } = options\n // The plan's `meta` rides in the root until the host's `SSR.headed` moves it.\n const styled = {\n ...(options.styles === undefined ? {} : { styles: options.styles }),\n metaInRoot: true,\n }\n // `Effect.result` would miss a defect, such as a view that throws, and a\n // `flags` that throws or rejects is not in the Effect at all: both would\n // reject `renderPage` instead of answering it.\n const exit = await Effect.runPromiseExit(\n Effect.gen(function* () {\n const flags =\n flagsOf === undefined ? undefined : yield* Effect.tryPromise(async () => flagsOf(request))\n const flagged = flagsOf === undefined ? {} : { flags }\n const prepared = prepare === undefined ? {} : { prepare }\n // Built for a post alone: a GET runs no Command, and no `resources`.\n const post = () => ({\n buildId: options.buildId,\n ...flagged,\n ...styled,\n ...prepared,\n ...(options.resources === undefined ? {} : { resources: options.resources(request) }),\n })\n if (posting && options.answerPost === 'redirect') {\n const model = yield* postedModel(request, config, plan, post())\n const extra = yield* Effect.sync(() => headersOf(request, Option.some(model)))\n const redirect = new Response(null, {\n status: 303,\n headers: { location: sameAddress(request.url) },\n })\n return Responded(extra === undefined ? redirect : merge(redirect, extra))\n }\n const start = { url: request.url, ...flagged }\n // Made before the render only when something reads it there.\n const started =\n posting || (prepare === undefined && redirectOf === undefined)\n ? Option.none()\n : Option.some(yield* preparedStart(request, config, start, prepare))\n const sentTo = Option.flatMap(started, ({ model }) =>\n redirectOf === undefined\n ? Option.none()\n : Option.map(redirectOf(model, request), path => ({ path, model })),\n )\n if (Option.isSome(sentTo)) {\n const { path, model } = sentTo.value\n // A path off this origin, or `headers` that throw, is a defect, answered 500.\n return yield* Effect.sync(() =>\n Responded(redirected(path, request.url, headersOf(request, Option.some(model)))),\n )\n }\n const served = posting\n ? yield* handleServed(request, config, plan, post())\n : yield* renderMatching(\n Option.match(started, { onNone: () => config, onSome: ({ config }) => config }),\n plan,\n { buildId: options.buildId, ...start, ...styled },\n matchOf(request.url),\n )\n // `headers` or `status` that throws is a defect, answered 500 and reported.\n const extra = yield* Effect.sync(() => headersOf(request, Option.some(served.model)))\n const status = Option.map(Option.fromUndefinedOr(statusOf), of => of(served.model, request))\n const unanswerable = Option.filter(\n status,\n given =>\n !Number.isInteger(given) ||\n given < 200 ||\n given > 599 ||\n given === 204 ||\n given === 205 ||\n given === 304,\n )\n if (Option.isSome(unanswerable)) {\n return yield* Effect.die(\n new Error(\n `status gave ${unanswerable.value} for the page, which is no status for a page with a body`,\n ),\n )\n }\n yield* reportUnnamed(config, plan, served.page.unnamed)\n // No `headers` or `status` key unless given: a `Rendered` that carries\n // neither stays generatable as a static file.\n return Rendered(served.page.rendered, {\n ...(extra === undefined ? {} : { headers: extra }),\n ...Option.match(status, { onNone: () => ({}), onSome: status => ({ status }) }),\n })\n }).pipe(reporting),\n )\n if (Exit.isFailure(exit)) {\n const refused = Cause.findErrorOption(exit.cause).pipe(\n Option.filter(error => error instanceof FallbackRefused),\n )\n if (Option.isSome(refused)) {\n return responded(plainText(400, `The form could not be handled: ${refused.value.message}`))\n }\n await Effect.runPromise(reporting(Diagnostics.report(pageFailed(request.url, exit.cause))))\n return responded(plainText(500, 'The page could not be rendered.'), { reported: true })\n }\n return exit.value\n }\n /**\n * A prerendered page, as the file every visitor is given: refused, by\n * rejecting, unless it was drawn from its URL alone and sets nothing a\n * file cannot carry.\n */\n const prerender = async (request: Request): Promise<EntryResult> => {\n const watched: Watched = { read: { names: new Set(), all: false }, reads: [] }\n const result = await answer(request, watched)\n const refuse = (reason: string) =>\n new Error(\n `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)`,\n )\n if (result._tag !== 'Rendered') throw refuse(`it was answered ${result.response.status}`)\n const set = [...new Headers(result.headers).keys()]\n const refused = notPublic(result.status ?? 200, watched).pipe(\n Option.orElse(() =>\n watched.read.names.size === 0\n ? Option.none()\n : Option.some(\n `it read the request's ${inWords([...watched.read.names])} header${watched.read.names.size > 1 ? 's' : ''}`,\n ),\n ),\n Option.orElse(() =>\n set.length === 0 ? Option.none() : Option.some(`its headers set ${inWords(set)}`),\n ),\n )\n if (Option.isSome(refused)) throw refuse(refused.value)\n return Rendered(result.application)\n }\n const prerendering = (request: Request): boolean => {\n const method = request.method.toUpperCase()\n return (method === 'GET' || method === 'HEAD') && matchOf(request.url) === 'path'\n }\n if (Option.isNone(cache)) {\n return {\n renderPage: request => (prerendering(request) ? prerender(request) : answer(request)),\n }\n }\n const { store, check, policy } = cache.value\n const reportTo = (request: Request) => {\n const { diagnostics } = options\n return reportingTo(\n diagnostics === undefined ? undefined : diagnostic => diagnostics(diagnostic, request),\n )\n }\n /** A page no store may keep for another request: its own `cache-control` stands. */\n const unkept = (result: EntryResult): EntryResult => {\n if (result._tag !== 'Rendered' || Option.isSome(headerOf(result.headers, 'cache-control')))\n return result\n const headers = new Headers(result.headers)\n headers.set('cache-control', 'private, no-store')\n return Rendered(result.application, { ...result, headers })\n }\n /** The page as a store keeps it, when nothing it was drawn from was the request's own. */\n const keepable = (\n request: Request,\n result: EntryResult,\n watched: Watched,\n ): Option.Option<{\n readonly page: KeptPage\n readonly maxAge: CachePolicy\n readonly tags: ReadonlyArray<string>\n }> => {\n if (result._tag !== 'Rendered' || Option.isSome(notPublic(result.status ?? 200, watched)))\n return Option.none()\n if (![...watched.read.names].every(name => !request.headers.has(name))) return Option.none()\n if (\n Option.isSome(headerOf(result.headers, 'set-cookie')) ||\n Option.isSome(headerOf(result.headers, 'cache-control'))\n )\n return Option.none()\n let shortest = policy\n const tags = new Set<string>()\n for (const read of watched.reads) {\n if (read._tag === 'Private') continue\n shortest = shorterPolicy(shortest, read.policy)\n for (const tag of read.tags) tags.add(tag)\n }\n const vary = [...watched.read.names].sort()\n const headers = new Headers(result.headers)\n headers.set('cache-control', `public, max-age=${maxAgeSeconds(shortest)}`)\n if (vary.length > 0) headers.set('vary', vary.join(', '))\n return Option.some({\n page: {\n application: result.application,\n ...(result.status === undefined ? {} : { status: result.status }),\n headers: [...headers],\n vary,\n },\n maxAge: shortest,\n tags: [...tags],\n })\n }\n const served = (page: KeptPage): EntryResult => {\n keptApplications.add(page.application)\n return Rendered(page.application, {\n ...(page.status === undefined ? {} : { status: page.status }),\n headers: page.headers.map(([name, value]): [string, string] => [name, value]),\n })\n }\n const renderPage = async (request: Request): Promise<EntryResult> => {\n if (prerendering(request)) return prerender(request)\n const method = request.method.toUpperCase()\n if (method !== 'GET' && method !== 'HEAD') return unkept(await answer(request))\n const key = await Effect.runPromise(pageKey(options.buildId, request.url))\n const kept = Option.filter(\n Option.flatMap(await Effect.runPromise(store.match(key)), decodeKept),\n page => fits(request, page.vary),\n )\n if (Option.isSome(kept)) {\n if (check !== true) return served(kept.value)\n const again = await answer(request)\n if (again._tag === 'Rendered' && samePage(again, kept.value, Date.now()))\n return served(kept.value)\n await Effect.runPromise(reportTo(request)(Diagnostics.report(cachedPageDiffers(request.url))))\n return unkept(again)\n }\n const watched: Watched = { read: { names: new Set(), all: false }, reads: [] }\n const result = await answer(request, watched)\n return Option.match(keepable(request, result, watched), {\n onNone: () => unkept(result),\n onSome: ({ page, maxAge, tags }) =>\n Effect.runPromise(\n Effect.as(\n store.put(key, JSON.stringify(page), { maxAge: maxAge.maxAge, tags }),\n served(page),\n ),\n ),\n })\n }\n return { renderPage }\n}\n\n/** What a render that may be kept read: of its request's headers, and through `pageReader`. */\ninterface Watched {\n readonly read: HeadersRead\n readonly reads: Array<CachedRead>\n}\n\n/**\n * Why a render drew a page from more than its URL, so it is no page every\n * visitor may be given: one not answered `200`, one that read every header,\n * or one that made a private read. None when it drew it from the URL alone,\n * the headers it read by name aside, which `cache` varies by and a\n * prerendered file cannot.\n */\nconst notPublic = (status: number, watched: Watched): Option.Option<string> => {\n if (status !== 200) return Option.some(`it was answered ${status}`)\n if (watched.read.all) {\n return Option.some(\n 'it read every header of its request (it listed them, cloned the request or read a request context)',\n )\n }\n for (const read of watched.reads) {\n if (read._tag === 'Private') {\n return Option.some(\n `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)`,\n )\n }\n }\n return Option.none()\n}\n\n/** Names in a sentence: `a`, `a and b`, `a, b and c`. */\nconst inWords = (names: ReadonlyArray<string>): string =>\n names.length < 2 ? names.join('') : `${names.slice(0, -1).join(', ')} and ${names.at(-1)}`\n\n/** Where `SSR.entry` keeps pages, for how long, and whether it checks them (`cache`). */\nexport type PageCache = CacheOptions & {\n readonly store: PageCacheStore\n readonly check?: boolean | undefined\n}\n\n/**\n * The page cache's checker, for a test: builds the entry with `make`, given a\n * store in memory and `check`, and answers each request twice, so a page\n * kept for one request is drawn again for every later one it serves.\n * Rejects naming each page drawn otherwise for a request it served, and\n * when no page was kept, which would check nothing. Give requests that\n * differ in who asks (a visitor's, and one with someone's cookie); each is a\n * function, since a request is read once.\n */\nconst checkCache = async (\n make: (options: {\n readonly cache: PageCache\n readonly diagnostics: (diagnostic: Diagnostic) => Effect.Effect<void>\n }) => EntryModule,\n requests: ReadonlyArray<() => Request>,\n): Promise<void> => {\n const store = CacheStore.memory()\n const differs: Array<string> = []\n const entry = make({\n cache: { store, maxAge: '1 hour', check: true },\n diagnostics: diagnostic =>\n Effect.sync(() => {\n // tag-check: open -- a Diagnostic's tag is any package's; this one is ours.\n if (diagnostic._tag === 'CachedPageDiffers') differs.push(diagnostic.message)\n }),\n })\n for (const _round of [1, 2]) {\n for (const request of requests) await entry.renderPage(request())\n }\n if (differs.length > 0) throw new Error(differs.join('\\n'))\n if (store.size() === 0) {\n throw new Error('SSR.checkCache: no page was kept, so nothing was checked')\n }\n}\n\n/**\n * Where a post's answer sends the browser: the address it posted to, its path\n * and query alone. Relative, so the browser resolves it against that address\n * and it names no other origin, whatever `Host` the request claimed; leading\n * slashes collapse to one, since `//elsewhere.test/` would name another host.\n */\nconst sameAddress = (url: string): string => {\n const { pathname, search } = new URL(url)\n return `${pathname.replace(/^\\/+/, '/')}${search}`\n}\n\n/**\n * `SSR.entry`'s answer to a page `redirect` sends elsewhere: a `303` to `path`\n * with the entry's `headers`, said `private, no-store` over theirs, since it\n * was decided for one reader. Throws for a path that is not one on the\n * request's own origin: resolved there, it must keep that origin and start\n * with a single `/`, so `//elsewhere.test`, `/\\elsewhere.test` (which a\n * browser reads as `//`), a scheme, or a path whose dot segments resolve to\n * `//` are refused. The location written is the path as resolved.\n */\nconst redirected = (path: string, url: string, headers: Headers | undefined): Response => {\n const origin = new URL(url).origin\n const resolved = path.startsWith('/') ? new URL(path, origin) : undefined\n if (resolved === undefined || resolved.origin !== origin || resolved.pathname.startsWith('//')) {\n throw new Error(\n `redirect gave ${JSON.stringify(path)}, which is no path on this origin: give one starting with a single /`,\n )\n }\n const response = new Response(null, {\n status: 303,\n headers: { location: `${resolved.pathname}${resolved.search}${resolved.hash}` },\n })\n headers?.forEach((value, name) => response.headers.append(name, value))\n // Set over whatever `headers` said: the redirect was decided for this reader.\n response.headers.set('cache-control', 'private, no-store')\n return response\n}\n\n/**\n * What `headers` may not set: what frames the response, which the host's\n * server writes, and `location`, which only the entry writes.\n */\nconst ENTRY_HEADERS: ReadonlySet<string> = new Set([\n 'connection',\n 'content-length',\n 'keep-alive',\n 'location',\n 'proxy-connection',\n 'te',\n 'trailer',\n 'transfer-encoding',\n 'upgrade',\n])\n\n/**\n * Whether a post came from one of `origins`, by what the browser sends and no\n * page or form can set: its `Origin`, or, where that is missing or opaque\n * (`Origin: null`, which a page served with `Referrer-Policy: no-referrer`\n * sends on its own forms), its Fetch Metadata `Sec-Fetch-Site`. A post with\n * neither header is refused. `foldkit-auth`'s resolver decides the same way.\n */\nconst postedFrom = (request: Request, origins: ReadonlySet<string>): boolean => {\n const origin = request.headers.get('origin')\n return origin === null || origin === 'null'\n ? request.headers.get('sec-fetch-site') === 'same-origin'\n : origins.has(origin)\n}\n\nconst plainText = (status: number, body: string): Response =>\n new Response(body, { status, headers: { 'content-type': 'text/plain; charset=utf-8' } })\n\n/** How a form's Message is written into the page for the fallback, when the plan has one. */\nconst fallbackEncoder = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n): ((message: unknown) => string | undefined) | undefined => {\n if (plan.fallback !== 'server' || plan.Message === undefined) return undefined\n const encode = Schema.encodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n return message => {\n const encoded = encode(message)\n return Result.isFailure(encoded) ? undefined : JSON.stringify(encoded.success)\n }\n}\n\n/** Why a posted form was not handled: the request, not the page or the plan, is at fault. */\nexport class FallbackRefused extends Schema.TaggedError<FallbackRefused>()('FallbackRefused', {\n reason: Schema.Literals(['Missing', 'Unreadable', 'Invalid', 'Unlisted', 'NoFallback']),\n message: Schema.String,\n}) {}\n\nconst refuseFallback = (reason: FallbackRefused['reason'], message: string) =>\n Effect.fail(new FallbackRefused({ reason, message }))\n\n/** A Command as Foldkit runs it: named, with the Effect that yields its Message. */\ninterface RunnableCommand {\n readonly name: string\n readonly effect: Effect.Effect<unknown, unknown, any>\n}\n\nconst isRunnable = (command: unknown): command is RunnableCommand =>\n typeof command === 'object' &&\n command !== null &&\n 'effect' in command &&\n Effect.isEffect(command.effect)\n\n/**\n * The most Messages and Commands one post may run. The browser's loop runs\n * for the life of the page, so a Command that schedules itself again, a tick\n * or a poll, is ordinary there; on the server it would hold the request open\n * for ever.\n */\nconst MAX_STEPS = 100\n\n/**\n * Foldkit's loop, once, on the server: `update` for each Message, then each\n * returned Command run under the config's `resources`, its Message folded\n * back through `update`, until no Command remains.\n */\nconst fold = <Model>(\n config: ResumableConfig<Model>,\n post: Context.Context<never>,\n model: Model,\n messages: ReadonlyArray<unknown>,\n commands: ReadonlyArray<unknown>,\n): Effect.Effect<Model> =>\n Effect.gen(function* () {\n let current = model\n const pending = [...messages]\n const queue = [...commands]\n let steps = 0\n let last = ''\n while (pending.length > 0 || queue.length > 0) {\n if (++steps > MAX_STEPS) {\n return yield* Effect.die(\n new Error(\n `SSR.handle: the post did not settle within ${MAX_STEPS} Messages and Commands; the last Command run was \"${last}\". A Command that schedules itself again cannot run on the server`,\n ),\n )\n }\n if (pending.length > 0) {\n const next = config.update(current, pending.shift()) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = next.model\n queue.push(...(next.commands ?? []))\n continue\n }\n const command = queue.shift()\n if (!isRunnable(command)) {\n return yield* Effect.die(\n new Error(`SSR.handle: a Command has no Effect to run: ${JSON.stringify(command)}`),\n )\n }\n // A Command that fails would crash Foldkit's runtime; here it is a defect\n // the entry answers with 500, since the config declares its requirements.\n // The post's own services first, so one it shares with the config's is its own.\n const own = Effect.provide(command.effect, post)\n const provided: Effect.Effect<unknown, unknown, never> =\n config.resources === undefined\n ? (own as Effect.Effect<unknown, unknown, never>)\n : (Effect.provide(own, config.resources) as Effect.Effect<unknown, unknown, never>)\n last = command.name\n const result = yield* Effect.orDie(provided)\n // A Command fired and forgotten yields no Message, and folds nothing in.\n if (result !== undefined && result !== null) pending.push(result)\n }\n return current\n })\n\n/** The Model `init` gives this request, as the server's render would start from. */\nconst startOf = <Model>(\n config: ResumableConfig<Model>,\n options: { readonly url?: string | undefined; readonly flags?: unknown },\n): Effect.Effect<ReturnType<ResumableConfig<Model>['init']>, RenderError> =>\n Effect.gen(function* () {\n let started: ReturnType<ResumableConfig<Model>['init']> | undefined\n yield* renderToString(\n {\n ...config,\n init: (...args: ReadonlyArray<unknown>) => (started = config.init(...args)),\n // Only `init`'s answer is wanted. The application's view drawn here\n // would also fill its memoized drawings (`createLazy`) outside any\n // render the plan records, and the post's own render, from a Model\n // holding the same values, would reuse them without their markers.\n view: (_model: unknown, h: HtmlBuilder<unknown>) => ({ title: '', body: h.div([], []) }),\n } as never,\n { buildId: 'x', ...options } as never,\n )\n return started!\n })\n\n/** Turns the Model `init` gave into the one a request starts from. */\nexport type Prepare<Model> = (model: Model, request: Request) => Effect.Effect<Model, unknown>\n\n/**\n * The config a request starts from: `init`'s answer, its Model prepared. A\n * failed `prepare` is a defect, answered 500 and reported as a failed render.\n */\nconst preparedStart = <Model>(\n request: Request,\n config: ResumableConfig<Model>,\n options: { readonly url: string; readonly flags?: unknown },\n prepare: Prepare<Model> | undefined,\n): Effect.Effect<{ readonly model: Model; readonly config: ResumableConfig<Model> }, RenderError> =>\n Effect.gen(function* () {\n const started = yield* startOf(config, options)\n const model =\n prepare === undefined ? started.model : yield* Effect.orDie(prepare(started.model, request))\n return {\n model,\n config: startingFrom(config, { ...started, model }) as ResumableConfig<Model>,\n }\n })\n\n/**\n * Answers a form posted by a page rendered with `fallback: 'server'`: the\n * posted Message is decoded through the plan's Message Schema, with posted\n * fields of the same names as its own overriding them, and must be one the\n * Surfaces active for the request's Model may send. The server then rebuilds\n * the Model the browser had, `init`, `prepare` and then the plan's `boot` with every\n * Command it leads to, runs `update` with the Message and every Command that\n * follows, and renders the result as a fresh page.\n */\nconst handle = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n request: Request,\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: HandleOptions<Model>,\n): Effect.Effect<RenderedPage, RenderError | ResumeUnsafe | FallbackRefused> =>\n Effect.map(handleServed(request, config, plan, options), served => served.page)\n\ninterface HandleOptions<Model> {\n readonly buildId: string\n readonly flags?: unknown\n readonly styles?: Head | undefined\n /** Carry the plan's `meta` in the root for `SSR.headed`, as `SSR.entry` serves a post's page. */\n readonly metaInRoot?: boolean | undefined\n /** The Model the post starts from, from `init`'s, as `SSR.entry`'s `prepare`. */\n readonly prepare?: Prepare<Model> | undefined\n /**\n * This post's own services, beside the config's `resources`: who is\n * asking, a client bound to them. Built once for the post; where both\n * provide a service, the post's is the one its Commands get.\n */\n readonly resources?: Layer.Layer<never, never, never> | undefined\n}\n\nconst handleServed = <Model, Fields extends Schema.Struct.Fields>(\n request: Request,\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n options: HandleOptions<Model>,\n): Effect.Effect<Served<Model>, RenderError | ResumeUnsafe | FallbackRefused> =>\n Effect.flatMap(postedModel(request, config, plan, options), model =>\n renderMatching(\n startingFrom(config, { model }) as ResumableConfig<Model>,\n plan,\n {\n buildId: options.buildId,\n url: request.url,\n ...(options.styles === undefined ? {} : { styles: options.styles }),\n ...(options.metaInRoot === true ? { metaInRoot: true } : {}),\n },\n 'full',\n ),\n )\n\n/** The Model a posted form reaches: its Message decoded and checked, then `update` and its Commands. */\nconst postedModel = <Model, Fields extends Schema.Struct.Fields>(\n request: Request,\n config: ResumableConfig<Model>,\n plan: ResumePlan<Model, Fields>,\n options: HandleOptions<Model>,\n): Effect.Effect<Model, RenderError | FallbackRefused> =>\n // The post's resources live as long as the post.\n Effect.scoped(\n Effect.gen(function* () {\n if (plan.fallback !== 'server' || plan.Message === undefined) {\n return yield* refuseFallback('NoFallback', `plan \"${plan.id}\" has no server fallback`)\n }\n const form = yield* Effect.tryPromise({\n try: () => request.formData(),\n catch: () =>\n new FallbackRefused({ reason: 'Unreadable', message: 'the body is not a form' }),\n })\n const posted = form.get(FALLBACK_FIELD)\n if (typeof posted !== 'string') {\n return yield* refuseFallback('Missing', `the form carries no ${FALLBACK_FIELD} field`)\n }\n let raw: unknown\n try {\n raw = JSON.parse(posted)\n } catch {\n return yield* refuseFallback('Unreadable', `${FALLBACK_FIELD} is not JSON`)\n }\n const decode = Schema.decodeUnknownResult(plan.Message as Schema.Codec<unknown, unknown>)\n const invalid = (failure: { readonly message: string }) =>\n refuseFallback('Invalid', `the posted Message does not decode: ${failure.message}`)\n // The posted Message is decoded before anything reads it.\n const written = decode(raw)\n if (Result.isFailure(written)) return yield* invalid(written.failure)\n // A form inside a placement posts the parent's Message; the fields it\n // names sit `depth` wrappers down.\n const postedDepth = form.get(FALLBACK_DEPTH_FIELD) ?? '0'\n if (typeof postedDepth !== 'string' || !/^\\d{1,2}$/.test(postedDepth)) {\n return yield* refuseFallback('Unreadable', `${FALLBACK_DEPTH_FIELD} is not a depth`)\n }\n const override = (value: unknown, down: number): unknown => {\n if (typeof value !== 'object' || value === null) return value\n const copy: Record<string, unknown> = { ...value }\n if (down > 0) {\n copy.message = override(copy.message, down - 1)\n return copy\n }\n form.forEach((field, name) => {\n if (name !== FALLBACK_FIELD && Object.hasOwn(copy, name) && typeof field === 'string') {\n copy[name] = field\n }\n })\n return copy\n }\n // The fields typed into the form, set into the Message and decoded again.\n const decoded = decode(override(raw, Number(postedDepth)))\n if (Result.isFailure(decoded)) return yield* invalid(decoded.failure)\n const message = decoded.success\n const started = yield* startOf(config, { url: request.url, ...options })\n const { prepare } = options\n const start =\n prepare === undefined ? started.model : yield* Effect.orDie(prepare(started.model, request))\n const allowed = allowedTags(plan, start)\n if (!allowed.has(tagOf(message))) {\n return yield* refuseFallback(\n 'Unlisted',\n `the posted ${tagOf(message)} is not one an active Surface lists in its messages`,\n )\n }\n // As the browser got here: `init` on the server, then the plan's `boot`\n // at hydration, and only then the user's Message. `init`'s own Commands\n // never run in the browser, so they do not run here.\n const boot = (plan.boot?.(start) as ReadonlyArray<unknown> | undefined) ?? []\n const post =\n options.resources === undefined ? Context.empty() : yield* Layer.build(options.resources)\n const booted = yield* fold(config, post, start, [], boot)\n return yield* fold(config, post, booted, [message], [])\n }),\n )\n\nexport const SSR = {\n plan,\n envelope,\n resume,\n render,\n page,\n hydrate: Client.hydrate,\n inspect,\n static: staticRegion,\n unbound,\n serving,\n generate,\n entry,\n checkCache,\n keptDocuments,\n headed,\n handle,\n serializeJsonScript,\n sitemap,\n robots,\n requestContext,\n}\n\nexport type { RequestContext } from './requestContext.js'\n\nexport {\n FOLDKIT_APP_ATTRIBUTE,\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n Resume,\n ResumeRefused,\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n UNTIL_LIMIT_MS,\n metaMarkup,\n type DecodedBinding,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableBuilder,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n type UnnamedHandler,\n type BundleUnloaded,\n type CachedPageDiffers,\n type HandlerUnnamed,\n type HeadNotMoved,\n type PageContained,\n type PageFailed,\n type SsrDiagnostic,\n type StaticRegionMissing,\n Diagnostics,\n type Diagnostic,\n type ReportDiagnostic,\n} from './client.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiGA,MAAM,gBAAgB,OAAO,IAAI,2BAA2B;;AAG5D,MAAM,qBACJ,MACA,UACG,KAAK,SAAS,SAAQ,WAAU,cAAc,QAAQ,KAAK,CAAC;;;;;AAYjE,MAAM,aACJ,MACA,UACY;CACZ,MAAM,QAAQ,OAAO,WAAW,QAAQ,KAAK,MAAM,MAAM,CAAC,CAAC,CAAC,KAAK,MAAM,IAAI,KAAK,CAAC;CACjF,IAAI,KAAK,MAAM,WAAW,GAAG,OAAO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,QAAQ;CACxB,MAAM,UAAU,OAAO,QAAQ,QAAQ;EAAE,KAAK,QAAQ;EAAK,GAAG;CAAQ,CAAC;CACvE,MAAM,EAAE,YAAY;CACpB,MAAM,QACJ,YAAY,KAAA,IAAY,QAAQ,QAAQ,OAAO,OAAO,MAAM,QAAQ,QAAQ,OAAO,OAAO,CAAC;CAE7F,IAAI,CADY,YAAY,MAAM,KACvB,CAAC,CAAC,IAAI,MAAM,OAAO,CAAC,GAC7B,OAAO,OAAO,eACZ,YACA,cAAc,MAAM,OAAO,EAAE,oDAC/B;CAKF,MAAM,OAAQ,KAAK,OAAO,KAAK,KAA4C,CAAC;CAC5E,MAAM,OACJ,QAAQ,cAAc,KAAA,IAAY,QAAQ,MAAM,IAAI,OAAO,MAAM,MAAM,QAAQ,SAAS;CAC1F,MAAM,SAAS,OAAO,KAAK,QAAQ,MAAM,OAAO,CAAC,GAAG,IAAI;CACxD,OAAO,OAAO,KAAK,QAAQ,MAAM,QAAQ,CAAC,OAAO,GAAG,CAAC,CAAC;AACxD,CAAC,CACH;AAEF,MAAa,MAAM;CACjB;CACA;CACA;CACA;CACA;CACA,SAASC,MAAO;CAChB;CACA,QAAQ;CACR;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF"}
package/dist/keep.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { n as DecodedBinding } from "./listen-DaUPRKVR.js";
1
+ import { n as DecodedBinding } from "./listen-7HzKBhqU.js";
2
2
  import { Result } from "effect";
3
3
  type Field = HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement;
4
4
  /** A marked field and the binding whose Message replays its typing. */
@@ -21,6 +21,10 @@ export declare const typedMessages: (fields: ReadonlyArray<KeptField>) => Readon
21
21
  export interface Held {
22
22
  readonly element: Field;
23
23
  readonly value: string;
24
+ /** A checkbox's or radio's. */
25
+ readonly checked?: boolean | undefined;
26
+ /** A `multiple` select's selected option indices: its `value` names only the first. */
27
+ readonly selected?: readonly number[] | undefined;
24
28
  readonly selection?: readonly [number, number, 'forward' | 'backward' | 'none'] | undefined;
25
29
  }
26
30
  /** Each changed field's state, to put back once hydration has re-asserted the served value. */
@@ -1 +1 @@
1
- {"version":3,"file":"keep.d.ts","names":[],"sources":["../src/keep.ts"],"mappings":";;KAeK,QAAQ,mBAAmB,sBAAsB;;iBAGrC;WACN,SAAS;WACT,SAAS;;;;;;;;qBAcP,aAAU,MACf,SAAO,UACH,cAAc,oBACvB,OAAO,OAAO,cAAc;;qBAsClB,UAAO,OAAW;;qBAIlB,gBAAa,QAAY,cAAc,eAAa;;iBAIhD;WACN,SAAS;WACT;WACA;;;qBAIE,OAAI,QAAY,cAAc,eAAa,cAAc;;;;;qBAkBzD,UAAO,MAAU,cAAc"}
1
+ {"version":3,"file":"keep.d.ts","names":[],"sources":["../src/keep.ts"],"mappings":";;KAgBK,QAAQ,mBAAmB,sBAAsB;;iBAGrC;WACN,SAAS;WACT,SAAS;;;;;;;;qBAkBP,aAAU,MACf,SAAO,UACH,cAAc,oBACvB,OAAO,OAAO,cAAc;;qBA8DlB,UAAO,OAAW;;qBAqBlB,gBAAa,QAAY,cAAc,eAAa;;iBAQhD;WACN,SAAS;WACT;;WAEA;;WAEA;WACA;;;qBAIE,OAAI,QAAY,cAAc,eAAa,cAAc;;;;;qBA2BzD,UAAO,MAAU,cAAc"}