foldkit-ssr 0.9.0 → 0.10.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 (39) hide show
  1. package/README.md +315 -36
  2. package/dist/{client-F16QT0sc.d.ts → client-XnpTQZHw.d.ts} +15 -5
  3. package/dist/client-XnpTQZHw.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 +1 -1
  11. package/dist/index.d.ts +83 -23
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +174 -54
  14. package/dist/index.js.map +1 -1
  15. package/dist/keep.d.ts +34 -0
  16. package/dist/keep.d.ts.map +1 -0
  17. package/dist/keep.js +80 -0
  18. package/dist/keep.js.map +1 -0
  19. package/dist/{listen-zNd0IIAT.d.ts → listen-DaUPRKVR.d.ts} +4 -2
  20. package/dist/listen-DaUPRKVR.d.ts.map +1 -0
  21. package/dist/listen.d.ts +2 -2
  22. package/dist/listen.js +31 -23
  23. package/dist/listen.js.map +1 -1
  24. package/dist/{resumable-BWItJsxF.d.ts → resumable-BPN_qQHU.d.ts} +33 -12
  25. package/dist/resumable-BPN_qQHU.d.ts.map +1 -0
  26. package/dist/resumable.d.ts +2 -2
  27. package/dist/resumable.js +51 -8
  28. package/dist/resumable.js.map +1 -1
  29. package/dist/{shared-v1u-OEQI.d.ts → shared-DbupL3vO.d.ts} +20 -5
  30. package/dist/shared-DbupL3vO.d.ts.map +1 -0
  31. package/dist/shared.d.ts +2 -2
  32. package/dist/shared.js +25 -2
  33. package/dist/shared.js.map +1 -1
  34. package/dist/vite.d.ts +1 -1
  35. package/package.json +9 -9
  36. package/dist/client-F16QT0sc.d.ts.map +0 -1
  37. package/dist/listen-zNd0IIAT.d.ts.map +0 -1
  38. package/dist/resumable-BWItJsxF.d.ts.map +0 -1
  39. package/dist/shared-v1u-OEQI.d.ts.map +0 -1
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { withContext } from "./context.js";
2
2
  import { handlerUnnamed, pageFailed, reportingTo } from "./diagnostics.js";
3
- import { BINDING_ATTRIBUTE, FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, SLOT_ATTRIBUTE } from "./resumable.js";
4
- import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, allowedTags, attributeOf, codecOf, metaMarkup, modelFrom, pathKey, plan, projectionsOf, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf } from "./shared.js";
3
+ import { BINDING_ATTRIBUTE, FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, KEEP_ATTRIBUTE, SLOT_ATTRIBUTE } from "./resumable.js";
4
+ import { FOLDKIT_APP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, ResumeRefused, STATIC_ATTRIBUTE, STYLES_MARKER, allowedTags, attributeOf, codecOf, metaMarkup, modelFrom, pathKey, plan, projectionsOf, resume, routeOf, serializeJsonScript, serving, startingFrom, staticRegion, tagOf } from "./shared.js";
5
5
  import { Diagnostics, Resume, SSR as SSR$1, UNTIL_LIMIT_MS } from "./client.js";
6
6
  import { requestContext } from "./requestContext.js";
7
7
  import { Cause, Context, Effect, Exit, Layer, Option, Result, Schema } from "effect";
