foldkit-ssr 0.10.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import { withContext } from "./context.js";
2
- import { handlerUnnamed, pageFailed, reportingTo } from "./diagnostics.js";
2
+ import { cachedPageDiffers, handlerUnnamed, pageFailed, reportingTo } from "./diagnostics.js";
3
3
  import { BINDING_ATTRIBUTE, FALLBACK_DEPTH_FIELD, FALLBACK_FIELD, KEEP_ATTRIBUTE, SLOT_ATTRIBUTE } from "./resumable.js";
4
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
+ import { decodeKept, fits, headerOf, keptApplications, keptDocuments, pageKey, samePage, tracked } from "./pageCache.js";
7
8
  import { Cause, Context, Effect, Exit, Layer, Option, Result, Schema } from "effect";
8
- import { Diagnostics as Diagnostics$1, Metadata } from "foldkit-surface";
9
+ import { CacheStore, Diagnostics as Diagnostics$1, Metadata, PageReads, cachePolicy, maxAgeSeconds, shorterPolicy } from "foldkit-surface";
9
10
  import { FOLDKIT_FLAGS_ATTRIBUTE, Rendered, Responded, injectIntoTemplate, renderToString } from "foldkit/experimental/server";
10
11
  // src/index.ts
11
12
  /**
@@ -245,16 +246,37 @@ const unlistedBindings = (plan, model, bindings) => {
245
246
  return bindings.filter((binding) => !allowed.has(tagOf(binding.message))).map((binding) => `the ${binding.event} binding on ${binding.element} dispatches ${tagOf(binding.message)}, which no active Surface lists in its messages`);
246
247
  };
247
248
  /**
249
+ * Whether `at` starts an attribute inside the start tag opened before it.
250
+ * A marker in a text node follows that tag's `>`, and one inside another
251
+ * attribute's value has its quotes escaped (`"`), so only a marker
252
+ * between a tag's `<` and a `>` outside a quoted value is an attribute.
253
+ */
254
+ const opensAttribute = (html, at) => {
255
+ if (at === 0 || !/[ \t\r\n]/.test(html[at - 1])) return false;
256
+ const open = html.lastIndexOf("<", at);
257
+ if (open === -1 || html.startsWith("<!--", open)) return false;
258
+ let quote;
259
+ for (let index = open + 1; index < at; index++) {
260
+ const char = html[index];
261
+ if (quote !== void 0) {
262
+ if (char === quote) quote = void 0;
263
+ } else if (char === "\"" || char === "'") quote = char;
264
+ else if (char === ">") return false;
265
+ }
266
+ return quote === void 0;
267
+ };
268
+ /**
248
269
  * A line for each `KeepTyped` the render drew on an element the resumable
249
270
  * builder did not build, whose marker still holds its server-render value:
250
271
  * 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.
272
+ * refuse the page. Only a marker that is an attribute counts: ordinary text
273
+ * can spell the same characters.
253
274
  */
254
275
  const unplacedKeeps = (html) => {
255
276
  const marker = `${KEEP_ATTRIBUTE}="?"`;
256
277
  const found = [];
257
278
  for (let at = html.indexOf(marker); at !== -1; at = html.indexOf(marker, at + 1)) {
279
+ if (!opensAttribute(html, at)) continue;
258
280
  const open = html.lastIndexOf("<", at);
259
281
  const tag = /^<([A-Za-z][A-Za-z0-9._-]*)/.exec(html.slice(open))?.[1] ?? "an element";
260
282
  const id = /\sid="([^"]*)"/.exec(html.slice(open, html.indexOf(">", at)))?.[1];
