@certrev/cert-block 1.2.0-canary.7 → 1.2.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 (33) hide show
  1. package/CHANGELOG.md +120 -63
  2. package/README.md +116 -21
  3. package/dist/builder/card-reader-css.d.ts +14 -0
  4. package/dist/builder/card-reader-css.d.ts.map +1 -0
  5. package/dist/builder/card-reader-css.js +17 -0
  6. package/dist/builder/card-reader-css.js.map +1 -0
  7. package/dist/builder/cert-review-card.d.ts +8 -0
  8. package/dist/builder/cert-review-card.d.ts.map +1 -1
  9. package/dist/builder/cert-review-card.js +234 -41
  10. package/dist/builder/cert-review-card.js.map +1 -1
  11. package/dist/builder/delivery-runtime.d.ts +15 -1
  12. package/dist/builder/delivery-runtime.d.ts.map +1 -1
  13. package/dist/builder/delivery-runtime.js +31 -3
  14. package/dist/builder/delivery-runtime.js.map +1 -1
  15. package/dist/builder/ssr-seed.d.ts +155 -0
  16. package/dist/builder/ssr-seed.d.ts.map +1 -0
  17. package/dist/builder/ssr-seed.js +278 -0
  18. package/dist/builder/ssr-seed.js.map +1 -0
  19. package/dist/verify/cache.d.ts +39 -2
  20. package/dist/verify/cache.d.ts.map +1 -1
  21. package/dist/verify/cache.js +61 -12
  22. package/dist/verify/cache.js.map +1 -1
  23. package/dist/verify/get-verified-delivery.d.ts +28 -3
  24. package/dist/verify/get-verified-delivery.d.ts.map +1 -1
  25. package/dist/verify/get-verified-delivery.js +46 -9
  26. package/dist/verify/get-verified-delivery.js.map +1 -1
  27. package/package.json +112 -112
  28. package/src/builder/card-reader-css.ts +19 -0
  29. package/src/builder/cert-review-card.tsx +308 -56
  30. package/src/builder/delivery-runtime.ts +33 -3
  31. package/src/builder/ssr-seed.ts +343 -0
  32. package/src/verify/cache.ts +87 -11
  33. package/src/verify/get-verified-delivery.ts +77 -11
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The server render's envelope seed (1.2.0): what lets a hydrated delivery card paint with NO browser read.
3
+ *
4
+ * Through 1.1.1 the browser re-read the Delivery API for every card it hydrated, because nothing handed the server's
5
+ * read to it. A storefront whose Content-Security-Policy `connect-src` does not name the CertREV origin (e.l.f.'s
6
+ * Hydrogen store is one) blocked that read, the read settled as a suppress, and the card the server had painted
7
+ * vanished. So the painted face now carries the envelope it was painted from, as one attribute on its wrapper:
8
+ * `data-certrev-envelope` = `{ v: 1, baseUrl, externalId, design?, payload, signature?, renderDef }`. `payload` is the
9
+ * signed envelope's payload as the Delivery API served it, less the fields the def hides (below); `renderDef` is the
10
+ * def the face was painted with; `design` is the design pin the read was made with (the canary replica's `?design=N`),
11
+ * present only on a pinned read. React escapes the attribute like any other, so no `<script>` and no CSP `script-src`
12
+ * are involved.
13
+ *
14
+ * HIDDEN FIELDS ARE ABSENT FROM THE PAGE, NOT JUST FROM THE FACE. A def's `hidden` set (`reviewerPhoto`, `memo`) is the
15
+ * brand's statement that the page does not show those fields; a seed that carried them would put the reviewer's photo
16
+ * URL or the memo text in the page source all the same. So `withoutHiddenContent` removes them from the payload
17
+ * BEFORE the card paints and before it serializes, and both the server's face and the browser's are painted from the
18
+ * stripped payload (so they are identical, and a hidden memo is not on the page in either place):
19
+ * - `reviewerPhoto` hides `content.expert.photoUrl` and the author's `content.author.photoUrl` (the reader face paints
20
+ * the author's photo under the same switch);
21
+ * - `memo` hides `content.memo`.
22
+ * `display.showExpertPhoto: false` is the payload's own switch for the same photos and is stripped the same way (the
23
+ * portal never writes the URL for it either): both photo URLs go, as for `reviewerPhoto`, whatever the def hides.
24
+ * `content.expert.compensationCue` is NEVER touched: the cue is a locked disclosure no def can hide, and the face
25
+ * paints "Compensated expert" from it in the banner, the memo and the sidebar (the floating pill's own markup has
26
+ * no disclosure line, as in the portal's snippets; its modal paints the cue from the same field).
27
+ *
28
+ * THE SIGNATURE IS LEFT OUT WHENEVER ANYTHING WAS STRIPPED. The signature signs the full payload, so a payload with a
29
+ * field removed no longer verifies against it, and a seed that carried both would hand a verifier a pair that fails.
30
+ * Leaving it out costs nothing: the browser never re-checks a seed's signature (next paragraph), it re-runs only
31
+ * `renderVerdict` (lifecycle and subject) at its own clock, and neither reads a field the strip removes. A seed whose
32
+ * payload was not stripped keeps the signature, so a verifier can still check the page's HTML against the issuer key.
33
+ *
34
+ * The browser trusts a seed as far as it trusts the server HTML the seed sits in: whoever can write that HTML can
35
+ * already write any card they like, so the signature is NOT re-verified here (which would make hydration async, and
36
+ * Ed25519 in WebCrypto is not in every browser). The client still re-runs the lifecycle and subject policy
37
+ * (`renderVerdict`) at its own clock once hydration is done; `cert-review-card.tsx` does that.
38
+ *
39
+ * A PINNED CARD TAKES ONLY A SEED WITH THE SAME PIN (and an unpinned card only an unpinned one): the pin is part of
40
+ * the seed's key, as it is part of the read's, so the canary replica's `?design=7` card never paints the design the
41
+ * page carried for another version.
42
+ *
43
+ * WHEN THE SERVER HAD NO ENVELOPE TO PAINT (1.2.0) the same attribute carries a fallback record instead of a seed:
44
+ * `{ v: 1, baseUrl, externalId, design?, face }`, where `face` is `'options'` (CertREV could not be reached, so the
45
+ * server painted the block's own options face) or `'none'` (the server painted nothing: revoked, expired, unverifiable,
46
+ * for another entry). A browser that renders the card again (hydration, or React's client re-render after a hydration
47
+ * error elsewhere on the page) paints what the record says, so it neither reads the Delivery API nor shows a card the
48
+ * server withheld. A record holds no payload, so `parseSeed` never takes one for a seed. A `'none'` record sits on a
49
+ * `hidden` element with nothing in it.
50
+ *
51
+ * React-free and browser-only in effect: with no `document` (a server) `pageSeedFor` finds nothing, so a server never
52
+ * reads or keeps a seed and a multi-tenant render process holds nothing per page.
53
+ */
54
+ import type { CertPayload, CertSignature } from '../contract/kernel.js';
55
+ import { type DesignPin } from '../verify/get-verified-delivery.js';
56
+ import type { CertChromeRenderDef } from './cert-chrome-data.js';
57
+ export declare const SEED_ATTRIBUTE = "data-certrev-envelope";
58
+ export interface DeliverySeed {
59
+ readonly baseUrl: string;
60
+ readonly externalId: string;
61
+ /** The design pin the read was made with; absent on an unpinned read (every production brand). */
62
+ readonly design?: DesignPin;
63
+ /** The payload as painted: with every field the def hides removed (`withoutHiddenContent`). */
64
+ readonly payload: CertPayload;
65
+ /**
66
+ * The envelope's signature as served; absent when the payload was stripped (it no longer verifies), and when a
67
+ * cache was filled by hand (a test, a custom cache).
68
+ */
69
+ readonly signature?: CertSignature;
70
+ readonly renderDef: CertChromeRenderDef | null;
71
+ }
72
+ /** A seed as read from the page: the parsed seed and the attribute's exact text (re-rendered verbatim on hydration). */
73
+ export interface PageSeed {
74
+ readonly seed: DeliverySeed;
75
+ readonly raw: string;
76
+ }
77
+ /** What the server painted with no verified envelope: the block's options face, or nothing. */
78
+ export type FallbackFace = 'options' | 'none';
79
+ /** The record a server writes where it had no envelope to paint (the file header). */
80
+ export interface DeliveryFallback {
81
+ readonly baseUrl: string;
82
+ readonly externalId: string;
83
+ readonly design?: DesignPin;
84
+ readonly face: FallbackFace;
85
+ }
86
+ /** A fallback record as read from the page, with the attribute's exact text. */
87
+ export interface PageFallback {
88
+ readonly fallback: DeliveryFallback;
89
+ readonly raw: string;
90
+ }
91
+ /** Whatever the server wrote for one placement: a seed or a fallback record. */
92
+ export type PageRecord = PageSeed | PageFallback;
93
+ /**
94
+ * The payload with the named people's photo URLs removed (`null`); the same object when neither had one. The card uses
95
+ * it for a photo the browser could not load (a brand's CSP `img-src`, a 404), so the face repaints with the initials.
96
+ */
97
+ export declare function withoutPhotos(payload: CertPayload, people: readonly ('expert' | 'author')[]): CertPayload;
98
+ /**
99
+ * The payload with every content field the def's `hidden` set controls removed, and whether anything was; the two
100
+ * photo URLs go as well when the payload's own `display.showExpertPhoto` is `false` (exactly `false`, as the reader
101
+ * face reads it: absent or `null` shows the photo).
102
+ *
103
+ * Only the ids in `HIDEABLE_FIELDS` count (a def may list others; the faces ignore them, so they hide nothing). A
104
+ * removed text field becomes `null`, so the content keeps the shape the contract types give it and every face reads it
105
+ * as absent. Nothing but those fields changes: the subject and lifecycle (what `renderVerdict` reads), the cue, the
106
+ * dates, the links and the names are the payload's own. Never throws on a hostile shape: a payload whose `expert` or
107
+ * `author` is not an object has no photo to strip.
108
+ */
109
+ export declare function withoutHiddenContent(payload: CertPayload, renderDef: CertChromeRenderDef | null): {
110
+ readonly payload: CertPayload;
111
+ readonly stripped: boolean;
112
+ };
113
+ /**
114
+ * The seed for a verified read: the payload stripped of what the def hides, and the signature only when nothing was
115
+ * stripped. The card paints from this seed's payload, on the server and in the browser alike.
116
+ */
117
+ export declare function seedFor(read: {
118
+ readonly baseUrl: string;
119
+ readonly externalId: string;
120
+ readonly design?: DesignPin;
121
+ readonly payload: CertPayload;
122
+ readonly signature?: CertSignature;
123
+ readonly renderDef: CertChromeRenderDef | null;
124
+ }): DeliverySeed;
125
+ export declare function serializeSeed(seed: DeliverySeed): string;
126
+ export declare function serializeFallback(fallback: DeliveryFallback): string;
127
+ /** The seed in one attribute value, or null for anything that is not one (never throws). */
128
+ export declare function parseSeed(raw: string): DeliverySeed | null;
129
+ /** A fallback record in one attribute value, or null for anything that is not one (a seed included; never throws). */
130
+ export declare function parseFallback(raw: string): DeliveryFallback | null;
131
+ /**
132
+ * The record the server wrote for this placement and pin: its seed, or its fallback record. By default: from the map,
133
+ * else from one scan of the document (which also records every other one on the page). With `live`, the map is not
134
+ * consulted: the document is scanned and decides, so what a hydrating card learns is what the server HTML in front of
135
+ * it carries, not what an earlier page in this process left behind. `undefined` when the page carries none, and always
136
+ * on a server.
137
+ */
138
+ export declare function pageRecordFor(baseUrl: string, externalId: string, design?: DesignPin, options?: {
139
+ readonly live?: boolean;
140
+ }): PageRecord | undefined;
141
+ /** `pageRecordFor`, seeds only: the seed the server painted for this placement and pin. */
142
+ export declare function pageSeedFor(baseUrl: string, externalId: string, design?: DesignPin, options?: {
143
+ readonly live?: boolean;
144
+ }): PageSeed | undefined;
145
+ /**
146
+ * Whether the live document holds server-rendered React HTML: any Suspense boundary marker. The delivery card sits in
147
+ * a `<Suspense>` of its own, so a server render of one always leaves a marker, a card the server painted nothing for
148
+ * (revoked, expired, unreachable) included, and a client render never does. This is how a card that is hydrating tells
149
+ * a browser hydrating server HTML (the document holds it) from a server render that merely runs where a `document`
150
+ * exists (a test's jsdom, a shim): there the document does not hold the HTML being produced.
151
+ */
152
+ export declare function pageHoldsServerHtml(): boolean;
153
+ /** Test seam: forget every seed (a new page). */
154
+ export declare function forgetPageSeedsForTests(): void;
155
+ //# sourceMappingURL=ssr-seed.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ssr-seed.d.ts","sourceRoot":"","sources":["../../src/builder/ssr-seed.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoDG;AAGH,OAAO,KAAK,EAAe,WAAW,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAA;AACpF,OAAO,EAAE,KAAK,SAAS,EAAkC,MAAM,oCAAoC,CAAA;AACnG,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAA;AAEhE,eAAO,MAAM,cAAc,0BAA0B,CAAA;AAErD,MAAM,WAAW,YAAY;IAC5B,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;IAC3B,kGAAkG;IAClG,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,CAAA;IAC3B,+FAA+F;IAC/F,QAAQ,CAAC,OAAO,EAAE,WAAW,CAAA;IAC7B;;;OAGG;IACH,QAAQ,CAAC,SAAS,CAAC,EAAE,aAAa,CAAA;IAClC,QAAQ,CAAC,SAAS,EAAE,mBAAmB,GAAG,IAAI,CAAA;CAC9C;AAED,wHAAwH;AACxH,MAAM,WAAW,QAAQ;IACxB,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAA;IAC3B,QAAQ,CAAC,GAAG,EAAE,MAAM,CAAA;CACpB;AAED,+FAA+F;AAC/F,MAAM,MAAM,YAAY,GAAG,SAAS,GAAG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AAED,wBAAgB,iBAAiB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,MAAM,CAQpE;AAWD,4FAA4F;AAC5F,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,YAAY,GAAG,IAAI,CAwB1D;AAED,sHAAsH;AACtH,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,gBAAgB,GAAG,IAAI,CAclE;AAiCD;;;;;;GAMG;AACH,wBAAgB,aAAa,CAC5B,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,EAClB,MAAM,CAAC,EAAE,SAAS,EAClB,OAAO,GAAE;IAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAA;CAAO,GACvC,UAAU,GAAG,SAAS,CAaxB;AAED,2FAA2F;AAC3F,wBAAgB,WAAW,CAC1B,OAAO,EAAE,MAAM,EACf,UAAU,EAAE,MAAM,EAClB,MAAM,CAAC,EAAE,SAAS,EAClB,OAAO,GAAE;IAAE,QAAQ,CAAC,IAAI,CAAC,EAAE,OAAO,CAAA;CAAO,GACvC,QAAQ,GAAG,SAAS,CAGtB;AAKD;;;;;;GAMG;AACH,wBAAgB,mBAAmB,IAAI,OAAO,CAO7C;AAED,iDAAiD;AACjD,wBAAgB,uBAAuB,IAAI,IAAI,CAE9C"}
@@ -0,0 +1,278 @@
1
+ /**
2
+ * The server render's envelope seed (1.2.0): what lets a hydrated delivery card paint with NO browser read.
3
+ *
4
+ * Through 1.1.1 the browser re-read the Delivery API for every card it hydrated, because nothing handed the server's
5
+ * read to it. A storefront whose Content-Security-Policy `connect-src` does not name the CertREV origin (e.l.f.'s
6
+ * Hydrogen store is one) blocked that read, the read settled as a suppress, and the card the server had painted
7
+ * vanished. So the painted face now carries the envelope it was painted from, as one attribute on its wrapper:
8
+ * `data-certrev-envelope` = `{ v: 1, baseUrl, externalId, design?, payload, signature?, renderDef }`. `payload` is the
9
+ * signed envelope's payload as the Delivery API served it, less the fields the def hides (below); `renderDef` is the
10
+ * def the face was painted with; `design` is the design pin the read was made with (the canary replica's `?design=N`),
11
+ * present only on a pinned read. React escapes the attribute like any other, so no `<script>` and no CSP `script-src`
12
+ * are involved.
13
+ *
14
+ * HIDDEN FIELDS ARE ABSENT FROM THE PAGE, NOT JUST FROM THE FACE. A def's `hidden` set (`reviewerPhoto`, `memo`) is the
15
+ * brand's statement that the page does not show those fields; a seed that carried them would put the reviewer's photo
16
+ * URL or the memo text in the page source all the same. So `withoutHiddenContent` removes them from the payload
17
+ * BEFORE the card paints and before it serializes, and both the server's face and the browser's are painted from the
18
+ * stripped payload (so they are identical, and a hidden memo is not on the page in either place):
19
+ * - `reviewerPhoto` hides `content.expert.photoUrl` and the author's `content.author.photoUrl` (the reader face paints
20
+ * the author's photo under the same switch);
21
+ * - `memo` hides `content.memo`.
22
+ * `display.showExpertPhoto: false` is the payload's own switch for the same photos and is stripped the same way (the
23
+ * portal never writes the URL for it either): both photo URLs go, as for `reviewerPhoto`, whatever the def hides.
24
+ * `content.expert.compensationCue` is NEVER touched: the cue is a locked disclosure no def can hide, and the face
25
+ * paints "Compensated expert" from it in the banner, the memo and the sidebar (the floating pill's own markup has
26
+ * no disclosure line, as in the portal's snippets; its modal paints the cue from the same field).
27
+ *
28
+ * THE SIGNATURE IS LEFT OUT WHENEVER ANYTHING WAS STRIPPED. The signature signs the full payload, so a payload with a
29
+ * field removed no longer verifies against it, and a seed that carried both would hand a verifier a pair that fails.
30
+ * Leaving it out costs nothing: the browser never re-checks a seed's signature (next paragraph), it re-runs only
31
+ * `renderVerdict` (lifecycle and subject) at its own clock, and neither reads a field the strip removes. A seed whose
32
+ * payload was not stripped keeps the signature, so a verifier can still check the page's HTML against the issuer key.
33
+ *
34
+ * The browser trusts a seed as far as it trusts the server HTML the seed sits in: whoever can write that HTML can
35
+ * already write any card they like, so the signature is NOT re-verified here (which would make hydration async, and
36
+ * Ed25519 in WebCrypto is not in every browser). The client still re-runs the lifecycle and subject policy
37
+ * (`renderVerdict`) at its own clock once hydration is done; `cert-review-card.tsx` does that.
38
+ *
39
+ * A PINNED CARD TAKES ONLY A SEED WITH THE SAME PIN (and an unpinned card only an unpinned one): the pin is part of
40
+ * the seed's key, as it is part of the read's, so the canary replica's `?design=7` card never paints the design the
41
+ * page carried for another version.
42
+ *
43
+ * WHEN THE SERVER HAD NO ENVELOPE TO PAINT (1.2.0) the same attribute carries a fallback record instead of a seed:
44
+ * `{ v: 1, baseUrl, externalId, design?, face }`, where `face` is `'options'` (CertREV could not be reached, so the
45
+ * server painted the block's own options face) or `'none'` (the server painted nothing: revoked, expired, unverifiable,
46
+ * for another entry). A browser that renders the card again (hydration, or React's client re-render after a hydration
47
+ * error elsewhere on the page) paints what the record says, so it neither reads the Delivery API nor shows a card the
48
+ * server withheld. A record holds no payload, so `parseSeed` never takes one for a seed. A `'none'` record sits on a
49
+ * `hidden` element with nothing in it.
50
+ *
51
+ * React-free and browser-only in effect: with no `document` (a server) `pageSeedFor` finds nothing, so a server never
52
+ * reads or keeps a seed and a multi-tenant render process holds nothing per page.
53
+ */
54
+ import { HIDEABLE_FIELDS } from '../components/render-def.js';
55
+ import { parseDesignPin, parseRenderDef } from '../verify/get-verified-delivery.js';
56
+ export const SEED_ATTRIBUTE = 'data-certrev-envelope';
57
+ const isRecord = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
58
+ /** A value worth hiding: anything but nothing (absent, null, the empty string). */
59
+ const hasValue = (v) => v !== undefined && v !== null && v !== '';
60
+ /**
61
+ * The payload with the named people's photo URLs removed (`null`); the same object when neither had one. The card uses
62
+ * it for a photo the browser could not load (a brand's CSP `img-src`, a 404), so the face repaints with the initials.
63
+ */
64
+ export function withoutPhotos(payload, people) {
65
+ let content = { ...payload.content };
66
+ let stripped = false;
67
+ for (const person of people) {
68
+ const fields = content[person];
69
+ if (isRecord(fields) && hasValue(fields.photoUrl)) {
70
+ content = { ...content, [person]: { ...fields, photoUrl: null } };
71
+ stripped = true;
72
+ }
73
+ }
74
+ return stripped ? { ...payload, content: content } : payload;
75
+ }
76
+ /**
77
+ * The payload with every content field the def's `hidden` set controls removed, and whether anything was; the two
78
+ * photo URLs go as well when the payload's own `display.showExpertPhoto` is `false` (exactly `false`, as the reader
79
+ * face reads it: absent or `null` shows the photo).
80
+ *
81
+ * Only the ids in `HIDEABLE_FIELDS` count (a def may list others; the faces ignore them, so they hide nothing). A
82
+ * removed text field becomes `null`, so the content keeps the shape the contract types give it and every face reads it
83
+ * as absent. Nothing but those fields changes: the subject and lifecycle (what `renderVerdict` reads), the cue, the
84
+ * dates, the links and the names are the payload's own. Never throws on a hostile shape: a payload whose `expert` or
85
+ * `author` is not an object has no photo to strip.
86
+ */
87
+ export function withoutHiddenContent(payload, renderDef) {
88
+ const hidden = (renderDef?.hidden ?? []).filter((id) => HIDEABLE_FIELDS.includes(id));
89
+ const display = payload.content?.display;
90
+ const photoOff = isRecord(display) && display.showExpertPhoto === false;
91
+ if (hidden.length === 0 && !photoOff)
92
+ return { payload, stripped: false };
93
+ let next = photoOff || hidden.includes('reviewerPhoto') ? withoutPhotos(payload, ['expert', 'author']) : payload;
94
+ if (hidden.includes('memo') && hasValue(next.content.memo)) {
95
+ next = { ...next, content: { ...next.content, memo: null } };
96
+ }
97
+ return { payload: next, stripped: next !== payload };
98
+ }
99
+ /**
100
+ * The seed for a verified read: the payload stripped of what the def hides, and the signature only when nothing was
101
+ * stripped. The card paints from this seed's payload, on the server and in the browser alike.
102
+ */
103
+ export function seedFor(read) {
104
+ const { payload, stripped } = withoutHiddenContent(read.payload, read.renderDef);
105
+ return {
106
+ baseUrl: read.baseUrl,
107
+ externalId: read.externalId,
108
+ ...(read.design ? { design: read.design } : {}),
109
+ payload,
110
+ ...(read.signature && !stripped ? { signature: read.signature } : {}),
111
+ renderDef: read.renderDef,
112
+ };
113
+ }
114
+ const serializedPin = (design) => design ? { design: { version: design.version, ...(design.brand === undefined ? {} : { brand: design.brand }) } } : {};
115
+ export function serializeSeed(seed) {
116
+ return JSON.stringify({
117
+ v: 1,
118
+ baseUrl: seed.baseUrl,
119
+ externalId: seed.externalId,
120
+ ...serializedPin(seed.design),
121
+ payload: seed.payload,
122
+ ...(seed.signature ? { signature: seed.signature } : {}),
123
+ renderDef: seed.renderDef,
124
+ });
125
+ }
126
+ export function serializeFallback(fallback) {
127
+ return JSON.stringify({
128
+ v: 1,
129
+ baseUrl: fallback.baseUrl,
130
+ externalId: fallback.externalId,
131
+ ...serializedPin(fallback.design),
132
+ face: fallback.face,
133
+ });
134
+ }
135
+ /** A pin a record names, judged by the same grammar the card's own pin is: undefined when absent, null when bad. */
136
+ function parsedPin(design) {
137
+ if (design === undefined)
138
+ return undefined;
139
+ const judged = isRecord(design)
140
+ ? parseDesignPin({ design: design.version, ...(design.brand === undefined ? {} : { designBrand: design.brand }) })
141
+ : 'invalid';
142
+ return judged === 'invalid' || judged === undefined ? null : judged;
143
+ }
144
+ /** The seed in one attribute value, or null for anything that is not one (never throws). */
145
+ export function parseSeed(raw) {
146
+ let value;
147
+ try {
148
+ value = JSON.parse(raw);
149
+ }
150
+ catch {
151
+ return null;
152
+ }
153
+ if (!isRecord(value) || value.v !== 1)
154
+ return null;
155
+ const { baseUrl, externalId, design, payload, signature, renderDef } = value;
156
+ if (typeof baseUrl !== 'string' || typeof externalId !== 'string')
157
+ return null;
158
+ if (!isRecord(payload) || !isRecord(payload.subject) || !isRecord(payload.lifecycle) || !isRecord(payload.content)) {
159
+ return null;
160
+ }
161
+ // A pin the seed names is judged by the same grammar the card's own pin is; one that fails it is not a seed.
162
+ const pin = parsedPin(design);
163
+ if (pin === null)
164
+ return null;
165
+ return {
166
+ baseUrl,
167
+ externalId,
168
+ ...(pin ? { design: pin } : {}),
169
+ payload: payload,
170
+ ...(isRecord(signature) ? { signature: signature } : {}),
171
+ renderDef: parseRenderDef(renderDef),
172
+ };
173
+ }
174
+ /** A fallback record in one attribute value, or null for anything that is not one (a seed included; never throws). */
175
+ export function parseFallback(raw) {
176
+ let value;
177
+ try {
178
+ value = JSON.parse(raw);
179
+ }
180
+ catch {
181
+ return null;
182
+ }
183
+ if (!isRecord(value) || value.v !== 1 || 'payload' in value)
184
+ return null;
185
+ const { baseUrl, externalId, design, face } = value;
186
+ if (typeof baseUrl !== 'string' || typeof externalId !== 'string')
187
+ return null;
188
+ if (face !== 'options' && face !== 'none')
189
+ return null;
190
+ const pin = parsedPin(design);
191
+ if (pin === null)
192
+ return null;
193
+ return { baseUrl, externalId, ...(pin ? { design: pin } : {}), face };
194
+ }
195
+ /** One placement's key: the origin, the entry and the pin (the read's own key, so a pin never shares a seed). */
196
+ function seedKey(baseUrl, externalId, design) {
197
+ return design ? `${baseUrl}|${externalId}|design=${design.version}|${design.brand ?? ''}` : `${baseUrl}|${externalId}`;
198
+ }
199
+ /**
200
+ * The seeds (and fallback records) this page's server HTML carried, by placement, for the page's lifetime: a card
201
+ * mounted later by a client-side render (an in-app navigation back to a server-rendered article, or React's client
202
+ * re-render after a hydration error) paints what the server painted, as the hydrated card it replaces would have.
203
+ */
204
+ const pageSeeds = new Map();
205
+ const recordKey = (record) => {
206
+ const r = 'seed' in record ? record.seed : record.fallback;
207
+ return seedKey(r.baseUrl, r.externalId, r.design);
208
+ };
209
+ /** Every seed and fallback record the live document carries, in document order. */
210
+ function scanDocument() {
211
+ const found = [];
212
+ for (const el of Array.from(document.querySelectorAll(`[${SEED_ATTRIBUTE}]`))) {
213
+ const raw = el.getAttribute(SEED_ATTRIBUTE);
214
+ if (!raw)
215
+ continue;
216
+ const seed = parseSeed(raw);
217
+ const fallback = seed ? null : parseFallback(raw);
218
+ if (seed)
219
+ found.push({ seed, raw });
220
+ else if (fallback)
221
+ found.push({ fallback, raw });
222
+ }
223
+ return found;
224
+ }
225
+ /**
226
+ * The record the server wrote for this placement and pin: its seed, or its fallback record. By default: from the map,
227
+ * else from one scan of the document (which also records every other one on the page). With `live`, the map is not
228
+ * consulted: the document is scanned and decides, so what a hydrating card learns is what the server HTML in front of
229
+ * it carries, not what an earlier page in this process left behind. `undefined` when the page carries none, and always
230
+ * on a server.
231
+ */
232
+ export function pageRecordFor(baseUrl, externalId, design, options = {}) {
233
+ const key = seedKey(baseUrl, externalId, design);
234
+ if (typeof document === 'undefined')
235
+ return undefined;
236
+ const known = options.live ? undefined : pageSeeds.get(key);
237
+ if (known)
238
+ return known;
239
+ let inDocument = false;
240
+ for (const found of scanDocument()) {
241
+ const k = recordKey(found);
242
+ if (k === key)
243
+ inDocument = true;
244
+ if (options.live || !pageSeeds.has(k))
245
+ pageSeeds.set(k, found);
246
+ }
247
+ // A live read answers for the document alone: a record an earlier page left in the map is not one this page carries.
248
+ return options.live && !inDocument ? undefined : pageSeeds.get(key);
249
+ }
250
+ /** `pageRecordFor`, seeds only: the seed the server painted for this placement and pin. */
251
+ export function pageSeedFor(baseUrl, externalId, design, options = {}) {
252
+ const record = pageRecordFor(baseUrl, externalId, design, options);
253
+ return record && 'seed' in record ? record : undefined;
254
+ }
255
+ /** A Suspense boundary's comment marker as React's server render writes it: `$` (done), `$?` (pending), `$!`, `$~`. */
256
+ const BOUNDARY_MARKER = /^\$[?!~]?$/;
257
+ /**
258
+ * Whether the live document holds server-rendered React HTML: any Suspense boundary marker. The delivery card sits in
259
+ * a `<Suspense>` of its own, so a server render of one always leaves a marker, a card the server painted nothing for
260
+ * (revoked, expired, unreachable) included, and a client render never does. This is how a card that is hydrating tells
261
+ * a browser hydrating server HTML (the document holds it) from a server render that merely runs where a `document`
262
+ * exists (a test's jsdom, a shim): there the document does not hold the HTML being produced.
263
+ */
264
+ export function pageHoldsServerHtml() {
265
+ if (typeof document === 'undefined' || !document.documentElement)
266
+ return false;
267
+ const walker = document.createTreeWalker(document.documentElement, 128 /* NodeFilter.SHOW_COMMENT */);
268
+ for (let node = walker.nextNode(); node; node = walker.nextNode()) {
269
+ if (BOUNDARY_MARKER.test(node.data))
270
+ return true;
271
+ }
272
+ return false;
273
+ }
274
+ /** Test seam: forget every seed (a new page). */
275
+ export function forgetPageSeedsForTests() {
276
+ pageSeeds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AAA;AAClB,CAAC"}
@@ -11,6 +11,13 @@
11
11
  * ONE fetch, not N.
12
12
  * 3. Negative-caches failures briefly so a hard-down origin doesn't get hammered, while
13
13
  * still recovering quickly (short negative TTL).
14
+ * 4. (1.2.0, opt-in through `staleMs`) STALE-WHILE-REVALIDATE and STALE-IF-ERROR: a positive
15
+ * entry past its TTL but inside the stale window is served at once while ONE background
16
+ * refresh replaces it; a refresh that only failed to reach the origin (`isTransient`)
17
+ * keeps the stale entry instead of overwriting it. So an origin that is slow or briefly
18
+ * down costs the page nothing it already had. A definitive answer (a revocation, say)
19
+ * replaces the entry the moment the refresh lands. With the default `staleMs` of 0 an
20
+ * expired entry is gone, exactly as before 1.2.0.
14
21
  *
15
22
  * It is deliberately tiny + dependency-free (a Map + timestamps) so it runs in any server
16
23
  * runtime (Node, edge, workerd). For multi-instance deployments this is per-instance L1 and
@@ -24,6 +31,18 @@ export interface TtlCacheOptions {
24
31
  readonly negativeTtlMs?: number;
25
32
  /** Max entries before LRU-ish eviction of the oldest insert (default 1000). */
26
33
  readonly maxEntries?: number;
34
+ /**
35
+ * 1.2.0: how long past its TTL a POSITIVE entry may still be served while a refresh runs (default 0: never). A
36
+ * negative entry is never served stale.
37
+ */
38
+ readonly staleMs?: number;
39
+ /**
40
+ * 1.2.0: how long an unsettled load may be joined by later callers (default: no limit). Past it, the next caller
41
+ * starts a fresh load. WHY: a runtime may cancel the I/O of a request that has finished (Cloudflare workerd does),
42
+ * which can leave a background refresh's promise pending forever; without a limit every later caller would join
43
+ * it and none would ever refresh again.
44
+ */
45
+ readonly inflightMaxMs?: number;
27
46
  /** Injectable clock for deterministic tests. */
28
47
  readonly now?: () => number;
29
48
  }
@@ -33,10 +52,21 @@ export declare class TtlCache<V> {
33
52
  private readonly ttlMs;
34
53
  private readonly negativeTtlMs;
35
54
  private readonly maxEntries;
55
+ private readonly staleMs;
56
+ private readonly inflightMaxMs;
36
57
  private readonly now;
37
58
  constructor(opts?: TtlCacheOptions);
38
- /** Read a live (non-expired) entry, or undefined. Prunes the entry if expired. */
59
+ /** The entry while it may still be served (fresh, or positive and inside the stale window); prunes it past that. */
60
+ private servable;
61
+ /** Read a live (non-expired) entry, or undefined. Never serves a stale one; prunes an entry past its stale window. */
39
62
  peek(key: string): V | undefined;
63
+ /**
64
+ * The synchronous stale-while-revalidate read: a fresh value; or a positive entry past its TTL but inside the stale
65
+ * window, returned at once while this starts (or joins) ONE background refresh through `loader`; else undefined,
66
+ * and the caller loads (`getOrLoad`). The refresh caches as `getOrLoad` does, with the same arguments; its failure
67
+ * is swallowed (the stale value was already served, and a thrown loader is never cached).
68
+ */
69
+ peekOrRefresh(key: string, loader: () => Promise<V>, isNegative?: (v: V) => boolean, positiveTtlMs?: number, isTransient?: (v: V) => boolean): V | undefined;
40
70
  /**
41
71
  * Get-or-load with single-flight. If a fresh value is cached, returns it. Otherwise
42
72
  * de-duplicates concurrent loads for `key`: the first caller runs `loader`, every
@@ -50,8 +80,15 @@ export declare class TtlCache<V> {
50
80
  * It deliberately does NOT apply to a negative result: a caller asking for a 10-minute
51
81
  * positive TTL is asking for fewer origin reads, not for a transient failure to be
52
82
  * remembered for ten minutes (see the negative-TTL rationale in the module header).
83
+ *
84
+ * 1.2.0: inside the stale window (`staleMs`) an expired positive entry is returned at once and refreshed in the
85
+ * background (`peekOrRefresh`). `isTransient(value)` marks a result that says only "the origin was not reached"
86
+ * (a timeout, a 5xx): when a servable positive entry exists, such a result is NOT cached over it and the caller
87
+ * gets that entry's value instead (stale-if-error). With no entry to keep, it is cached as `isNegative` says.
53
88
  */
54
- getOrLoad(key: string, loader: () => Promise<V>, isNegative?: (v: V) => boolean, positiveTtlMs?: number): Promise<V>;
89
+ getOrLoad(key: string, loader: () => Promise<V>, isNegative?: (v: V) => boolean, positiveTtlMs?: number, isTransient?: (v: V) => boolean): Promise<V>;
90
+ /** Single-flight load and cache (joins an unsettled load younger than `inflightMaxMs`). */
91
+ private load;
55
92
  /** Insert/overwrite an entry. `ttlMsOverride` replaces the TTL this write would otherwise
56
93
  * get (positive or negative); omit it for the cache's configured TTLs. */
57
94
  set(key: string, value: V, negative?: boolean, ttlMsOverride?: number): void;
@@ -1 +1 @@
1
- {"version":3,"file":"cache.d.ts","sourceRoot":"","sources":["../../src/verify/cache.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AAEH,MAAM,WAAW,eAAe;IAC/B,kDAAkD;IAClD,QAAQ,CAAC,KAAK,CAAC,EAAE,MAAM,CAAA;IACvB,8DAA8D;IAC9D,QAAQ,CAAC,aAAa,CAAC,EAAE,MAAM,CAAA;IAC/B,+EAA+E;IAC/E,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,gDAAgD;IAChD,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,MAAM,CAAA;CAC3B;AAQD,qBAAa,QAAQ,CAAC,CAAC;IACtB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAA8B;IACpD,OAAO,CAAC,QAAQ,CAAC,QAAQ,CAAgC;IACzD,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAQ;IAC9B,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAQ;IACtC,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAQ;IACnC,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAc;gBAEtB,IAAI,GAAE,eAAoB;IAOtC,kFAAkF;IAClF,IAAI,CAAC,GAAG,EAAE,MAAM,GAAG,CAAC,GAAG,SAAS;IAUhC;;;;;;;;;;;;;OAaG;IACG,SAAS,CACd,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,EACxB,UAAU,CAAC,EAAE,CAAC,CAAC,EAAE,CAAC,KAAK,OAAO,EAC9B,aAAa,CAAC,EAAE,MAAM,GACpB,OAAO,CAAC,CAAC,CAAC;IAoBb;+EAC2E;IAC3E,GAAG,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,CAAC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