foldkit-ssr 0.9.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.
Files changed (52) hide show
  1. package/README.md +402 -36
  2. package/dist/{client-F16QT0sc.d.ts → client-qmdYY-Eb.d.ts} +15 -5
  3. package/dist/client-qmdYY-Eb.d.ts.map +1 -0
  4. package/dist/client.d.ts +5 -5
  5. package/dist/client.js +126 -54
  6. package/dist/client.js.map +1 -1
  7. package/dist/context.d.ts +1 -1
  8. package/dist/context.js +12 -0
  9. package/dist/context.js.map +1 -1
  10. package/dist/diagnostics.d.ts +2 -2
  11. package/dist/diagnostics.js +8 -1
  12. package/dist/diagnostics.js.map +1 -1
  13. package/dist/index.d.ts +127 -25
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +317 -59
  16. package/dist/index.js.map +1 -1
  17. package/dist/keep.d.ts +36 -0
  18. package/dist/keep.d.ts.map +1 -0
  19. package/dist/keep.js +109 -0
  20. package/dist/keep.js.map +1 -0
  21. package/dist/{listen-zNd0IIAT.d.ts → listen-DaUPRKVR.d.ts} +4 -2
  22. package/dist/listen-DaUPRKVR.d.ts.map +1 -0
  23. package/dist/listen.d.ts +2 -2
  24. package/dist/listen.js +31 -23
  25. package/dist/listen.js.map +1 -1
  26. package/dist/pageCache-DO0pOgnc.d.ts +80 -0
  27. package/dist/pageCache-DO0pOgnc.d.ts.map +1 -0
  28. package/dist/pageCache.d.ts +2 -0
  29. package/dist/pageCache.js +112 -0
  30. package/dist/pageCache.js.map +1 -0
  31. package/dist/{requestContext-D9nsbGSJ.d.ts → requestContext-DmwmQeci.d.ts} +12 -2
  32. package/dist/requestContext-DmwmQeci.d.ts.map +1 -0
  33. package/dist/requestContext.d.ts +2 -2
  34. package/dist/requestContext.js +30 -13
  35. package/dist/requestContext.js.map +1 -1
  36. package/dist/{resumable-BWItJsxF.d.ts → resumable-BPN_qQHU.d.ts} +33 -12
  37. package/dist/resumable-BPN_qQHU.d.ts.map +1 -0
  38. package/dist/resumable.d.ts +2 -2
  39. package/dist/resumable.js +51 -8
  40. package/dist/resumable.js.map +1 -1
  41. package/dist/{shared-v1u-OEQI.d.ts → shared-CJN-m58Z.d.ts} +37 -10
  42. package/dist/shared-CJN-m58Z.d.ts.map +1 -0
  43. package/dist/shared.d.ts +2 -2
  44. package/dist/shared.js +31 -7
  45. package/dist/shared.js.map +1 -1
  46. package/dist/vite.d.ts +1 -1
  47. package/package.json +9 -9
  48. package/dist/client-F16QT0sc.d.ts.map +0 -1
  49. package/dist/listen-zNd0IIAT.d.ts.map +0 -1
  50. package/dist/requestContext-D9nsbGSJ.d.ts.map +0 -1
  51. package/dist/resumable-BWItJsxF.d.ts.map +0 -1
  52. package/dist/shared-v1u-OEQI.d.ts.map +0 -1
package/dist/shared.js CHANGED
@@ -4,6 +4,7 @@ import { decodeBindings, readBindings } from "./listen.js";
4
4
  import { Effect, Option, Result, Schema, Stream } from "effect";
5
5
  import { ModelRef } from "foldkit-surface";
6
6
  import { inertHtml } from "foldkit/html";
7
+ import { fromString } from "foldkit/url";
7
8
  // src/shared.ts
8
9
  /**
9
10
  * What the server and the browser both read: the plan, the envelope as the
@@ -24,6 +25,12 @@ const FOLDKIT_APP_ATTRIBUTE = "data-foldkit-app";
24
25
  const RESUME_ATTRIBUTE = "data-foldkit-plus-resume";
25
26
  /** The envelope format this package writes and reads. */
26
27
  const PROTOCOL = 1;
28
+ /**
29
+ * The comment a render's `styles` follow in the stamped root. Hydration
30
+ * removes children the view does not draw, so `SSR.hydrate` moves what
31
+ * follows it into the head before adopting the page.
32
+ */
33
+ const STYLES_MARKER = "foldkit-plus-styles";
27
34
  const LINE_SEPARATOR = String.fromCharCode(8232);
28
35
  const PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
29
36
  /**
@@ -33,12 +40,13 @@ const PARAGRAPH_SEPARATOR = String.fromCharCode(8233);
33
40
  */
34
41
  const serializeJsonScript = (value) => JSON.stringify(value).replaceAll("<", "\\u003c").replaceAll(LINE_SEPARATOR, "\\u2028").replaceAll(PARAGRAPH_SEPARATOR, "\\u2029");
35
42
  /**
36
- * The envelope JSON as the stamped root carries it: `serializeJsonScript`
37
- * already escaped `<` and the line separators, and an attribute must escape
38
- * `&` and `"` besides, so no string in the Model can break out of the value.
39
- * `getAttribute` resolves the entities back, which is exactly the JSON.
43
+ * The envelope JSON as the stamped root carries it, in single quotes so the
44
+ * JSON's own double quotes need no escape. `&` and `'` are escaped, so no
45
+ * string in the Model can break out of the value; `getAttribute` resolves the
46
+ * entities back to exactly the JSON. `serializeJsonScript` has already escaped
47
+ * `<` and the line separators.
40
48
  */
41
- const attributeOf = (json) => ` ${RESUME_ATTRIBUTE}="${json.replaceAll("&", "&amp;").replaceAll("\"", "&quot;")}"`;
49
+ const attributeOf = (json) => ` ${RESUME_ATTRIBUTE}='${json.replaceAll("&", "&amp;").replaceAll("'", "&#39;")}'`;
42
50
  /** Marks each head element a plan's `meta` wrote, so the browser can replace them. */
43
51
  const META_ATTRIBUTE = "data-foldkit-meta";
