foldkit-ssr 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -200,6 +200,12 @@ const html = SSR.page(template, result, {
200
200
  })
201
201
  ```
202
202
 
203
+ With `foldkit-mixins/vite`, the stylesheet is a hashed file, and the page
204
+ links it from the document's head instead (`renderDocument`'s `head`):
205
+ `<link rel="stylesheet" href="${href}" data-foldkit-styles-href>`. A link in
206
+ the head is fetched before the first paint; `styles`, below, is written as the
207
+ root's last children, so a large page paints unstyled until it has all arrived.
208
+
203
209
  A served page has no template head to write to, so `SSR.render`, `SSR.entry`
204
210
  and `SSR.handle` take the same function as `styles` instead, carried as the
205
211
  rendered root's last children. `foldkit-mixins/foundations` writes the theme
@@ -395,8 +401,8 @@ SSR.entry(config, Post, {
395
401
  ```
396
402
 
397
403
  The page is rendered and resumed as any other; only the response's status
398
- changes. A status outside `200`–`599`, or a `status` that throws, is answered
399
- `500` and reported.
404
+ changes. A status outside `200`–`599`, a `204`, `205` or `304` that cannot
405
+ carry the page, or a `status` that throws, is answered `500` and reported.
400
406
 
401
407
  What the page says of itself (`meta`) and per-page `head` markup are written
402
408
  into a template's head, which the host owns here: a plan with `meta` is
@@ -454,6 +460,87 @@ serves. [`examples/auth`](../../examples/auth)'s `src/host.ts` is the whole
454
460
  site behind one handler; its development server, another process, attaches
455
461
  an HTTP reader instead.
456
462
 
