@ogygia/postrender 0.0.0-stage → 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/LICENSE +21 -0
- package/README.md +48 -2
- package/dist/adapters/akamai.d.ts +17 -0
- package/dist/adapters/akamai.js +72 -0
- package/dist/adapters/cloudflare-kv.d.ts +20 -0
- package/dist/adapters/cloudflare-kv.js +57 -0
- package/dist/adapters/cloudflare.d.ts +13 -0
- package/dist/adapters/cloudflare.js +38 -0
- package/dist/adapters/cloudfront.d.ts +9 -0
- package/dist/adapters/cloudfront.js +89 -0
- package/dist/adapters/upstash.d.ts +7 -0
- package/dist/adapters/upstash.js +87 -0
- package/dist/adapters/valkey.d.ts +18 -0
- package/dist/adapters/valkey.js +90 -0
- package/dist/app.d.ts +4 -0
- package/dist/app.js +9 -0
- package/dist/handle.d.ts +3 -0
- package/dist/handle.js +16 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +42 -0
- package/dist/key.d.ts +22 -0
- package/dist/key.js +37 -0
- package/dist/memory-store.d.ts +2 -0
- package/dist/memory-store.js +46 -0
- package/dist/observe.d.ts +17 -0
- package/dist/observe.js +77 -0
- package/dist/registry.d.ts +50 -0
- package/dist/registry.js +177 -0
- package/dist/server.d.ts +32 -0
- package/dist/server.js +334 -0
- package/dist/stitch.d.ts +61 -0
- package/dist/stitch.js +126 -0
- package/dist/types.d.ts +94 -0
- package/dist/types.js +0 -0
- package/dist/vite.d.ts +9 -0
- package/dist/vite.js +30 -0
- package/package.json +59 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import { handle } from "./handle.js";
|
|
2
|
+
import { invalidate, invalidateWhere } from "./registry.js";
|
|
3
|
+
import { memory_store } from "./memory-store.js";
|
|
4
|
+
import { valkey } from "./adapters/valkey.js";
|
|
5
|
+
import { upstash } from "./adapters/upstash.js";
|
|
6
|
+
import { cloudflareKv } from "./adapters/cloudflare-kv.js";
|
|
7
|
+
import { akamai } from "./adapters/akamai.js";
|
|
8
|
+
import { cloudfront } from "./adapters/cloudfront.js";
|
|
9
|
+
import { cloudflare } from "./adapters/cloudflare.js";
|
|
10
|
+
// src/index.ts
|
|
11
|
+
/**
|
|
12
|
+
* `@ogygia/postrender` — pages stored at request time. SERVER ONLY.
|
|
13
|
+
*
|
|
14
|
+
* Prerender renders a page at build time; postrender renders it on its first request, stores it
|
|
15
|
+
* whole, and serves the stored bytes until an invalidation clears it.
|
|
16
|
+
*
|
|
17
|
+
* ```ts
|
|
18
|
+
* // vite.config: the switch (+ serializable policy)
|
|
19
|
+
* import { postrender } from '@ogygia/postrender/vite';
|
|
20
|
+
* plugins: [ogygia(), postrender(), sveltekit()]
|
|
21
|
+
*
|
|
22
|
+
* // hooks.server.ts: the live store and CDN edges, BEFORE ogygia's handle
|
|
23
|
+
* import { postrender, valkey, akamai } from '@ogygia/postrender';
|
|
24
|
+
* export const handle = sequence(
|
|
25
|
+
* postrender.handle({ store: valkey(client), edge: [akamai(creds)] }),
|
|
26
|
+
* ogygia.handle()
|
|
27
|
+
* );
|
|
28
|
+
*
|
|
29
|
+
* // a route opts out in Kit's own config: export const config = { postrender: false };
|
|
30
|
+
*
|
|
31
|
+
* // anywhere server-side (CMS publish webhook):
|
|
32
|
+
* await postrender.invalidate('/fr/fr/solar/'); // exact URL
|
|
33
|
+
* await postrender.invalidate(loadContent, [args]); // og.source reverse index
|
|
34
|
+
* await postrender.invalidateWhere({ prefix: '/fr/fr/' }); // subtree nuke
|
|
35
|
+
* ```
|
|
36
|
+
*/
|
|
37
|
+
const postrender = {
|
|
38
|
+
handle,
|
|
39
|
+
invalidate,
|
|
40
|
+
invalidateWhere
|
|
41
|
+
};
|
|
42
|
+
export { akamai, cloudfront as awsCloudfront, cloudflare, cloudflareKv, cloudfront, memory_store as memoryStore, postrender, upstash, valkey };
|
package/dist/key.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* postrender — keying. v1 keying law (internal/notes/freeze.md, RESTRUCTURE): the key IS the
|
|
3
|
+
* URL pathname. Zero sources, zero markers; `invalidate(url)` is exact because a CMS publish
|
|
4
|
+
* payload carries its urlPath, and bulk eviction is a key-prefix scan (`invalidateWhere({
|
|
5
|
+
* prefix: '/fr/fr/' })` — locale nukes are one case of it, not the contract). Query-stringed
|
|
6
|
+
* requests are never stored (a `?` is an unbounded personalization axis — utm, search,
|
|
7
|
+
* pagination — v1 keeps the store bounded).
|
|
8
|
+
*/
|
|
9
|
+
/** The store key for a request URL: the decoded pathname, verbatim (trailing slash preserved —
|
|
10
|
+
* `/fr/fr/` and `/fr/fr` are different documents to Kit and to the CDN). */
|
|
11
|
+
export declare function store_key(pathname: string): string;
|
|
12
|
+
/** How many leading path segments become edge prefix tags (`p:/fr`, `p:/fr/fr`, `p:/fr/fr/x`).
|
|
13
|
+
* Depth-capped so tag counts stay bounded on deep trees; a purge deeper than the cap falls back
|
|
14
|
+
* to origin eviction + edge TTL. Shared by the akamai adapter and its emulator personality. */
|
|
15
|
+
export declare const PREFIX_TAG_DEPTH = 3;
|
|
16
|
+
/** Normalize a prefix filter: leading slash enforced, trailing slash stripped (except root). */
|
|
17
|
+
export declare function normalize_prefix(prefix: string): string;
|
|
18
|
+
/** The key prefix a normalized prefix's SUBTREE shares: `/fr/fr` → `/fr/fr/` (never `/fr/fright`),
|
|
19
|
+
* and the root `/` → `/` itself (every key; `'/' + '/'` would match nothing). */
|
|
20
|
+
export declare function subtree_prefix(normalized: string): string;
|
|
21
|
+
/** The depth-capped prefix list for a pathname — the edge tag vocabulary for this response. */
|
|
22
|
+
export declare function prefix_tags(pathname: string): string[];
|
package/dist/key.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
// src/key.ts
|
|
2
|
+
/**
|
|
3
|
+
* postrender — keying. v1 keying law (internal/notes/freeze.md, RESTRUCTURE): the key IS the
|
|
4
|
+
* URL pathname. Zero sources, zero markers; `invalidate(url)` is exact because a CMS publish
|
|
5
|
+
* payload carries its urlPath, and bulk eviction is a key-prefix scan (`invalidateWhere({
|
|
6
|
+
* prefix: '/fr/fr/' })` — locale nukes are one case of it, not the contract). Query-stringed
|
|
7
|
+
* requests are never stored (a `?` is an unbounded personalization axis — utm, search,
|
|
8
|
+
* pagination — v1 keeps the store bounded).
|
|
9
|
+
*/
|
|
10
|
+
/** The store key for a request URL: the decoded pathname, verbatim (trailing slash preserved —
|
|
11
|
+
* `/fr/fr/` and `/fr/fr` are different documents to Kit and to the CDN). */
|
|
12
|
+
function store_key(pathname) {
|
|
13
|
+
return pathname;
|
|
14
|
+
}
|
|
15
|
+
/** How many leading path segments become edge prefix tags (`p:/fr`, `p:/fr/fr`, `p:/fr/fr/x`).
|
|
16
|
+
* Depth-capped so tag counts stay bounded on deep trees; a purge deeper than the cap falls back
|
|
17
|
+
* to origin eviction + edge TTL. Shared by the akamai adapter and its emulator personality. */
|
|
18
|
+
const PREFIX_TAG_DEPTH = 3;
|
|
19
|
+
/** Normalize a prefix filter: leading slash enforced, trailing slash stripped (except root). */
|
|
20
|
+
function normalize_prefix(prefix) {
|
|
21
|
+
let p = prefix.startsWith("/") ? prefix : "/" + prefix;
|
|
22
|
+
while (p.length > 1 && p.endsWith("/")) p = p.slice(0, -1);
|
|
23
|
+
return p;
|
|
24
|
+
}
|
|
25
|
+
/** The key prefix a normalized prefix's SUBTREE shares: `/fr/fr` → `/fr/fr/` (never `/fr/fright`),
|
|
26
|
+
* and the root `/` → `/` itself (every key; `'/' + '/'` would match nothing). */
|
|
27
|
+
function subtree_prefix(normalized) {
|
|
28
|
+
return normalized.endsWith("/") ? normalized : normalized + "/";
|
|
29
|
+
}
|
|
30
|
+
/** The depth-capped prefix list for a pathname — the edge tag vocabulary for this response. */
|
|
31
|
+
function prefix_tags(pathname) {
|
|
32
|
+
const segs = pathname.split("/").filter(Boolean);
|
|
33
|
+
const out = [];
|
|
34
|
+
for (let i = 1; i <= Math.min(segs.length, 3); i++) out.push("/" + segs.slice(0, i).join("/"));
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
export { PREFIX_TAG_DEPTH, normalize_prefix, prefix_tags, store_key, subtree_prefix };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { normalize_prefix, subtree_prefix } from "./key.js";
|
|
2
|
+
import { SizedLru } from "@ogygia/core/plugin/utils";
|
|
3
|
+
// src/memory-store.ts
|
|
4
|
+
/** Resident budget for stored pages (a stored page can be multi-MB; a count alone bounds nothing). */
|
|
5
|
+
const DEFAULT_MAX_BYTES = 67108864;
|
|
6
|
+
const DEFAULT_MAX_ENTRIES = 1e3;
|
|
7
|
+
/** What an entry costs to keep: a page is its HTML; a redirect is a few dozen bytes. */
|
|
8
|
+
const entry_bytes = (entry) => entry.kind === "page" ? entry.html.length : 64;
|
|
9
|
+
function memory_store(max_entries = DEFAULT_MAX_ENTRIES, max_bytes = DEFAULT_MAX_BYTES) {
|
|
10
|
+
const entries = new SizedLru(max_bytes, max_entries);
|
|
11
|
+
const tag_index = /* @__PURE__ */ new Map();
|
|
12
|
+
return {
|
|
13
|
+
async get(key) {
|
|
14
|
+
return entries.get(key, Date.now());
|
|
15
|
+
},
|
|
16
|
+
async put(key, entry, options) {
|
|
17
|
+
entries.set(key, entry, entry_bytes(entry), Date.now() + options.ttl * 1e3);
|
|
18
|
+
for (const tag of options.tags ?? []) {
|
|
19
|
+
let set = tag_index.get(tag);
|
|
20
|
+
if (!set) tag_index.set(tag, set = /* @__PURE__ */ new Set());
|
|
21
|
+
set.add(key);
|
|
22
|
+
}
|
|
23
|
+
},
|
|
24
|
+
async evict(key) {
|
|
25
|
+
entries.delete(key);
|
|
26
|
+
},
|
|
27
|
+
async evictWhere({ prefix }) {
|
|
28
|
+
const p = normalize_prefix(prefix);
|
|
29
|
+
const subtree = subtree_prefix(p);
|
|
30
|
+
for (const key of entries.keys()) if (key === p || key.startsWith(subtree)) entries.delete(key);
|
|
31
|
+
},
|
|
32
|
+
async evictByTag(tag) {
|
|
33
|
+
const set = tag_index.get(tag);
|
|
34
|
+
if (!set) return [];
|
|
35
|
+
tag_index.delete(tag);
|
|
36
|
+
const evicted = [];
|
|
37
|
+
for (const key of set) if (entries.delete(key)) evicted.push(key);
|
|
38
|
+
return evicted;
|
|
39
|
+
},
|
|
40
|
+
async size() {
|
|
41
|
+
entries.sweep(Date.now());
|
|
42
|
+
return entries.size;
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export { memory_store };
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { RequestEvent } from "@sveltejs/kit";
|
|
2
|
+
export interface Observation {
|
|
3
|
+
/** First personalization read that returned a NON-default value, or null — the verdict input.
|
|
4
|
+
* Named (`cookie:consent`, `header:accept-language`, `locals.user`) for the dev note. It IS the
|
|
5
|
+
* request's `perVisitor` fact: a flag read or a streamed promise lands there too. */
|
|
6
|
+
readonly disqualified_by: string | null;
|
|
7
|
+
/** The render (or the app) wrote a cookie — always per-request. */
|
|
8
|
+
wrote_cookie: boolean;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Patch `event.cookies` / `event.locals` / `event.request.headers` in place, recording reads.
|
|
12
|
+
* Returns the live observation the verdict reads after the render. Patching is per-request
|
|
13
|
+
* (the event dies with the request) — nothing to restore.
|
|
14
|
+
*/
|
|
15
|
+
export declare function observe_event(event: RequestEvent, facts?: {
|
|
16
|
+
perVisitor: string | null;
|
|
17
|
+
}): Observation;
|
package/dist/observe.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
// src/observe.ts
|
|
2
|
+
/** Personalization-bearing request headers: reading one during an eligible render disqualifies
|
|
3
|
+
* the page. Everything else (host, sec-fetch-*, accept-encoding, …) is delivery plumbing. */
|
|
4
|
+
const DISQUALIFYING_HEADERS = /* @__PURE__ */ new Set([
|
|
5
|
+
"cookie",
|
|
6
|
+
"authorization",
|
|
7
|
+
"accept-language",
|
|
8
|
+
"user-agent",
|
|
9
|
+
"referer",
|
|
10
|
+
"x-user",
|
|
11
|
+
"x-user-id",
|
|
12
|
+
"x-session",
|
|
13
|
+
"x-session-id"
|
|
14
|
+
]);
|
|
15
|
+
/** Default-valued reads still store: undefined/null/''/false, empty plain object, empty array. */
|
|
16
|
+
function is_default_value(value) {
|
|
17
|
+
if (value === void 0 || value === null || value === "" || value === false) return true;
|
|
18
|
+
if (Array.isArray(value)) return value.length === 0;
|
|
19
|
+
if (typeof value === "object") {
|
|
20
|
+
const proto = Object.getPrototypeOf(value);
|
|
21
|
+
if (proto === Object.prototype || proto === null) return Object.keys(value).length === 0;
|
|
22
|
+
}
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Patch `event.cookies` / `event.locals` / `event.request.headers` in place, recording reads.
|
|
27
|
+
* Returns the live observation the verdict reads after the render. Patching is per-request
|
|
28
|
+
* (the event dies with the request) — nothing to restore.
|
|
29
|
+
*/
|
|
30
|
+
function observe_event(event, facts = { perVisitor: null }) {
|
|
31
|
+
const obs = {
|
|
32
|
+
get disqualified_by() {
|
|
33
|
+
return facts.perVisitor;
|
|
34
|
+
},
|
|
35
|
+
wrote_cookie: false
|
|
36
|
+
};
|
|
37
|
+
const disqualify = (label) => {
|
|
38
|
+
if (facts.perVisitor === null) facts.perVisitor = label;
|
|
39
|
+
};
|
|
40
|
+
const cookies = event.cookies;
|
|
41
|
+
const orig_get = cookies.get.bind(cookies);
|
|
42
|
+
const orig_get_all = cookies.getAll.bind(cookies);
|
|
43
|
+
const orig_set = cookies.set.bind(cookies);
|
|
44
|
+
const orig_delete = cookies.delete.bind(cookies);
|
|
45
|
+
cookies.get = ((name, opts) => {
|
|
46
|
+
const value = orig_get(name, opts);
|
|
47
|
+
if (!is_default_value(value)) disqualify(`cookie:${name}`);
|
|
48
|
+
return value;
|
|
49
|
+
});
|
|
50
|
+
cookies.getAll = ((opts) => {
|
|
51
|
+
const all = orig_get_all(opts);
|
|
52
|
+
if (all.length > 0) disqualify("cookies.getAll");
|
|
53
|
+
return all;
|
|
54
|
+
});
|
|
55
|
+
cookies.set = ((...args) => {
|
|
56
|
+
obs.wrote_cookie = true;
|
|
57
|
+
return orig_set(...args);
|
|
58
|
+
});
|
|
59
|
+
cookies.delete = ((...args) => {
|
|
60
|
+
obs.wrote_cookie = true;
|
|
61
|
+
return orig_delete(...args);
|
|
62
|
+
});
|
|
63
|
+
const headers = event.request.headers;
|
|
64
|
+
const orig_header_get = headers.get.bind(headers);
|
|
65
|
+
headers.get = ((name) => {
|
|
66
|
+
const value = orig_header_get(name);
|
|
67
|
+
if (value !== null && DISQUALIFYING_HEADERS.has(name.toLowerCase())) disqualify(`header:${name.toLowerCase()}`);
|
|
68
|
+
return value;
|
|
69
|
+
});
|
|
70
|
+
event.locals = new Proxy(event.locals, { get(target, prop, receiver) {
|
|
71
|
+
const value = Reflect.get(target, prop, receiver);
|
|
72
|
+
if (typeof prop === "string" && !is_default_value(value) && typeof value !== "function") disqualify(`locals.${prop}`);
|
|
73
|
+
return value;
|
|
74
|
+
} });
|
|
75
|
+
return obs;
|
|
76
|
+
}
|
|
77
|
+
export { observe_event };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { EdgeAdapter, PostrenderEntry, PostrenderHandleOptions, PostrenderPutOptions, PostrenderStore } from "./types.js";
|
|
2
|
+
import { RequestEvent } from "@sveltejs/kit";
|
|
3
|
+
/** One server's live settings: what its `postrender.handle({ store, edge })` was given. */
|
|
4
|
+
export interface Runtime {
|
|
5
|
+
readonly store: PostrenderStore;
|
|
6
|
+
readonly edges: readonly EdgeAdapter[];
|
|
7
|
+
}
|
|
8
|
+
/** `postrender.handle(options)`'s first half: make these settings this server's runtime. */
|
|
9
|
+
export declare function install(options: PostrenderHandleOptions): Runtime;
|
|
10
|
+
/** The handle's per-request half: this request came through it, with these settings. */
|
|
11
|
+
export declare function mark_handled(event: RequestEvent, runtime: Runtime): void;
|
|
12
|
+
/** The runtime of the `postrender.handle()` that saw this request first, or null. */
|
|
13
|
+
export declare function handled_runtime(event: RequestEvent): Runtime | null;
|
|
14
|
+
/** The latest `postrender.handle()` made in this process, or null when hooks.server.ts has none. */
|
|
15
|
+
export declare function installed_runtime(): Runtime | null;
|
|
16
|
+
/** This server's runtime: its handle's, else the memory default. */
|
|
17
|
+
export declare function current_runtime(): Runtime;
|
|
18
|
+
/** Harness/test escape hatch: no handle made, a fresh memory default. */
|
|
19
|
+
export declare function reset_for_tests(): void;
|
|
20
|
+
/** Evict every stored page carrying ANY of `tags` (origin + every edge). The receiving half of a
|
|
21
|
+
* thaw notice; also what `invalidate(fn, args)` does for one receipt tag. */
|
|
22
|
+
export declare function invalidate_tags(tags: readonly string[], runtime?: Runtime): Promise<string[]>;
|
|
23
|
+
export declare function store_get(runtime: Runtime, key: string): Promise<PostrenderEntry | null>;
|
|
24
|
+
export declare function store_put(runtime: Runtime, key: string, entry: PostrenderEntry, options: PostrenderPutOptions): Promise<void>;
|
|
25
|
+
export type FlightOutcome = {
|
|
26
|
+
stored: PostrenderEntry | null;
|
|
27
|
+
};
|
|
28
|
+
export declare function join_flight(key: string): Promise<FlightOutcome> | null;
|
|
29
|
+
export declare function begin_flight(key: string): (outcome: FlightOutcome) => void;
|
|
30
|
+
/** A function stamped by the `import.meta.og.source` macro (core's data sources). */
|
|
31
|
+
type SourceFn = (...args: never[]) => unknown;
|
|
32
|
+
/**
|
|
33
|
+
* Evict everywhere — two shapes:
|
|
34
|
+
* `invalidate('/fr/fr/solar/')` exact URL (the v1 keying law: publish payloads carry it)
|
|
35
|
+
* `invalidate(loadContent, [args])` og.source PRECISION: the reverse index answers which
|
|
36
|
+
* stored pages consumed `(source, args)` — those exact
|
|
37
|
+
* URLs are evicted at origin AND purged at every edge.
|
|
38
|
+
* Reaches the store and edges `postrender.handle()` was given in hooks.server.ts.
|
|
39
|
+
*/
|
|
40
|
+
export declare function invalidate(target: string | SourceFn, args?: unknown[]): Promise<void>;
|
|
41
|
+
/** Bulk eviction by URL subtree — `{ prefix: '/fr/fr/' }` is a locale nuke, `{ prefix: '/docs' }`
|
|
42
|
+
* a section nuke. One origin scan + one purge per edge (Akamai: prefix tag; CloudFront: wildcard;
|
|
43
|
+
* Cloudflare: prefix purge). */
|
|
44
|
+
export declare function invalidateWhere(filter: {
|
|
45
|
+
prefix: string;
|
|
46
|
+
}): Promise<void>;
|
|
47
|
+
/** Action self-evict: a successful non-GET on a page URL evicts that URL (origin only — the
|
|
48
|
+
* edge copy follows via its s-maxage or the app's explicit invalidate; fire-and-forget). */
|
|
49
|
+
export declare function self_evict(runtime: Runtime, pathname: string): void;
|
|
50
|
+
export {};
|
package/dist/registry.js
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { memory_store } from "./memory-store.js";
|
|
2
|
+
import { normalize_prefix } from "./key.js";
|
|
3
|
+
import { postrender_app } from "./app.js";
|
|
4
|
+
import { sourceTag } from "@ogygia/core/plugin/utils";
|
|
5
|
+
// src/registry.ts
|
|
6
|
+
const slot = globalThis[Symbol.for("ogygia.postrender.v1")] ??= {
|
|
7
|
+
installed: null,
|
|
8
|
+
handled: /* @__PURE__ */ new WeakMap(),
|
|
9
|
+
fallback: null
|
|
10
|
+
};
|
|
11
|
+
/** A server event into the current request's devtools stream (a no-op unless devtools is on). */
|
|
12
|
+
function record(event) {
|
|
13
|
+
postrender_app()?.devtools(event);
|
|
14
|
+
}
|
|
15
|
+
let warned_replica_blindspot = false;
|
|
16
|
+
/** `postrender.handle(options)`'s first half: make these settings this server's runtime. */
|
|
17
|
+
function install(options) {
|
|
18
|
+
const edges = [...options.edge ?? []];
|
|
19
|
+
if (edges.length && !options.store && !warned_replica_blindspot) {
|
|
20
|
+
warned_replica_blindspot = true;
|
|
21
|
+
console.warn("[ogygia] postrender: edge adapters are configured but the store is the per-instance memory default — invalidations cannot reach other replicas. Use a shared store (valkey / upstash / cloudflareKv) in multi-instance deploys.");
|
|
22
|
+
}
|
|
23
|
+
const runtime = {
|
|
24
|
+
store: options.store ?? memory_store(),
|
|
25
|
+
edges
|
|
26
|
+
};
|
|
27
|
+
slot.installed = runtime;
|
|
28
|
+
return runtime;
|
|
29
|
+
}
|
|
30
|
+
/** The handle's per-request half: this request came through it, with these settings. */
|
|
31
|
+
function mark_handled(event, runtime) {
|
|
32
|
+
slot.handled.set(event.request, runtime);
|
|
33
|
+
}
|
|
34
|
+
/** The runtime of the `postrender.handle()` that saw this request first, or null. */
|
|
35
|
+
function handled_runtime(event) {
|
|
36
|
+
return slot.handled.get(event.request) ?? null;
|
|
37
|
+
}
|
|
38
|
+
/** The latest `postrender.handle()` made in this process, or null when hooks.server.ts has none. */
|
|
39
|
+
function installed_runtime() {
|
|
40
|
+
return slot.installed;
|
|
41
|
+
}
|
|
42
|
+
/** This server's runtime: its handle's, else the memory default. */
|
|
43
|
+
function current_runtime() {
|
|
44
|
+
return slot.installed ?? (slot.fallback ??= {
|
|
45
|
+
store: memory_store(),
|
|
46
|
+
edges: []
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
/** Harness/test escape hatch: no handle made, a fresh memory default. */
|
|
50
|
+
function reset_for_tests() {
|
|
51
|
+
slot.installed = null;
|
|
52
|
+
slot.handled = /* @__PURE__ */ new WeakMap();
|
|
53
|
+
slot.fallback = null;
|
|
54
|
+
warned_replica_blindspot = false;
|
|
55
|
+
}
|
|
56
|
+
function notify_thaw(tags) {
|
|
57
|
+
postrender_app()?.notify.invalidated(tags);
|
|
58
|
+
}
|
|
59
|
+
/** Evict every stored page carrying ANY of `tags` (origin + every edge). The receiving half of a
|
|
60
|
+
* thaw notice; also what `invalidate(fn, args)` does for one receipt tag. */
|
|
61
|
+
async function invalidate_tags(tags, runtime = current_runtime()) {
|
|
62
|
+
const { store, edges } = runtime;
|
|
63
|
+
const evict_by_tag = store.evictByTag?.bind(store);
|
|
64
|
+
if (!evict_by_tag) {
|
|
65
|
+
console.warn("[ogygia] postrender: the configured store has no evictByTag — tag invalidation needs it (memory/valkey/upstash/cloudflareKv all provide it).");
|
|
66
|
+
return [];
|
|
67
|
+
}
|
|
68
|
+
const keys = /* @__PURE__ */ new Set();
|
|
69
|
+
for (const tag of tags) try {
|
|
70
|
+
for (const key of await evict_by_tag(tag)) keys.add(key);
|
|
71
|
+
} catch (e) {
|
|
72
|
+
console.warn(`[ogygia] postrender.invalidate(tags): the store failed to evict tag ${tag} (evictByTag); its pages stay stored until they expire —`, e);
|
|
73
|
+
}
|
|
74
|
+
const jobs = [];
|
|
75
|
+
for (const key of keys) for (const edge of edges) jobs.push(edge_job(edge, (e) => e.purgeUrl(key)));
|
|
76
|
+
await settle_all("invalidate(tags)", jobs);
|
|
77
|
+
return [...keys];
|
|
78
|
+
}
|
|
79
|
+
async function store_get(runtime, key) {
|
|
80
|
+
try {
|
|
81
|
+
return await runtime.store.get(key);
|
|
82
|
+
} catch {
|
|
83
|
+
return null;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
async function store_put(runtime, key, entry, options) {
|
|
87
|
+
try {
|
|
88
|
+
await runtime.store.put(key, entry, options);
|
|
89
|
+
} catch {}
|
|
90
|
+
}
|
|
91
|
+
const inflight = /* @__PURE__ */ new Map();
|
|
92
|
+
function join_flight(key) {
|
|
93
|
+
return inflight.get(key) ?? null;
|
|
94
|
+
}
|
|
95
|
+
function begin_flight(key) {
|
|
96
|
+
let settle;
|
|
97
|
+
const flight = new Promise((res) => {
|
|
98
|
+
settle = res;
|
|
99
|
+
});
|
|
100
|
+
inflight.set(key, flight);
|
|
101
|
+
return (outcome) => {
|
|
102
|
+
inflight.delete(key);
|
|
103
|
+
settle(outcome);
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
/** A call as a promise, a synchronous throw included. */
|
|
107
|
+
const attempt = (call) => Promise.resolve().then(call);
|
|
108
|
+
const store_job = (op, call) => ({
|
|
109
|
+
what: `the store failed to ${op}`,
|
|
110
|
+
run: attempt(call)
|
|
111
|
+
});
|
|
112
|
+
const edge_job = (edge, call) => ({
|
|
113
|
+
what: `the purge at edge "${edge.name}" failed`,
|
|
114
|
+
run: attempt(() => call(edge))
|
|
115
|
+
});
|
|
116
|
+
async function settle_all(label, jobs) {
|
|
117
|
+
(await Promise.allSettled(jobs.map((job) => job.run))).forEach((r, i) => {
|
|
118
|
+
if (r.status === "rejected") console.warn(`[ogygia] postrender.${label}: ${jobs[i].what} —`, r.reason);
|
|
119
|
+
});
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* Evict everywhere — two shapes:
|
|
123
|
+
* `invalidate('/fr/fr/solar/')` exact URL (the v1 keying law: publish payloads carry it)
|
|
124
|
+
* `invalidate(loadContent, [args])` og.source PRECISION: the reverse index answers which
|
|
125
|
+
* stored pages consumed `(source, args)` — those exact
|
|
126
|
+
* URLs are evicted at origin AND purged at every edge.
|
|
127
|
+
* Reaches the store and edges `postrender.handle()` was given in hooks.server.ts.
|
|
128
|
+
*/
|
|
129
|
+
async function invalidate(target, args) {
|
|
130
|
+
if (typeof target === "string") {
|
|
131
|
+
record({
|
|
132
|
+
domain: "server",
|
|
133
|
+
name: "server.postrender",
|
|
134
|
+
op: "invalidate",
|
|
135
|
+
url: target
|
|
136
|
+
});
|
|
137
|
+
const { store, edges } = current_runtime();
|
|
138
|
+
const jobs = [store_job(`evict ${target}`, () => store.evict(target))];
|
|
139
|
+
for (const edge of edges) jobs.push(edge_job(edge, (e) => e.purgeUrl(target)));
|
|
140
|
+
await settle_all("invalidate", jobs);
|
|
141
|
+
notify_thaw([`p:${target}`]);
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
const tag = sourceTag(target, args ?? []);
|
|
145
|
+
if (!tag) throw new Error("[ogygia] postrender.invalidate(fn, args): the function is not a declared source — wrap its definition: `export const fn = import.meta.og.source(async (…) => …)`.");
|
|
146
|
+
await invalidate_tags([tag]);
|
|
147
|
+
notify_thaw([tag]);
|
|
148
|
+
}
|
|
149
|
+
/** Bulk eviction by URL subtree — `{ prefix: '/fr/fr/' }` is a locale nuke, `{ prefix: '/docs' }`
|
|
150
|
+
* a section nuke. One origin scan + one purge per edge (Akamai: prefix tag; CloudFront: wildcard;
|
|
151
|
+
* Cloudflare: prefix purge). */
|
|
152
|
+
async function invalidateWhere(filter) {
|
|
153
|
+
const prefix = normalize_prefix(filter.prefix);
|
|
154
|
+
record({
|
|
155
|
+
domain: "server",
|
|
156
|
+
name: "server.postrender",
|
|
157
|
+
op: "invalidate-where",
|
|
158
|
+
url: prefix
|
|
159
|
+
});
|
|
160
|
+
const { store, edges } = current_runtime();
|
|
161
|
+
const jobs = [store_job(`evict prefix ${prefix}`, () => store.evictWhere({ prefix }))];
|
|
162
|
+
for (const edge of edges) jobs.push(edge_job(edge, (e) => e.purgeWhere({ prefix })));
|
|
163
|
+
await settle_all("invalidateWhere", jobs);
|
|
164
|
+
notify_thaw("all");
|
|
165
|
+
}
|
|
166
|
+
/** Action self-evict: a successful non-GET on a page URL evicts that URL (origin only — the
|
|
167
|
+
* edge copy follows via its s-maxage or the app's explicit invalidate; fire-and-forget). */
|
|
168
|
+
function self_evict(runtime, pathname) {
|
|
169
|
+
record({
|
|
170
|
+
domain: "server",
|
|
171
|
+
name: "server.postrender",
|
|
172
|
+
op: "self-evict",
|
|
173
|
+
url: pathname
|
|
174
|
+
});
|
|
175
|
+
runtime.store.evict(pathname).catch(() => {});
|
|
176
|
+
}
|
|
177
|
+
export { begin_flight, current_runtime, handled_runtime, install, installed_runtime, invalidate, invalidateWhere, invalidate_tags, join_flight, mark_handled, reset_for_tests, self_evict, store_get, store_put };
|
package/dist/server.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { FlightOutcome, Runtime } from "./registry.js";
|
|
2
|
+
import { Observation } from "./observe.js";
|
|
3
|
+
import { PostrenderEntry } from "./types.js";
|
|
4
|
+
import { ServerPlugin } from "@ogygia/core/plugin";
|
|
5
|
+
/** The plugin's serializable policy (`postrender({ ttl, default })`, normalized by the factory). */
|
|
6
|
+
export interface PostrenderServerOptions {
|
|
7
|
+
/** TTL backstop, seconds (clamped to [1, 86400]). */
|
|
8
|
+
ttl: number;
|
|
9
|
+
/** The app-wide opt-in: true = every eligible page (a route opts OUT with `export const config
|
|
10
|
+
* = { postrender: false }`); false = nothing unless a route opts IN. */
|
|
11
|
+
default: boolean;
|
|
12
|
+
}
|
|
13
|
+
interface State {
|
|
14
|
+
/** the store + edges this request reads and writes (its `postrender.handle()`'s) */
|
|
15
|
+
runtime: Runtime | null;
|
|
16
|
+
/** settles the stampede flight this request opened (null when it opened none) */
|
|
17
|
+
settle: ((outcome: FlightOutcome) => void) | null;
|
|
18
|
+
/** the personalization observation (eligible requests only) */
|
|
19
|
+
obs: Observation | null;
|
|
20
|
+
/** the request was eligible to be stored */
|
|
21
|
+
eligible: boolean;
|
|
22
|
+
}
|
|
23
|
+
export declare const MISSING_HANDLE: string;
|
|
24
|
+
export declare const MISORDERED_HANDLE: string;
|
|
25
|
+
/** Rebuild a Response from a stored page. `via` rides a debug header the harness asserts on.
|
|
26
|
+
* With the incoming `request`, a matching validator answers 304 — plain-HTTP conditional
|
|
27
|
+
* requests (RFC 9110), which is what makes a CDN or browser revalidation of a stored page cost
|
|
28
|
+
* zero body bytes. Validators live on the ENTRY, never in edge adapters: they are the render's
|
|
29
|
+
* identity, not a CDN dialect. */
|
|
30
|
+
export declare function postrender_response(entry: PostrenderEntry, via: "hit" | "join" | "stored", request?: Request): Response;
|
|
31
|
+
declare const server: ServerPlugin<PostrenderServerOptions, State>;
|
|
32
|
+
export { server as default };
|