44
52
  const attributeText = (text) => text.replaceAll("&", "&amp;").replaceAll("\"", "&quot;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
@@ -208,7 +216,10 @@ const resume = (plan, page, options = {}) => {
208
216
  if (v !== 1) return refuse("Protocol", `the envelope is protocol ${String(v)}, not 1`);
209
217
  if (id !== plan.id) return refuse("Plan", `the envelope is for plan "${String(id)}", not "${plan.id}"`);
210
218
  if (route !== void 0 && options.route !== void 0) {
211
- if (!(match === "path" ? pathKey(String(route)) === pathKey(options.route) : route === options.route)) return refuse("Route", `the page was ${match === "path" ? "generated" : "rendered"} for ${String(route)}, not ${options.route}`);
219
+ if (!(match === "path" ? pathKey(String(route)) === pathKey(options.route) : route === options.route)) {
220
+ const served = match !== "path" && pathKey(String(route)) === pathKey(options.route) ? `; a page a static host serves for every query must record its path alone: generate it with SSR.generate, or name its path in SSR.entry's prerendered` : "";
221
+ return refuse("Route", `the page was ${match === "path" ? "generated" : "rendered"} for ${String(route)}, not ${options.route}${served}`);
222
+ }
212
223
  }
213
224
  const resumed = modelFrom(plan, {
214
225
  state,
@@ -216,6 +227,19 @@ const resume = (plan, page, options = {}) => {
216
227
  });
217
228
  return Result.isFailure(resumed) ? refuse("Invalid", resumed.failure) : Result.succeed(resumed.success);
218
229
  };
230
+ /**
231
+ * The Message telling the application the URL it is at, when the page was
232
+ * recorded for its path alone and the browser is at a query: `init` never ran
233
+ * here, so the application would otherwise never learn the query. None for
234
+ * an application without routing, or a page at no query.
235
+ */
236
+ const arrival = (config, page, href) => {
237
+ const routing = config.routing;
238
+ if (routing === void 0 || new URL(href).search === "") return Option.none();
239
+ const read = readEnvelope(page);
240
+ if (Result.isFailure(read) || read.success.match !== "path") return Option.none();
241
+ return Option.map(fromString(href), routing.onUrlChange);
242
+ };
219
243
  /** The tag a Message value carries, for naming it. */
220
244
  const tagOf = (message) => typeof message === "object" && message !== null && "_tag" in message && typeof message._tag === "string" ? message._tag : "an untagged Message";
221
245
  /**
@@ -319,6 +343,6 @@ const bindingsAndEvents = (plan, page, root, model) => {
319
343
  events: events.success
320
344
  });
321
345
  };
322
- export { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, PROTOCOL, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, allowedTags, attributeOf, bindings, bindingsAndEvents, codecOf, metaEntry, metaMarkup, modelFrom, pathKey, plan, projectionsOf, refuse, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf };
346
+ export { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, PROTOCOL, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, STYLES_MARKER, allowedTags, arrival, attributeOf, bindings, bindingsAndEvents, codecOf, metaEntry, metaMarkup, modelFrom, pathKey, plan, projectionsOf, refuse, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf };
323
347
 
324
348
  //# sourceMappingURL=shared.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"shared.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * What the server and the browser both read: the plan, the envelope as the\n * browser reads it, static regions, and the page's bindings. Nothing here\n * imports Foldkit's server renderer, so `client.ts` can carry all of it.\n */\nimport { Effect, Option, Result, Schema, Stream, type Layer } from 'effect'\nimport type { Runtime } from 'foldkit'\nimport { inertHtml, type Html, type HtmlBuilder } from 'foldkit/html'\nimport type { Ports } from 'foldkit/port'\nimport {\n ModelRef,\n type ActiveSurface,\n type Metadata,\n type ModelPlace,\n type SurfaceSource,\n type WritableProjection,\n} from 'foldkit-surface'\nimport { current, type Region } from './context.js'\nimport { staticRegionMissing } from './diagnostics.js'\nimport { decodeBindings, readBindings, type DecodedBinding } from './listen.js'\n\n/**\n * The attribute Foldkit's server stamps on an application's root, as\n * `foldkit/experimental/server` exports it. Written out here so a page can\n * find its root without that module; a test pins the two together.\n */\nexport const FOLDKIT_APP_ATTRIBUTE = 'data-foldkit-app'\n\n/**\n * The attribute on the stamped root that carries a page's resume envelope.\n * Foldkit pairs its own handoff the same way: the build id rides on the root\n * beside the app stamp, and the client reads it before adopting anything.\n */\nexport const RESUME_ATTRIBUTE = 'data-foldkit-plus-resume'\n\n/** The envelope format this package writes and reads. */\nexport const PROTOCOL = 1\n\nconst LINE_SEPARATOR = String.fromCharCode(0x2028)\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029)\n\n/**\n * JSON for a script element: `<` is escaped so `</script>` in the data ends\n * nothing. U+2028 and U+2029 are escaped too: they are fine in JSON and break a\n * reader that treats the text as JavaScript.\n */\nexport const serializeJsonScript = (value: unknown): string =>\n JSON.stringify(value)\n .replaceAll('<', '\\\\u003c')\n .replaceAll(LINE_SEPARATOR, '\\\\u2028')\n .replaceAll(PARAGRAPH_SEPARATOR, '\\\\u2029')\n\n/**\n * The envelope JSON as the stamped root carries it: `serializeJsonScript`\n * already escaped `<` and the line separators, and an attribute must escape\n * `&` and `\"` besides, so no string in the Model can break out of the value.\n * `getAttribute` resolves the entities back, which is exactly the JSON.\n */\nexport const attributeOf = (json: string): string =>\n ` ${RESUME_ATTRIBUTE}=\"${json.replaceAll('&', '&amp;').replaceAll('\"', '&quot;')}\"`\n\n/**\n * What a page says of itself beyond Foldkit's `Document` (`title`, `lang`,\n * `dir`, `canonical`, `ogUrl`): what a search result and a link preview show.\n * `title` is the preview's title (`og:title`), when it differs from the\n * document's. Dates are ISO 8601 text; `jsonLd` is structured data, each\n * entry written as its own script.\n */\nexport interface Meta {\n readonly description?: string | undefined\n readonly title?: string | undefined\n readonly image?: string | undefined\n readonly type?: 'website' | 'article' | undefined\n readonly siteName?: string | undefined\n readonly article?:\n | { readonly published?: string | undefined; readonly modified?: string | undefined }\n | undefined\n readonly robots?: string | undefined\n readonly alternates?:\n | ReadonlyArray<{ readonly hreflang: string; readonly href: string }>\n | undefined\n readonly jsonLd?: ReadonlyArray<Readonly<Record<string, unknown>>> | undefined\n}\n\n/** Marks each head element a plan's `meta` wrote, so the browser can replace them. */\nexport const META_ATTRIBUTE = 'data-foldkit-meta'\n\nconst attributeText = (text: string): string =>\n text\n .replaceAll('&', '&amp;')\n .replaceAll('\"', '&quot;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n\n/** The head markup of a `Meta`, every value escaped, one element per line. */\nexport const metaMarkup = (meta: Meta): string => {\n const tag = (element: string, attributes: ReadonlyArray<readonly [string, string]>) =>\n `<${element} ${META_ATTRIBUTE} ${attributes.map(([name, value]) => `${name}=\"${attributeText(value)}\"`).join(' ')}>`\n const named = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['name', name],\n ['content', value],\n ]),\n ]\n const property = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['property', name],\n ['content', value],\n ]),\n ]\n return [\n ...named('description', meta.description),\n ...property('og:title', meta.title),\n ...property('og:description', meta.description),\n ...property('og:type', meta.type),\n ...property('og:site_name', meta.siteName),\n ...property('og:image', meta.image),\n ...(meta.description === undefined && meta.image === undefined && meta.title === undefined\n ? []\n : named('twitter:card', meta.image === undefined ? 'summary' : 'summary_large_image')),\n ...property('article:published_time', meta.article?.published),\n ...property('article:modified_time', meta.article?.modified),\n ...named('robots', meta.robots),\n ...(meta.alternates ?? []).map(({ hreflang, href }) =>\n tag('link', [\n ['rel', 'alternate'],\n ['hreflang', hreflang],\n ['href', href],\n ]),\n ),\n ...(meta.jsonLd ?? []).map(\n data =>\n `<script ${META_ATTRIBUTE} type=\"application/ld+json\">${serializeJsonScript(data)}</script>`,\n ),\n ].join('\\n')\n}\n\n/**\n * The Subscription entry that keeps the head's `meta` elements in step with\n * the Model, so a move within the page (another post) changes its\n * description too. It writes the head and sends no Message.\n */\nexport const metaEntry = <Model>(meta: (model: Model) => Meta) => ({\n dependenciesSchema: Schema.String,\n modelToDependencies: (model: Model) => metaMarkup(meta(model)),\n dependenciesToStream: (markup: string) =>\n Stream.drain(\n Stream.fromEffect(\n Effect.sync(() => {\n const written = document.createElement('template')\n written.innerHTML = markup\n for (const old of document.head.querySelectorAll(`[${META_ATTRIBUTE}]`)) old.remove()\n document.head.append(written.content)\n }),\n ),\n ),\n})\n\n/** One entry of a resume plan's `surfaces`: a lone Surface, or a `Surface.each` family. */\nexport type PlanSurface<Model> = ActiveSurface<Model> | SurfaceSource<Model>\n\n/**\n * What a plan entry resolves to for a Model: the lone projection of a\n * `Surface.at`/`Surface.when` value, or a family's parent first and then each\n * instance. The parent joins so the envelope carries what the instances were\n * discovered through, not just what they read.\n */\nexport const projectionsOf = <Model>(\n source: PlanSurface<Model>,\n model: Model,\n): ReadonlyArray<{ readonly metadata: Metadata }> => {\n if (typeof (source as Partial<SurfaceSource<Model>>).instancesOf === 'function') {\n const origin = source as SurfaceSource<Model>\n const from = (source as { readonly from?: ActiveSurface<Model> }).from\n const parent = from === undefined ? [] : Option.toArray(from.projectionOf(model))\n return [...parent, ...origin.instancesOf(model).map(instance => instance.projection)]\n }\n return Option.toArray((source as ActiveSurface<Model>).projectionOf(model))\n}\n\n/**\n * Which part of the Model the browser owns, and what it starts from.\n *\n * `state` is a writable projection of that part, from `Projection.pick` or\n * `Projection.compose`. `baseline` is the Model the browser sets it onto, by\n * default the application's own initial Model. `boot` names the Commands the\n * browser runs on load, since `init` does not run there.\n */\nexport interface ResumePlan<Model, Fields extends Schema.Struct.Fields, Commands = unknown> {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline: Model\n readonly boot?: ((model: Model) => Commands) | undefined\n /** Model paths allowed to start from the baseline, as each place's focus gives them. */\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n /** The Surfaces the browser may activate, which the plan must cover. */\n readonly surfaces: ReadonlyArray<PlanSurface<Model>>\n /** State another package owns, each captured and restored by that package. */\n readonly parts: ReadonlyArray<ResumePart<Model>>\n /** The application's Message Schema, which encodes the page's bindings. */\n readonly Message?: Schema.Top | undefined\n /**\n * When the browser boots the runtime: `now` on load, `idle` when the browser\n * is idle or on the first interaction, `on-interaction` on the first only.\n * Until then the page answers events from its bindings and queues the\n * Messages, which the runtime runs through `update` before any other.\n */\n readonly start: Start\n /** Subscription and Managed Resource keys that may start late (decision 10). */\n readonly deferrable: ReadonlyArray<string>\n /**\n * `server`: a form whose `OnSubmit` names a Message also posts it to the\n * page's own URL, and `SSR.handle` runs `update` there, so the form works\n * with scripts off or not yet loaded.\n */\n readonly fallback?: 'server' | undefined\n /**\n * What the page says of itself, from the Model: rendered into the head on\n * the server, checked like the view, and kept in step in the browser.\n */\n readonly meta?: ((model: Model) => Meta) | undefined\n /**\n * The data the page was built from, for the browser's freshness check: a\n * Remote cursor, a revision number, anything the check compares. Unset\n * when the page has no age.\n */\n readonly version?: unknown | undefined\n}\n\nexport type Start = 'now' | 'idle' | 'on-interaction'\n\n/**\n * A package's contribution to the envelope, for state the plan's slice cannot\n * carry, such as Remote's normalized store. On the server `capture` takes what\n * the active Surfaces' projections read and returns it as JSON; in the browser\n * `restore` sets it onto the Model, or says why it cannot. A part owns its\n * encoding: this package only carries the value.\n *\n * `covers` names the metadata keys whose reads the part resumes, so the\n * coverage check counts those reads as sent. `Remote.resume(Data)` is one.\n */\nexport interface ResumePart<Model> {\n readonly id: string\n readonly covers: ReadonlyArray<string>\n readonly capture: (\n model: Model,\n projections: ReadonlyArray<{ readonly metadata: Metadata }>,\n ) => unknown\n readonly restore: (model: Model, value: unknown) => Result.Result<Model, string>\n /**\n * Whether a Subscription or Managed Resource entry of this part's package\n * may start late, when a deferred boot is asked for. A part knows its own\n * entries; nothing is deferrable by default.\n */\n readonly deferrable?: ((key: string, entry: unknown) => boolean) | undefined\n}\n\n/** Why a page's resume envelope was refused. */\nexport class ResumeRefused extends Schema.TaggedError<ResumeRefused>()('ResumeRefused', {\n reason: Schema.Literals([\n 'Missing',\n 'Duplicate',\n 'Unreadable',\n 'Protocol',\n 'Plan',\n 'Invalid',\n 'Route',\n ]),\n message: Schema.String,\n}) {}\n\nexport const refuse = (reason: ResumeRefused['reason'], message: string) =>\n Result.fail(new ResumeRefused({ reason, message }))\n\n/**\n * The slice's Schema as a codec needing no services. A resume plan's state is\n * plain data, so any field that needs one cannot cross a page anyway.\n */\nexport const codecOf = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>\n schema as unknown as Schema.Codec<Schema.Struct.Type<Fields>, unknown>\n\n/**\n * A resume plan for an application. The baseline defaults to the\n * application's initial Model. It is never written: a writable projection's\n * `set` returns a new Model, so a baseline Foldkit freezes in development is\n * safe to start from.\n *\n * `surfaces` are the Surfaces the browser may activate, and `local` the Model\n * fields allowed to start from the baseline, such as an open menu. Rendering\n * refuses a plan that leaves a Surface's read or activation in neither.\n */\nexport const plan = <Model, Fields extends Schema.Struct.Fields, Commands = unknown>(\n application: {\n readonly initial: Model\n readonly owner?: object\n readonly Message?: Schema.Top | undefined\n },\n config: {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline?: Model | undefined\n readonly boot?: ((model: Model) => Commands) | undefined\n readonly local?: ReadonlyArray<ModelPlace<NoInfer<Model>>> | undefined\n readonly surfaces?: ReadonlyArray<PlanSurface<Model>> | undefined\n readonly parts?: ReadonlyArray<ResumePart<Model>> | undefined\n readonly start?: Start | undefined\n readonly deferrable?: ReadonlyArray<string> | undefined\n readonly fallback?: 'server' | undefined\n readonly meta?: ((model: Model) => Meta) | undefined\n readonly version?: unknown | undefined\n },\n): ResumePlan<Model, Fields, Commands> => {\n const surfaces = config.surfaces ?? []\n const parts = config.parts ?? []\n const repeated = parts.find((part, index) => parts.findIndex(p => p.id === part.id) !== index)\n if (repeated !== undefined) {\n throw new Error(\n `SSR.plan: two parts of plan \"${config.id}\" share the id \"${repeated.id}\"; give one an id of its own`,\n )\n }\n // A family joins its parent's requirements with its instances', so the\n // parent's application is checked too: a family smuggling another\n // application's Surface is refused here, not at its reads.\n const entered = surfaces.flatMap(surface => {\n const from = (surface as { readonly from?: PlanSurface<Model> }).from\n return from === undefined ? [surface] : [surface, from]\n })\n const foreign = entered.find(\n surface => application.owner !== undefined && surface.owner !== application.owner,\n )\n if (foreign !== undefined) {\n throw new Error(\n `SSR.plan: the Surface \"${foreign.name}\" belongs to another application than plan \"${config.id}\"`,\n )\n }\n return {\n id: config.id,\n state: config.state,\n baseline: config.baseline ?? application.initial,\n ...(config.boot === undefined ? {} : { boot: config.boot }),\n local: (config.local ?? []).map(place => ModelRef.focus(place).dependency),\n surfaces,\n parts,\n ...(application.Message === undefined ? {} : { Message: application.Message }),\n start: config.start ?? 'now',\n deferrable: config.deferrable ?? [],\n ...(config.fallback === undefined ? {} : { fallback: config.fallback }),\n ...(config.meta === undefined ? {} : { meta: config.meta }),\n ...(config.version === undefined ? {} : { version: config.version }),\n }\n}\n\n/**\n * How a page's recorded route is compared with the browser's. `full` compares\n * path and query. `path` compares the path alone, ignoring a trailing slash or\n * `index.html`, for a page generated as a file: a static host serves one file\n * for every query, and for `/about` and `/about/` alike.\n */\nexport type RouteMatch = 'full' | 'path'\n\n/** A path as a `path` match compares it. */\nexport const pathKey = (route: string): string => {\n const path = route.split(/[?#]/)[0] ?? ''\n const trimmed = path.replace(/\\/index\\.html$/, '/').replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\n/**\n * The Model a payload resumes: the baseline with the slice set onto it, then\n * each part restored, in order. Every part the plan names must be there and\n * restore, and no other may be: a page is never half-restored.\n */\nexport const modelFrom = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: { readonly state: unknown; readonly parts?: unknown },\n): Result.Result<Model, string> => {\n const decoded = Schema.decodeUnknownResult(codecOf(plan.state.schema))(payload.state)\n if (Result.isFailure(decoded)) {\n return Result.fail(`the envelope's state does not decode: ${decoded.failure.message}`)\n }\n const given = payload.parts ?? {}\n if (typeof given !== 'object' || Array.isArray(given)) {\n return Result.fail(\"the envelope's parts are not an object of parts by id\")\n }\n const parts = given as Readonly<Record<string, unknown>>\n const unknown = Object.keys(parts).find(id => !plan.parts.some(part => part.id === id))\n if (unknown !== undefined) {\n return Result.fail(`the envelope carries a part \"${unknown}\" the plan does not name`)\n }\n let model = plan.state.set(plan.baseline, decoded.success)\n for (const part of plan.parts) {\n if (!Object.hasOwn(parts, part.id))\n return Result.fail(`the envelope carries no \"${part.id}\" part`)\n const restored = part.restore(model, parts[part.id])\n if (Result.isFailure(restored)) {\n return Result.fail(`the \"${part.id}\" part does not restore: ${restored.failure}`)\n }\n model = restored.success\n }\n return Result.succeed(model)\n}\n\n/** The page's envelope, read off its stamped root; refused when there is no root, more than one, no envelope, or not JSON. */\nconst readEnvelope = (\n page: ParentNode,\n): Result.Result<Readonly<Record<string, unknown>>, ResumeRefused> => {\n const roots = page.querySelectorAll(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (roots.length === 0) return refuse('Missing', 'the page holds no stamped application root')\n if (roots.length > 1) {\n return refuse('Duplicate', `the page holds ${roots.length} stamped application roots`)\n }\n const carried = roots[0]?.getAttribute(RESUME_ATTRIBUTE)\n if (carried === null || carried === undefined) {\n return refuse('Missing', 'the page holds no resume envelope')\n }\n try {\n const parsed: unknown = JSON.parse(carried)\n return Result.succeed((parsed ?? {}) as Readonly<Record<string, unknown>>)\n } catch (error) {\n return refuse('Unreadable', `the resume envelope is not JSON: ${String(error)}`)\n }\n}\n\n/**\n * The Model a page resumes from: the baseline with the stamped root's envelope\n * set onto it. Refused, with the reason, when the page holds no stamped root\n * or more than one, when the root carries no envelope or not JSON, when it is\n * not this protocol or this plan, or when the slice does not decode through\n * the plan's Schema. A page is never half-restored.\n */\nexport const resume = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n options: { readonly route?: string | undefined } = {},\n): Result.Result<Model, ResumeRefused> => {\n const read = readEnvelope(page)\n if (Result.isFailure(read)) return Result.fail(read.failure)\n const parsed = read.success\n const { v, plan: id, state, parts, route, match } = parsed\n if (v !== PROTOCOL) {\n return refuse('Protocol', `the envelope is protocol ${String(v)}, not ${PROTOCOL}`)\n }\n if (id !== plan.id) {\n return refuse('Plan', `the envelope is for plan \"${String(id)}\", not \"${plan.id}\"`)\n }\n // The route the Model was made for. The runtime never reports the URL at\n // boot, so a page resumed on another route would show one and be on the\n // other.\n if (route !== undefined && options.route !== undefined) {\n const matches =\n match === 'path' ? pathKey(String(route)) === pathKey(options.route) : route === options.route\n if (!matches) {\n return refuse(\n 'Route',\n `the page was ${match === 'path' ? 'generated' : 'rendered'} for ${String(route)}, not ${options.route}`,\n )\n }\n }\n const resumed = modelFrom(plan, { state, parts })\n return Result.isFailure(resumed)\n ? refuse('Invalid', resumed.failure)\n : Result.succeed(resumed.success)\n}\n\n/** The tag a Message value carries, for naming it. */\nexport const tagOf = (message: unknown): string =>\n typeof message === 'object' &&\n message !== null &&\n '_tag' in message &&\n typeof message._tag === 'string'\n ? message._tag\n : 'an untagged Message'\n\n/**\n * The Message tags the plan's Surfaces active for `model` may send, which is\n * what a page's bindings may dispatch (the design's rule 3).\n */\nexport const allowedTags = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlySet<string> =>\n new Set(\n plan.surfaces.flatMap(source =>\n projectionsOf(source, model).length > 0 ? source.messages : [],\n ),\n )\n\n/** The attribute on a static region's element, naming the region. */\nexport const STATIC_ATTRIBUTE = 'data-foldkit-plus-static'\n\nconst boundary = (id: string, trusted: string | undefined, children: Region): Html =>\n inertHtml.div(\n [\n inertHtml.Attribute(STATIC_ATTRIBUTE, id),\n ...(trusted === undefined ? [] : [inertHtml.InnerHTML(trusted)]),\n ],\n children,\n )\n\n/**\n * A region of the page the server owns for the life of the document. It is\n * rendered on the server with the inert builder, so it can dispatch no\n * Message. The browser adopts the server's markup as trusted `InnerHTML` and\n * never runs `render`, so the region reads nothing from the browser's Model\n * and a plan need not send what it reads.\n *\n * A region changes only with a new document. Content a Message should change\n * belongs in a Surface, not here.\n */\nexport const staticRegion = (id: string, render: (ih: HtmlBuilder<never>) => Region): Html => {\n const now = current()\n if (now?.mode === 'resume') {\n const snapshot = now.snapshots.get(id)\n if (snapshot !== undefined) return boundary(id, snapshot, [])\n if (!now.reported.has(id)) {\n now.reported.add(id)\n now.report(staticRegionMissing(id))\n }\n return boundary(id, undefined, render(inertHtml))\n }\n const replayed = now?.mode === 'replay' ? now.regions.get(id) : undefined\n if (replayed !== undefined) return boundary(id, undefined, replayed)\n if (now?.mode !== 'collect') return boundary(id, undefined, render(inertHtml))\n const outer = now.region\n now.region = id\n try {\n const children = render(inertHtml)\n if (now.regions.has(id)) now.duplicates.add(id)\n else now.regions.set(id, children)\n return boundary(id, undefined, children)\n } finally {\n now.region = outer\n }\n}\n\n/**\n * Whether the view call in progress is the server rendering a page, rather than the browser: true\n * through both of `render`'s passes, false while the browser resumes and outside any render. For a\n * view that sends markup it will adopt in the browser rather than draw there, such as\n * `foldkit-richtext-dom`'s editor host, whose placement takes this as `serverRendered`.\n */\nexport const serving = (): boolean => {\n const mode = current()?.mode\n return mode === 'collect' || mode === 'replay'\n}\n\n/**\n * The `makeApplication` options `SSR` hands to Foldkit as they are, typed as\n * Foldkit types them.\n */\ntype ApplicationOptions<Model, Message> = Partial<\n Pick<\n Runtime.RoutingApplicationConfig<Model, Message, never, never, Ports | undefined>,\n | 'routing'\n | 'ports'\n | 'crash'\n | 'slow'\n | 'viewTransition'\n | 'freezeModel'\n | 'preserveScroll'\n | 'devTools'\n >\n>\n\n/**\n * The part of a Foldkit application config a server render and a resumed\n * client need. The full `makeApplication` config fits, whichever of its four\n * shapes, and its callbacks (`routing`'s, say) are typed from `update`'s\n * Message as Foldkit types them.\n */\nexport interface ResumableConfig<Model, Message = any> extends ApplicationOptions<Model, Message> {\n readonly Model: Schema.Codec<Model, any, unknown, unknown>\n readonly init: (...args: ReadonlyArray<any>) => {\n readonly model: Model\n readonly commands?: ReadonlyArray<{ readonly name: string }> | undefined\n }\n readonly update: (model: Model, message: Message) => { readonly model: Model }\n readonly view: (model: Model, h: any) => unknown\n readonly container: HTMLElement | null\n readonly Flags?: unknown\n readonly subscriptions?: Readonly<Record<string, unknown>> | undefined\n readonly managedResources?: Readonly<Record<string, unknown>> | undefined\n /** The services Commands need, as Foldkit's runtime provides them. */\n readonly resources?: Layer.Layer<never, never, never> | undefined\n /**\n * Bundles whose bodies load on demand (`Bundle.lazy`). The server loads\n * them before it renders; the browser loads them before it boots, answering\n * from the markers meanwhile, so a page never shows a bundle's placeholder.\n */\n readonly lazy?: ReadonlyArray<Loadable> | undefined\n}\n\n/** What `SSR` needs of a lazy bundle: `Bundle.lazy` gives it. */\nexport interface Loadable {\n readonly name: string\n readonly load: () => Promise<void>\n readonly isLoaded: () => boolean\n}\n\n/**\n * The config without a `Flags` key at all. Deleted, never set to `undefined`:\n * Foldkit's server asks whether `Flags` is defined and its client whether the\n * key exists, so an `undefined` one renders and is then refused.\n */\nconst withoutFlags = <Config extends { readonly Flags?: unknown }>(config: Config) => {\n const { Flags: _flags, ...rest } = config\n return rest\n}\n\n/** The config whose `init` returns this start, whatever arguments it is given. */\nexport const startingFrom = <Model>(\n config: ResumableConfig<Model>,\n start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> },\n) => ({ ...withoutFlags(config), init: () => start })\n\n/** A route as the envelope records it: the path and the query. */\nexport const routeOf = (url: string): string => {\n const parsed = new URL(url, 'http://localhost')\n return `${parsed.pathname}${parsed.search}`\n}\n\n/**\n * The page's bindings, decoded through the plan's Message Schema, kept to the\n * Messages the Surfaces active for `model` may send, and checked against\n * every marker in `root`. Refused, with the reason, when the page carries\n * none, an entry is not one of the application's Messages or one no active\n * Surface lists, or a marker names a binding the page does not carry: a page\n * is answered whole or not at all.\n */\nexport const bindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<ReadonlyArray<DecodedBinding>, ResumeRefused> =>\n Result.map(bindingsAndEvents(plan, page, root, model), read => read.bindings)\n\nconst EnvelopeEvents = Schema.optional(Schema.Array(Schema.String))\n\n/**\n * `bindings`, and the events the envelope says the markers name, if it says:\n * a page from before the envelope listed them leaves `listen` to find them.\n */\nexport const bindingsAndEvents = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<\n {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n ResumeRefused\n> => {\n const parsed = readEnvelope(page)\n if (Result.isFailure(parsed)) return Result.fail(parsed.failure)\n const read = readBindings(parsed.success.bindings ?? [])\n if (Result.isFailure(read)) {\n return refuse('Invalid', `the page's bindings are malformed: ${read.failure}`)\n }\n const encoded = read.success\n if (encoded.length > 0 && plan.surfaces.length === 0) {\n return refuse(\n 'Invalid',\n 'the page has bindings and the plan declares no surfaces to allow them',\n )\n }\n const events = Schema.decodeUnknownResult(EnvelopeEvents)(parsed.success.events)\n if (Result.isFailure(events)) {\n return refuse('Invalid', `the page's events are malformed: ${events.failure.message}`)\n }\n const decoded = decodeBindings(plan.Message, encoded, root, allowedTags(plan, model))\n return Result.isFailure(decoded)\n ? refuse('Invalid', decoded.failure)\n : Result.succeed({ bindings: decoded.success, events: events.success })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,MAAa,wBAAwB;;;;;;AAOrC,MAAa,mBAAmB;;AAGhC,MAAa,WAAW;AAExB,MAAM,iBAAiB,OAAO,aAAa,IAAM;AACjD,MAAM,sBAAsB,OAAO,aAAa,IAAM;;;;;;AAOtD,MAAa,uBAAuB,UAClC,KAAK,UAAU,KAAK,CAAC,CAClB,WAAW,KAAK,SAAS,CAAC,CAC1B,WAAW,gBAAgB,SAAS,CAAC,CACrC,WAAW,qBAAqB,SAAS;;;;;;;AAQ9C,MAAa,eAAe,SAC1B,IAAI,iBAAiB,IAAI,KAAK,WAAW,KAAK,OAAO,CAAC,CAAC,WAAW,MAAK,QAAQ,EAAE;;AA0BnF,MAAa,iBAAiB;AAE9B,MAAM,iBAAiB,SACrB,KACG,WAAW,KAAK,OAAO,CAAC,CACxB,WAAW,MAAK,QAAQ,CAAC,CACzB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM;;AAG3B,MAAa,cAAc,SAAuB;CAChD,MAAM,OAAO,SAAiB,eAC5B,IAAI,QAAQ,GAAG,eAAe,GAAG,WAAW,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,IAAI,cAAc,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE;CACpH,MAAM,SAAS,MAAc,UAC3B,UAAU,KAAA,IACN,CAAC,IACD,CACE,IAAI,QAAQ,CACV,CAAC,QAAQ,IAAI,GACb,CAAC,WAAW,KAAK,CACnB,CAAC,CACH;CACN,MAAM,YAAY,MAAc,UAC9B,UAAU,KAAA,IACN,CAAC,IACD,CACE,IAAI,QAAQ,CACV,CAAC,YAAY,IAAI,GACjB,CAAC,WAAW,KAAK,C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CAAC;;;;;AAMlE,MAAa,qBACX,MACA,MACA,MACA,UAOG;CACH,MAAM,SAAS,aAAa,IAAI;CAChC,IAAI,OAAO,UAAU,MAAM,GAAG,OAAO,OAAO,KAAK,OAAO,OAAO;CAC/D,MAAM,OAAO,aAAa,OAAO,QAAQ,YAAY,CAAC,CAAC;CACvD,IAAI,OAAO,UAAU,IAAI,GACvB,OAAO,OAAO,WAAW,sCAAsC,KAAK,SAAS;CAE/E,MAAM,UAAU,KAAK;CACrB,IAAI,QAAQ,SAAS,KAAK,KAAK,SAAS,WAAW,GACjD,OAAO,OACL,WACA,uEACF;CAEF,MAAM,SAAS,OAAO,oBAAoB,cAAc,CAAC,CAAC,OAAO,QAAQ,MAAM;CAC/E,IAAI,OAAO,UAAU,MAAM,GACzB,OAAO,OAAO,WAAW,oCAAoC,OAAO,QAAQ,SAAS;CAEvF,MAAM,UAAU,eAAe,KAAK,SAAS,SAAS,MAAM,YAAY,MAAM,KAAK,CAAC;CACpF,OAAO,OAAO,UAAU,OAAO,IAC3B,OAAO,WAAW,QAAQ,OAAO,IACjC,OAAO,QAAQ;EAAE,UAAU,QAAQ;EAAS,QAAQ,OAAO;CAAQ,CAAC;AAC1E"}
1
+ {"version":3,"file":"shared.js","names":[],"sources":["../src/shared.ts"],"sourcesContent":["/**\n * What the server and the browser both read: the plan, the envelope as the\n * browser reads it, static regions, and the page's bindings. Nothing here\n * imports Foldkit's server renderer, so `client.ts` can carry all of it.\n */\nimport { Effect, Option, Result, Schema, Stream, type Layer } from 'effect'\nimport type { Runtime } from 'foldkit'\nimport { inertHtml, type Html, type HtmlBuilder } from 'foldkit/html'\nimport type { Ports } from 'foldkit/port'\nimport { fromString } from 'foldkit/url'\nimport {\n ModelRef,\n type ActiveSurface,\n type Metadata,\n type ModelPlace,\n type SurfaceSource,\n type WritableProjection,\n} from 'foldkit-surface'\nimport { current, type Region } from './context.js'\nimport { staticRegionMissing } from './diagnostics.js'\nimport { decodeBindings, readBindings, type DecodedBinding } from './listen.js'\n\n/**\n * The attribute Foldkit's server stamps on an application's root, as\n * `foldkit/experimental/server` exports it. Written out here so a page can\n * find its root without that module; a test pins the two together.\n */\nexport const FOLDKIT_APP_ATTRIBUTE = 'data-foldkit-app'\n\n/**\n * The attribute on the stamped root that carries a page's resume envelope.\n * Foldkit pairs its own handoff the same way: the build id rides on the root\n * beside the app stamp, and the client reads it before adopting anything.\n */\nexport const RESUME_ATTRIBUTE = 'data-foldkit-plus-resume'\n\n/** The envelope format this package writes and reads. */\nexport const PROTOCOL = 1\n\n/**\n * The comment a render's `styles` follow in the stamped root. Hydration\n * removes children the view does not draw, so `SSR.hydrate` moves what\n * follows it into the head before adopting the page.\n */\nexport const STYLES_MARKER = 'foldkit-plus-styles'\n\nconst LINE_SEPARATOR = String.fromCharCode(0x2028)\nconst PARAGRAPH_SEPARATOR = String.fromCharCode(0x2029)\n\n/**\n * JSON for a script element: `<` is escaped so `</script>` in the data ends\n * nothing. U+2028 and U+2029 are escaped too: they are fine in JSON and break a\n * reader that treats the text as JavaScript.\n */\nexport const serializeJsonScript = (value: unknown): string =>\n JSON.stringify(value)\n .replaceAll('<', '\\\\u003c')\n .replaceAll(LINE_SEPARATOR, '\\\\u2028')\n .replaceAll(PARAGRAPH_SEPARATOR, '\\\\u2029')\n\n/**\n * The envelope JSON as the stamped root carries it, in single quotes so the\n * JSON's own double quotes need no escape. `&` and `'` are escaped, so no\n * string in the Model can break out of the value; `getAttribute` resolves the\n * entities back to exactly the JSON. `serializeJsonScript` has already escaped\n * `<` and the line separators.\n */\nexport const attributeOf = (json: string): string =>\n ` ${RESUME_ATTRIBUTE}='${json.replaceAll('&', '&amp;').replaceAll(\"'\", '&#39;')}'`\n\n/**\n * What a page says of itself beyond Foldkit's `Document` (`title`, `lang`,\n * `dir`, `canonical`, `ogUrl`): what a search result and a link preview show.\n * `title` is the preview's title (`og:title`), when it differs from the\n * document's. Dates are ISO 8601 text; `jsonLd` is structured data, each\n * entry written as its own script.\n */\nexport interface Meta {\n readonly description?: string | undefined\n readonly title?: string | undefined\n readonly image?: string | undefined\n readonly type?: 'website' | 'article' | undefined\n readonly siteName?: string | undefined\n readonly article?:\n | { readonly published?: string | undefined; readonly modified?: string | undefined }\n | undefined\n readonly robots?: string | undefined\n readonly alternates?:\n | ReadonlyArray<{ readonly hreflang: string; readonly href: string }>\n | undefined\n readonly jsonLd?: ReadonlyArray<Readonly<Record<string, unknown>>> | undefined\n}\n\n/** Marks each head element a plan's `meta` wrote, so the browser can replace them. */\nexport const META_ATTRIBUTE = 'data-foldkit-meta'\n\nconst attributeText = (text: string): string =>\n text\n .replaceAll('&', '&amp;')\n .replaceAll('\"', '&quot;')\n .replaceAll('<', '&lt;')\n .replaceAll('>', '&gt;')\n\n/** The head markup of a `Meta`, every value escaped, one element per line. */\nexport const metaMarkup = (meta: Meta): string => {\n const tag = (element: string, attributes: ReadonlyArray<readonly [string, string]>) =>\n `<${element} ${META_ATTRIBUTE} ${attributes.map(([name, value]) => `${name}=\"${attributeText(value)}\"`).join(' ')}>`\n const named = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['name', name],\n ['content', value],\n ]),\n ]\n const property = (name: string, value: string | undefined) =>\n value === undefined\n ? []\n : [\n tag('meta', [\n ['property', name],\n ['content', value],\n ]),\n ]\n return [\n ...named('description', meta.description),\n ...property('og:title', meta.title),\n ...property('og:description', meta.description),\n ...property('og:type', meta.type),\n ...property('og:site_name', meta.siteName),\n ...property('og:image', meta.image),\n ...(meta.description === undefined && meta.image === undefined && meta.title === undefined\n ? []\n : named('twitter:card', meta.image === undefined ? 'summary' : 'summary_large_image')),\n ...property('article:published_time', meta.article?.published),\n ...property('article:modified_time', meta.article?.modified),\n ...named('robots', meta.robots),\n ...(meta.alternates ?? []).map(({ hreflang, href }) =>\n tag('link', [\n ['rel', 'alternate'],\n ['hreflang', hreflang],\n ['href', href],\n ]),\n ),\n ...(meta.jsonLd ?? []).map(\n data =>\n `<script ${META_ATTRIBUTE} type=\"application/ld+json\">${serializeJsonScript(data)}</script>`,\n ),\n ].join('\\n')\n}\n\n/**\n * The Subscription entry that keeps the head's `meta` elements in step with\n * the Model, so a move within the page (another post) changes its\n * description too. It writes the head and sends no Message.\n */\nexport const metaEntry = <Model>(meta: (model: Model) => Meta) => ({\n dependenciesSchema: Schema.String,\n modelToDependencies: (model: Model) => metaMarkup(meta(model)),\n dependenciesToStream: (markup: string) =>\n Stream.drain(\n Stream.fromEffect(\n Effect.sync(() => {\n const written = document.createElement('template')\n written.innerHTML = markup\n for (const old of document.head.querySelectorAll(`[${META_ATTRIBUTE}]`)) old.remove()\n document.head.append(written.content)\n }),\n ),\n ),\n})\n\n/** One entry of a resume plan's `surfaces`: a lone Surface, or a `Surface.each` family. */\nexport type PlanSurface<Model> = ActiveSurface<Model> | SurfaceSource<Model>\n\n/**\n * What a plan entry resolves to for a Model: the lone projection of a\n * `Surface.at`/`Surface.when` value, or a family's parent first and then each\n * instance. The parent joins so the envelope carries what the instances were\n * discovered through, not just what they read.\n */\nexport const projectionsOf = <Model>(\n source: PlanSurface<Model>,\n model: Model,\n): ReadonlyArray<{ readonly metadata: Metadata }> => {\n if (typeof (source as Partial<SurfaceSource<Model>>).instancesOf === 'function') {\n const origin = source as SurfaceSource<Model>\n const from = (source as { readonly from?: ActiveSurface<Model> }).from\n const parent = from === undefined ? [] : Option.toArray(from.projectionOf(model))\n return [...parent, ...origin.instancesOf(model).map(instance => instance.projection)]\n }\n return Option.toArray((source as ActiveSurface<Model>).projectionOf(model))\n}\n\n/**\n * Which part of the Model the browser owns, and what it starts from.\n *\n * `state` is a writable projection of that part, from `Projection.pick` or\n * `Projection.compose`. `baseline` is the Model the browser sets it onto, by\n * default the application's own initial Model. `boot` names the Commands the\n * browser runs on load, since `init` does not run there.\n */\nexport interface ResumePlan<Model, Fields extends Schema.Struct.Fields, Commands = unknown> {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline: Model\n readonly boot?: ((model: Model) => Commands) | undefined\n /** Model paths allowed to start from the baseline, as each place's focus gives them. */\n readonly local: ReadonlyArray<ReadonlyArray<string>>\n /** The Surfaces the browser may activate, which the plan must cover. */\n readonly surfaces: ReadonlyArray<PlanSurface<Model>>\n /** State another package owns, each captured and restored by that package. */\n readonly parts: ReadonlyArray<ResumePart<Model>>\n /** The application's Message Schema, which encodes the page's bindings. */\n readonly Message?: Schema.Top | undefined\n /**\n * When the browser boots the runtime: `now` on load, `idle` when the browser\n * is idle or on the first interaction, `on-interaction` on the first only.\n * Until then the page answers events from its bindings and queues the\n * Messages, which the runtime runs through `update` before any other.\n */\n readonly start: Start\n /** Subscription and Managed Resource keys that may start late (decision 10). */\n readonly deferrable: ReadonlyArray<string>\n /**\n * `server`: a form whose `OnSubmit` names a Message also posts it to the\n * page's own URL, and `SSR.handle` runs `update` there, so the form works\n * with scripts off or not yet loaded.\n */\n readonly fallback?: 'server' | undefined\n /**\n * What the page says of itself, from the Model: rendered into the head on\n * the server, checked like the view, and kept in step in the browser.\n */\n readonly meta?: ((model: Model) => Meta) | undefined\n /**\n * The data the page was built from, for the browser's freshness check: a\n * Remote cursor, a revision number, anything the check compares. Unset\n * when the page has no age.\n */\n readonly version?: unknown | undefined\n}\n\nexport type Start = 'now' | 'idle' | 'on-interaction'\n\n/**\n * A package's contribution to the envelope, for state the plan's slice cannot\n * carry, such as Remote's normalized store. On the server `capture` takes what\n * the active Surfaces' projections read and returns it as JSON; in the browser\n * `restore` sets it onto the Model, or says why it cannot. A part owns its\n * encoding: this package only carries the value.\n *\n * `covers` names the metadata keys whose reads the part resumes, so the\n * coverage check counts those reads as sent. `Remote.resume(Data)` is one.\n */\nexport interface ResumePart<Model> {\n readonly id: string\n readonly covers: ReadonlyArray<string>\n readonly capture: (\n model: Model,\n projections: ReadonlyArray<{ readonly metadata: Metadata }>,\n ) => unknown\n readonly restore: (model: Model, value: unknown) => Result.Result<Model, string>\n /**\n * Whether a Subscription or Managed Resource entry of this part's package\n * may start late, when a deferred boot is asked for. A part knows its own\n * entries; nothing is deferrable by default.\n */\n readonly deferrable?: ((key: string, entry: unknown) => boolean) | undefined\n}\n\n/** Why a page's resume envelope was refused. */\nexport class ResumeRefused extends Schema.TaggedError<ResumeRefused>()('ResumeRefused', {\n reason: Schema.Literals([\n 'Missing',\n 'Duplicate',\n 'Unreadable',\n 'Protocol',\n 'Plan',\n 'Invalid',\n 'Route',\n ]),\n message: Schema.String,\n}) {}\n\nexport const refuse = (reason: ResumeRefused['reason'], message: string) =>\n Result.fail(new ResumeRefused({ reason, message }))\n\n/**\n * The slice's Schema as a codec needing no services. A resume plan's state is\n * plain data, so any field that needs one cannot cross a page anyway.\n */\nexport const codecOf = <Fields extends Schema.Struct.Fields>(schema: Schema.Struct<Fields>) =>\n schema as unknown as Schema.Codec<Schema.Struct.Type<Fields>, unknown>\n\n/**\n * A resume plan for an application. The baseline defaults to the\n * application's initial Model. It is never written: a writable projection's\n * `set` returns a new Model, so a baseline Foldkit freezes in development is\n * safe to start from.\n *\n * `surfaces` are the Surfaces the browser may activate, and `local` the Model\n * fields allowed to start from the baseline, such as an open menu. Rendering\n * refuses a plan that leaves a Surface's read or activation in neither.\n */\nexport const plan = <Model, Fields extends Schema.Struct.Fields, Commands = unknown>(\n application: {\n readonly initial: Model\n readonly owner?: object\n readonly Message?: Schema.Top | undefined\n },\n config: {\n readonly id: string\n readonly state: WritableProjection<Model, Fields>\n readonly baseline?: Model | undefined\n readonly boot?: ((model: Model) => Commands) | undefined\n readonly local?: ReadonlyArray<ModelPlace<NoInfer<Model>>> | undefined\n readonly surfaces?: ReadonlyArray<PlanSurface<Model>> | undefined\n readonly parts?: ReadonlyArray<ResumePart<Model>> | undefined\n readonly start?: Start | undefined\n readonly deferrable?: ReadonlyArray<string> | undefined\n readonly fallback?: 'server' | undefined\n readonly meta?: ((model: Model) => Meta) | undefined\n readonly version?: unknown | undefined\n },\n): ResumePlan<Model, Fields, Commands> => {\n const surfaces = config.surfaces ?? []\n const parts = config.parts ?? []\n const repeated = parts.find((part, index) => parts.findIndex(p => p.id === part.id) !== index)\n if (repeated !== undefined) {\n throw new Error(\n `SSR.plan: two parts of plan \"${config.id}\" share the id \"${repeated.id}\"; give one an id of its own`,\n )\n }\n // A family joins its parent's requirements with its instances', so the\n // parent's application is checked too: a family smuggling another\n // application's Surface is refused here, not at its reads.\n const entered = surfaces.flatMap(surface => {\n const from = (surface as { readonly from?: PlanSurface<Model> }).from\n return from === undefined ? [surface] : [surface, from]\n })\n const foreign = entered.find(\n surface => application.owner !== undefined && surface.owner !== application.owner,\n )\n if (foreign !== undefined) {\n throw new Error(\n `SSR.plan: the Surface \"${foreign.name}\" belongs to another application than plan \"${config.id}\"`,\n )\n }\n return {\n id: config.id,\n state: config.state,\n baseline: config.baseline ?? application.initial,\n ...(config.boot === undefined ? {} : { boot: config.boot }),\n local: (config.local ?? []).map(place => ModelRef.focus(place).dependency),\n surfaces,\n parts,\n ...(application.Message === undefined ? {} : { Message: application.Message }),\n start: config.start ?? 'now',\n deferrable: config.deferrable ?? [],\n ...(config.fallback === undefined ? {} : { fallback: config.fallback }),\n ...(config.meta === undefined ? {} : { meta: config.meta }),\n ...(config.version === undefined ? {} : { version: config.version }),\n }\n}\n\n/**\n * How a page's recorded route is compared with the browser's. `full` compares\n * path and query. `path` compares the path alone, ignoring a trailing slash or\n * `index.html`, for a page generated as a file: a static host serves one file\n * for every query, and for `/about` and `/about/` alike.\n */\nexport type RouteMatch = 'full' | 'path'\n\n/** A path as a `path` match compares it. */\nexport const pathKey = (route: string): string => {\n const path = route.split(/[?#]/)[0] ?? ''\n const trimmed = path.replace(/\\/index\\.html$/, '/').replace(/\\/+$/, '')\n return trimmed === '' ? '/' : trimmed\n}\n\n/**\n * The Model a payload resumes: the baseline with the slice set onto it, then\n * each part restored, in order. Every part the plan names must be there and\n * restore, and no other may be: a page is never half-restored.\n */\nexport const modelFrom = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n payload: { readonly state: unknown; readonly parts?: unknown },\n): Result.Result<Model, string> => {\n const decoded = Schema.decodeUnknownResult(codecOf(plan.state.schema))(payload.state)\n if (Result.isFailure(decoded)) {\n return Result.fail(`the envelope's state does not decode: ${decoded.failure.message}`)\n }\n const given = payload.parts ?? {}\n if (typeof given !== 'object' || Array.isArray(given)) {\n return Result.fail(\"the envelope's parts are not an object of parts by id\")\n }\n const parts = given as Readonly<Record<string, unknown>>\n const unknown = Object.keys(parts).find(id => !plan.parts.some(part => part.id === id))\n if (unknown !== undefined) {\n return Result.fail(`the envelope carries a part \"${unknown}\" the plan does not name`)\n }\n let model = plan.state.set(plan.baseline, decoded.success)\n for (const part of plan.parts) {\n if (!Object.hasOwn(parts, part.id))\n return Result.fail(`the envelope carries no \"${part.id}\" part`)\n const restored = part.restore(model, parts[part.id])\n if (Result.isFailure(restored)) {\n return Result.fail(`the \"${part.id}\" part does not restore: ${restored.failure}`)\n }\n model = restored.success\n }\n return Result.succeed(model)\n}\n\n/** The page's envelope, read off its stamped root; refused when there is no root, more than one, no envelope, or not JSON. */\nconst readEnvelope = (\n page: ParentNode,\n): Result.Result<Readonly<Record<string, unknown>>, ResumeRefused> => {\n const roots = page.querySelectorAll(`[${FOLDKIT_APP_ATTRIBUTE}]`)\n if (roots.length === 0) return refuse('Missing', 'the page holds no stamped application root')\n if (roots.length > 1) {\n return refuse('Duplicate', `the page holds ${roots.length} stamped application roots`)\n }\n const carried = roots[0]?.getAttribute(RESUME_ATTRIBUTE)\n if (carried === null || carried === undefined) {\n return refuse('Missing', 'the page holds no resume envelope')\n }\n try {\n const parsed: unknown = JSON.parse(carried)\n return Result.succeed((parsed ?? {}) as Readonly<Record<string, unknown>>)\n } catch (error) {\n return refuse('Unreadable', `the resume envelope is not JSON: ${String(error)}`)\n }\n}\n\n/**\n * The Model a page resumes from: the baseline with the stamped root's envelope\n * set onto it. Refused, with the reason, when the page holds no stamped root\n * or more than one, when the root carries no envelope or not JSON, when it is\n * not this protocol or this plan, or when the slice does not decode through\n * the plan's Schema. A page is never half-restored.\n */\nexport const resume = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n options: { readonly route?: string | undefined } = {},\n): Result.Result<Model, ResumeRefused> => {\n const read = readEnvelope(page)\n if (Result.isFailure(read)) return Result.fail(read.failure)\n const parsed = read.success\n const { v, plan: id, state, parts, route, match } = parsed\n if (v !== PROTOCOL) {\n return refuse('Protocol', `the envelope is protocol ${String(v)}, not ${PROTOCOL}`)\n }\n if (id !== plan.id) {\n return refuse('Plan', `the envelope is for plan \"${String(id)}\", not \"${plan.id}\"`)\n }\n // The route the Model was made for. The runtime never reports the URL at\n // boot, so a page resumed on another route would show one and be on the\n // other.\n if (route !== undefined && options.route !== undefined) {\n const matches =\n match === 'path' ? pathKey(String(route)) === pathKey(options.route) : route === options.route\n if (!matches) {\n // Only the query differs: a static host served a page rendered for one\n // query for another, which only a page recorded for its path survives.\n const served =\n match !== 'path' && pathKey(String(route)) === pathKey(options.route)\n ? `; a page a static host serves for every query must record its path alone: generate it with SSR.generate, or name its path in SSR.entry's prerendered`\n : ''\n return refuse(\n 'Route',\n `the page was ${match === 'path' ? 'generated' : 'rendered'} for ${String(route)}, not ${options.route}${served}`,\n )\n }\n }\n const resumed = modelFrom(plan, { state, parts })\n return Result.isFailure(resumed)\n ? refuse('Invalid', resumed.failure)\n : Result.succeed(resumed.success)\n}\n\n/**\n * The Message telling the application the URL it is at, when the page was\n * recorded for its path alone and the browser is at a query: `init` never ran\n * here, so the application would otherwise never learn the query. None for\n * an application without routing, or a page at no query.\n */\nexport const arrival = <Model, Message>(\n config: ResumableConfig<Model, Message>,\n page: ParentNode,\n href: string,\n): Option.Option<Message> => {\n const routing = config.routing\n if (routing === undefined || new URL(href).search === '') return Option.none()\n const read = readEnvelope(page)\n if (Result.isFailure(read) || read.success.match !== 'path') return Option.none()\n return Option.map(fromString(href), routing.onUrlChange)\n}\n\n/** The tag a Message value carries, for naming it. */\nexport const tagOf = (message: unknown): string =>\n typeof message === 'object' &&\n message !== null &&\n '_tag' in message &&\n typeof message._tag === 'string'\n ? message._tag\n : 'an untagged Message'\n\n/**\n * The Message tags the plan's Surfaces active for `model` may send, which is\n * what a page's bindings may dispatch (the design's rule 3).\n */\nexport const allowedTags = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n model: Model,\n): ReadonlySet<string> =>\n new Set(\n plan.surfaces.flatMap(source =>\n projectionsOf(source, model).length > 0 ? source.messages : [],\n ),\n )\n\n/** The attribute on a static region's element, naming the region. */\nexport const STATIC_ATTRIBUTE = 'data-foldkit-plus-static'\n\nconst boundary = (id: string, trusted: string | undefined, children: Region): Html =>\n inertHtml.div(\n [\n inertHtml.Attribute(STATIC_ATTRIBUTE, id),\n ...(trusted === undefined ? [] : [inertHtml.InnerHTML(trusted)]),\n ],\n children,\n )\n\n/**\n * A region of the page the server owns for the life of the document. It is\n * rendered on the server with the inert builder, so it can dispatch no\n * Message. The browser adopts the server's markup as trusted `InnerHTML` and\n * never runs `render`, so the region reads nothing from the browser's Model\n * and a plan need not send what it reads.\n *\n * A region changes only with a new document. Content a Message should change\n * belongs in a Surface, not here.\n */\nexport const staticRegion = (id: string, render: (ih: HtmlBuilder<never>) => Region): Html => {\n const now = current()\n if (now?.mode === 'resume') {\n const snapshot = now.snapshots.get(id)\n if (snapshot !== undefined) return boundary(id, snapshot, [])\n if (!now.reported.has(id)) {\n now.reported.add(id)\n now.report(staticRegionMissing(id))\n }\n return boundary(id, undefined, render(inertHtml))\n }\n const replayed = now?.mode === 'replay' ? now.regions.get(id) : undefined\n if (replayed !== undefined) return boundary(id, undefined, replayed)\n if (now?.mode !== 'collect') return boundary(id, undefined, render(inertHtml))\n const outer = now.region\n now.region = id\n try {\n const children = render(inertHtml)\n if (now.regions.has(id)) now.duplicates.add(id)\n else now.regions.set(id, children)\n return boundary(id, undefined, children)\n } finally {\n now.region = outer\n }\n}\n\n/**\n * Whether the view call in progress is the server rendering a page, rather than the browser: true\n * through both of `render`'s passes, false while the browser resumes and outside any render. For a\n * view that sends markup it will adopt in the browser rather than draw there, such as\n * `foldkit-richtext-dom`'s editor host, whose placement takes this as `serverRendered`.\n */\nexport const serving = (): boolean => {\n const mode = current()?.mode\n return mode === 'collect' || mode === 'replay'\n}\n\n/**\n * The `makeApplication` options `SSR` hands to Foldkit as they are, typed as\n * Foldkit types them.\n */\ntype ApplicationOptions<Model, Message> = Partial<\n Pick<\n Runtime.RoutingApplicationConfig<Model, Message, never, never, Ports | undefined>,\n | 'routing'\n | 'ports'\n | 'crash'\n | 'slow'\n | 'viewTransition'\n | 'freezeModel'\n | 'preserveScroll'\n | 'devTools'\n >\n>\n\n/**\n * The part of a Foldkit application config a server render and a resumed\n * client need. The full `makeApplication` config fits, whichever of its four\n * shapes, and its callbacks (`routing`'s, say) are typed from `update`'s\n * Message as Foldkit types them.\n */\nexport interface ResumableConfig<Model, Message = any> extends ApplicationOptions<Model, Message> {\n readonly Model: Schema.Codec<Model, any, unknown, unknown>\n readonly init: (...args: ReadonlyArray<any>) => {\n readonly model: Model\n readonly commands?: ReadonlyArray<{ readonly name: string }> | undefined\n }\n readonly update: (model: Model, message: Message) => { readonly model: Model }\n readonly view: (model: Model, h: any) => unknown\n readonly container: HTMLElement | null\n readonly Flags?: unknown\n readonly subscriptions?: Readonly<Record<string, unknown>> | undefined\n readonly managedResources?: Readonly<Record<string, unknown>> | undefined\n /** The services Commands need, as Foldkit's runtime provides them. */\n readonly resources?: Layer.Layer<never, never, never> | undefined\n /**\n * Bundles whose bodies load on demand (`Bundle.lazy`). The server loads\n * them before it renders; the browser loads them before it boots, answering\n * from the markers meanwhile, so a page never shows a bundle's placeholder.\n */\n readonly lazy?: ReadonlyArray<Loadable> | undefined\n}\n\n/** What `SSR` needs of a lazy bundle: `Bundle.lazy` gives it. */\nexport interface Loadable {\n readonly name: string\n readonly load: () => Promise<void>\n readonly isLoaded: () => boolean\n}\n\n/**\n * The config without a `Flags` key at all. Deleted, never set to `undefined`:\n * Foldkit's server asks whether `Flags` is defined and its client whether the\n * key exists, so an `undefined` one renders and is then refused.\n */\nconst withoutFlags = <Config extends { readonly Flags?: unknown }>(config: Config) => {\n const { Flags: _flags, ...rest } = config\n return rest\n}\n\n/** The config whose `init` returns this start, whatever arguments it is given. */\nexport const startingFrom = <Model>(\n config: ResumableConfig<Model>,\n start: { readonly model: Model; readonly commands?: ReadonlyArray<unknown> | undefined },\n) => ({ ...withoutFlags(config), init: () => start })\n\n/** A route as the envelope records it: the path and the query. */\nexport const routeOf = (url: string): string => {\n const parsed = new URL(url, 'http://localhost')\n return `${parsed.pathname}${parsed.search}`\n}\n\n/**\n * The page's bindings, decoded through the plan's Message Schema, kept to the\n * Messages the Surfaces active for `model` may send, and checked against\n * every marker in `root`. Refused, with the reason, when the page carries\n * none, an entry is not one of the application's Messages or one no active\n * Surface lists, or a marker names a binding the page does not carry: a page\n * is answered whole or not at all.\n */\nexport const bindings = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<ReadonlyArray<DecodedBinding>, ResumeRefused> =>\n Result.map(bindingsAndEvents(plan, page, root, model), read => read.bindings)\n\nconst EnvelopeEvents = Schema.optional(Schema.Array(Schema.String))\n\n/**\n * `bindings`, and the events the envelope says the markers name, if it says:\n * a page from before the envelope listed them leaves `listen` to find them.\n */\nexport const bindingsAndEvents = <Model, Fields extends Schema.Struct.Fields>(\n plan: ResumePlan<Model, Fields>,\n page: ParentNode,\n root: Element,\n model: Model,\n): Result.Result<\n {\n readonly bindings: ReadonlyArray<DecodedBinding>\n readonly events: ReadonlyArray<string> | undefined\n },\n ResumeRefused\n> => {\n const parsed = readEnvelope(page)\n if (Result.isFailure(parsed)) return Result.fail(parsed.failure)\n const read = readBindings(parsed.success.bindings ?? [])\n if (Result.isFailure(read)) {\n return refuse('Invalid', `the page's bindings are malformed: ${read.failure}`)\n }\n const encoded = read.success\n if (encoded.length > 0 && plan.surfaces.length === 0) {\n return refuse(\n 'Invalid',\n 'the page has bindings and the plan declares no surfaces to allow them',\n )\n }\n const events = Schema.decodeUnknownResult(EnvelopeEvents)(parsed.success.events)\n if (Result.isFailure(events)) {\n return refuse('Invalid', `the page's events are malformed: ${events.failure.message}`)\n }\n const decoded = decodeBindings(plan.Message, encoded, root, allowedTags(plan, model))\n return Result.isFailure(decoded)\n ? refuse('Invalid', decoded.failure)\n : Result.succeed({ bindings: decoded.success, events: events.success })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA2BA,MAAa,wBAAwB;;;;;;AAOrC,MAAa,mBAAmB;;AAGhC,MAAa,WAAW;;;;;;AAOxB,MAAa,gBAAgB;AAE7B,MAAM,iBAAiB,OAAO,aAAa,IAAM;AACjD,MAAM,sBAAsB,OAAO,aAAa,IAAM;;;;;;AAOtD,MAAa,uBAAuB,UAClC,KAAK,UAAU,KAAK,CAAC,CAClB,WAAW,KAAK,SAAS,CAAC,CAC1B,WAAW,gBAAgB,SAAS,CAAC,CACrC,WAAW,qBAAqB,SAAS;;;;;;;;AAS9C,MAAa,eAAe,SAC1B,IAAI,iBAAiB,IAAI,KAAK,WAAW,KAAK,OAAO,CAAC,CAAC,WAAW,KAAK,OAAO,EAAE;;AA0BlF,MAAa,iBAAiB;AAE9B,MAAM,iBAAiB,SACrB,KACG,WAAW,KAAK,OAAO,CAAC,CACxB,WAAW,MAAK,QAAQ,CAAC,CACzB,WAAW,KAAK,MAAM,CAAC,CACvB,WAAW,KAAK,MAAM;;AAG3B,MAAa,cAAc,SAAuB;CAChD,MAAM,OAAO,SAAiB,eAC5B,IAAI,QAAQ,GAAG,eAAe,GAAG,WAAW,KAAK,CAAC,MAAM,WAAW,GAAG,KAAK,IAAI,cAAc,KAAK,EAAE,EAAE,CAAC,CAAC,KAAK,GAAG,EAAE;CACpH,MAAM,SAAS,MAAc,UAC3B,UAAU,KAAA,IACN,CAAC,IACD,CACE,IAAI,QAA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C;CACpF,OAAO,OAAO,UAAU,OAAO,IAC3B,OAAO,WAAW,QAAQ,OAAO,IACjC,OAAO,QAAQ;EAAE,UAAU,QAAQ;EAAS,QAAQ,OAAO;CAAQ,CAAC;AAC1E"}
package/dist/vite.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { c as ResumableConfig, u as ResumePlan } from "./shared-v1u-OEQI.js";
1
+ import { c as ResumableConfig, u as ResumePlan } from "./shared-CJN-m58Z.js";
2
2
  import { Head, ResumeUnsafe } from "./index.js";
3
3
  import { Effect, Schema } from "effect";
4
4
  import { RenderError } from "foldkit/experimental/server";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-ssr",
3
- "version": "0.9.0",
3
+ "version": "0.11.0",
4
4
  "description": "Server rendering for Foldkit Plus: render once on the server, hand the Model over, and hydrate without rerunning init.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -51,12 +51,12 @@
51
51
  "foldkit": "^0.170.0"
52
52
  },
53
53
  "dependencies": {
54
- "foldkit-surface": "0.11.0"
54
+ "foldkit-surface": "0.13.0"
55
55
  },
56
56
  "devDependencies": {
57
- "@effect/platform-browser": "^4.1.0",
57
+ "@effect/platform-browser": "^4.1.1",
58
58
  "@types/jsdom": "30.0.0",
59
- "effect": "^4.1.0",
59
+ "effect": "^4.1.1",
60
60
  "esbuild": "0.28.2",
61
61
  "foldkit": "0.170.0",
62
62
  "jsdom": "30.1.3",
@@ -64,13 +64,13 @@
64
64
  "tsdown": "^0.23.1",
65
65
  "typescript": "7.0.2",
66
66
  "vite": "8.3.5",
67
- "foldkit-bundle": "0.9.0",
68
- "foldkit-mirror": "0.7.0",
69
- "foldkit-remote": "0.22.0",
70
- "foldkit-entity": "0.14.0"
67
+ "foldkit-entity": "0.16.0",
68
+ "foldkit-mirror": "0.9.0",
69
+ "foldkit-remote": "0.24.0",
70
+ "foldkit-bundle": "0.11.0"
71
71
  },
72
72
  "scripts": {
73
- "build": "tsdown",
73
+ "build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",
74
74
  "typecheck": "tsc -b"
75
75
  }
76
76
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"client-F16QT0sc.d.ts","names":[],"sources":["../src/client.ts"],"mappings":";;;;;;;;;;;;;;;cAoEM,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;;;;;;;;WAQV,cAAc;;;cA8Gd;;cA+JA;;;;;;;cAGA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"listen-zNd0IIAT.d.ts","names":[],"sources":["../src/listen.ts"],"mappings":";;;;;;;;;UA0BiB;WACN;WACA;WACA,OAAO;WACP;WACA;;;;;;;;;cAaE,eAAY,mBAEtB,OAAO,OAAO,cAAc;;UA+Bd;WACN;WACA;WACA;WACA,OAAO;WACP;WACA;;;;;;;;cASE,iBAAc,SAChB,OAAO,iBAAe,SACtB,cAAc,iBAAe,MAChC,YAAU,SACP,wBACR,OAAO,OAAO,cAAc;;;;;;;UAoHd;WACN,OAAO;WACP,UAAU;WACV,UAAU;;UAGJ;WACN,UAAU,cAAc;WACxB,WAAW,QAAQ;;;;;;;WAOnB,SAAS;;;;;;cAOP,SAAM,MAAU,SAAO,SAAW"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"requestContext-D9nsbGSJ.d.ts","names":[],"sources":["../src/requestContext.ts"],"mappings":";;UA+BiB,eAAe;WACrB;;WAEA,SAAS,SAAS,SAAS,OAAO,MAAM;;;;;;WAMxC,KAAK,SAAS,YAAY,OAAO,OAAO;;;;;;;cAQtC,iBAAkB,GAAC,iBAAiB,eAAe"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"resumable-BWItJsxF.d.ts","names":[],"sources":["../src/resumable.ts"],"m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AAO,gBAAgB,YAAY,KAAG,SAC5B,OAAO,OAAO,IAAI,iBAAiB,UAAU,cAAc,SAAG,OAEjE,OAAK,GAAK,YAAU"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"shared-v1u-OEQI.d.ts","names":[],"sources":["../src/diagnostics.ts","../src/context.ts","../src/shared.ts"],"mappings":";;;;;;;UAaiB,sBAAsB;WAC5B;;;;;WAKA,qCAAqC;;;UAI/B,4BAA4B;WAClC;WACA;;;UAIM,uBAAuB;WAC7B;WACA;;;UAIM,mBAAmB;WACzB;WACA;WACA,OAAO,MAAM;;;UAIP,uBAAuB;WAC7B;WACA;WACA;WACA;;;KAIC,gBACR,gBACA,sBACA,iBACA,aACA;cAES,gBAAa,QAAY,yBAAuB,mBAAmB;cAQnE,WAAW;;cAMX,aAAU,QAAY,OAAO,gBAAc,mBAAmB;cAS9D,sBAAmB,mBAAqB;cAQxC,iBAAc,mBAAqB;cAQnC,aAAU,aAAe,OAAS,MAAM,mBAAiB;cASzD,iBAAc,cAAgB,iBAAiB,kBAAkB;;cAWjE,cAAW,QACb,kCACR,GAAG,GAAG,GAAC,QAAU,OAAO,OAAO,GAAG,GAAG,OAAK,OAAO,OAAO,GAAG,GAAG;KCpGrD,SAAS,cAAc;;UAGlB;WACN;WACA;;;;;;;;;UAUM;;WAEN;WACA;WACA;WACA;WACA,OAAO;;WAEP;WACA;;KAGC;WAEG;WACA,SAAS,YAAY;WACrB,YAAY;WACZ,UAAU,MAAM;;WAEhB,YAAY;;EAErB,OAAO;;EAEP;;EAEA;;WAES,UAAU;aACR;aACA;aACA;;;WAGF,SAAS,MAAM;;WAGf;WACA,SAAS,oBAAoB;WAC7B,UAAU,MAAM;WAChB,YAAY;EACrB,OAAO;EACP;;WAGS;WACA,WAAW;;WAEX,UAAU;WACV,SAAS,YAAY;;;cAMvB,eAAc;cAEd,SAAU,GAAC,MAAQ,eAAa,WAAa,MAAI;;cAWjD,cAAe;WAA0B,OAAO,YAAY;GAAoB,QACnF,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