@ogygia/postrender 0.0.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/server.js ADDED
@@ -0,0 +1,334 @@
1
+ import { begin_flight, current_runtime, handled_runtime, installed_runtime, invalidate_tags, join_flight, self_evict, store_get, store_put } from "./registry.js";
2
+ import { observe_event } from "./observe.js";
3
+ import { esi_rewrite, stitch_html, stitch_modes } from "./stitch.js";
4
+ import { set_postrender_app } from "./app.js";
5
+ import { createHash } from "node:crypto";
6
+ import { building, dev } from "$app/env";
7
+ import { STORED_DOCUMENT_META, defineServer } from "@ogygia/core/plugin";
8
+ // src/server.ts
9
+ /**
10
+ * The postrender plugin's server half (imported by the build through
11
+ * `virtual:ogygia/server-plugins`, with the `postrender({ ttl, default })` options).
12
+ *
13
+ * `page`: the read path. A GET, no query string, not prerendering, on a route that opts in: a stored
14
+ * copy answers — Kit, loads and Svelte never run. A concurrent cold miss JOINS the in-flight render
15
+ * (the stampede law: N concurrent requests, ONE render). The first cold request opens the flight,
16
+ * marks the render `facts.storable` (its holes mint prerender-grade, its data-source receipts are
17
+ * kept) and observes it for personalization. The store and edges are the ones the request's
18
+ * `postrender.handle()` carried in (registry.ts) — which must therefore run before this stage.
19
+ *
20
+ * `response`: the write path. The verdict (nothing personal read, nothing streamed, a cacheable
21
+ * 200 or permanent redirect) stores the page and sends the stored copy; a refusal stamps
22
+ * `private, no-store` when the app set nothing. A successful mutation self-evicts its page.
23
+ *
24
+ * In dev nothing is stored or served — HMR truth beats byte reuse — but the verdict still runs and
25
+ * teaches: an eligible page gets `x-ogygia-postrender: would-store`, a refused one a console note.
26
+ */
27
+ /** The header a response carries to say how postrender answered it. */
28
+ const VIA_HEADER = "x-ogygia-postrender";
29
+ /** Kit's boot declares its deferred map ONLY on pages with pending (streamed) load promises —
30
+ * verified against @sveltejs/kit 2.70 (render.js: `blocks.push('const deferred = new Map();')`). */
31
+ const KIT_DEFERRED_BOOT_RE = /const deferred = new Map\(\);/;
32
+ /** The build marker key in the store (NUL-prefixed: no page path can collide with it). */
33
+ const BUILD_MARKER_KEY = "\0og:build";
34
+ /** How long the store keeps the build marker: ten years. It records a fact (the last build this
35
+ * store saw), not a page, so the pages' TTL backstop must not apply to it: a deploy a month after
36
+ * the last one still has to find it. */
37
+ const BUILD_MARKER_TTL_SEC = 31536e4;
38
+ /** The TTL backstop on read: a stored entry older than `ttl` seconds is a miss. A store with native
39
+ * expiry has dropped it already; one without (a custom store) still lets its pages expire. An
40
+ * entry with no usable creation time cannot be aged, and is a miss too. */
41
+ function within_ttl(entry, ttl, now = Date.now()) {
42
+ return Number.isFinite(entry.created) && now - entry.created < ttl * 1e3;
43
+ }
44
+ /** The two setup mistakes the read path can see, with the line that fixes each. */
45
+ const SEQUENCE_LINE = "export const handle = sequence(postrender.handle(), ogygia.handle());";
46
+ const MISSING_HANDLE = `postrender.handle() is not in src/hooks.server.ts, so pages are kept in this process’s memory store. Add it before ogygia's handle: \`${SEQUENCE_LINE}\``;
47
+ const MISORDERED_HANDLE = `postrender.handle() must run before ogygia.handle() (the stored page is served before anything renders), and this request reached ogygia first. Put it first: \`${SEQUENCE_LINE}\``;
48
+ /**
49
+ * The store + edges for this request: what its `postrender.handle()` carried in. Two mistakes are
50
+ * named here, never silent. No handle made at all → the memory default, with one warning. A handle
51
+ * made but not run before ogygia's (it sits after it in the `sequence()`, or outside it) → in dev an
52
+ * error, so it is fixed before it ships; in production one warning, and the server's runtime serves.
53
+ */
54
+ function runtime_of(ctx) {
55
+ const handled = handled_runtime(ctx.event);
56
+ if (handled) return handled;
57
+ const installed = installed_runtime();
58
+ if (!installed) {
59
+ ctx.app.warn(MISSING_HANDLE);
60
+ return current_runtime();
61
+ }
62
+ if (dev) throw new Error(`[${ctx.app.name}] ${MISORDERED_HANDLE}`);
63
+ ctx.app.warn(MISORDERED_HANDLE);
64
+ return installed;
65
+ }
66
+ /** Rebuild a Response from a stored page. `via` rides a debug header the harness asserts on.
67
+ * With the incoming `request`, a matching validator answers 304 — plain-HTTP conditional
68
+ * requests (RFC 9110), which is what makes a CDN or browser revalidation of a stored page cost
69
+ * zero body bytes. Validators live on the ENTRY, never in edge adapters: they are the render's
70
+ * identity, not a CDN dialect. */
71
+ function postrender_response(entry, via, request) {
72
+ if (entry.kind === "redirect") return new Response(null, {
73
+ status: entry.status,
74
+ headers: {
75
+ location: entry.location,
76
+ [VIA_HEADER]: via
77
+ }
78
+ });
79
+ if (request) {
80
+ const etag = entry.headers.etag;
81
+ const inm = request.headers.get("if-none-match");
82
+ const ims = request.headers.get("if-modified-since");
83
+ const last_modified = entry.headers["last-modified"];
84
+ if (!!etag && !!inm && inm.split(",").some((t) => t.trim() === etag) || !inm && !!ims && !!last_modified && Date.parse(ims) >= Date.parse(last_modified)) {
85
+ const headers = { [VIA_HEADER]: via };
86
+ for (const h of [
87
+ "etag",
88
+ "last-modified",
89
+ "cache-control"
90
+ ]) if (entry.headers[h]) headers[h] = entry.headers[h];
91
+ return new Response(null, {
92
+ status: 304,
93
+ headers
94
+ });
95
+ }
96
+ }
97
+ return new Response(served_html(entry, via), {
98
+ status: 200,
99
+ headers: {
100
+ ...entry.headers,
101
+ [VIA_HEADER]: via
102
+ }
103
+ });
104
+ }
105
+ /** The stored page as served: copies served FROM the store carry the doc marker so live regions
106
+ * self-freshen (`stored` = the render that JUST happened — fresh by definition, no marker). The
107
+ * marker goes in by slicing at the entry's `</head>` (recorded at capture; found once for an
108
+ * entry written before the field existed) — never a `replace` over a multi-MB page per hit. */
109
+ function served_html(entry, via) {
110
+ if (via === "stored") return entry.html;
111
+ const at = entry.head_end ?? entry.html.indexOf("</head>");
112
+ return at === -1 ? entry.html : entry.html.slice(0, at) + STORED_DOCUMENT_META + entry.html.slice(at);
113
+ }
114
+ /** Serve-time stitching: fill every `stitch` hole in the stored shell with a fresh SERVER render
115
+ * (`ctx.renderHole` verifies the hole's own signed MAC and renders with THIS request's event, so
116
+ * the visitor's cookies ride in and the splice is personalized in the first response). FAIL-OPEN
117
+ * per hole (a null render keeps the fallback + client fetch). hit/join serves still carry the doc
118
+ * marker first, so live regions inside keep self-freshening. */
119
+ async function serve_stitched(entry, via, ctx) {
120
+ const html = await stitch_html(served_html(entry, via), (endpoint) => ctx.renderHole(endpoint));
121
+ return new Response(html, {
122
+ status: 200,
123
+ headers: {
124
+ ...entry.headers,
125
+ [VIA_HEADER]: via
126
+ }
127
+ });
128
+ }
129
+ function serve(entry, via, ctx) {
130
+ return entry.kind === "page" && entry.stitch ? serve_stitched(entry, via, ctx) : postrender_response(entry, via, ctx.event.request);
131
+ }
132
+ /** The verdict's other word: a REFUSED page gets `private, no-store` when the app set nothing —
133
+ * per-page proven headers replace blanket CDN rules in both directions. Best-effort (some
134
+ * platforms hand out immutable headers). */
135
+ function stamp_no_store(response) {
136
+ try {
137
+ if (response.status !== 200) return;
138
+ if (!(response.headers.get("content-type") ?? "").includes("text/html")) return;
139
+ if (response.headers.get("cache-control")) return;
140
+ response.headers.set("cache-control", "private, no-store");
141
+ } catch {}
142
+ }
143
+ /** DEV teaching leg: the verdict runs but never stores/serves. Eligible → a `would-store`
144
+ * header to read in the network panel; refused → ONE console note per path naming the read. */
145
+ const dev_noted_paths = /* @__PURE__ */ new Set();
146
+ function dev_postrender_note(response, ctx, obs) {
147
+ const refusal = obs.disqualified_by ?? (obs.wrote_cookie ? "a cookie write" : null) ?? (response.status !== 200 ? `status ${response.status}` : null) ?? (response.headers.has("set-cookie") ? "a set-cookie response header" : null) ?? (!(response.headers.get("content-type") ?? "").includes("text/html") ? "a non-html response" : null) ?? (ctx.facts.streamed ? "streamed load promises" : null);
148
+ if (!refusal) {
149
+ try {
150
+ response.headers.set(VIA_HEADER, "would-store");
151
+ } catch {}
152
+ return;
153
+ }
154
+ if (dev_noted_paths.has(ctx.path)) return;
155
+ dev_noted_paths.add(ctx.path);
156
+ console.warn(`[ogygia] postrender: ${ctx.path} stays per-request — the render read ${refusal}. Personalize inside a render:'deferred' hole to make the shell storable.`);
157
+ }
158
+ /**
159
+ * The write-path verdict + store. Returns the stored entry AND a fresh Response (reading the
160
+ * body consumes the original) — or null when the page must stay per-request. Pre-body guards
161
+ * run FIRST so an ineligible response's stream is never consumed.
162
+ */
163
+ async function capture(response, ctx, runtime, obs, ttl) {
164
+ const { path, facts } = ctx;
165
+ const tags = facts.sources ?? [];
166
+ if (obs.disqualified_by || obs.wrote_cookie) return null;
167
+ if (response.status === 301 || response.status === 308) {
168
+ const location = response.headers.get("location");
169
+ if (!location) return null;
170
+ const entry = {
171
+ kind: "redirect",
172
+ status: response.status,
173
+ location,
174
+ created: Date.now()
175
+ };
176
+ await store_put(runtime, path, entry, {
177
+ ttl,
178
+ tags
179
+ });
180
+ return {
181
+ entry,
182
+ response
183
+ };
184
+ }
185
+ if (response.status !== 200) return null;
186
+ if (response.headers.has("set-cookie")) return null;
187
+ const content_type = response.headers.get("content-type") ?? "";
188
+ if (!content_type.includes("text/html")) return null;
189
+ const app_cc = response.headers.get("cache-control") ?? "";
190
+ if (app_cc.includes("private") || app_cc.includes("no-store")) return null;
191
+ if (facts.streamed) return null;
192
+ const html = await response.text();
193
+ if (KIT_DEFERRED_BOOT_RE.test(html)) return null;
194
+ const created = Date.now();
195
+ const modes = stitch_modes(html);
196
+ const has_serve = modes.serve;
197
+ const stored_html = !has_serve && modes.edge ? esi_rewrite(html, path) : html;
198
+ const headers = has_serve ? {
199
+ "content-type": content_type,
200
+ "cache-control": "private, no-store"
201
+ } : {
202
+ "content-type": content_type,
203
+ "cache-control": `public, s-maxage=${ttl}`,
204
+ etag: `"${createHash("sha256").update(stored_html).digest("hex").slice(0, 32)}"`,
205
+ "last-modified": new Date(created).toUTCString(),
206
+ ...modes.edge ? { "surrogate-control": "content=\"ESI/1.0\"" } : {}
207
+ };
208
+ if (!has_serve) for (const edge of runtime.edges) try {
209
+ Object.assign(headers, edge.headers({
210
+ url: path,
211
+ ttl
212
+ }));
213
+ } catch {}
214
+ const entry = {
215
+ kind: "page",
216
+ html: stored_html,
217
+ head_end: stored_html.indexOf("</head>"),
218
+ headers,
219
+ created,
220
+ ...has_serve ? { stitch: true } : {}
221
+ };
222
+ await store_put(runtime, path, entry, {
223
+ ttl,
224
+ tags
225
+ });
226
+ return {
227
+ entry,
228
+ response: postrender_response(entry, "stored")
229
+ };
230
+ }
231
+ /** This request's value for the `postrender` key of Kit's `config` (the route's, merged from its
232
+ * layouts), or the app-wide default when no level sets a boolean. */
233
+ function opted_in(ctx) {
234
+ const declared = ctx.routeConfig("postrender");
235
+ if (typeof declared === "boolean") return declared;
236
+ if (declared !== void 0) ctx.app.warn(`\`config.postrender\` must be true or false (got ${JSON.stringify(declared)}); the app-wide default applies.`);
237
+ return ctx.options.default;
238
+ }
239
+ const server = defineServer({
240
+ setup(app) {
241
+ set_postrender_app(app);
242
+ },
243
+ state: () => ({
244
+ runtime: null,
245
+ settle: null,
246
+ obs: null,
247
+ eligible: false
248
+ }),
249
+ async page(ctx) {
250
+ const { event, path, facts, state } = ctx;
251
+ const runtime = state.runtime = runtime_of(ctx);
252
+ if (!(!facts.private && !building && event.request.method.toUpperCase() === "GET" && event.url.search === "" && !path.endsWith("__data.json") && !facts.answerForm && opted_in(ctx))) return;
253
+ state.eligible = true;
254
+ if (dev) {
255
+ state.obs = observe_event(event, facts);
256
+ return;
257
+ }
258
+ const hit = await store_get(runtime, path);
259
+ if (hit && within_ttl(hit, ctx.options.ttl)) {
260
+ ctx.app.devtools({
261
+ domain: "server",
262
+ name: "server.postrender",
263
+ op: "hit",
264
+ url: path
265
+ });
266
+ return serve(hit, "hit", ctx);
267
+ }
268
+ const flight = join_flight(path);
269
+ if (flight) {
270
+ const outcome = await flight;
271
+ if (outcome.stored) {
272
+ ctx.app.devtools({
273
+ domain: "server",
274
+ name: "server.postrender",
275
+ op: "join",
276
+ url: path
277
+ });
278
+ return serve(outcome.stored, "join", ctx);
279
+ }
280
+ return;
281
+ }
282
+ state.settle = begin_flight(path);
283
+ state.obs = observe_event(event, facts);
284
+ facts.storable = true;
285
+ facts.sources ??= [];
286
+ },
287
+ async response(ctx, response) {
288
+ const { event, path, state } = ctx;
289
+ const runtime = state.runtime ?? current_runtime();
290
+ if (event.request.method.toUpperCase() !== "GET" && response.status < 400) self_evict(runtime, path);
291
+ const { settle, obs } = state;
292
+ if (settle && obs) try {
293
+ const stored = await capture(response, ctx, runtime, obs, ctx.options.ttl);
294
+ settle({ stored: stored?.entry ?? null });
295
+ ctx.app.devtools(stored ? {
296
+ domain: "server",
297
+ name: "server.postrender",
298
+ op: "stored",
299
+ url: path,
300
+ bytes: stored.entry.kind === "page" ? stored.entry.html.length : 0
301
+ } : {
302
+ domain: "server",
303
+ name: "server.postrender",
304
+ op: "skip",
305
+ url: path,
306
+ reason: obs.disqualified_by ?? "response-ineligible"
307
+ });
308
+ if (stored) return stored.entry.kind === "page" && stored.entry.stitch ? await serve_stitched(stored.entry, "stored", ctx) : stored.response;
309
+ stamp_no_store(response);
310
+ } catch {
311
+ settle({ stored: null });
312
+ }
313
+ else if (dev && obs && state.eligible) dev_postrender_note(response, ctx, obs);
314
+ },
315
+ async invalidate(tags) {
316
+ await invalidate_tags(tags);
317
+ },
318
+ async lastBuild(version) {
319
+ const { store } = current_runtime();
320
+ const marker = await store.get(BUILD_MARKER_KEY);
321
+ const seen = marker?.kind === "page" ? marker.html : void 0;
322
+ await store.put(BUILD_MARKER_KEY, {
323
+ kind: "page",
324
+ html: version,
325
+ headers: {},
326
+ created: Date.now()
327
+ }, {
328
+ ttl: BUILD_MARKER_TTL_SEC,
329
+ tags: []
330
+ });
331
+ return seen;
332
+ }
333
+ });
334
+ export { MISORDERED_HANDLE, MISSING_HANDLE, server as default, postrender_response };
@@ -0,0 +1,61 @@
1
+ /**
2
+ * postrender — SERVE-TIME STITCHING (the zero-flash upgrade over `render: 'live'`).
3
+ *
4
+ * A `with { render: 'deferred', stitch: 'serve' }` hole ships in the stored shell as a normal
5
+ * signed hole PLUS a `stitch` attribute. On every serve of that entry the handle renders the
6
+ * hole server-side RIGHT THEN (the visitor's cookies ride the request) and SPLICES the HTML
7
+ * into the stored bytes — one response, personalized first paint, view-source included.
8
+ *
9
+ * Laws: fail-open PER HOLE (a failed/timed-out render keeps the fallback + the client fetch —
10
+ * a slow upstream never blocks the page); the spliced wrapper becomes a neutral
11
+ * `display:contents` div so nested islands inside the stitched HTML are TOP-LEVEL regions that
12
+ * wake themselves (no region ancestor to ride or wait on); stitched entries are per-visitor —
13
+ * the capture stamps them `private, no-store` and mints no validators.
14
+ *
15
+ * Pure string functions (unit-tested); the handle threads its own `#render_capability`.
16
+ */
17
+ /** Cheap presence probe — the capture uses it to flag entries; serves use it to skip the scan. */
18
+ export declare const STITCH_HOLE_RE: RegExp;
19
+ /** How a stitch hole fills: `'serve'` = the ORIGIN re-renders + splices on every serve (per-visitor
20
+ * page, edge-bypassed) · `'edge'` = the CDN fills an ESI include per request (the shell stays
21
+ * edge-cached; origin renders only the hole). */
22
+ export type StitchMode = "serve" | "edge";
23
+ export interface StitchHole {
24
+ /** Absolute span of the WHOLE region block (open tag through matching close). */
25
+ start: number;
26
+ end: number;
27
+ /** The signed capability URL from the `endpoint` attribute, entity-unescaped. */
28
+ endpoint: string;
29
+ mode: StitchMode;
30
+ }
31
+ /** Which stitch modes a stored page carries. One `'serve'` hole makes the WHOLE page per-visitor
32
+ * (serve taints); a page whose stitch holes are all `'edge'` stays edge-cacheable. */
33
+ export declare function stitch_modes(html: string): {
34
+ serve: boolean;
35
+ edge: boolean;
36
+ };
37
+ /**
38
+ * EDGE STITCHING (ESI): rewrite every `stitch="edge"` hole so an ESI-capable CDN (Akamai, Fastly,
39
+ * Varnish) fills it per request from the hole's own signed capability, while the shell around it
40
+ * stays cached at the edge. The region block is wrapped in `<esi:remove>` and followed by an
41
+ * `<esi:include>`:
42
+ * - on an ESI edge the wrapper is stripped and the include is fetched from origin (with the
43
+ * viewer's cookies, per the edge config) → a personal first paint, shell served from cache,
44
+ * origin renders ONE region;
45
+ * - anywhere ESI is not processed (direct origin, dev, a non-ESI CDN) `<esi:remove>` is an
46
+ * unknown element whose CHILDREN still render and `<esi:include>` is inert — the hole ships its
47
+ * fallback and the client fetches it exactly like a normal deferred hole. Graceful either way.
48
+ * Pure string function; the capture runs it at store time (the etag is minted over the result).
49
+ * `page_path` is the stored page's pathname: the hole's endpoint is emitted PAGE-RELATIVE
50
+ * (`../../__ogygia__?…` under Kit's relative paths), and an ESI include must be an absolute path
51
+ * the edge can fetch from origin without knowing the page — so each src is resolved here.
52
+ */
53
+ export declare function esi_rewrite(html: string, page_path?: string): string;
54
+ /** Find every TOP-LEVEL stitch-marked region block, balanced across nested regions. */
55
+ export declare function find_stitch_holes(html: string): StitchHole[];
56
+ /**
57
+ * Splice fresh renders into every stitch hole. `render` resolves an endpoint to HTML or null;
58
+ * null (failure/timeout) keeps the original block VERBATIM — the fallback ships and the client
59
+ * fetches exactly as an unstitched hole would (fail-open). Holes render in PARALLEL.
60
+ */
61
+ export declare function stitch_html(html: string, render: (endpoint: string) => Promise<string | null>): Promise<string>;
package/dist/stitch.js ADDED
@@ -0,0 +1,126 @@
1
+ import { escapeAttr } from "@ogygia/core/plugin/utils";
2
+ // src/stitch.ts
3
+ /**
4
+ * postrender — SERVE-TIME STITCHING (the zero-flash upgrade over `render: 'live'`).
5
+ *
6
+ * A `with { render: 'deferred', stitch: 'serve' }` hole ships in the stored shell as a normal
7
+ * signed hole PLUS a `stitch` attribute. On every serve of that entry the handle renders the
8
+ * hole server-side RIGHT THEN (the visitor's cookies ride the request) and SPLICES the HTML
9
+ * into the stored bytes — one response, personalized first paint, view-source included.
10
+ *
11
+ * Laws: fail-open PER HOLE (a failed/timed-out render keeps the fallback + the client fetch —
12
+ * a slow upstream never blocks the page); the spliced wrapper becomes a neutral
13
+ * `display:contents` div so nested islands inside the stitched HTML are TOP-LEVEL regions that
14
+ * wake themselves (no region ancestor to ride or wait on); stitched entries are per-visitor —
15
+ * the capture stamps them `private, no-store` and mints no validators.
16
+ *
17
+ * Pure string functions (unit-tested); the handle threads its own `#render_capability`.
18
+ */
19
+ /** Cheap presence probe — the capture uses it to flag entries; serves use it to skip the scan. */
20
+ const STITCH_HOLE_RE = /<ogygia-region\b[^>]*\bstitch\b[^>]*>/;
21
+ const REGION_TOKEN_RE = /<ogygia-region\b[^>]*>|<\/ogygia-region>/g;
22
+ const STITCH_ATTR_RE = /\bstitch\b/;
23
+ /** `stitch="edge"` — the ESI mode. Anything else that carries `stitch` (`"serve"`, or the bare
24
+ * attribute an older build emitted) is the origin-serve mode. */
25
+ const STITCH_EDGE_RE = /\bstitch="edge"/;
26
+ const ENDPOINT_ATTR_RE = /\bendpoint="([^"]*)"/;
27
+ const AMP_RE = /&amp;/g;
28
+ /** Which stitch modes a stored page carries. One `'serve'` hole makes the WHOLE page per-visitor
29
+ * (serve taints); a page whose stitch holes are all `'edge'` stays edge-cacheable. */
30
+ function stitch_modes(html) {
31
+ if (!STITCH_HOLE_RE.test(html)) return {
32
+ serve: false,
33
+ edge: false
34
+ };
35
+ const holes = find_stitch_holes(html);
36
+ return {
37
+ serve: holes.some((h) => h.mode === "serve"),
38
+ edge: holes.some((h) => h.mode === "edge")
39
+ };
40
+ }
41
+ /**
42
+ * EDGE STITCHING (ESI): rewrite every `stitch="edge"` hole so an ESI-capable CDN (Akamai, Fastly,
43
+ * Varnish) fills it per request from the hole's own signed capability, while the shell around it
44
+ * stays cached at the edge. The region block is wrapped in `<esi:remove>` and followed by an
45
+ * `<esi:include>`:
46
+ * - on an ESI edge the wrapper is stripped and the include is fetched from origin (with the
47
+ * viewer's cookies, per the edge config) → a personal first paint, shell served from cache,
48
+ * origin renders ONE region;
49
+ * - anywhere ESI is not processed (direct origin, dev, a non-ESI CDN) `<esi:remove>` is an
50
+ * unknown element whose CHILDREN still render and `<esi:include>` is inert — the hole ships its
51
+ * fallback and the client fetches it exactly like a normal deferred hole. Graceful either way.
52
+ * Pure string function; the capture runs it at store time (the etag is minted over the result).
53
+ * `page_path` is the stored page's pathname: the hole's endpoint is emitted PAGE-RELATIVE
54
+ * (`../../__ogygia__?…` under Kit's relative paths), and an ESI include must be an absolute path
55
+ * the edge can fetch from origin without knowing the page — so each src is resolved here.
56
+ */
57
+ function esi_rewrite(html, page_path = "/") {
58
+ const holes = find_stitch_holes(html).filter((h) => h.mode === "edge");
59
+ if (!holes.length) return html;
60
+ let out = "";
61
+ let last = 0;
62
+ for (const h of holes) {
63
+ const abs = new URL(h.endpoint, "http://o" + page_path);
64
+ const src = escapeAttr(abs.pathname + abs.search);
65
+ out += html.slice(last, h.start);
66
+ out += `<esi:remove>${html.slice(h.start, h.end)}</esi:remove><esi:include src="${src}" onerror="continue"/>`;
67
+ last = h.end;
68
+ }
69
+ out += html.slice(last);
70
+ return out;
71
+ }
72
+ /** Find every TOP-LEVEL stitch-marked region block, balanced across nested regions. */
73
+ function find_stitch_holes(html) {
74
+ const holes = [];
75
+ let depth = 0;
76
+ let open = null;
77
+ REGION_TOKEN_RE.lastIndex = 0;
78
+ let m;
79
+ while (m = REGION_TOKEN_RE.exec(html)) {
80
+ const token = m[0];
81
+ if (token[1] === "/") {
82
+ depth--;
83
+ if (depth === 0 && open) {
84
+ if (STITCH_ATTR_RE.test(open.tag)) {
85
+ const endpoint = ENDPOINT_ATTR_RE.exec(open.tag)?.[1]?.replace(AMP_RE, "&") ?? "";
86
+ if (endpoint) holes.push({
87
+ start: open.start,
88
+ end: m.index + token.length,
89
+ endpoint,
90
+ mode: STITCH_EDGE_RE.test(open.tag) ? "edge" : "serve"
91
+ });
92
+ }
93
+ open = null;
94
+ }
95
+ } else {
96
+ if (depth === 0) open = {
97
+ start: m.index,
98
+ tag: token
99
+ };
100
+ depth++;
101
+ }
102
+ }
103
+ return holes;
104
+ }
105
+ /**
106
+ * Splice fresh renders into every stitch hole. `render` resolves an endpoint to HTML or null;
107
+ * null (failure/timeout) keeps the original block VERBATIM — the fallback ships and the client
108
+ * fetches exactly as an unstitched hole would (fail-open). Holes render in PARALLEL.
109
+ */
110
+ async function stitch_html(html, render) {
111
+ const holes = find_stitch_holes(html);
112
+ if (!holes.length) return html;
113
+ const rendered = await Promise.all(holes.map((h) => render(h.endpoint).catch(() => null)));
114
+ let out = "";
115
+ let last = 0;
116
+ for (let i = 0; i < holes.length; i++) {
117
+ const fill = rendered[i];
118
+ if (fill === null) continue;
119
+ out += html.slice(last, holes[i].start);
120
+ out += `<div style="display:contents" data-og-stitched="">${fill}</div>`;
121
+ last = holes[i].end;
122
+ }
123
+ out += html.slice(last);
124
+ return out;
125
+ }
126
+ export { STITCH_HOLE_RE, esi_rewrite, find_stitch_holes, stitch_html, stitch_modes };
@@ -0,0 +1,94 @@
1
+ /**
2
+ * postrender — pages stored at request time. Shared contracts.
3
+ *
4
+ * The store holds THE RENDER: a full response (html + headers) or a permanent redirect,
5
+ * keyed by URL pathname. Two tiny adapter contracts (see internal/notes/freeze.md):
6
+ * every store impl passes ONE shared contract spec; every edge adapter speaks its CDN's
7
+ * real purge API. Fan-out (allSettled across edges) lives in ogygia, never in adapters.
8
+ *
9
+ * Bulk eviction is PREFIX-shaped, not locale-shaped: the key is the URL, so any URL subtree
10
+ * (`/fr/fr/` — a locale; `/docs/` — a section) evicts with one call. Locale was the bcms
11
+ * motivating case, never the contract.
12
+ */
13
+ /** A stored page: a finished page response, or a permanent redirect. */
14
+ export type PostrenderEntry = {
15
+ kind: "page";
16
+ html: string;
17
+ /** Index of `</head>` in `html` — where a served-from-store copy gets its doc marker
18
+ * stamped by slicing (no copy of the page per hit). Absent on entries written before
19
+ * the field existed; the read side then finds it once. */
20
+ head_end?: number;
21
+ /** Headers to replay on a hit (content-type + the verdict's cache-control + edge extras). */
22
+ headers: Record<string, string>;
23
+ /** Epoch ms at store time — the read side's TTL backstop (a page older than the TTL is a miss). */
24
+ created: number;
25
+ /** The shell contains serve-time STITCH holes: every serve re-renders them with the
26
+ * visitor's request and splices — per-visitor responses, `private, no-store`, no
27
+ * validators. See postrender/stitch.ts. */
28
+ stitch?: boolean;
29
+ } | {
30
+ kind: "redirect";
31
+ status: 301 | 308;
32
+ location: string;
33
+ created: number;
34
+ };
35
+ /** Options `put` receives beyond the entry. */
36
+ export interface PostrenderPutOptions {
37
+ /** How long to keep the entry, in seconds: for a page, the TTL backstop (≤ 86400); for the build
38
+ * marker the deploy thaw keeps (a NUL-prefixed key), years. A store with native expiry (valkey
39
+ * EX) uses it directly. Either way postrender also ages a page on read against `entry.created`,
40
+ * so a page from a store without expiry is a miss once it is older than the TTL. */
41
+ ttl: number;
42
+ /** Source receipts recorded during the render (`s:<id>:<fp>` from `import.meta.og.source`
43
+ * wrappers) — the REVERSE INDEX feeding `evictByTag`. Empty/omitted = no receipts. */
44
+ tags?: string[];
45
+ }
46
+ /**
47
+ * The store contract — four calls. Implementations MUST pass the shared contract spec
48
+ * (test/postrender.test.ts): tier-1 memory ships built-in; valkey rides `REDIS_URL` infra.
49
+ * Keys are URL pathnames, so `evictWhere({ prefix })` is a key-prefix scan by construction.
50
+ */
51
+ export interface PostrenderStore {
52
+ get(key: string): Promise<PostrenderEntry | null>;
53
+ put(key: string, entry: PostrenderEntry, options: PostrenderPutOptions): Promise<void>;
54
+ evict(key: string): Promise<void>;
55
+ evictWhere(filter: {
56
+ prefix: string;
57
+ }): Promise<void>;
58
+ /** The reverse index (og.source precision): evict every key whose receipts carry `tag` and
59
+ * RETURN those keys — ogygia fans the returned URLs out to the edge adapters' `purgeUrl`.
60
+ * Optional: a store without it degrades `invalidate(fn, args)` to a warning. */
61
+ evictByTag?(tag: string): Promise<string[]>;
62
+ /** Optional introspection for harnesses/devtools: number of live entries. */
63
+ size?(): Promise<number>;
64
+ }
65
+ /** What `EdgeAdapter.headers` receives — enough to write the edge's storage instructions. */
66
+ export interface PostrenderMeta {
67
+ /** Request pathname (the store key). */
68
+ url: string;
69
+ /** The policy TTL in seconds (the s-maxage the verdict grants). */
70
+ ttl: number;
71
+ }
72
+ /**
73
+ * The edge contract. `headers(meta)` returns extra response headers the CDN stores by —
74
+ * Akamai stamps depth-capped PREFIX tags (`p:/fr`, `p:/fr/fr`, …) since Fast Purge can't take
75
+ * an arbitrary prefix; CloudFront needs none (path wildcards are native). `purgeUrl`/`purgeWhere`
76
+ * speak the CDN's REAL purge API. Adapters never fan out — ogygia calls every edge with
77
+ * `allSettled` (one edge down ≠ publish down).
78
+ */
79
+ export interface EdgeAdapter {
80
+ /** Adapter name for logs/harness assertions ("akamai", "cloudfront"). */
81
+ name: string;
82
+ headers(meta: PostrenderMeta): Record<string, string>;
83
+ purgeUrl(url: string): Promise<void>;
84
+ purgeWhere(filter: {
85
+ prefix: string;
86
+ }): Promise<void>;
87
+ }
88
+ /** `postrender.handle({ … })` — the live objects (clients, creds) a server keeps its pages with. */
89
+ export interface PostrenderHandleOptions {
90
+ /** Where pages are kept (default: an in-process memory store). */
91
+ store?: PostrenderStore;
92
+ /** The CDNs in front of the app, purged on every invalidation. */
93
+ edge?: EdgeAdapter[];
94
+ }
package/dist/types.js ADDED
File without changes
package/dist/vite.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ import { PostrenderServerOptions } from "./server.js";
2
+ import { OgygiaPlugin } from "@ogygia/core/vite";
3
+ export interface PostrenderOptions {
4
+ /** TTL backstop in seconds (default 86400, clamped to [1, 86400]): nothing is stale forever. */
5
+ ttl?: number;
6
+ /** The app-wide opt-in (default true). */
7
+ default?: boolean;
8
+ }
9
+ export declare function postrender(options?: PostrenderOptions): OgygiaPlugin<PostrenderServerOptions>;
package/dist/vite.js ADDED
@@ -0,0 +1,30 @@
1
+ import { definePlugin } from "@ogygia/core/vite";
2
+ // src/vite.ts
3
+ /**
4
+ * `postrender()` — pages stored at request time, listed beside `ogygia()` in vite.config. The
5
+ * SWITCH + serializable policy, nothing else: a page whose render observed no personalization is
6
+ * stored whole on its first request and served as bytes until `postrender.invalidate(url)` /
7
+ * `postrender.invalidateWhere({ prefix })` or the TTL backstop. Live adapters (a valkey client, CDN
8
+ * purge creds) are the argument of `postrender.handle({ store, edge })` in hooks.server.ts, from
9
+ * `@ogygia/postrender`.
10
+ *
11
+ * `default` sets the app-wide opt-in: `true` (the default) keeps the auto behaviour — every eligible
12
+ * page is stored, observed purity refuses the rest, and a route opts OUT in Kit's own config:
13
+ * `export const config = { postrender: false }`. `false` flips the app to OPT-IN: nothing is stored
14
+ * unless a page or a layout above it sets `config = { postrender: true }`. Kit merges `config` from
15
+ * the layouts into the page (the page's own key wins), and so does the build that reads it.
16
+ */
17
+ function postrender(options = {}) {
18
+ return definePlugin({
19
+ name: "@ogygia/postrender",
20
+ server: import.meta.resolve("./server.js"),
21
+ options: {
22
+ ttl: Math.min(86400, Math.max(1, Math.floor(options.ttl ?? 86400))),
23
+ default: options.default ?? true
24
+ },
25
+ build(b) {
26
+ b.routeConfig("postrender");
27
+ }
28
+ });
29
+ }
30
+ export { postrender };