463
+ ### Keeping pages: `cache`
464
+
465
+ A page drawn from its URL alone is the same page for everyone who asks for
466
+ that URL, and drawing it again costs the same every time. With `cache`, the
467
+ entry keeps such a page and answers the next request for it from a store:
468
+
469
+ ```text
470
+ GET url -> kept for this build and url, and the request lacks every header it read?
471
+ -> yes: the kept page
472
+ -> no: render, watching what the render reads
473
+ every read public, every header it read absent, no cookie set, 200?
474
+ -> keep it, cache-control: public, max-age=…, vary: <headers read>
475
+ -> otherwise cache-control: private, no-store
476
+ ```
477
+
478
+ ```ts
479
+ import { CacheStore } from 'foldkit-surface'
480
+
481
+ export const cached = SSR.entry(config, Post, {
482
+ buildId,
483
+ cache: { store: CacheStore.memory(), maxAge: '60 seconds' },
484
+ })
485
+ ```
486
+
487
+ Whether a page may be kept is decided from what its render read, not from
488
+ a declaration. The render is handed a request that records each header
489
+ `flags`, `prepare`, `headers` or `status` reads; a page is kept only when
490
+ every one of them was absent from the request, so it was drawn from the URL
491
+ alone. A header read by name (the cart cookie, say) that was absent goes in
492
+ `vary`, and the kept page serves only requests that lack it too: a request
493
+ with that cookie is drawn for itself, and is never kept. Reading every
494
+ header, cloning the request, or reading an `SSR.requestContext` (which may
495
+ say who is asking) keeps nothing. Handing the request itself to `fetch` or
496
+ `new Request` fails the render, since the platform cannot read the watched
497
+ request.
498
+
499
+ Reads count through `foldkit-remote-server`'s `pageReader`, which notes each
500
+ one (`PageReads`): the page is kept only when every read was public, for the
501
+ shortest of `maxAge` and their freshness, tagged with the rows they hold. A
502
+ write `serveFetch` answers purges, from the same store, the pages holding a
503
+ row it names. A read made other than through `pageReader` is not seen, so
504
+ `maxAge` is all that bounds it. A page whose `headers` set a cookie or a
505
+ `cache-control` of their own, one not `200`, and every post, are not kept;
506
+ an unkept page says `private, no-store` unless `headers` said otherwise.
507
+
508
+ The key is the build id and the full URL, so a deploy never serves another
509
+ build's page (the browser would refuse it anyway, as `OtherBuild`).
510
+ `CacheStore.workers(caches.default)` keeps pages in the Workers Cache API.
511
+
512
+ The host draws each page into its document, which parses the page again
513
+ (Foldkit's `injectIntoTemplate`), so a kept page would still cost that on
514
+ every request. Wrap the server entry's `renderDocument` in
515
+ `SSR.keptDocuments` and the document of a kept page is drawn once per set
516
+ of assets (the last 32 are held):
517
+
518
+ ```ts
519
+ import { renderDocument as renderShell, type DocumentRenderer } from 'foldkit/experimental/server'
520
+
521
+ export const renderDocument: DocumentRenderer = SSR.keptDocuments(renderShell)
522
+ ```
523
+
524
+ The checker draws a kept page again for each request it serves.
525
+ `cache.check` does so on every request a kept page serves, and where the
526
+ two differ reports `CachedPageDiffers` and answers with the page drawn
527
+ again: a development mode. Times stamped on the page (13 digits within a day
528
+ of now, as a read's `updatedAt`) are not compared. `SSR.checkCache(make,
529
+ requests)` is the same, for a test: `make` builds the entry from the
530
+ `cache` and `diagnostics` it is given, and each request is answered twice;
531
+ it rejects a difference, or a set of requests that kept no page. Give it
532
+ requests from more than one reader, a visitor's and one with a cookie:
533
+
534
+ ```ts
535
+ export const checked = SSR.checkCache(
536
+ options => SSR.entry(config, Post, { buildId, ...options }),
537
+ [
538
+ () => new Request('https://example.com/posts/1'),
539
+ () => new Request('https://example.com/posts/1', { headers: { cookie: 'session=abc' } }),
540
+ ],
541
+ )
542
+ ```
543
+
457
544
  ### At build time
458
545
 
459
546
  ```ts
@@ -1,6 +1,6 @@
1
1
  import { o as listen } from "./listen-DaUPRKVR.js";
2
2
  import { g as view, h as builder } from "./resumable-BPN_qQHU.js";
3
- import { E as plan, M as serving, P as staticRegion, c as ResumableConfig, k as resume, u as ResumePlan, y as bindings } from "./shared-DbupL3vO.js";
3
+ import { E as plan, M as serving, P as staticRegion, c as ResumableConfig, k as resume, u as ResumePlan, y as bindings } from "./shared-CJN-m58Z.js";
4
4
  import { Effect, Schema } from "effect";
5
5
  import { Diagnostic as Diagnostic$1, Diagnostics as Diagnostics$1, ReportDiagnostic, ReportDiagnostic as ReportDiagnostic$1 } from "foldkit-surface";
6
6
  /**
@@ -82,4 +82,4 @@ declare const SSR: {
82
82
  serving: typeof serving;
83
83
  };
84
84
  export { SSR as a, Resume as i, Diagnostics$1 as n, UNTIL_LIMIT_MS as o, ReportDiagnostic$1 as r, Diagnostic$1 as t };
85
- //# sourceMappingURL=client-XnpTQZHw.d.ts.map
85
+ //# sourceMappingURL=client-qmdYY-Eb.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"client-XnpTQZHw.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;;;;;;;;;;;cAgFM,UAAW,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAa,QAChE,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;WAEpB;;;;;;;WAOA,SAAS,MAAM;;;;;;;WAOf;;;;;;;;WAQA,UAAU,OAAO;;;;;;;;WAQjB,UAAU;;;;;;;;;;WAUV,YAAY,OAAO,UAAU,OAAO,OAAO;;;;;;;;WAQ3C,cAAc;;;cAwMd;;cAuKA;;;;;;;cAGA"}
1
+ {"version":3,"file":"client-qmdYY-Eb.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;;;;;;;;;;;cAgFM,UAAW,OAAO,eAAe,OAAO,OAAO,QAAQ,eAAa,QAChE,gBAAgB,OAAO,UAAQ,MACjC,WAAW,OAAO,SAAO;WAEpB;;;;;;;WAOA,SAAS,MAAM;;;;;;;WAOf;;;;;;;;WAQA,UAAU,OAAO;;;;;;;;WAQjB,UAAU;;;;;;;;;;WAUV,YAAY,OAAO,UAAU,OAAO,OAAO;;;;;;;;WAQ3C,cAAc;;;cA8Md;;cAuKA;;;;;;;cAGA"}
package/dist/client.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { n as DecodedBinding } from "./listen-DaUPRKVR.js";
2
2
  import { a as FALLBACK_FIELD, d as SLOT_ATTRIBUTE, n as BINDING_ATTRIBUTE, s as KEEP_ATTRIBUTE, u as ResumableBuilder } from "./resumable-BPN_qQHU.js";
3
- import { C as metaMarkup, G as PageContained, J as StaticRegionMissing, K as PageFailed, U as BundleUnloaded, W as HandlerUnnamed, c as ResumableConfig, d as ResumeRefused, h as Start, i as Meta, l as ResumePart, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, q as SsrDiagnostic, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, z as UnnamedHandler } from "./shared-DbupL3vO.js";
4
- import { a as SSR, i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-XnpTQZHw.js";
5
- export { BINDING_ATTRIBUTE, type BundleUnloaded, type DecodedBinding, type Diagnostic, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type HandlerUnnamed, KEEP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, type PageContained, type PageFailed, type PlanSurface, RESUME_ATTRIBUTE, type ReportDiagnostic, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, type SsrDiagnostic, type Start, type StaticRegionMissing, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
3
+ import { C as metaMarkup, G as HandlerUnnamed, J as SsrDiagnostic, K as PageContained, U as BundleUnloaded, W as CachedPageDiffers, Y as StaticRegionMissing, c as ResumableConfig, d as ResumeRefused, h as Start, i as Meta, l as ResumePart, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, q as PageFailed, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, z as UnnamedHandler } from "./shared-CJN-m58Z.js";
4
+ import { a as SSR, i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-qmdYY-Eb.js";
5
+ export { BINDING_ATTRIBUTE, type BundleUnloaded, type CachedPageDiffers, type DecodedBinding, type Diagnostic, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, type HandlerUnnamed, KEEP_ATTRIBUTE, type Loadable, META_ATTRIBUTE, type Meta, type PageContained, type PageFailed, type PlanSurface, RESUME_ATTRIBUTE, type ReportDiagnostic, type ResumableBuilder, type ResumableConfig, Resume, type ResumePart, type ResumePlan, ResumeRefused, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, type SsrDiagnostic, type Start, type StaticRegionMissing, UNTIL_LIMIT_MS, type UnnamedHandler, metaMarkup };
package/dist/client.js CHANGED
@@ -86,7 +86,7 @@ const hydrate$1 = (config, plan, options) => {
86
86
  }
87
87
  const adoptFrom = (model) => {
88
88
  const arrived = arrival(config, document, window.location.href);
89
- const commands = plan.boot?.(model) ?? [];
89
+ const bootCommands = (started) => plan.boot?.(started) ?? [];
90
90
  const resuming = {
91
91
  mode: "resume",
92
92
  snapshots: snapshotsOf(root),
@@ -112,13 +112,13 @@ const hydrate$1 = (config, plan, options) => {
112
112
  const startOf = () => Option.match(arrived, {
113
113
  onNone: () => ({
114
114
  model,
115
- commands
115
+ commands: bootCommands(model)
116
116
  }),
117
117
  onSome: (message) => {
118
118
  const step = apply(model, message);
119
119
  return {
120
120
  model: step.model,
121
- commands: [...commands, ...step.commands ?? []]
121
+ commands: [...bootCommands(step.model), ...step.commands ?? []]
122
122
  };
123
123
  }
124
124
  });
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":["hydrate","Diagnostics","adopt"],"sources":["../src/client.ts"],"sourcesContent":["/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Option, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { Diagnostics, type ReportDiagnostic } from 'foldkit-surface'\nimport { withContext, type RenderContext } from './context.js'\nimport {\n bundleUnloaded,\n noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { hold, keptFields, restore, typedMessages, type Held, type KeptField } from './keep.js'\nimport { listen, type DecodedBinding } from './listen.js'\nimport {\n BINDING_ATTRIBUTE,\n FALLBACK_DEPTH_FIELD,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n builder,\n view,\n} from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n STYLES_MARKER,\n arrival,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is reported (`options.diagnostics`). A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * With `otherwise: 'render'`, when the fresh application is ready to be\n * seen: until a Model it has drawn satisfies this, it draws out of view\n * and the served page stays, so a page is not swapped for its loading\n * state and back. Omitted, the fresh application replaces the page at\n * once. The served page stays no longer than `UNTIL_LIMIT_MS`.\n */\n readonly until?: ((model: Model) => boolean) | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n /**\n * What only this browser adds to the resumed Model before it is adopted,\n * and the view does not draw: a session minted for this page load (an\n * outbox's `session`). Run once, for a page that resumes; the runtime\n * starts when it succeeds. What the view draws, such as a queue read from\n * storage, arrives after, as a Message: here it would make the first\n * client view differ from the served page. Must not fail, as `when` must\n * not throw.\n */\n readonly prepare?: ((model: Model) => Effect.Effect<Model>) | undefined\n /**\n * Where what the page met goes: a page contained rather than resumed, a\n * static region the server's page lacked, a lazy bundle that did not\n * load. Each is reported before or apart from the runtime, so its\n * resources' reporter is not in effect. Omitted, Effect's log: the\n * browser's console.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): void => {\n const report = (diagnostic: SsrDiagnostic): void => {\n Effect.runFork(reportingTo(options.diagnostics)(Diagnostics.report(diagnostic)))\n }\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (root !== null) keepStyles(root)\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n if (options.otherwise !== 'render') contain()\n else if (options.until === undefined)\n run(makeApplication({ ...config, container: root } as never))\n else renderBeside(config, root, options.until)\n return\n }\n // The type says a string, but `import.meta.env` is `any`: with the variable\n // unset the id arrives undefined, and Foldkit, given none, takes its own\n // compiled id, which matches the page, so the baseline was adopted in silence.\n if (typeof options.buildId !== 'string') {\n report(noBuildId)\n contain()\n return\n }\n const served = root.getAttribute(BUILD_ATTRIBUTE)\n if (served !== options.buildId) {\n report(otherBuild(Option.fromNullOr(served), options.buildId))\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n report(pageContained(resumed.failure.reason, resumed.failure.message))\n contain()\n return\n }\n const adoptFrom = (model: Model): void => {\n // A page recorded for its path, opened at a query: the application learns\n // the URL, as from a navigation, and the page starts now, since what it\n // shows is not yet the address.\n const arrived = arrival(config, document, window.location.href)\n const commands = (plan.boot?.(model) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n report,\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n // The URL goes into the Model the runtime starts from, not into `answered`:\n // Subscriptions start from that Model before any Message lands, and a URL\n // mirror among them would write the served address back over the real one.\n // The first render then differs from the served page where the URL does, and\n // Foldkit rebuilds that part, as a navigation would redraw it. Applied at\n // boot, once any lazy bundle's `update` has loaded.\n const startOf = () =>\n Option.match(arrived, {\n onNone: () => ({ model, commands }),\n onSome: message => {\n const step = apply(model, message) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n return { model: step.model, commands: [...commands, ...(step.commands ?? [])] }\n },\n })\n const boot = (entries: Readonly<Record<string, unknown>> = {}) => {\n unmark(root)\n return adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, startOf()), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n }\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n const start = Option.isSome(arrived) ? 'now' : plan.start\n const eager = start === 'now' && pending.length === 0\n if (eager && root.querySelector(`[${KEEP_ATTRIBUTE}]`) === null) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n report(pageContained(decoded.failure.reason, decoded.failure.message))\n contain()\n return\n }\n const kept = keptFields(root, decoded.success.bindings)\n if (Result.isFailure(kept)) {\n report(pageContained('Invalid', kept.failure))\n contain()\n return\n }\n // What was typed before this script ran, first in the queue: everything the\n // page answers from here on happened after it.\n answered.push(...typedMessages(kept.success))\n if (eager && answered.length === 0) {\n boot()\n return\n }\n // Typing is an interaction, whenever it happened: a page that waits for\n // one starts now, so what was typed is answered as soon as the script runs.\n const typed = answered.length > 0 ? 'now' : start\n deferBoot(root, decoded.success, typed, { boot, answered }, pending, report, kept.success)\n }\n const prepare = options.prepare\n if (prepare === undefined) adoptFrom(resumed.success)\n else void Effect.runPromise(prepare(resumed.success)).then(adoptFrom)\n}\n\n/**\n * Takes out of the served page what the server wrote for this script to read\n * and no view draws: the envelope, each binding's and kept field's marker,\n * each placement's slot, and each form's fallback (its `method` and hidden\n * fields). Left in, each is in what Foldkit records of the served page and\n * gone after its first patch, so Foldkit reconciles every such element, and\n * a development build reports that the server's markup and the view\n * disagree. Run as the page boots, so a form submitted before then still\n * posts.\n */\nconst unmark = (root: Element): void => {\n root.removeAttribute(RESUME_ATTRIBUTE)\n for (const element of [root, ...root.querySelectorAll('*')]) {\n for (const name of element.getAttributeNames()) {\n if (name.startsWith(BINDING_ATTRIBUTE) || name === KEEP_ATTRIBUTE || name === SLOT_ATTRIBUTE)\n element.removeAttribute(name)\n }\n }\n for (const field of root.querySelectorAll(`input[type=\"hidden\"][name=\"${FALLBACK_FIELD}\"]`)) {\n const form = field.parentElement\n form?.removeAttribute('method')\n form?.querySelector(`:scope > input[type=\"hidden\"][name=\"${FALLBACK_DEPTH_FIELD}\"]`)?.remove()\n field.remove()\n }\n}\n\n/**\n * Moves what a render's `styles` put in the root into the head, before\n * anything adopts the page: the view does not draw it, so hydration would\n * remove it, and a page that never renders again would lose the rules its\n * classes need. Whatever adopts the page next finds them in the head.\n */\nconst keepStyles = (root: Element): void => {\n const marker = Array.from(root.childNodes).find(\n node => node.nodeType === Node.COMMENT_NODE && node.nodeValue === STYLES_MARKER,\n )\n if (marker === undefined) return\n for (let next = marker.nextSibling; next !== null; next = marker.nextSibling) {\n if (next instanceof Element) document.head.append(next)\n else next.remove()\n }\n marker.remove()\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport const UNTIL_LIMIT_MS = 3000\n\n/**\n * Runs the application afresh out of view, beside the served page, and puts\n * it in the page's place once a Model it drew satisfies `until`, or after\n * `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its\n * Mounts start in the document as they would in place.\n */\nconst renderBeside = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n served: HTMLElement,\n until: (model: Model) => boolean,\n): void => {\n const holder = document.createElement('div')\n holder.hidden = true\n const container = document.createElement('div')\n // The runtime refuses a container without an id; the served page gives its own up.\n container.id = served.id === '' ? 'foldkit-ssr-app' : served.id\n served.removeAttribute('id')\n // Nor does it boot beside a page stamped as a server render, which this one,\n // never adopted, no longer is.\n served.removeAttribute(FOLDKIT_APP_ATTRIBUTE)\n holder.append(container)\n served.after(holder)\n let shown = false\n const show = () => {\n if (shown) return\n shown = true\n clearTimeout(limit)\n holder.replaceWith(...holder.childNodes)\n served.remove()\n }\n const limit = setTimeout(show, UNTIL_LIMIT_MS)\n const view: ResumableConfig<Model, Message>['view'] = (model, h) => {\n const drawn = config.view(model, h)\n // Shown once the drawing this view returns is patched in, which the\n // runtime does in the same task.\n if (!shown && until(model)) queueMicrotask(show)\n return drawn\n }\n run(makeApplication({ ...config, view, container } as never))\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n * Each kept field the person changed is put back, value and selection, as\n * the first render commits, since that render re-asserts the served value.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n report: (diagnostic: SsrDiagnostic) => void,\n kept: ReadonlyArray<KeptField>,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n // The kept fields as the person left them, which the first render resets.\n let held: ReadonlyArray<Held> = []\n const stop = listen(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n // Before the queue runs, so its Messages find the fields holding their values.\n restore(held)\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n held = hold(kept)\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n report(bundleUnloaded(error))\n commit()\n })\n }\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n/** The diagnostics channel `hydrate` reports into, re-exported so a page needs no other import. */\nexport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nexport type {\n BundleUnloaded,\n HandlerUnnamed,\n PageContained,\n PageFailed,\n SsrDiagnostic,\n StaticRegionMissing,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuDA,MAAM,eAAe,SACnB,IAAI,IACF,MAAM,KAAK,KAAK,iBAAiB,IAAI,iBAAiB,EAAE,IAAG,YAAW,CACpE,QAAQ,aAAA,0BAA6B,KAAK,IAC1C,QAAQ,SACV,CAAC,CACH;;;;;;AAOF,MAAM,kBAAkB;;;;;;;;;;;AAYxB,MAAMA,aACJ,QACA,MACA,YAmDS;CACT,MAAM,UAAU,eAAoC;EAClD,OAAO,QAAQ,YAAY,QAAQ,WAAW,CAAC,CAACC,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ACL,OAAO,QACL,KAAK,aAAA,kBAAkC,IAAI,OAAO,cAAc,OAAO,MACvE,OAAO,KAAK,QAAQ,CACtB,GACA,QACF,CACF;EACJ,EACF,CAAC;EACD,IAAI,CAAC,KAAK,aAAA,kBAAkC,GAAG,SAAS;CAC1D;CACA,MAAM,iBAAiB;EACrB,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,IAAI,QAAQ,WAAW,GAAG;GACxB,OAAO;GACP;EACF;EACA,QAAa,IAAI,QAAQ,KAAI,WAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,UAAmB;GACtF,OAAO,eAAe,KAAK,CAAC;GAC5B,OAAO;EACT,CAAC;CACH;CACA,IAAI,UAAU,OAAO,SAAS;MACzB,IAAI,UAAU,QAAQ;EACzB,IAAI,OAAO,OAAO,wBAAwB,YAAY,OAAO,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;AAAQ"}
1
+ {"version":3,"file":"client.js","names":["hydrate","Diagnostics","adopt"],"sources":["../src/client.ts"],"sourcesContent":["/**\n * `foldkit-ssr/client`: what a browser page needs to take a server render\n * over, and nothing that renders one. It never imports\n * `foldkit/experimental/server`, whose renderer and HTML parser a hydrating\n * page would otherwise carry; `foldkit-ssr` is this and the server side.\n */\nimport { Effect, Option, Result, Schema, Stream } from 'effect'\nimport { hydrate as adopt, makeApplication, run } from 'foldkit/runtime'\nimport * as Render from 'foldkit/render'\nimport { Diagnostics, type ReportDiagnostic } from 'foldkit-surface'\nimport { withContext, type RenderContext } from './context.js'\nimport {\n bundleUnloaded,\n noBuildId,\n otherBuild,\n pageContained,\n reportingTo,\n type SsrDiagnostic,\n} from './diagnostics.js'\nimport { hold, keptFields, restore, typedMessages, type Held, type KeptField } from './keep.js'\nimport { listen, type DecodedBinding } from './listen.js'\nimport {\n BINDING_ATTRIBUTE,\n FALLBACK_DEPTH_FIELD,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n builder,\n view,\n} from './resumable.js'\nimport {\n FOLDKIT_APP_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n STYLES_MARKER,\n arrival,\n bindings,\n bindingsAndEvents,\n metaEntry,\n plan,\n resume,\n routeOf,\n serving,\n startingFrom,\n staticRegion,\n type Loadable,\n type ResumableConfig,\n type ResumePlan,\n type Start,\n} from './shared.js'\n\n/** Foldkit's root stamp, defined beside the envelope that rides on the same root. */\nexport { FOLDKIT_APP_ATTRIBUTE } from './shared.js'\n\n/** Each static region's markup in the page, read before hydration touches it. */\nconst snapshotsOf = (root: Element): ReadonlyMap<string, string> =>\n new Map(\n Array.from(root.querySelectorAll(`[${STATIC_ATTRIBUTE}]`), element => [\n element.getAttribute(STATIC_ATTRIBUTE) ?? '',\n element.innerHTML,\n ]),\n )\n\n/**\n * The build attribute on Foldkit's hydration root. Foldkit does not export it,\n * as it does the app and Flags attributes; a test pins it to what Foldkit's\n * server stamps.\n */\nconst BUILD_ATTRIBUTE = 'data-foldkit-build'\n\n/**\n * Starts the browser from the page's resumed Model, without running `init`.\n *\n * In the order Foldkit checks a page: the build id first, before the payload\n * is read, then the envelope and its route. A page from another build is\n * refused by Foldkit itself. A page that cannot resume is refused and contained\n * by Foldkit's own refusal, and the reason is reported (`options.diagnostics`). A server page is never\n * rendered again on the client. A page with no server render at all, no\n * stamped root, is rendered on the client as usual.\n */\nconst hydrate = <Model, Fields extends Schema.Struct.Fields, Message = any>(\n config: ResumableConfig<Model, Message>,\n plan: ResumePlan<Model, Fields>,\n options: {\n readonly buildId: string\n /**\n * Whether this page is taken over: asked before anything is adopted, so\n * a page showing another reader's data never becomes live facts. Omitted\n * adopts as before. Must not throw: a throwing predicate propagates out\n * of `hydrate` with no runtime booted and nothing contained.\n */\n readonly when?: ((page: Document) => boolean) | undefined\n /**\n * What a declined or stale page does: `render` runs the application\n * afresh where the rendered page is, replacing its markup in place (the\n * config's container with no served page). Omitted contains the page the\n * way a resume failure does.\n */\n readonly otherwise?: 'render' | undefined\n /**\n * With `otherwise: 'render'`, when the fresh application is ready to be\n * seen: until a Model it has drawn satisfies this, it draws out of view\n * and the served page stays, so a page is not swapped for its loading\n * state and back. Omitted, the fresh application replaces the page at\n * once. The served page stays no longer than `UNTIL_LIMIT_MS`.\n */\n readonly until?: ((model: Model) => boolean) | undefined\n /**\n * Whether the plan's data version is still current: asked once, with\n * `plan.version`, before anything is adopted. Omitted never asks. A plan\n * with no version still asks, with `undefined` (a check shaped like\n * `version === expected` then marks every such page stale). Must not\n * throw, as `when`.\n */\n readonly fresh?: ((version: unknown) => boolean) | undefined\n /**\n * What only this browser adds to the resumed Model before it is adopted,\n * and the view does not draw: a session minted for this page load (an\n * outbox's `session`). Run once, for a page that resumes; the runtime\n * starts when it succeeds. What the view draws, such as a queue read from\n * storage, arrives after, as a Message: here it would make the first\n * client view differ from the served page. Must not fail, as `when` must\n * not throw.\n */\n readonly prepare?: ((model: Model) => Effect.Effect<Model>) | undefined\n /**\n * Where what the page met goes: a page contained rather than resumed, a\n * static region the server's page lacked, a lazy bundle that did not\n * load. Each is reported before or apart from the runtime, so its\n * resources' reporter is not in effect. Omitted, Effect's log: the\n * browser's console.\n */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n): void => {\n const report = (diagnostic: SsrDiagnostic): void => {\n Effect.runFork(reportingTo(options.diagnostics)(Diagnostics.report(diagnostic)))\n }\n const planMeta = plan.meta\n if (planMeta !== undefined) {\n config = {\n ...config,\n subscriptions: { ...config.subscriptions, 'foldkit-ssr.meta': metaEntry(planMeta) },\n }\n }\n const root = document.querySelector<HTMLElement>(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (root !== null) keepStyles(root)\n // A page that is declined or stale never adopts. `render` draws afresh at\n // the root's place, replacing it; anything else contains the served page.\n // With no served page the application renders afresh regardless.\n const declined = options.when !== undefined && !options.when(document)\n const stale = options.fresh !== undefined && !options.fresh(plan.version)\n if (root === null) {\n run(makeApplication(config as never))\n return\n }\n const program = (start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> }) =>\n makeApplication({ ...startingFrom(config, start), container: root } as never)\n // Contain the served page the way Foldkit refuses one: adopt the baseline\n // with an empty build id, with nothing copied here.\n const contain = () => adopt(program({ model: plan.baseline }), { buildId: '' })\n if (declined || stale) {\n if (options.otherwise !== 'render') contain()\n else if (options.until === undefined)\n run(makeApplication({ ...config, container: root } as never))\n else renderBeside(config, root, options.until)\n return\n }\n // The type says a string, but `import.meta.env` is `any`: with the variable\n // unset the id arrives undefined, and Foldkit, given none, takes its own\n // compiled id, which matches the page, so the baseline was adopted in silence.\n if (typeof options.buildId !== 'string') {\n report(noBuildId)\n contain()\n return\n }\n const served = root.getAttribute(BUILD_ATTRIBUTE)\n if (served !== options.buildId) {\n report(otherBuild(Option.fromNullOr(served), options.buildId))\n adopt(program({ model: plan.baseline }), { buildId: options.buildId })\n return\n }\n const resumed = resume(plan, document, { route: routeOf(window.location.href) })\n if (Result.isFailure(resumed)) {\n report(pageContained(resumed.failure.reason, resumed.failure.message))\n contain()\n return\n }\n const adoptFrom = (model: Model): void => {\n // A page recorded for its path, opened at a query: the application learns\n // the URL, as from a navigation, and the page starts now, since what it\n // shows is not yet the address.\n const arrived = arrival(config, document, window.location.href)\n const bootCommands = (started: Model): ReadonlyArray<unknown> =>\n (plan.boot?.(started) as ReadonlyArray<unknown> | undefined) ?? []\n const resuming: RenderContext = {\n mode: 'resume',\n snapshots: snapshotsOf(root),\n reported: new Set(),\n report,\n }\n // The runtime starts from the resumed Model, so its first render is the\n // served markup and Foldkit adopts every node. The Messages the page\n // answered before the live page listened wait in `answered`, and the first\n // Message the runtime processes, whatever it is, runs them through `update`\n // ahead of itself: they reach the Model before anything the live page\n // answers, an event dispatched in the task that boots it included.\n const answered: Array<unknown> = []\n // Each answered Message was decoded through the plan's Message Schema.\n const apply: ResumableConfig<Model>['update'] = config.update\n const update = (current: Model, message: unknown) => {\n const handingOver = message === HANDOVER\n if (answered.length === 0) return handingOver ? { model: current } : apply(current, message)\n const returned: Array<unknown> = []\n for (const next of [...answered.splice(0), ...(handingOver ? [] : [message])]) {\n const step = apply(current, next) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n current = step.model\n returned.push(...(step.commands ?? []))\n }\n return { model: current, commands: returned }\n }\n // The URL goes into the Model the runtime starts from, not into `answered`:\n // Subscriptions start from that Model before any Message lands, and a URL\n // mirror among them would write the served address back over the real one.\n // The first render then differs from the served page where the URL does, and\n // Foldkit rebuilds that part, as a navigation would redraw it. Applied at\n // boot, once any lazy bundle's `update` has loaded. The boot Commands are\n // planned from the Model the runtime actually starts with, so one derived\n // from the route or query sees the address the page arrived at.\n const startOf = () =>\n Option.match(arrived, {\n onNone: () => ({ model, commands: bootCommands(model) }),\n onSome: message => {\n const step = apply(model, message) as {\n readonly model: Model\n readonly commands?: ReadonlyArray<unknown> | undefined\n }\n return {\n model: step.model,\n commands: [...bootCommands(step.model), ...(step.commands ?? [])],\n }\n },\n })\n const boot = (entries: Readonly<Record<string, unknown>> = {}) => {\n unmark(root)\n return adopt(\n makeApplication({\n ...withContext(startingFrom({ ...config, update }, startOf()), resuming),\n container: root,\n subscriptions: { ...config.subscriptions, ...entries },\n } as never),\n { buildId: options.buildId },\n )\n }\n const pending = (config.lazy ?? []).filter(bundle => !bundle.isLoaded())\n const start = Option.isSome(arrived) ? 'now' : plan.start\n const eager = start === 'now' && pending.length === 0\n if (eager && root.querySelector(`[${KEEP_ATTRIBUTE}]`) === null) {\n boot()\n return\n }\n const decoded = bindingsAndEvents(plan, document, root, model)\n if (Result.isFailure(decoded)) {\n report(pageContained(decoded.failure.reason, decoded.failure.message))\n contain()\n return\n }\n const kept = keptFields(root, decoded.success.bindings)\n if (Result.isFailure(kept)) {\n report(pageContained('Invalid', kept.failure))\n contain()\n return\n }\n // What was typed before this script ran, first in the queue: everything the\n // page answers from here on happened after it.\n answered.push(...typedMessages(kept.success))\n if (eager && answered.length === 0) {\n boot()\n return\n }\n // Typing is an interaction, whenever it happened: a page that waits for\n // one starts now, so what was typed is answered as soon as the script runs.\n const typed = answered.length > 0 ? 'now' : start\n deferBoot(root, decoded.success, typed, { boot, answered }, pending, report, kept.success)\n }\n const prepare = options.prepare\n if (prepare === undefined) adoptFrom(resumed.success)\n else void Effect.runPromise(prepare(resumed.success)).then(adoptFrom)\n}\n\n/**\n * Takes out of the served page what the server wrote for this script to read\n * and no view draws: the envelope, each binding's and kept field's marker,\n * each placement's slot, and each form's fallback (its `method` and hidden\n * fields). Left in, each is in what Foldkit records of the served page and\n * gone after its first patch, so Foldkit reconciles every such element, and\n * a development build reports that the server's markup and the view\n * disagree. Run as the page boots, so a form submitted before then still\n * posts.\n */\nconst unmark = (root: Element): void => {\n root.removeAttribute(RESUME_ATTRIBUTE)\n for (const element of [root, ...root.querySelectorAll('*')]) {\n for (const name of element.getAttributeNames()) {\n if (name.startsWith(BINDING_ATTRIBUTE) || name === KEEP_ATTRIBUTE || name === SLOT_ATTRIBUTE)\n element.removeAttribute(name)\n }\n }\n for (const field of root.querySelectorAll(`input[type=\"hidden\"][name=\"${FALLBACK_FIELD}\"]`)) {\n const form = field.parentElement\n form?.removeAttribute('method')\n form?.querySelector(`:scope > input[type=\"hidden\"][name=\"${FALLBACK_DEPTH_FIELD}\"]`)?.remove()\n field.remove()\n }\n}\n\n/**\n * Moves what a render's `styles` put in the root into the head, before\n * anything adopts the page: the view does not draw it, so hydration would\n * remove it, and a page that never renders again would lose the rules its\n * classes need. Whatever adopts the page next finds them in the head.\n */\nconst keepStyles = (root: Element): void => {\n const marker = Array.from(root.childNodes).find(\n node => node.nodeType === Node.COMMENT_NODE && node.nodeValue === STYLES_MARKER,\n )\n if (marker === undefined) return\n for (let next = marker.nextSibling; next !== null; next = marker.nextSibling) {\n if (next instanceof Element) document.head.append(next)\n else next.remove()\n }\n marker.remove()\n}\n\n/** The longest a served page stays in view while a fresh application waits for `until`. */\nexport const UNTIL_LIMIT_MS = 3000\n\n/**\n * Runs the application afresh out of view, beside the served page, and puts\n * it in the page's place once a Model it drew satisfies `until`, or after\n * `UNTIL_LIMIT_MS`. It draws in a hidden element, not a detached one, so its\n * Mounts start in the document as they would in place.\n */\nconst renderBeside = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n served: HTMLElement,\n until: (model: Model) => boolean,\n): void => {\n const holder = document.createElement('div')\n holder.hidden = true\n const container = document.createElement('div')\n // The runtime refuses a container without an id; the served page gives its own up.\n container.id = served.id === '' ? 'foldkit-ssr-app' : served.id\n served.removeAttribute('id')\n // Nor does it boot beside a page stamped as a server render, which this one,\n // never adopted, no longer is.\n served.removeAttribute(FOLDKIT_APP_ATTRIBUTE)\n holder.append(container)\n served.after(holder)\n let shown = false\n const show = () => {\n if (shown) return\n shown = true\n clearTimeout(limit)\n holder.replaceWith(...holder.childNodes)\n served.remove()\n }\n const limit = setTimeout(show, UNTIL_LIMIT_MS)\n const view: ResumableConfig<Model, Message>['view'] = (model, h) => {\n const drawn = config.view(model, h)\n // Shown once the drawing this view returns is patched in, which the\n // runtime does in the same task.\n if (!shown && until(model)) queueMicrotask(show)\n return drawn\n }\n run(makeApplication({ ...config, view, container } as never))\n}\n\n/**\n * The Message the handover entry sends so the runtime takes the answered\n * Messages when nothing else has asked it to. The wrapped `update` consumes\n * it; the application never sees it.\n */\nconst HANDOVER: unknown = Object.freeze({ _tag: 'foldkit-ssr/Handover' })\n\n/**\n * Lets the page answer from its bindings until something asks for the\n * runtime, then boots it and hands over to the live page.\n *\n * Every Message the page answers goes to `answered`, which the runtime takes\n * before its first Message. An event only the live page can answer is kept\n * and sent again to where it first went once the live page listens. The page\n * stops listening as soon as the runtime's first render has committed: when\n * `hydrate` returns, which Foldkit does today, or else when a handover\n * Subscription entry starts, after `Render.afterCommit`. When lazy bundles\n * must load first, the boot waits for them and the page keeps answering.\n * Each kept field the person changed is put back, value and selection, as\n * the first render commits, since that render re-asserts the served value.\n */\nconst deferBoot = (\n root: HTMLElement,\n decoded: {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n start: Start,\n runtime: {\n readonly boot: (entries: Readonly<Record<string, unknown>>) => void\n readonly answered: Array<unknown>\n },\n pending: ReadonlyArray<Loadable>,\n report: (diagnostic: SsrDiagnostic) => void,\n kept: ReadonlyArray<KeptField>,\n): void => {\n // Events only the live page can answer, met before it listened.\n const unanswered: Array<{ readonly event: Event; readonly element: Element }> = []\n // `waiting` for an interaction or idle, `loading` bodies, `starting` the\n // runtime until its first render commits, then `live`.\n let phase: 'waiting' | 'loading' | 'starting' | 'live' = 'waiting'\n // The kept fields as the person left them, which the first render resets.\n let held: ReadonlyArray<Held> = []\n const stop = listen(root, {\n bindings: decoded.bindings,\n ...(decoded.events === undefined ? {} : { events: decoded.events }),\n onAnswer: ({ event, messages, unnamed }) => {\n // An answer the markers could not complete is left to the live page.\n if (unnamed !== undefined) {\n startNow()\n // Once the live page listens, this event reaches it in the rest of\n // its own dispatch; until then it is kept for the handover.\n if (phase !== 'live' && event.target instanceof Element) {\n unanswered.push({ event, element: event.target })\n }\n return\n }\n // Nothing answered it: it goes on to the page, a plain link to the\n // router, as it would have.\n if (messages.length === 0) {\n startNow()\n return\n }\n // Taken by the runtime before anything else. The live page must not\n // answer this one as well.\n runtime.answered.push(...messages)\n event.stopPropagation()\n startNow()\n },\n })\n const handOver = () => {\n if (phase === 'live') return\n phase = 'live'\n // Before the queue runs, so its Messages find the fields holding their values.\n restore(held)\n stop()\n for (const { event, element } of unanswered.splice(0)) {\n const Ctor = event.constructor as new (type: string, init: Event) => Event\n element.dispatchEvent(new Ctor(event.type, event))\n }\n }\n const commit = () => {\n phase = 'starting'\n held = hold(kept)\n runtime.boot({\n 'foldkit-ssr.handover': {\n dependenciesSchema: Schema.Null,\n modelToDependencies: () => null,\n // Foldkit strips the root's stamp just before its first patch, so a\n // stamped root still has a render to wait for.\n dependenciesToStream: () =>\n Stream.fromEffect(\n Effect.as(\n Effect.andThen(\n root.hasAttribute(FOLDKIT_APP_ATTRIBUTE) ? Render.afterCommit : Effect.void,\n Effect.sync(handOver),\n ),\n HANDOVER,\n ),\n ),\n },\n })\n if (!root.hasAttribute(FOLDKIT_APP_ATTRIBUTE)) handOver()\n }\n const startNow = () => {\n if (phase !== 'waiting') return\n phase = 'loading'\n if (pending.length === 0) {\n commit()\n return\n }\n void Promise.all(pending.map(bundle => bundle.load())).then(commit, (error: unknown) => {\n report(bundleUnloaded(error))\n commit()\n })\n }\n if (start === 'now') startNow()\n else if (start === 'idle') {\n if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(startNow)\n else setTimeout(startNow, 0)\n }\n}\n\n/** The resumable track: bindings the server's markup names, so a page can answer before it boots. */\nexport const Resume = { builder, view, bindings, listen }\n\n/** The browser's part of `SSR`: the same functions, without the server's. */\nexport const SSR = { plan, resume, hydrate, static: staticRegion, serving }\n\nexport {\n META_ATTRIBUTE,\n RESUME_ATTRIBUTE,\n STATIC_ATTRIBUTE,\n ResumeRefused,\n metaMarkup,\n type Loadable,\n type Meta,\n type PlanSurface,\n type ResumableConfig,\n type ResumePart,\n type ResumePlan,\n type Start,\n} from './shared.js'\nexport {\n BINDING_ATTRIBUTE,\n FALLBACK_FIELD,\n KEEP_ATTRIBUTE,\n SLOT_ATTRIBUTE,\n type ResumableBuilder,\n} from './resumable.js'\nexport type { DecodedBinding } from './listen.js'\nexport type { UnnamedHandler } from './context.js'\n/** The diagnostics channel `hydrate` reports into, re-exported so a page needs no other import. */\nexport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nexport type {\n BundleUnloaded,\n CachedPageDiffers,\n HandlerUnnamed,\n PageContained,\n PageFailed,\n SsrDiagnostic,\n StaticRegionMissing,\n} from './diagnostics.js'\n"],"mappings":";;;;;;;;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AI,UAAU,QAAQ;EACtB,QAAQ;EAER,QAAQ,IAAI;EACZ,KAAK;EACL,KAAK,MAAM,EAAE,OAAO,aAAa,WAAW,OAAO,CAAC,GAAG;GACrD,MAAM,OAAO,MAAM;GACnB,QAAQ,cAAc,IAAI,KAAK,MAAM,MAAM,KAAK,CAAC;EACnD;CACF;CACA,MAAM,eAAe;EACnB,QAAQ;EACR,OAAO,KAAK,IAAI;EAChB,QAAQ,KAAK,EACX,wBAAwB;GACtB,oBAAoB,OAAO;GAC3B,2BAA2B;GAG3B,4BACE,OAAO,WACL,OAAO,GACL,OAAO,QACL,KAAK,aAAA,kBAAkC,IAAI,OAAO,cAAc,OAAO,MACvE,OAAO,KAAK,QAAQ,CACtB,GACA,QACF,CACF;EACJ,EACF,CAAC;EACD,IAAI,CAAC,KAAK,aAAA,kBAAkC,GAAG,SAAS;CAC1D;CACA,MAAM,iBAAiB;EACrB,IAAI,UAAU,WAAW;EACzB,QAAQ;EACR,IAAI,QAAQ,WAAW,GAAG;GACxB,OAAO;GACP;EACF;EACA,QAAa,IAAI,QAAQ,KAAI,WAAU,OAAO,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,SAAS,UAAmB;GACtF,OAAO,eAAe,KAAK,CAAC;GAC5B,OAAO;EACT,CAAC;CACH;CACA,IAAI,UAAU,OAAO,SAAS;MACzB,IAAI,UAAU,QAAQ;EACzB,IAAI,OAAO,OAAO,wBAAwB,YAAY,OAAO,oBAAoB,QAAQ;OACpF,WAAW,UAAU,CAAC;CAC7B;AACF;;AAGA,MAAa,SAAS;CAAE;CAAS;CAAM;CAAU;AAAO;;AAGxD,MAAa,MAAM;CAAE;CAAM;CAAQ,SAAA;CAAS,QAAQ;CAAc;AAAQ"}
package/dist/context.d.ts CHANGED
@@ -1,2 +1,2 @@
1
- import { B as current, H as within, I as Binding, L as Region, R as RenderContext, V as withContext, z as UnnamedHandler } from "./shared-DbupL3vO.js";
1
+ import { B as current, H as within, I as Binding, L as Region, R as RenderContext, V as withContext, z as UnnamedHandler } from "./shared-CJN-m58Z.js";
2
2
  export { Binding, Region, RenderContext, UnnamedHandler, current, withContext, within };
@@ -1,2 +1,2 @@
1
- import { $ as pageContained, G as PageContained, J as StaticRegionMissing, K as PageFailed, Q as otherBuild, U as BundleUnloaded, W as HandlerUnnamed, X as handlerUnnamed, Y as bundleUnloaded, Z as noBuildId, et as pageFailed, nt as staticRegionMissing, q as SsrDiagnostic, tt as reportingTo } from "./shared-DbupL3vO.js";
2
- export { BundleUnloaded, HandlerUnnamed, PageContained, PageFailed, SsrDiagnostic, StaticRegionMissing, bundleUnloaded, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
1
+ import { $ as noBuildId, G as HandlerUnnamed, J as SsrDiagnostic, K as PageContained, Q as handlerUnnamed, U as BundleUnloaded, W as CachedPageDiffers, X as bundleUnloaded, Y as StaticRegionMissing, Z as cachedPageDiffers, et as otherBuild, it as staticRegionMissing, nt as pageFailed, q as PageFailed, rt as reportingTo, tt as pageContained } from "./shared-CJN-m58Z.js";
2
+ export { BundleUnloaded, CachedPageDiffers, HandlerUnnamed, PageContained, PageFailed, SsrDiagnostic, StaticRegionMissing, bundleUnloaded, cachedPageDiffers, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
@@ -54,6 +54,13 @@ const handlerUnnamed = (plan, element, event) => ({
54
54
  });
55
55
  /** `effect` reporting to `report` when one is given, else to the reporter in its context. */
56
56
  const reportingTo = (report) => (effect) => report === void 0 ? effect : Effect.provideService(effect, Diagnostics.Reporter, report);
57
- export { bundleUnloaded, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
57
+ const cachedPageDiffers = (url) => ({
58
+ _tag: "CachedPageDiffers",
59
+ source,
60
+ level: "error",
61
+ message: `the page kept for ${url} was drawn otherwise for a request it served, so something the render read is not the URL alone; find what in flags, prepare, headers, status or the view differs between requests`,
62
+ url
63
+ });
64
+ export { bundleUnloaded, cachedPageDiffers, handlerUnnamed, noBuildId, otherBuild, pageContained, pageFailed, reportingTo, staticRegionMissing };
58
65
 
59
66
  //# sourceMappingURL=diagnostics.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * What SSR meets and keeps going past: a page the browser contains rather\n * than resumes, a static region or lazy bundle it draws without, a request\n * answered 500, and a handler that keeps a page from answering before boot.\n * Each is reported through `Diagnostics.report`, by default to the log.\n */\nimport { Cause, Effect, Option } from 'effect'\nimport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nimport type { ResumeRefused } from './shared.js'\n\nconst source = 'foldkit-ssr'\n\n/** A served page the browser contained instead of resuming: it stays in view, inert, and no runtime starts. */\nexport interface PageContained extends Diagnostic {\n readonly _tag: 'PageContained'\n /**\n * `NoBuildId` when `SSR.hydrate` was given none, `OtherBuild` when the page\n * names another deployment; otherwise why the envelope was refused.\n */\n readonly reason: 'NoBuildId' | 'OtherBuild' | ResumeRefused['reason']\n}\n\n/** A static region the browser asked for that the server's page did not hold, rendered in the browser. */\nexport interface StaticRegionMissing extends Diagnostic {\n readonly _tag: 'StaticRegionMissing'\n readonly region: string\n}\n\n/** A lazy bundle whose bodies did not load; the runtime boots without them. */\nexport interface BundleUnloaded extends Diagnostic {\n readonly _tag: 'BundleUnloaded'\n readonly error: unknown\n}\n\n/** A request answered 500: its `headers` threw, or its page could not be rendered. */\nexport interface PageFailed extends Diagnostic {\n readonly _tag: 'PageFailed'\n readonly url: string\n readonly cause: Cause.Cause<unknown>\n}\n\n/** A handler the page cannot name, so its event waits for the live runtime. Reported once per process. */\nexport interface HandlerUnnamed extends Diagnostic {\n readonly _tag: 'HandlerUnnamed'\n readonly plan: string\n readonly element: string\n readonly event: string\n}\n\n/** Every diagnostic SSR reports. */\nexport type SsrDiagnostic =\n | PageContained\n | StaticRegionMissing\n | BundleUnloaded\n | PageFailed\n | HandlerUnnamed\n\nexport const pageContained = (reason: PageContained['reason'], detail: string): PageContained => ({\n _tag: 'PageContained',\n source,\n level: 'error',\n message: `the page cannot resume, so it is contained: ${detail}`,\n reason,\n})\n\nexport const noBuildId: PageContained = pageContained(\n 'NoBuildId',\n \"SSR.hydrate was given no build id, so it cannot tell this page from another deployment's. Pass the id the server stamped: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID (or `foldkit({ buildId })`) so that `import.meta.env.FOLDKIT_BUILD_ID` is defined in the client too.\",\n)\n\n/** The page's stamped build id, if it has one, is not the client's `client`. */\nexport const otherBuild = (served: Option.Option<string>, client: string): PageContained =>\n pageContained(\n 'OtherBuild',\n `it was served by ${Option.match(served, {\n onNone: () => 'no known deployment',\n onSome: id => `deployment \"${id}\"`,\n })}, but this client belongs to deployment \"${client}\". If both came from one build, they were given different ids: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID in the build's environment, or once in vite.config.ts before \\`foldkit()\\` reads it (\\`process.env.FOLDKIT_BUILD_ID ??= randomUUID()\\`). Otherwise serve the page from the running deployment.`,\n )\n\nexport const staticRegionMissing = (region: string): StaticRegionMissing => ({\n _tag: 'StaticRegionMissing',\n source,\n level: 'error',\n message: `the static region \"${region}\" is not in the server's page, so it is rendered in the browser`,\n region,\n})\n\nexport const bundleUnloaded = (error: unknown): BundleUnloaded => ({\n _tag: 'BundleUnloaded',\n source,\n level: 'error',\n message: `a bundle's bodies did not load, and the page boots without them: ${String(error)}`,\n error,\n})\n\nexport const pageFailed = (url: string, cause: Cause.Cause<unknown>): PageFailed => ({\n _tag: 'PageFailed',\n source,\n level: 'error',\n message: `${url} was answered 500: ${Cause.pretty(cause)}`,\n url,\n cause,\n})\n\nexport const handlerUnnamed = (plan: string, element: string, event: string): HandlerUnnamed => ({\n _tag: 'HandlerUnnamed',\n source,\n level: 'warning',\n message: `plan \"${plan}\": ${element} handles ${event} with a function, which the page cannot name, so that event waits for the live runtime. Give the handler a Message, or, for OnInput, OnChange, OnKeyDown or OnKeyUp, the Message's constructor with the field the event fills left out.`,\n plan,\n element,\n event,\n})\n\n/** `effect` reporting to `report` when one is given, else to the reporter in its context. */\nexport const reportingTo =\n (report: ReportDiagnostic | undefined) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n report === undefined ? effect : Effect.provideService(effect, Diagnostics.Reporter, report)\n"],"mappings":";;;;;;;;;AAUA,MAAM,SAAS;AA+Cf,MAAa,iBAAiB,QAAiC,YAAmC;CAChG,MAAM;CACN;CACA,OAAO;CACP,SAAS,+CAA+C;CACxD;AACF;AAEA,MAAa,YAA2B,cACtC,aACA,gRACF;;AAGA,MAAa,cAAc,QAA+B,WACxD,cACE,cACA,oBAAoB,OAAO,MAAM,QAAQ;CACvC,cAAc;CACd,SAAQ,OAAM,eAAe,GAAG;AAClC,CAAC,EAAE,2CAA2C,OAAO,8SACvD;AAEF,MAAa,uBAAuB,YAAyC;CAC3E,MAAM;CACN;CACA,OAAO;CACP,SAAS,sBAAsB,OAAO;CACtC;AACF;AAEA,MAAa,kBAAkB,WAAoC;CACjE,MAAM;CACN;CACA,OAAO;CACP,SAAS,oEAAoE,OAAO,KAAK;CACzF;AACF;AAEA,MAAa,cAAc,KAAa,WAA6C;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,IAAI,qBAAqB,MAAM,OAAO,KAAK;CACvD;CACA;AACF;AAEA,MAAa,kBAAkB,MAAc,SAAiB,WAAmC;CAC/F,MAAM;CACN;CACA,OAAO;CACP,SAAS,SAAS,KAAK,KAAK,QAAQ,WAAW,MAAM;CACrD;CACA;CACA;AACF;;AAGA,MAAa,eACV,YACS,WACR,WAAW,KAAA,IAAY,SAAS,OAAO,eAAe,QAAQ,YAAY,UAAU,MAAM"}
1
+ {"version":3,"file":"diagnostics.js","names":[],"sources":["../src/diagnostics.ts"],"sourcesContent":["/**\n * What SSR meets and keeps going past: a page the browser contains rather\n * than resumes, a static region or lazy bundle it draws without, a request\n * answered 500, and a handler that keeps a page from answering before boot.\n * Each is reported through `Diagnostics.report`, by default to the log.\n */\nimport { Cause, Effect, Option } from 'effect'\nimport { Diagnostics, type Diagnostic, type ReportDiagnostic } from 'foldkit-surface'\nimport type { ResumeRefused } from './shared.js'\n\nconst source = 'foldkit-ssr'\n\n/** A served page the browser contained instead of resuming: it stays in view, inert, and no runtime starts. */\nexport interface PageContained extends Diagnostic {\n readonly _tag: 'PageContained'\n /**\n * `NoBuildId` when `SSR.hydrate` was given none, `OtherBuild` when the page\n * names another deployment; otherwise why the envelope was refused.\n */\n readonly reason: 'NoBuildId' | 'OtherBuild' | ResumeRefused['reason']\n}\n\n/** A static region the browser asked for that the server's page did not hold, rendered in the browser. */\nexport interface StaticRegionMissing extends Diagnostic {\n readonly _tag: 'StaticRegionMissing'\n readonly region: string\n}\n\n/** A lazy bundle whose bodies did not load; the runtime boots without them. */\nexport interface BundleUnloaded extends Diagnostic {\n readonly _tag: 'BundleUnloaded'\n readonly error: unknown\n}\n\n/** A request answered 500: its `headers` threw, or its page could not be rendered. */\nexport interface PageFailed extends Diagnostic {\n readonly _tag: 'PageFailed'\n readonly url: string\n readonly cause: Cause.Cause<unknown>\n}\n\n/** A handler the page cannot name, so its event waits for the live runtime. Reported once per process. */\nexport interface HandlerUnnamed extends Diagnostic {\n readonly _tag: 'HandlerUnnamed'\n readonly plan: string\n readonly element: string\n readonly event: string\n}\n\n/**\n * A kept page drawn otherwise for the request it served (`SSR.entry`'s\n * `cache.check`): the render read something of the request, or anything\n * else that differs between requests, that the cache could not see. The\n * request was given the page drawn again.\n */\nexport interface CachedPageDiffers extends Diagnostic {\n readonly _tag: 'CachedPageDiffers'\n readonly url: string\n}\n\n/** Every diagnostic SSR reports. */\nexport type SsrDiagnostic =\n | PageContained\n | StaticRegionMissing\n | BundleUnloaded\n | PageFailed\n | HandlerUnnamed\n | CachedPageDiffers\n\nexport const pageContained = (reason: PageContained['reason'], detail: string): PageContained => ({\n _tag: 'PageContained',\n source,\n level: 'error',\n message: `the page cannot resume, so it is contained: ${detail}`,\n reason,\n})\n\nexport const noBuildId: PageContained = pageContained(\n 'NoBuildId',\n \"SSR.hydrate was given no build id, so it cannot tell this page from another deployment's. Pass the id the server stamped: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID (or `foldkit({ buildId })`) so that `import.meta.env.FOLDKIT_BUILD_ID` is defined in the client too.\",\n)\n\n/** The page's stamped build id, if it has one, is not the client's `client`. */\nexport const otherBuild = (served: Option.Option<string>, client: string): PageContained =>\n pageContained(\n 'OtherBuild',\n `it was served by ${Option.match(served, {\n onNone: () => 'no known deployment',\n onSome: id => `deployment \"${id}\"`,\n })}, but this client belongs to deployment \"${client}\". If both came from one build, they were given different ids: with @foldkit/vite-plugin, set FOLDKIT_BUILD_ID in the build's environment, or once in vite.config.ts before \\`foldkit()\\` reads it (\\`process.env.FOLDKIT_BUILD_ID ??= randomUUID()\\`). Otherwise serve the page from the running deployment.`,\n )\n\nexport const staticRegionMissing = (region: string): StaticRegionMissing => ({\n _tag: 'StaticRegionMissing',\n source,\n level: 'error',\n message: `the static region \"${region}\" is not in the server's page, so it is rendered in the browser`,\n region,\n})\n\nexport const bundleUnloaded = (error: unknown): BundleUnloaded => ({\n _tag: 'BundleUnloaded',\n source,\n level: 'error',\n message: `a bundle's bodies did not load, and the page boots without them: ${String(error)}`,\n error,\n})\n\nexport const pageFailed = (url: string, cause: Cause.Cause<unknown>): PageFailed => ({\n _tag: 'PageFailed',\n source,\n level: 'error',\n message: `${url} was answered 500: ${Cause.pretty(cause)}`,\n url,\n cause,\n})\n\nexport const handlerUnnamed = (plan: string, element: string, event: string): HandlerUnnamed => ({\n _tag: 'HandlerUnnamed',\n source,\n level: 'warning',\n message: `plan \"${plan}\": ${element} handles ${event} with a function, which the page cannot name, so that event waits for the live runtime. Give the handler a Message, or, for OnInput, OnChange, OnKeyDown or OnKeyUp, the Message's constructor with the field the event fills left out.`,\n plan,\n element,\n event,\n})\n\n/** `effect` reporting to `report` when one is given, else to the reporter in its context. */\nexport const reportingTo =\n (report: ReportDiagnostic | undefined) =>\n <A, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R> =>\n report === undefined ? effect : Effect.provideService(effect, Diagnostics.Reporter, report)\n\nexport const cachedPageDiffers = (url: string): CachedPageDiffers => ({\n _tag: 'CachedPageDiffers',\n source,\n level: 'error',\n message: `the page kept for ${url} was drawn otherwise for a request it served, so something the render read is not the URL alone; find what in flags, prepare, headers, status or the view differs between requests`,\n url,\n})\n"],"mappings":";;;;;;;;;AAUA,MAAM,SAAS;AA2Df,MAAa,iBAAiB,QAAiC,YAAmC;CAChG,MAAM;CACN;CACA,OAAO;CACP,SAAS,+CAA+C;CACxD;AACF;AAEA,MAAa,YAA2B,cACtC,aACA,gRACF;;AAGA,MAAa,cAAc,QAA+B,WACxD,cACE,cACA,oBAAoB,OAAO,MAAM,QAAQ;CACvC,cAAc;CACd,SAAQ,OAAM,eAAe,GAAG;AAClC,CAAC,EAAE,2CAA2C,OAAO,8SACvD;AAEF,MAAa,uBAAuB,YAAyC;CAC3E,MAAM;CACN;CACA,OAAO;CACP,SAAS,sBAAsB,OAAO;CACtC;AACF;AAEA,MAAa,kBAAkB,WAAoC;CACjE,MAAM;CACN;CACA,OAAO;CACP,SAAS,oEAAoE,OAAO,KAAK;CACzF;AACF;AAEA,MAAa,cAAc,KAAa,WAA6C;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,IAAI,qBAAqB,MAAM,OAAO,KAAK;CACvD;CACA;AACF;AAEA,MAAa,kBAAkB,MAAc,SAAiB,WAAmC;CAC/F,MAAM;CACN;CACA,OAAO;CACP,SAAS,SAAS,KAAK,KAAK,QAAQ,WAAW,MAAM;CACrD;CACA;CACA;AACF;;AAGA,MAAa,eACV,YACS,WACR,WAAW,KAAA,IAAY,SAAS,OAAO,eAAe,QAAQ,YAAY,UAAU,MAAM;AAE9F,MAAa,qBAAqB,SAAoC;CACpE,MAAM;CACN;CACA,OAAO;CACP,SAAS,qBAAqB,IAAI;CAClC;AACF"}
package/dist/index.d.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import { n as DecodedBinding, r as EncodedBinding } from "./listen-DaUPRKVR.js";
2
2
  import { a as FALLBACK_FIELD, d as SLOT_ATTRIBUTE, n as BINDING_ATTRIBUTE, s as KEEP_ATTRIBUTE, u as ResumableBuilder } from "./resumable-BPN_qQHU.js";
3
- import { C as metaMarkup, E as plan, G as PageContained, J as StaticRegionMissing, K as PageFailed, M as serving, P as staticRegion, U as BundleUnloaded, W as HandlerUnnamed, c as ResumableConfig, d as ResumeRefused, f as RouteMatch, h as Start, i as Meta, j as serializeJsonScript, k as resume, l as ResumePart, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, q as SsrDiagnostic, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, z as UnnamedHandler } from "./shared-DbupL3vO.js";
4
- import { i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-XnpTQZHw.js";
5
- import { n as requestContext, t as RequestContext } from "./requestContext-D9nsbGSJ.js";
3
+ import { C as metaMarkup, E as plan, G as HandlerUnnamed, J as SsrDiagnostic, K as PageContained, M as serving, P as staticRegion, U as BundleUnloaded, Y as StaticRegionMissing, c as ResumableConfig, d as ResumeRefused, f as RouteMatch, h as Start, i as Meta, j as serializeJsonScript, k as resume, l as ResumePart, n as Loadable, o as PlanSurface, p as STATIC_ATTRIBUTE, q as PageFailed, r as META_ATTRIBUTE, s as RESUME_ATTRIBUTE, t as FOLDKIT_APP_ATTRIBUTE, u as ResumePlan, z as UnnamedHandler } from "./shared-CJN-m58Z.js";
4
+ import { i as Resume, n as Diagnostics, o as UNTIL_LIMIT_MS, r as ReportDiagnostic, t as Diagnostic } from "./client-qmdYY-Eb.js";
5
+ import { s as keptDocuments } from "./pageCache-DO0pOgnc.js";
6
+ import { n as requestContext, t as RequestContext } from "./requestContext-DmwmQeci.js";
6
7
  import { Cause, Effect, Layer, Option, Schema } from "effect";
7
- import { Diagnostic as Diagnostic$1, MetadataSummary } from "foldkit-surface";
8
+ import { CacheOptions, CacheStore, Diagnostic as Diagnostic$1, MetadataSummary } from "foldkit-surface";
8
9
  import { EntryModule, RenderError, RenderedApplication } from "foldkit/experimental/server";
9
10
  interface EnvelopeOptions {
10
11
  readonly route?: string | undefined;
@@ -284,8 +285,9 @@ declare const entry: <Model, Fields extends Schema.Struct.Fields, Message = any>
284
285
  /**
285
286
  * The status a rendered page is answered with, from the Model the server
286
287
  * reached and the request: `404` for a route the Model says is not found.
287
- * Omitted, every page is `200`. One outside `200`–`599`, or a `status`
288
- * that throws, is answered `500` and reported, as a failed render is.
288
+ * Omitted, every page is `200`. One outside `200`–`599`, a `204`, `205`
289
+ * or `304` that carries no body, or a `status` that throws, is answered
290
+ * `500` and reported, as a failed render is.
289
291
  */
290
292
  readonly status?: ((model: Model, request: Request) => number) | undefined;
291
293
  /**
@@ -313,7 +315,45 @@ declare const entry: <Model, Fields extends Schema.Struct.Fields, Message = any>
313
315
  * (`Diagnostics.Reporter`) when not given, by default the log.
314
316
  */
315
317
  readonly diagnostics?: ((diagnostic: Diagnostic$1, request: Request) => Effect.Effect<void>) | undefined;
318
+ /**
319
+ * Keeps rendered `GET` and `HEAD` pages in `store` by build and URL
320
+ * (#428). A page is kept only when every read the render made through
321
+ * `foldkit-remote-server`'s `pageReader` was public, every request
322
+ * header `flags`, `prepare`, `headers` or `status` read was absent (the
323
+ * request's `cookie` included), `headers` set no `cookie` or
324
+ * `cache-control` of its own, and the status is `200`: drawn from the
325
+ * URL alone. It is kept for `maxAge` or its reads' shortest, and serves
326
+ * each later request that also lacks the headers it read; it says
327
+ * `cache-control: public, max-age=…` and `vary` with those names. Every
328
+ * other page says `private, no-store`. A read made other than through
329
+ * `pageReader` is not seen, so `maxAge` is all that bounds it.
330
+ *
331
+ * The render reads a request that records its headers: one handed to
332
+ * `fetch` or `new Request` fails the render. With `check`, for
333
+ * development and tests, a kept page is drawn again for the request it
334
+ * serves, and a difference is reported (`CachedPageDiffers`) and
335
+ * answered with the page drawn again.
336
+ */
337
+ readonly cache?: PageCache | undefined;
316
338
  }) => EntryModule;
339
+ /** Where `SSR.entry` keeps pages, for how long, and whether it checks them (`cache`). */
340
+ export type PageCache = CacheOptions & {
341
+ readonly store: CacheStore;
342
+ readonly check?: boolean | undefined;
343
+ };
344
+ /**
345
+ * The page cache's checker, for a test: builds the entry with `make`, given a
346
+ * store in memory and `check`, and answers each request twice, so a page
347
+ * kept for one request is drawn again for every later one it serves.
348
+ * Rejects naming each page drawn otherwise for a request it served, and
349
+ * when no page was kept, which would check nothing. Give requests that
350
+ * differ in who asks (a visitor's, and one with someone's cookie); each is a
351
+ * function, since a request is read once.
352
+ */
353
+ declare const checkCache: (make: (options: {
354
+ readonly cache: PageCache;
355
+ readonly diagnostics: (diagnostic: Diagnostic$1) => Effect.Effect<void>;
356
+ }) => EntryModule, requests: ReadonlyArray<() => Request>) => Promise<void>;
317
357
  declare const FallbackRefused_base: Schema.Class<FallbackRefused, Schema.TaggedStruct<"FallbackRefused", {
318
358
  readonly reason: Schema.Literals<readonly ["Missing", "Unreadable", "Invalid", "Unlisted", "NoFallback"]>;
319
359
  readonly message: Schema.String;
@@ -365,6 +405,8 @@ export declare const SSR: {
365
405
  serving: typeof serving;
366
406
  generate: typeof generate;
367
407
  entry: typeof entry;
408
+ checkCache: typeof checkCache;
409
+ keptDocuments: typeof keptDocuments;
368
410
  handle: typeof handle;
369
411
  serializeJsonScript: typeof serializeJsonScript;
370
412
  sitemap: typeof sitemap;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":["Diagnostic"],"sources":["../src/index.ts"],"mappings":";;;;;;;;UAgGU;WACC;WACA,QAAQ;WACR,WAAW,cAAc;;WAEzB,SAAS;;;;;;;;;cAUd,WAAY,OAAO,eAAe,OAAO,OAAO,QAAM,QAClD,WA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