@@ -618,6 +640,10 @@ const generate = (config, plan, options) => Effect.gen(function* () {
618
640
  * `meta` is refused when the entry is made, and served with `SSR.generate`.
619
641
  */
620
642
  const entry = (config, plan, options) => {
643
+ const cache = Option.map(Option.fromUndefinedOr(options.cache), (given) => ({
644
+ ...given,
645
+ policy: cachePolicy(given)
646
+ }));
621
647
  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`);
622
648
  const listed = options.origins === "same-origin" ? [] : options.origins ?? [];
623
649
  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`);
@@ -643,11 +669,17 @@ const entry = (config, plan, options) => {
643
669
  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
670
  return headers;
645
671
  };
646
- const answer = async (request) => {
672
+ /**
673
+ * One request answered. `watched`, for a render that may be kept, records
674
+ * what the render read of the request's headers and through `pageReader`.
675
+ */
676
+ const answer = async (given, watched) => {
677
+ const request = watched === void 0 ? given : tracked(given, watched.read);
647
678
  const method = request.method.toUpperCase();
648
679
  const posting = method === "POST" && plan.fallback === "server";
649
680
  const { diagnostics } = options;
650
- const reporting = reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request));
681
+ const reported = reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, given));
682
+ const reporting = (effect) => reported(watched === void 0 ? effect : Effect.provideService(effect, PageReads, Option.some((read) => watched.reads.push(read))));
651
683
  const responded = async (response, { reported = false } = {}) => {
652
684
  let extra;
653
685
  try {
@@ -702,8 +734,8 @@ const entry = (config, plan, options) => {
702
734
  }, matchOf(request.url));
703
735
  const extra = yield* Effect.sync(() => headersOf(request, Option.some(served.model)));
704
736
  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`));
737
+ const unanswerable = Option.filter(status, (given) => !Number.isInteger(given) || given < 200 || given > 599 || given === 204 || given === 205 || given === 304);
738
+ if (Option.isSome(unanswerable)) return yield* Effect.die(/* @__PURE__ */ new Error(`status gave ${unanswerable.value} for the page, which is no status for a page with a body`));
707
739
  yield* reportUnnamed(config, plan, served.page.unnamed);
708
740
  return Rendered(served.page.rendered, {
709
741
  ...extra === void 0 ? {} : { headers: extra },
@@ -721,7 +753,111 @@ const entry = (config, plan, options) => {
721
753
  }
722
754
  return exit.value;
723
755
  };
724
- return { renderPage: answer };
756
+ if (Option.isNone(cache)) return { renderPage: (request) => answer(request) };
757
+ const { store, check, policy } = cache.value;
758
+ const reportTo = (request) => {
759
+ const { diagnostics } = options;
760
+ return reportingTo(diagnostics === void 0 ? void 0 : (diagnostic) => diagnostics(diagnostic, request));
761
+ };
762
+ /** A page no store may keep for another request: its own `cache-control` stands. */
763
+ const unkept = (result) => {
764
+ if (result._tag !== "Rendered" || Option.isSome(headerOf(result.headers, "cache-control"))) return result;
765
+ const headers = new Headers(result.headers);
766
+ headers.set("cache-control", "private, no-store");
767
+ return Rendered(result.application, {
768
+ ...result,
769
+ headers
770
+ });
771
+ };
772
+ /** The page as a store keeps it, when nothing it was drawn from was the request's own. */
773
+ const keepable = (request, result, watched) => {
774
+ if (result._tag !== "Rendered" || (result.status ?? 200) !== 200 || watched.read.all) return Option.none();
775
+ if (![...watched.read.names].every((name) => !request.headers.has(name))) return Option.none();
776
+ if (Option.isSome(headerOf(result.headers, "set-cookie")) || Option.isSome(headerOf(result.headers, "cache-control"))) return Option.none();
777
+ let shortest = policy;
778
+ const tags = /* @__PURE__ */ new Set();
779
+ for (const read of watched.reads) {
780
+ if (read._tag === "Private") return Option.none();
781
+ shortest = shorterPolicy(shortest, read.policy);
782
+ for (const tag of read.tags) tags.add(tag);
783
+ }
784
+ const vary = [...watched.read.names].sort();
785
+ const headers = new Headers(result.headers);
786
+ headers.set("cache-control", `public, max-age=${maxAgeSeconds(shortest)}`);
787
+ if (vary.length > 0) headers.set("vary", vary.join(", "));
788
+ return Option.some({
789
+ page: {
790
+ application: result.application,
791
+ ...result.status === void 0 ? {} : { status: result.status },
792
+ headers: [...headers],
793
+ vary
794
+ },
795
+ maxAge: shortest,
796
+ tags: [...tags]
797
+ });
798
+ };
799
+ const served = (page) => {
800
+ keptApplications.add(page.application);
801
+ return Rendered(page.application, {
802
+ ...page.status === void 0 ? {} : { status: page.status },
803
+ headers: page.headers.map(([name, value]) => [name, value])
804
+ });
805
+ };
806
+ const renderPage = async (request) => {
807
+ const method = request.method.toUpperCase();
808
+ if (method !== "GET" && method !== "HEAD") return unkept(await answer(request));
809
+ const key = await Effect.runPromise(pageKey(options.buildId, request.url));
810
+ const kept = Option.filter(Option.flatMap(await Effect.runPromise(store.match(key)), decodeKept), (page) => fits(request, page.vary));
811
+ if (Option.isSome(kept)) {
812
+ if (check !== true) return served(kept.value);
813
+ const again = await answer(request);
814
+ if (again._tag === "Rendered" && samePage(again, kept.value, Date.now())) return served(kept.value);
815
+ await Effect.runPromise(reportTo(request)(Diagnostics$1.report(cachedPageDiffers(request.url))));
816
+ return unkept(again);
817
+ }
818
+ const watched = {
819
+ read: {
820
+ names: /* @__PURE__ */ new Set(),
821
+ all: false
822
+ },
823
+ reads: []
824
+ };
825
+ const result = await answer(request, watched);
826
+ return Option.match(keepable(request, result, watched), {
827
+ onNone: () => unkept(result),
828
+ onSome: ({ page, maxAge, tags }) => Effect.runPromise(Effect.as(store.put(key, JSON.stringify(page), {
829
+ maxAge: maxAge.maxAge,
830
+ tags
831
+ }), served(page)))
832
+ });
833
+ };
834
+ return { renderPage };
835
+ };
836
+ /**
837
+ * The page cache's checker, for a test: builds the entry with `make`, given a
838
+ * store in memory and `check`, and answers each request twice, so a page
839
+ * kept for one request is drawn again for every later one it serves.
840
+ * Rejects naming each page drawn otherwise for a request it served, and
841
+ * when no page was kept, which would check nothing. Give requests that
842
+ * differ in who asks (a visitor's, and one with someone's cookie); each is a
843
+ * function, since a request is read once.
844
+ */
845
+ const checkCache = async (make, requests) => {
846
+ const store = CacheStore.memory();
847
+ const differs = [];
848
+ const entry = make({
849
+ cache: {
850
+ store,
851
+ maxAge: "1 hour",
852
+ check: true
853
+ },
854
+ diagnostics: (diagnostic) => Effect.sync(() => {
855
+ if (diagnostic._tag === "CachedPageDiffers") differs.push(diagnostic.message);
856
+ })
857
+ });
858
+ for (const _round of [1, 2]) for (const request of requests) await entry.renderPage(request());
859
+ if (differs.length > 0) throw new Error(differs.join("\n"));
860
+ if (store.size() === 0) throw new Error("SSR.checkCache: no page was kept, so nothing was checked");
725
861
  };
726
862
  /**
727
863
  * Where a post's answer sends the browser: the address it posted to, its path
@@ -930,6 +1066,8 @@ const SSR = {
930
1066
  serving,
931
1067
  generate,
932
1068
  entry,
1069
+ checkCache,
1070
+ keptDocuments,
933
1071
  handle,
934
1072
  serializeJsonScript,
935
1073
  sitemap,