@@ -63,9 +63,8 @@ const envelopeOf = (resume, payload, options) => serializeJsonScript({
63
63
  * Foldkit's own app and build stamps. `injectIntoTemplate` accepts the
64
64
  * envelope there, as part of the root, and refuses it beside the root, so a
65
65
  * page the host injects carries the handover without the entry owning the
66
- * template. Hydration adopts the server's nodes around it and drops the
67
- * attribute on its first patch, so the browser reads the envelope before it
68
- * boots.
66
+ * template. The browser reads the envelope, then takes the attribute off
67
+ * as the page boots, before Foldkit adopts the server's nodes around it.
69
68
  */
70
69
  const withEnvelopeAttribute = (html, json) => {
71
70
  const stamp = "data-foldkit-app=\"";
@@ -97,10 +96,11 @@ const isInRootTag = (html, at) => {
97
96
  return true;
98
97
  };
99
98
  /**
100
- * The rendered markup with `extra` as the root's last child, so the first
101
- * paint is styled before any script runs where no template head can take it.
102
- * A void root holds no children: styles for one are refused, naming the tag,
103
- * rather than served where no browser could keep them.
99
+ * The rendered markup with `extra` as the root's last children, after the
100
+ * styles marker, so the first paint is styled before any script runs where no
101
+ * template head can take it; `SSR.hydrate` moves them into the head. A void
102
+ * root holds no children: styles for one are refused, naming the tag, rather
103
+ * than served where no browser could keep them.
104
104
  */
105
105
  const withInRoot = (html, extra) => {
106
106
  const tag = /^<([A-Za-z][A-Za-z0-9-]*)/.exec(html)?.[1];
@@ -109,7 +109,7 @@ const withInRoot = (html, extra) => {
109
109
  reason: "VoidRootWithStyles",
110
110
  message: `styles need a root element that can hold them, but the view returned <${tag ?? "?"}>: put the styles in the template's head with SSR.generate, or return an element root`
111
111
  }));
112
- return Result.succeed(`${html.slice(0, at)}${extra}${html.slice(at)}`);
112
+ return Result.succeed(`${html.slice(0, at)}<!--${STYLES_MARKER}-->${extra}${html.slice(at)}`);
113
113
  };
114
114
  /**
115
115
  * The Model the browser will start from when the server's Model is `model`:
@@ -234,7 +234,8 @@ var ResumeUnsafe = class extends Schema.TaggedError()("ResumeUnsafe", {
234
234
  "EagerStartRequired",
235
235
  "UndeclaredSurfaces",
236
236
  "BindingInStaticRegion",
237
- "VoidRootWithStyles"
237
+ "VoidRootWithStyles",
238
+ "UnkeepableField"
238
239
  ]),
239
240
  message: Schema.String
240
241
  }) {};
@@ -243,6 +244,24 @@ const unlistedBindings = (plan, model, bindings) => {
243
244
  const allowed = allowedTags(plan, model);
244
245
  return bindings.filter((binding) => !allowed.has(tagOf(binding.message))).map((binding) => `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`);
245
246
  };
247
+ /**
248
+ * A line for each `KeepTyped` the render drew on an element the resumable
249
+ * builder did not build, whose marker still holds its server-render value:
250
+ * nothing marks which binding replays such a field, so every browser would
251
+ * refuse the page. Foldkit escapes `<` in text and attribute values, so the
252
+ * last `<` before the marker opens its element.
253
+ */
254
+ const unplacedKeeps = (html) => {
255
+ const marker = `${KEEP_ATTRIBUTE}="?"`;
256
+ const found = [];
257
+ for (let at = html.indexOf(marker); at !== -1; at = html.indexOf(marker, at + 1)) {
258
+ const open = html.lastIndexOf("<", at);
259
+ const tag = /^<([A-Za-z][A-Za-z0-9._-]*)/.exec(html.slice(open))?.[1] ?? "an element";
260
+ const id = /\sid="([^"]*)"/.exec(html.slice(open, html.indexOf(">", at)))?.[1];
261
+ found.push(`KeepTyped on ${id === void 0 ? tag : `${tag}#${id}`}, which Resume.builder did not build, so nothing marks the binding its typing replays as: build the element with the resumable builder (rh.input), not h`);
262
+ }
263
+ return found;
264
+ };
246
265
  /** Loads every lazy bundle's bodies, so the view renders whole. */
247
266
  const loadLazy = (config) => Effect.promise(() => Promise.all((config.lazy ?? []).map((bundle) => bundle.load())));
248
267
  /** Foldkit's own Flags script, which a resumed page never carries. */
@@ -313,7 +332,7 @@ const eagerEntries = (config, plan, model) => {
313
332
  * Foldkit would rebuild that part of the page silently, so this is the one
314
333
  * place it shows.
315
334
  */
316
- const render = (config, plan, options) => renderMatching(config, plan, options, "full");
335
+ const render = (config, plan, options) => Effect.map(renderMatching(config, plan, options, "full"), (served) => served.page);
317
336
  const renderMatching = (config, plan, options, match) => Effect.gen(function* () {
318
337
  yield* loadLazy(config);
319
338
  let served;
@@ -323,6 +342,7 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
323
342
  const browserBindings = [];
324
343
  const inStatic = [];
325
344
  const unnamed = [];
345
+ const unkeepable = [];
326
346
  const fallback = fallbackEncoder(plan);
327
347
  const capturing = withContext({
328
348
  ...config,
@@ -337,9 +357,11 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
337
357
  depth: 0,
338
358
  region: void 0,
339
359
  inStatic,
340
- unnamed
360
+ unnamed,
361
+ unkeepable
341
362
  });
342
363
  const full = yield* renderToString(capturing, options);
364
+ unkeepable.push(...unplacedKeeps(full.html));
343
365
  if (duplicates.size > 0) return yield* new ResumeUnsafe({
344
366
  reason: "DuplicateStaticRegion",
345
367
  message: `two static regions share the id ${[...duplicates].map((id) => `"${id}"`).join(", ")}: the browser could adopt only one`
@@ -348,6 +370,10 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
348
370
  reason: "BindingInStaticRegion",
349
371
  message: `a static region is the server's alone, and these would never run: ${inStatic.map(({ region, element, event }) => `a ${event} handler on ${element} in "${region}"`).join(", ")}. What a Message changes belongs in a Surface`
350
372
  });
373
+ if (unkeepable.length > 0) return yield* new ResumeUnsafe({
374
+ reason: "UnkeepableField",
375
+ message: `the page cannot keep what is typed into these fields before it boots:\n- ${unkeepable.join("\n- ")}`
376
+ });
351
377
  const started = served;
352
378
  const commands = started.commands ?? [];
353
379
  if (commands.length > 0 && plan.boot === void 0) return yield* new ResumeUnsafe({
@@ -409,13 +435,16 @@ const renderMatching = (config, plan, options, match) => Effect.gen(function* ()
409
435
  const styled = options.styles === void 0 ? Result.succeed(rendered.html) : withInRoot(rendered.html, options.styles(rendered));
410
436
  if (Result.isFailure(styled)) return yield* styled.failure;
411
437
  return {
412
- rendered: {
413
- ...rendered,
414
- html: withEnvelopeAttribute(styled.success, envelope)
438
+ page: {
439
+ rendered: {
440
+ ...rendered,
441
+ html: withEnvelopeAttribute(styled.success, envelope)
442
+ },
443
+ meta,
444
+ envelope,
445
+ unnamed
415
446
  },
416
- meta,
417
- envelope,
418
- unnamed
447
+ model: started.model
419
448
  };
420
449
  });
421
450
  /**
@@ -551,7 +580,7 @@ const generate = (config, plan, options) => Effect.gen(function* () {
551
580
  buildId: options.buildId,
552
581
  url: new URL(path, options.origin).href,
553
582
  ...options.flags === void 0 ? {} : { flags: options.flags(path) }
554
- }, "path").pipe(Effect.tap((result) => reportUnnamed(config, plan, result.unnamed)), Effect.map((result) => ({
583
+ }, "path").pipe(Effect.map((served) => served.page), Effect.tap((result) => reportUnnamed(config, plan, result.unnamed)), Effect.map((result) => ({
555
584
  path,
556
585
  file: fileOf(path),
557
586
  html: page(options.template, result, { head: options.head })
@@ -564,15 +593,18 @@ const generate = (config, plan, options) => Effect.gen(function* () {
564
593
  * served by Node and Workers alike.
565
594
  *
566
595
  * `GET` and `HEAD` render the page against the plan, with the request's URL
567
- * and, when the application has Flags, `flags(request)`. `POST` goes to
596
+ * and, when the application has Flags, `flags(request)`; `prepare(model,
597
+ * request)` turns the Model `init` gave into the one rendered, a read made
598
+ * before the render (`Data.satisfy`). `POST` goes to
568
599
  * `SSR.handle` when the plan has a server fallback, and is answered `400` when
569
600
  * the post is unusable. `OPTIONS` is answered `204`, and any other method
570
601
  * `405`, each with the methods the entry answers in `allow` (`handleRequest`
571
602
  * passes every method through). A render that fails, or a plan the render
572
603
  * refuses, is answered `500` with the reason reported (`diagnostics`), never with a page the
573
- * browser cannot resume. `headers(request)` rides on the `Rendered` result, so
574
- * Foldkit's `toResponse` sets it over its own on the page: a cache policy, or
575
- * a CORS answer to a preflight.
604
+ * browser cannot resume. `headers(request, model)` is set over Foldkit's own
605
+ * on every answer: a cache policy, a CORS answer to a preflight, or a cookie
606
+ * written from the Model a post reached. `status(model, request)` gives a page
607
+ * its status from that Model, `404` for a route not found.
576
608
  *
577
609
  * The page is answered as `Rendered`: the rendered application carries the
578
610
  * envelope in its root, so the host injects it into its own template with
@@ -587,29 +619,45 @@ const generate = (config, plan, options) => Effect.gen(function* () {
587
619
  */
588
620
  const entry = (config, plan, options) => {
589
621
  if (plan.meta !== void 0) throw new Error(`foldkit-ssr: plan "${plan.id}" says what the page says of itself (meta), which is written into the template's head, and the template is the host's: serve it with SSR.generate, not SSR.entry`);
590
- for (const origin of options.origins ?? []) if (!URL.canParse(origin) || new URL(origin).origin !== origin) throw new Error(`foldkit-ssr: ${JSON.stringify(origin)} in origins is not an origin`);
622
+ const listed = options.origins === "same-origin" ? [] : options.origins ?? [];
623
+ for (const origin of listed) if (!URL.canParse(origin) || new URL(origin).origin !== origin) throw new Error(`foldkit-ssr: ${JSON.stringify(origin)} in origins is not an origin`);
624
+ if (options.answerPost !== void 0 && plan.fallback !== "server") throw new Error(`foldkit-ssr: plan "${plan.id}" has no server fallback, so no form is posted to answer (answerPost)`);
591
625
  if (plan.fallback === "server" && options.origins === void 0) throw new Error(`foldkit-ssr: plan "${plan.id}" handles posted forms, which run as whoever posted; name the origins a form may be posted from (origins)`);
592
- const origins = new Set(options.origins ?? []);
626
+ for (const path of options.prerendered ?? []) if (!path.startsWith("/") || /[?#]/.test(path)) throw new Error(`foldkit-ssr: "${path}" in prerendered is not a path a file can be served at: start it with / and leave out any query or fragment`);
627
+ const prerendered = new Set((options.prerendered ?? []).map(pathKey));
628
+ const matchOf = (url) => {
629
+ const route = routeOf(url);
630
+ return !route.includes("?") && prerendered.has(pathKey(route)) ? "path" : "full";
631
+ };
632
+ const origins = new Set(listed);
633
+ const originsOf = (request) => options.origins === "same-origin" ? /* @__PURE__ */ new Set([new URL(request.url).origin]) : origins;
593
634
  const allow = plan.fallback === "server" ? "GET, HEAD, POST, OPTIONS" : "GET, HEAD, OPTIONS";
594
635
  const merge = (response, extra) => {
595
636
  for (const name of new Set(extra.keys())) response.headers.delete(name);
596
637
  extra.forEach((value, name) => response.headers.append(name, value));
597
638
  return response;
598
639
  };
640
+ const headersOf = (request, model) => {
641
+ if (options.headers === void 0) return void 0;
642
+ const headers = new Headers(options.headers(request, model));
643
+ for (const name of headers.keys()) if (ENTRY_HEADERS.has(name)) throw new Error(`headers set ${name}, which the entry writes and an application may not`);
644
+ return headers;
645
+ };
599
646
  const answer = async (request) => {
600
647
  const method = request.method.toUpperCase();
601
648
  const posting = method === "POST" && plan.fallback === "server";
602
649
  const { diagnostics } = options;
603
650
  const reporting = reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request));
604
- const headersOf = options.headers;
605
- let extra;
606
- if (headersOf !== void 0) try {
607
- extra = new Headers(headersOf(request));
608
- } catch (error) {
609
- await Effect.runPromise(reporting(Diagnostics$1.report(pageFailed(request.url, Cause.die(error)))));
610
- return Responded(plainText(500, "The page could not be rendered."));
611
- }
612
- const responded = (response) => Responded(extra === void 0 ? response : merge(response, extra));
651
+ const responded = async (response, { reported = false } = {}) => {
652
+ let extra;
653
+ try {
654
+ extra = headersOf(request, Option.none());
655
+ } catch (error) {
656
+ if (!reported) await Effect.runPromise(reporting(Diagnostics$1.report(pageFailed(request.url, Cause.die(error)))));
657
+ return Responded(plainText(500, "The page could not be rendered."));
658
+ }
659
+ return Responded(extra === void 0 ? response : merge(response, extra));
660
+ };
613
661
  if (method === "OPTIONS") return responded(new Response(null, {
614
662
  status: 204,
615
663
  headers: { allow }
@@ -618,37 +666,89 @@ const entry = (config, plan, options) => {
618
666
  status: 405,
619
667
  headers: { allow }
620
668
  }));
621
- if (posting && !postedFrom(request, origins)) return responded(plainText(403, "The form was not posted from this site."));
669
+ if (posting && !postedFrom(request, originsOf(request))) return responded(plainText(403, "The form was not posted from this site."));
622
670
  const flagsOf = options.flags;
671
+ const statusOf = options.status;
672
+ const { prepare } = options;
623
673
  const styled = options.styles === void 0 ? {} : { styles: options.styles };
624
674
  const exit = await Effect.runPromiseExit(Effect.gen(function* () {
625
675
  const flags = flagsOf === void 0 ? void 0 : yield* Effect.tryPromise(async () => flagsOf(request));
626
676
  const flagged = flagsOf === void 0 ? {} : { flags };
627
- if (posting) return yield* handle(request, config, plan, {
677
+ const prepared = prepare === void 0 ? {} : { prepare };
678
+ const post = () => ({
628
679
  buildId: options.buildId,
629
680
  ...flagged,
630
681
  ...styled,
682
+ ...prepared,
631
683
  ...options.resources === void 0 ? {} : { resources: options.resources(request) }
632
684
  });
633
- return yield* render(config, plan, {
685
+ if (posting && options.answerPost === "redirect") {
686
+ const model = yield* postedModel(request, config, plan, post());
687
+ const extra = yield* Effect.sync(() => headersOf(request, Option.some(model)));
688
+ const redirect = new Response(null, {
689
+ status: 303,
690
+ headers: { location: sameAddress(request.url) }
691
+ });
692
+ return Responded(extra === void 0 ? redirect : merge(redirect, extra));
693
+ }
694
+ const served = posting ? yield* handleServed(request, config, plan, post()) : yield* renderMatching(prepare === void 0 ? config : yield* preparedStart(request, config, {
695
+ url: request.url,
696
+ ...flagged
697
+ }, prepare), plan, {
634
698
  buildId: options.buildId,
635
699
  url: request.url,
636
700
  ...flagged,
637
701
  ...styled
702
+ }, matchOf(request.url));
703
+ const extra = yield* Effect.sync(() => headersOf(request, Option.some(served.model)));
704
+ const status = Option.map(Option.fromUndefinedOr(statusOf), (of) => of(served.model, request));
705
+ const unanswerable = Option.filter(status, (given) => !Number.isInteger(given) || given < 200 || given > 599);
706
+ if (Option.isSome(unanswerable)) return yield* Effect.die(/* @__PURE__ */ new Error(`status gave ${unanswerable.value} for the page, which is no status between 200 and 599`));
707
+ yield* reportUnnamed(config, plan, served.page.unnamed);
708
+ return Rendered(served.page.rendered, {
709
+ ...extra === void 0 ? {} : { headers: extra },
710
+ ...Option.match(status, {
711
+ onNone: () => ({}),
712
+ onSome: (status) => ({ status })
713
+ })
638
714
  });
639
715
  }).pipe(reporting));
640
716
  if (Exit.isFailure(exit)) {
641
717
  const refused = Cause.findErrorOption(exit.cause).pipe(Option.filter((error) => error instanceof FallbackRefused));
642
718
  if (Option.isSome(refused)) return responded(plainText(400, `The form could not be handled: ${refused.value.message}`));
643
719
  await Effect.runPromise(reporting(Diagnostics$1.report(pageFailed(request.url, exit.cause))));
644
- return responded(plainText(500, "The page could not be rendered."));
720
+ return responded(plainText(500, "The page could not be rendered."), { reported: true });
645
721
  }
646
- await Effect.runPromise(reporting(reportUnnamed(config, plan, exit.value.unnamed)));
647
- return extra === void 0 ? Rendered(exit.value.rendered) : Rendered(exit.value.rendered, { headers: extra });
722
+ return exit.value;
648
723
  };
649
724
  return { renderPage: answer };
650
725
  };
651
726
  /**
727
+ * Where a post's answer sends the browser: the address it posted to, its path
728
+ * and query alone. Relative, so the browser resolves it against that address
729
+ * and it names no other origin, whatever `Host` the request claimed; leading
730
+ * slashes collapse to one, since `//elsewhere.test/` would name another host.
731
+ */
732
+ const sameAddress = (url) => {
733
+ const { pathname, search } = new URL(url);
734
+ return `${pathname.replace(/^\/+/, "/")}${search}`;
735
+ };
736
+ /**
737
+ * What `headers` may not set: what frames the response, which the host's
738
+ * server writes, and `location`, which only the entry writes.
739
+ */
740
+ const ENTRY_HEADERS = /* @__PURE__ */ new Set([
741
+ "connection",
742
+ "content-length",
743
+ "keep-alive",
744
+ "location",
745
+ "proxy-connection",
746
+ "te",
747
+ "trailer",
748
+ "transfer-encoding",
749
+ "upgrade"
750
+ ]);
751
+ /**
652
752
  * Whether a post came from one of `origins`, by what the browser sends and no
653
753
  * page or form can set: its `Origin`, or, where that is missing or opaque
654
754
  * (`Origin: null`, which a page served with `Referrer-Policy: no-referrer`
@@ -729,7 +829,11 @@ const startOf = (config, options) => Effect.gen(function* () {
729
829
  let started;
730
830
  yield* renderToString({
731
831
  ...config,
732
- init: (...args) => started = config.init(...args)
832
+ init: (...args) => started = config.init(...args),
833
+ view: (_model, h) => ({
834
+ title: "",
835
+ body: h.div([], [])
836
+ })
733
837
  }, {
734
838
  buildId: "x",
735
839
  ...options
@@ -737,15 +841,34 @@ const startOf = (config, options) => Effect.gen(function* () {
737
841
  return started;
738
842
  });
739
843
  /**
844
+ * The config a request starts from: `init`'s answer, its Model prepared. A
845
+ * failed `prepare` is a defect, answered 500 and reported as a failed render.
846
+ */
847
+ const preparedStart = (request, config, options, prepare) => Effect.gen(function* () {
848
+ const started = yield* startOf(config, options);
849
+ const model = yield* Effect.orDie(prepare(started.model, request));
850
+ return startingFrom(config, {
851
+ ...started,
852
+ model
853
+ });
854
+ });
855
+ /**
740
856
  * Answers a form posted by a page rendered with `fallback: 'server'`: the
741
857
  * posted Message is decoded through the plan's Message Schema, with posted
742
858
  * fields of the same names as its own overriding them, and must be one the
743
859
  * Surfaces active for the request's Model may send. The server then rebuilds
744
- * the Model the browser had, `init` and then the plan's `boot` with every
860
+ * the Model the browser had, `init`, `prepare` and then the plan's `boot` with every
745
861
  * Command it leads to, runs `update` with the Message and every Command that
746
862
  * follows, and renders the result as a fresh page.
747
863
  */
748
- const handle = (request, config, plan, options) => Effect.scoped(Effect.gen(function* () {
864
+ const handle = (request, config, plan, options) => Effect.map(handleServed(request, config, plan, options), (served) => served.page);
865
+ const handleServed = (request, config, plan, options) => Effect.flatMap(postedModel(request, config, plan, options), (model) => renderMatching(startingFrom(config, { model }), plan, {
866
+ buildId: options.buildId,
867
+ url: request.url,
868
+ ...options.styles === void 0 ? {} : { styles: options.styles }
869
+ }, "full"));
870
+ /** The Model a posted form reaches: its Message decoded and checked, then `update` and its Commands. */
871
+ const postedModel = (request, config, plan, options) => Effect.scoped(Effect.gen(function* () {
749
872
  if (plan.fallback !== "server" || plan.Message === void 0) return yield* refuseFallback("NoFallback", `plan "${plan.id}" has no server fallback`);
750
873
  const form = yield* Effect.tryPromise({
751
874
  try: () => request.formData(),
@@ -787,16 +910,13 @@ const handle = (request, config, plan, options) => Effect.scoped(Effect.gen(func
787
910
  url: request.url,
788
911
  ...options
789
912
  });
790
- if (!allowedTags(plan, started.model).has(tagOf(message))) return yield* refuseFallback("Unlisted", `the posted ${tagOf(message)} is not one an active Surface lists in its messages`);
791
- const boot = plan.boot?.(started.model) ?? [];
913
+ const { prepare } = options;
914
+ const start = prepare === void 0 ? started.model : yield* Effect.orDie(prepare(started.model, request));
915
+ if (!allowedTags(plan, start).has(tagOf(message))) return yield* refuseFallback("Unlisted", `the posted ${tagOf(message)} is not one an active Surface lists in its messages`);
916
+ const boot = plan.boot?.(start) ?? [];
792
917
  const post = options.resources === void 0 ? Context.empty() : yield* Layer.build(options.resources);
793
- const booted = yield* fold(config, post, started.model, [], boot);
794
- const model = yield* fold(config, post, booted, [message], []);
795
- return yield* render(startingFrom(config, { model }), plan, {
796
- buildId: options.buildId,
797
- url: request.url,
798
- ...options.styles === void 0 ? {} : { styles: options.styles }
799
- });
918
+ const booted = yield* fold(config, post, start, [], boot);
919
+ return yield* fold(config, post, booted, [message], []);
800
920
  }));
801
921
  const SSR = {
802
922
  plan,
@@ -816,6 +936,6 @@ const SSR = {
816
936
  robots,
817
937
  requestContext
818
938
  };
819
- export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, FallbackRefused, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
939
+ export { BINDING_ATTRIBUTE, Diagnostics, FALLBACK_FIELD, FOLDKIT_APP_ATTRIBUTE, FallbackRefused, KEEP_ATTRIBUTE, META_ATTRIBUTE, RESUME_ATTRIBUTE, Resume, ResumeRefused, ResumeUnsafe, SLOT_ATTRIBUTE, SSR, STATIC_ATTRIBUTE, UNTIL_LIMIT_MS, metaMarkup };
820
940
 
821
941
  //# sourceMappingURL=index.js.map