@decocms/blocks 8.0.0 → 8.1.0-next.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/bin/deco.js +13 -0
- package/package.json +39 -3
- package/src/cms/applySectionConventions.ts +26 -2
- package/src/cms/blockSource.ts +37 -0
- package/src/cms/client.ts +5 -0
- package/src/cms/deferredTrigger.ts +58 -0
- package/src/cms/draftSource.ts +171 -57
- package/src/cms/index.ts +32 -3
- package/src/cms/loader.ts +318 -59
- package/src/cms/registry.ts +22 -0
- package/src/cms/renderJson.ts +179 -0
- package/src/cms/resolve.ts +396 -95
- package/src/cms/schema.ts +9 -5
- package/src/cms/sectionLoaders.ts +106 -56
- package/src/hooks/Image.tsx +70 -6
- package/src/hooks/LiveControls.tsx +30 -8
- package/src/hooks/Stats.tsx +134 -0
- package/src/hooks/index.ts +5 -0
- package/src/hooks/useLoadMore.ts +100 -0
- package/src/index.ts +37 -0
- package/src/middleware/observability.ts +173 -16
- package/src/preview/DraftPreviewBadge.tsx +306 -0
- package/src/preview/decoMark.ts +11 -0
- package/src/preview/index.ts +8 -0
- package/src/protocol/assets.ts +124 -0
- package/src/protocol/canonical.ts +7 -0
- package/src/protocol/ciphertext.ts +6 -0
- package/src/protocol/client.ts +170 -0
- package/src/protocol/conformance/cases/assets.ts +81 -0
- package/src/protocol/conformance/cases/guards.ts +314 -0
- package/src/protocol/conformance/cases/reads.ts +168 -0
- package/src/protocol/conformance/cases/types.ts +9 -0
- package/src/protocol/conformance/cases/wire.ts +138 -0
- package/src/protocol/conformance/cases/writes.ts +345 -0
- package/src/protocol/conformance/contentHashFixtures.ts +79 -0
- package/src/protocol/conformance/context.ts +222 -0
- package/src/protocol/conformance/index.ts +140 -0
- package/src/protocol/errors.ts +142 -0
- package/src/protocol/index.ts +39 -0
- package/src/protocol/keys.ts +279 -0
- package/src/protocol/params.ts +67 -0
- package/src/protocol/secrets.ts +231 -0
- package/src/protocol/server/assets.ts +119 -0
- package/src/protocol/server/auth.ts +49 -0
- package/src/protocol/server/bodyCache.ts +84 -0
- package/src/protocol/server/content.ts +175 -0
- package/src/protocol/server/core.ts +112 -0
- package/src/protocol/server/handler.ts +102 -0
- package/src/protocol/server/http.ts +139 -0
- package/src/protocol/server/index.ts +11 -0
- package/src/protocol/server/methods/apply.ts +341 -0
- package/src/protocol/server/methods/read.ts +156 -0
- package/src/protocol/server/rpc.ts +136 -0
- package/src/protocol/storage/fs/hash.ts +21 -0
- package/src/protocol/storage/fs/index.ts +338 -0
- package/src/protocol/storage/fs/lock.ts +68 -0
- package/src/protocol/storage/fs/transaction.ts +183 -0
- package/src/protocol/storage/fs/unsupported.ts +15 -0
- package/src/protocol/storage/memory.ts +238 -0
- package/src/protocol/storage.ts +182 -0
- package/src/protocol/types.ts +172 -0
- package/src/sdk/abTesting.ts +60 -3
- package/src/sdk/analytics.ts +72 -2
- package/src/sdk/cacheHeaders.ts +210 -10
- package/src/sdk/cacheStorage.ts +287 -0
- package/src/sdk/cachedLoader.ts +143 -90
- package/src/sdk/crypto.ts +16 -2
- package/src/sdk/deepOmit.ts +52 -0
- package/src/sdk/encoding.ts +2 -5
- package/src/sdk/experiments.ts +314 -0
- package/src/sdk/fetchCache.ts +269 -0
- package/src/sdk/fetchTimeout.ts +58 -0
- package/src/sdk/flags.ts +38 -8
- package/src/sdk/index.ts +7 -0
- package/src/sdk/instrumentedFetch.ts +25 -2
- package/src/sdk/nonce.ts +46 -0
- package/src/sdk/normalizeUrls.ts +2 -2
- package/src/sdk/observability.ts +8 -1
- package/src/sdk/otel.ts +131 -25
- package/src/sdk/otelHttpLog.ts +4 -4
- package/src/sdk/otelHttpMeter.ts +39 -13
- package/src/sdk/otelHttpTracer.ts +4 -4
- package/src/sdk/redirects.ts +113 -5
- package/src/sdk/responseCache.ts +82 -0
- package/src/sdk/urlUtils.ts +49 -0
- package/src/sdk/useSuggestions.ts +1 -1
- package/src/v8/analytics.ts +50 -0
- package/src/v8/background.ts +107 -0
- package/src/v8/builtins/data.ts +23 -0
- package/src/v8/builtins/index.ts +26 -0
- package/src/v8/builtins/lazy.ts +23 -0
- package/src/v8/builtins/legacy.ts +65 -0
- package/src/v8/builtins/matchers.ts +31 -0
- package/src/v8/builtins/multivariate.ts +25 -0
- package/src/v8/builtins/secret.ts +82 -0
- package/src/v8/canonical.ts +117 -0
- package/src/v8/ciphertext.ts +158 -0
- package/src/v8/cli/builtins.ts +20 -0
- package/src/v8/cli/check/index.ts +774 -0
- package/src/v8/cli/check/messages.ts +168 -0
- package/src/v8/cli/content.ts +287 -0
- package/src/v8/cli/index.ts +17 -0
- package/src/v8/cli/log.ts +18 -0
- package/src/v8/cli/main.ts +12 -0
- package/src/v8/cli/root.ts +66 -0
- package/src/v8/cli/run.ts +236 -0
- package/src/v8/cli/schema/builtinSchemas.ts +236 -0
- package/src/v8/cli/schema/generate.ts +507 -0
- package/src/v8/cli/schema/index.ts +63 -0
- package/src/v8/cli/schema/tsProgram.ts +497 -0
- package/src/v8/cli/schema/typeToSchema.ts +689 -0
- package/src/v8/cli/serve/server.ts +303 -0
- package/src/v8/cli/watch.ts +86 -0
- package/src/v8/client.ts +147 -0
- package/src/v8/cms.ts +237 -0
- package/src/v8/content.ts +195 -0
- package/src/v8/draft.ts +136 -0
- package/src/v8/errors.ts +59 -0
- package/src/v8/fetch.ts +152 -0
- package/src/v8/identity.ts +65 -0
- package/src/v8/index.ts +39 -0
- package/src/v8/json.ts +74 -0
- package/src/v8/matchRoute.ts +204 -0
- package/src/v8/remoteLoader.ts +282 -0
- package/src/v8/resolver.ts +278 -0
- package/src/v8/secrets.ts +17 -0
- package/src/v8/telemetry.ts +533 -0
- package/src/v8/types.ts +240 -0
- package/src/cms/blockSource.test.ts +0 -76
- package/src/cms/client.browserBundle.test.ts +0 -44
- package/src/cms/draftSource.test.ts +0 -343
- package/src/cms/layoutCacheRace.test.ts +0 -181
- package/src/cms/loadDecofileDirectory.test.ts +0 -109
- package/src/cms/loader.test.ts +0 -200
- package/src/cms/registry.test.ts +0 -110
- package/src/cms/resolve.test.ts +0 -980
- package/src/cms/schema.test.ts +0 -356
- package/src/cms/sectionLoaderContext.test.ts +0 -111
- package/src/cms/sectionLoaders.test.ts +0 -533
- package/src/cms/sectionMixins.test.ts +0 -167
- package/src/cms/stickyFlags.test.ts +0 -117
- package/src/flags/flags.test.ts +0 -148
- package/src/hooks/Image.test.ts +0 -100
- package/src/hooks/RenderSection.test.tsx +0 -81
- package/src/matchers/builtins.test.ts +0 -318
- package/src/matchers/override.test.ts +0 -205
- package/src/middleware/hydrationContext.test.ts +0 -61
- package/src/middleware/observability.test.ts +0 -242
- package/src/middleware/validateSection.test.ts +0 -147
- package/src/sdk/abTesting.test.ts +0 -326
- package/src/sdk/cacheHeaders.test.ts +0 -115
- package/src/sdk/cachedLoader.test.ts +0 -122
- package/src/sdk/cachedLoaderModule.test.ts +0 -209
- package/src/sdk/cn.test.ts +0 -34
- package/src/sdk/composite.test.ts +0 -121
- package/src/sdk/cookie.test.ts +0 -108
- package/src/sdk/encoding.test.ts +0 -71
- package/src/sdk/env.test.ts +0 -33
- package/src/sdk/flags.test.ts +0 -91
- package/src/sdk/http.test.ts +0 -71
- package/src/sdk/inflightTimeout.test.ts +0 -35
- package/src/sdk/instrumentedFetch.test.ts +0 -559
- package/src/sdk/invoke.test.ts +0 -115
- package/src/sdk/logger.test.ts +0 -432
- package/src/sdk/otel.test.ts +0 -526
- package/src/sdk/otelAdapters.test.ts +0 -89
- package/src/sdk/otelHttpLog.test.ts +0 -457
- package/src/sdk/otelHttpMeter.test.ts +0 -292
- package/src/sdk/otelHttpTracer.test.ts +0 -474
- package/src/sdk/requestContextStorage.browser.test.ts +0 -29
- package/src/sdk/urlRedaction.test.ts +0 -73
- package/src/sdk/useDevice.test.ts +0 -130
- package/src/sdk/useScript.test.ts +0 -128
- package/src/sdk/useSuggestions.test.ts +0 -230
- package/tsconfig.json +0 -7
package/src/sdk/analytics.ts
CHANGED
|
@@ -18,9 +18,15 @@ export function useSendEvent({ on, event }: DataEventParams) {
|
|
|
18
18
|
/**
|
|
19
19
|
* Inline script that observes data-event attributes and dispatches events.
|
|
20
20
|
* Inject once in the root layout via a <script> tag.
|
|
21
|
+
*
|
|
22
|
+
* Prerender-safe: while a Speculation Rules prerender is running the document
|
|
23
|
+
* is hidden and its IntersectionObserver could fire phantom `view` events, so
|
|
24
|
+
* all init is deferred until the page is actually activated. On a normal load
|
|
25
|
+
* `document.prerendering` is false and it runs immediately (no behavior change).
|
|
21
26
|
*/
|
|
22
27
|
export const ANALYTICS_SCRIPT = `
|
|
23
28
|
(function() {
|
|
29
|
+
function start() {
|
|
24
30
|
function dispatch(event) {
|
|
25
31
|
if (window.dataLayer) {
|
|
26
32
|
window.dataLayer.push({ event: event.name, ...event.params });
|
|
@@ -67,11 +73,75 @@ export const ANALYTICS_SCRIPT = `
|
|
|
67
73
|
} else {
|
|
68
74
|
setTimeout(function() { mo.observe(document.body, { childList: true, subtree: true }); }, 0);
|
|
69
75
|
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
if (document.prerendering) {
|
|
79
|
+
document.addEventListener('prerenderingchange', start, { once: true });
|
|
80
|
+
} else {
|
|
81
|
+
start();
|
|
82
|
+
}
|
|
83
|
+
})();
|
|
84
|
+
`;
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Dev-only guardrail for Speculation Rules. While a prerender is running (the
|
|
88
|
+
* hidden pre-navigation document), NOTHING analytics-related should hit the
|
|
89
|
+
* network — otherwise the pageview/event is counted for a navigation that may
|
|
90
|
+
* never happen. This script patches the common egress sinks (sendBeacon, fetch,
|
|
91
|
+
* injected tracker <script>/<img>) and `console.error`s the offending call so
|
|
92
|
+
* the dev knows exactly which loader still needs a `document.prerendering`
|
|
93
|
+
* guard before activating speculation rules on that site.
|
|
94
|
+
*
|
|
95
|
+
* Emit only in dev (see DecoRootLayout) — it self-disables outside prerender,
|
|
96
|
+
* so it is inert on real navigations.
|
|
97
|
+
*/
|
|
98
|
+
export const SPECULATION_DEV_WARN_SCRIPT = `
|
|
99
|
+
(function(){
|
|
100
|
+
if (!document.prerendering) return;
|
|
101
|
+
var TRACKERS = /googletagmanager\\.com|google-analytics\\.com|analytics\\.google|gtag\\/js|gtm\\.js|connect\\.facebook\\.net|analytics\\.tiktok|hotjar|clarity\\.ms|doubleclick|\\/sgtm|sgtm\\.|\\/collect(\\?|$)|\\/j\\.php|vwo|tr\\?id=/i;
|
|
102
|
+
function err(what, detail){
|
|
103
|
+
console.error(
|
|
104
|
+
'[deco][speculation] ' + what + ' ran during prerender and will double-count when the page activates. ' +
|
|
105
|
+
'Guard its loader with: if (document.prerendering) { document.addEventListener("prerenderingchange", init, { once: true }); } else { init(); }',
|
|
106
|
+
detail
|
|
107
|
+
);
|
|
108
|
+
}
|
|
109
|
+
var sb = navigator.sendBeacon;
|
|
110
|
+
if (sb) navigator.sendBeacon = function(url){ err('navigator.sendBeacon', url); return sb.apply(navigator, arguments); };
|
|
111
|
+
var of = window.fetch;
|
|
112
|
+
if (of) window.fetch = function(input){
|
|
113
|
+
var u = (input && input.url) || input;
|
|
114
|
+
if (TRACKERS.test(String(u))) err('fetch()', u);
|
|
115
|
+
return of.apply(window, arguments);
|
|
116
|
+
};
|
|
117
|
+
var mo = new MutationObserver(function(muts){
|
|
118
|
+
for (var i=0;i<muts.length;i++){
|
|
119
|
+
var nodes = muts[i].addedNodes || [];
|
|
120
|
+
for (var j=0;j<nodes.length;j++){
|
|
121
|
+
var n = nodes[j];
|
|
122
|
+
if (!n || !n.tagName) continue;
|
|
123
|
+
if (n.tagName === 'SCRIPT' && n.src && TRACKERS.test(n.src)) err('tracker <script> load', n.src);
|
|
124
|
+
else if (n.tagName === 'IMG' && n.src && TRACKERS.test(n.src)) err('tracker pixel <img>', n.src);
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
});
|
|
128
|
+
mo.observe(document.documentElement, { childList: true, subtree: true });
|
|
129
|
+
document.addEventListener('prerenderingchange', function(){
|
|
130
|
+
mo.disconnect();
|
|
131
|
+
if (sb) navigator.sendBeacon = sb;
|
|
132
|
+
if (of) window.fetch = of;
|
|
133
|
+
}, { once: true });
|
|
70
134
|
})();
|
|
71
135
|
`;
|
|
72
136
|
|
|
73
|
-
/**
|
|
137
|
+
/**
|
|
138
|
+
* Returns a GTM container snippet. Returns empty string if no containerId.
|
|
139
|
+
*
|
|
140
|
+
* Prerender-safe: container load is deferred until the page is activated so a
|
|
141
|
+
* Speculation Rules prerender that never activates can't fire GTM (pageview /
|
|
142
|
+
* tags) in the hidden document. No-op guard on normal loads.
|
|
143
|
+
*/
|
|
74
144
|
export function gtmScript(containerId?: string): string {
|
|
75
145
|
if (!containerId) return "";
|
|
76
|
-
return `(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','${containerId}');`;
|
|
146
|
+
return `(function(){function boot(){(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src='https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);})(window,document,'script','dataLayer','${containerId}');}if(document.prerendering){document.addEventListener('prerenderingchange',boot,{once:true});}else{boot();}})();`;
|
|
77
147
|
}
|
package/src/sdk/cacheHeaders.ts
CHANGED
|
@@ -17,6 +17,8 @@
|
|
|
17
17
|
* ```
|
|
18
18
|
*/
|
|
19
19
|
|
|
20
|
+
import { isTrackingParam } from "./urlUtils";
|
|
21
|
+
|
|
20
22
|
// ---------------------------------------------------------------------------
|
|
21
23
|
// Types
|
|
22
24
|
// ---------------------------------------------------------------------------
|
|
@@ -149,15 +151,45 @@ export function setCacheProfile(
|
|
|
149
151
|
overrides: CacheProfileOverrides,
|
|
150
152
|
): void {
|
|
151
153
|
const current = PROFILES[profile];
|
|
154
|
+
|
|
155
|
+
// `private`/`cart`/`none` are the profiles that keep authenticated pages off
|
|
156
|
+
// the shared edge (and, once CDN caching is on, off the CDN). Flipping one to
|
|
157
|
+
// public is how a checkout page ends up served to another visitor, so it
|
|
158
|
+
// takes more than an `isPublic: true` in a props bag — see
|
|
159
|
+
// `allowPublicPrivateProfile`.
|
|
160
|
+
let isPublic = overrides.isPublic ?? current.isPublic;
|
|
161
|
+
if (isPublic && !current.isPublic && !publicPrivateProfilesAllowed) {
|
|
162
|
+
console.warn(
|
|
163
|
+
`[deco] setCacheProfile("${profile}", { isPublic: true }) ignored: making a ` +
|
|
164
|
+
`non-public profile public would let authenticated pages be shared between ` +
|
|
165
|
+
`visitors. Call allowPublicPrivateProfile() first if this is deliberate.`,
|
|
166
|
+
);
|
|
167
|
+
isPublic = current.isPublic;
|
|
168
|
+
}
|
|
169
|
+
|
|
152
170
|
PROFILES[profile] = {
|
|
153
171
|
edge: { ...current.edge, ...overrides.edge },
|
|
154
172
|
browser: { ...current.browser, ...overrides.browser },
|
|
155
173
|
loader: { ...current.loader, ...overrides.loader },
|
|
156
174
|
client: { ...current.client, ...overrides.client },
|
|
157
|
-
isPublic
|
|
175
|
+
isPublic,
|
|
158
176
|
};
|
|
159
177
|
}
|
|
160
178
|
|
|
179
|
+
let publicPrivateProfilesAllowed = false;
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Opt out of the guard in `setCacheProfile` that refuses to turn a non-public
|
|
183
|
+
* profile (`private`, `cart`, `none`) public.
|
|
184
|
+
*
|
|
185
|
+
* There is no legitimate storefront reason to call this. It exists so the
|
|
186
|
+
* escape hatch has a name you have to type, rather than being a silent side
|
|
187
|
+
* effect of passing `isPublic: true`.
|
|
188
|
+
*/
|
|
189
|
+
export function allowPublicPrivateProfile(): void {
|
|
190
|
+
publicPrivateProfilesAllowed = true;
|
|
191
|
+
}
|
|
192
|
+
|
|
161
193
|
// ---------------------------------------------------------------------------
|
|
162
194
|
// Derivation: Cache-Control headers (browser layer)
|
|
163
195
|
// ---------------------------------------------------------------------------
|
|
@@ -262,12 +294,95 @@ interface CachePattern {
|
|
|
262
294
|
profile: CacheProfileName;
|
|
263
295
|
}
|
|
264
296
|
|
|
265
|
-
|
|
266
|
-
|
|
297
|
+
// Authenticated / per-user areas that must never be edge-cached. Anything not
|
|
298
|
+
// matched here falls through to the cacheable `listing` default, so a missing
|
|
299
|
+
// entry is a live content leak, not a missed optimization (see
|
|
300
|
+
// decocms/blocks#412, which added the hyphenless `myaccount` VTEX wrapper path
|
|
301
|
+
// and the pt-BR account routes).
|
|
302
|
+
//
|
|
303
|
+
// Three properties this regex must keep, each of which was a real hole:
|
|
304
|
+
// - case-insensitive: `/Checkout` used to fall through to `listing`.
|
|
305
|
+
// - optional locale prefix: `/pt/checkout`, `/br/minha-conta` likewise. Only
|
|
306
|
+
// matches when followed by a private segment, so a legitimate two-letter
|
|
307
|
+
// route can't be swallowed by it.
|
|
308
|
+
// - wishlist / profile / signup / returns: absent until the CDN work, which
|
|
309
|
+
// is what served a live store's `/listadedesejos` from the shared entry.
|
|
310
|
+
const PRIVATE_SEGMENTS = [
|
|
311
|
+
"cart",
|
|
312
|
+
"carrinho",
|
|
313
|
+
"checkout",
|
|
314
|
+
"account",
|
|
315
|
+
"myaccount",
|
|
316
|
+
"my-account",
|
|
317
|
+
"minha-conta",
|
|
318
|
+
"meus-pedidos",
|
|
319
|
+
"pedidos",
|
|
320
|
+
"orders",
|
|
321
|
+
"order-placed",
|
|
322
|
+
"login",
|
|
323
|
+
"logout",
|
|
324
|
+
"sair",
|
|
325
|
+
"cadastro",
|
|
326
|
+
"signup",
|
|
327
|
+
"register",
|
|
328
|
+
"profile",
|
|
329
|
+
"perfil",
|
|
330
|
+
"wishlist",
|
|
331
|
+
"favoritos",
|
|
332
|
+
"listadedesejos",
|
|
333
|
+
"lista-de-desejos",
|
|
334
|
+
"minha-lista",
|
|
335
|
+
"assinaturas",
|
|
336
|
+
"subscriptions",
|
|
337
|
+
"troca",
|
|
338
|
+
"trocas",
|
|
339
|
+
"devolucao",
|
|
340
|
+
"devolucoes",
|
|
341
|
+
];
|
|
342
|
+
|
|
343
|
+
const LOCALE_PREFIX = "(?:\\/[a-z]{2}(?:-[a-z]{2})?)?";
|
|
344
|
+
|
|
345
|
+
const PRIVATE_PREFIX_RE = new RegExp(
|
|
346
|
+
`^${LOCALE_PREFIX}\\/(?:${PRIVATE_SEGMENTS.join("|")})(?:\\/|$)`,
|
|
347
|
+
"i",
|
|
348
|
+
);
|
|
349
|
+
|
|
350
|
+
// Site-registered private prefixes (see `registerPrivatePaths`). Kept separate
|
|
351
|
+
// from `PRIVATE_SEGMENTS` so a site can only ever ADD to the private set.
|
|
352
|
+
const extraPrivatePaths: string[] = [];
|
|
353
|
+
|
|
354
|
+
/**
|
|
355
|
+
* Mark additional path prefixes as private — never edge-cached, never served
|
|
356
|
+
* from the CDN.
|
|
357
|
+
*
|
|
358
|
+
* This is the safe half of cache configuration: it can only restrict, never
|
|
359
|
+
* relax. Prefer it over `registerCachePattern` (which can also make things
|
|
360
|
+
* public, and is evaluated before the built-in private check).
|
|
361
|
+
*
|
|
362
|
+
* @example
|
|
363
|
+
* ```ts
|
|
364
|
+
* registerPrivatePaths(["/listadedesejos", "/trocas"]);
|
|
365
|
+
* ```
|
|
366
|
+
*/
|
|
367
|
+
export function registerPrivatePaths(paths: string[]): void {
|
|
368
|
+
for (const path of paths) {
|
|
369
|
+
const normalized = path.startsWith("/") ? path : `/${path}`;
|
|
370
|
+
if (!extraPrivatePaths.includes(normalized)) extraPrivatePaths.push(normalized);
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
function isPrivatePath(pathname: string): boolean {
|
|
375
|
+
if (PRIVATE_PREFIX_RE.test(pathname)) return true;
|
|
376
|
+
const lower = pathname.toLowerCase();
|
|
377
|
+
return extraPrivatePaths.some((prefix) => {
|
|
378
|
+
const p = prefix.toLowerCase();
|
|
379
|
+
return lower === p || lower.startsWith(`${p}/`);
|
|
380
|
+
});
|
|
381
|
+
}
|
|
267
382
|
|
|
268
383
|
const builtinPatterns: CachePattern[] = [
|
|
269
384
|
{
|
|
270
|
-
test: (p) =>
|
|
385
|
+
test: (p) => isPrivatePath(p),
|
|
271
386
|
profile: "private",
|
|
272
387
|
},
|
|
273
388
|
{
|
|
@@ -295,7 +410,13 @@ const customPatterns: CachePattern[] = [];
|
|
|
295
410
|
|
|
296
411
|
/**
|
|
297
412
|
* Register additional URL-to-profile patterns. Custom patterns are evaluated
|
|
298
|
-
* before built-in ones, so they can override defaults
|
|
413
|
+
* before built-in ones, so they can override defaults — with one exception:
|
|
414
|
+
* a custom pattern resolving to a PUBLIC profile cannot override the built-in
|
|
415
|
+
* private check (see `detectCacheProfile`). A broad site pattern would
|
|
416
|
+
* otherwise silently capture `/checkout` and make it cacheable.
|
|
417
|
+
*
|
|
418
|
+
* To mark routes as private, prefer {@link registerPrivatePaths} — it can only
|
|
419
|
+
* restrict, and isn't subject to ordering rules.
|
|
299
420
|
*/
|
|
300
421
|
export function registerCachePattern(pattern: CachePattern): void {
|
|
301
422
|
customPatterns.push(pattern);
|
|
@@ -320,8 +441,15 @@ export function detectCacheProfile(pathnameOrUrl: string | URL): CacheProfileNam
|
|
|
320
441
|
searchParams = url.searchParams;
|
|
321
442
|
}
|
|
322
443
|
|
|
444
|
+
// A private path can never be talked into a public profile by a site pattern.
|
|
445
|
+
// Custom patterns still win for anything non-public (a site can always make a
|
|
446
|
+
// route MORE restricted), and for public-vs-public overrides on other paths.
|
|
447
|
+
const privatePath = isPrivatePath(pathname);
|
|
448
|
+
|
|
323
449
|
for (const pattern of customPatterns) {
|
|
324
|
-
if (pattern.test(pathname, searchParams))
|
|
450
|
+
if (!pattern.test(pathname, searchParams)) continue;
|
|
451
|
+
if (privatePath && PROFILES[pattern.profile].isPublic) return "private";
|
|
452
|
+
return pattern.profile;
|
|
325
453
|
}
|
|
326
454
|
for (const pattern of builtinPatterns) {
|
|
327
455
|
if (pattern.test(pathname, searchParams)) return pattern.profile;
|
|
@@ -380,6 +508,55 @@ export function serverFnPagePath(url: URL): string | null {
|
|
|
380
508
|
}
|
|
381
509
|
}
|
|
382
510
|
|
|
511
|
+
/**
|
|
512
|
+
* `true` when a server-fn payload (GET `payload` param or POST body) embeds a
|
|
513
|
+
* route path or absolute URL carrying a tracking param — e.g. a deferred
|
|
514
|
+
* section's `pageUrl` built from `location.href` on an ad landing. Same walk as
|
|
515
|
+
* {@link canonicalizeServerFnPayloadForCacheKey}. Returns `false` on any parse
|
|
516
|
+
* failure (fail-safe: the caller keeps its normal behavior).
|
|
517
|
+
*/
|
|
518
|
+
export function payloadHasTrackingParams(payload: string): boolean {
|
|
519
|
+
try {
|
|
520
|
+
let found = false;
|
|
521
|
+
const check = (s: string): void => {
|
|
522
|
+
let search: string;
|
|
523
|
+
if (/^https?:\/\//i.test(s)) {
|
|
524
|
+
try {
|
|
525
|
+
search = new URL(s).search;
|
|
526
|
+
} catch {
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
} else if (s.startsWith("/") && !s.startsWith("//")) {
|
|
530
|
+
const q = s.indexOf("?");
|
|
531
|
+
if (q < 0) return;
|
|
532
|
+
search = s.slice(q);
|
|
533
|
+
} else {
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
for (const k of new URLSearchParams(search).keys()) {
|
|
537
|
+
if (isTrackingParam(k)) {
|
|
538
|
+
found = true;
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
}
|
|
542
|
+
};
|
|
543
|
+
const visit = (v: unknown): void => {
|
|
544
|
+
if (found) return;
|
|
545
|
+
if (typeof v === "string") {
|
|
546
|
+
check(v);
|
|
547
|
+
} else if (Array.isArray(v)) {
|
|
548
|
+
for (const x of v) visit(x);
|
|
549
|
+
} else if (v && typeof v === "object") {
|
|
550
|
+
for (const x of Object.values(v)) visit(x);
|
|
551
|
+
}
|
|
552
|
+
};
|
|
553
|
+
visit(JSON.parse(payload));
|
|
554
|
+
return found;
|
|
555
|
+
} catch {
|
|
556
|
+
return false;
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
383
560
|
/**
|
|
384
561
|
* Search params that never change a CMS page's resolved server-fn response and
|
|
385
562
|
* so must not fragment its edge cache key. `skuId`/`idsku` select a product
|
|
@@ -394,9 +571,11 @@ export const DEFAULT_SERVERFN_CACHE_IGNORE_PARAMS = ["skuId", "idsku"];
|
|
|
394
571
|
/**
|
|
395
572
|
* Canonicalize a TanStack GET server-fn `payload` for use in the edge cache
|
|
396
573
|
* key: re-serialize it (so equivalent requests always produce byte-identical
|
|
397
|
-
* keys) and strip the
|
|
398
|
-
*
|
|
399
|
-
*
|
|
574
|
+
* keys) and strip the cache-irrelevant search params — `ignoreParams` plus every
|
|
575
|
+
* known tracking param — from any embedded route path or absolute URL. This
|
|
576
|
+
* makes `/product/p?skuId=148940`, `/product/p?utm_source=ads` and `/product/p`
|
|
577
|
+
* share one cache entry, since `loadCmsPage` resolves all three to the same
|
|
578
|
+
* page.
|
|
400
579
|
*
|
|
401
580
|
* Returns the original payload unchanged on any parse failure (fail-safe: the
|
|
402
581
|
* caller keeps the raw payload, never worse than before).
|
|
@@ -406,13 +585,34 @@ export function canonicalizeServerFnPayloadForCacheKey(
|
|
|
406
585
|
ignoreParams: string[] = DEFAULT_SERVERFN_CACHE_IGNORE_PARAMS,
|
|
407
586
|
): string {
|
|
408
587
|
try {
|
|
588
|
+
const drop = (sp: URLSearchParams): void => {
|
|
589
|
+
for (const p of ignoreParams) sp.delete(p);
|
|
590
|
+
// Tracking params never change what the server fn resolves, but they DO
|
|
591
|
+
// change this key — so a shopper arriving from paid media mints a brand
|
|
592
|
+
// new entry on every SPA interaction. Measured on a production
|
|
593
|
+
// storefront: `/_serverFn/:id` at 84% MISS, 1401ms average.
|
|
594
|
+
for (const k of [...sp.keys()]) if (isTrackingParam(k)) sp.delete(k);
|
|
595
|
+
};
|
|
409
596
|
const stripQuery = (s: string): string => {
|
|
597
|
+
// Absolute URL: sites embed one in the payload (the deferred-section
|
|
598
|
+
// `pageUrl` is built with `new URL(...)`), and it fragments the key
|
|
599
|
+
// exactly like a relative path does — but the guard below skipped it, so
|
|
600
|
+
// not even `skuId` was canonicalized there.
|
|
601
|
+
if (/^https?:\/\//i.test(s)) {
|
|
602
|
+
try {
|
|
603
|
+
const u = new URL(s);
|
|
604
|
+
drop(u.searchParams);
|
|
605
|
+
return u.toString();
|
|
606
|
+
} catch {
|
|
607
|
+
return s;
|
|
608
|
+
}
|
|
609
|
+
}
|
|
410
610
|
if (!s.startsWith("/") || s.startsWith("//")) return s;
|
|
411
611
|
const qIdx = s.indexOf("?");
|
|
412
612
|
if (qIdx < 0) return s;
|
|
413
613
|
const path = s.slice(0, qIdx);
|
|
414
614
|
const sp = new URLSearchParams(s.slice(qIdx + 1));
|
|
415
|
-
|
|
615
|
+
drop(sp);
|
|
416
616
|
const rest = sp.toString();
|
|
417
617
|
return rest ? `${path}?${rest}` : path;
|
|
418
618
|
};
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { RequestContext } from "./requestContext";
|
|
2
|
+
|
|
3
|
+
/** Storage only. Values are serialized by the caller; expiration is absolute epoch ms. */
|
|
4
|
+
export interface CacheStorage {
|
|
5
|
+
get(key: string): Promise<string | null>;
|
|
6
|
+
set(key: string, value: string, expiresAt: number): Promise<void>;
|
|
7
|
+
delete(key: string): Promise<void>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export interface CacheStorageContext {
|
|
11
|
+
storage: CacheStorage | null;
|
|
12
|
+
/** Include site, deployment and content revision. Never use a tenant-wide global binding. */
|
|
13
|
+
scope: string;
|
|
14
|
+
/** Bypass both memory and shared storage for previews or private requests. */
|
|
15
|
+
disabled?: boolean;
|
|
16
|
+
waitUntil?: (work: Promise<unknown>) => void;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
const BAG_KEY = "deco:cache-storage";
|
|
20
|
+
|
|
21
|
+
export function bindCacheStorage(context: CacheStorageContext): void {
|
|
22
|
+
RequestContext.setBag(BAG_KEY, context);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export function getCacheStorageContext(): CacheStorageContext | undefined {
|
|
26
|
+
return RequestContext.getBag<CacheStorageContext>(BAG_KEY);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Keep optional cache work alive on Workers, without letting storage errors fail a request. */
|
|
30
|
+
export function cacheBackground(work: Promise<unknown>): void {
|
|
31
|
+
const safe = work.catch(() => {});
|
|
32
|
+
getCacheStorageContext()?.waitUntil?.(safe);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export async function hashCacheKey(key: string): Promise<string> {
|
|
36
|
+
const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(key));
|
|
37
|
+
return Array.from(new Uint8Array(bytes), (b) => b.toString(16).padStart(2, "0")).join("");
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
interface StoredValue {
|
|
41
|
+
value: string;
|
|
42
|
+
expiresAt: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function decode(raw: string | null): string | null {
|
|
46
|
+
if (raw === null) return null;
|
|
47
|
+
try {
|
|
48
|
+
const entry = JSON.parse(raw) as StoredValue;
|
|
49
|
+
return typeof entry.value === "string" &&
|
|
50
|
+
Number.isFinite(entry.expiresAt) &&
|
|
51
|
+
Date.now() < entry.expiresAt
|
|
52
|
+
? entry.value
|
|
53
|
+
: null;
|
|
54
|
+
} catch {
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Bounded LRU adapter, useful in Node, development and tests. */
|
|
60
|
+
export function createMemoryCacheStorage(maxBytes = 32 * 1024 * 1024): CacheStorage {
|
|
61
|
+
const entries = new Map<string, string>();
|
|
62
|
+
let bytes = 0;
|
|
63
|
+
function remove(key: string) {
|
|
64
|
+
const old = entries.get(key);
|
|
65
|
+
if (old !== undefined) bytes -= (key.length + old.length) * 2;
|
|
66
|
+
entries.delete(key);
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
async get(key) {
|
|
70
|
+
const raw = entries.get(key);
|
|
71
|
+
const value = decode(raw ?? null);
|
|
72
|
+
if (value === null) remove(key);
|
|
73
|
+
else {
|
|
74
|
+
entries.delete(key);
|
|
75
|
+
entries.set(key, raw!);
|
|
76
|
+
}
|
|
77
|
+
return value;
|
|
78
|
+
},
|
|
79
|
+
async set(key, value, expiresAt) {
|
|
80
|
+
remove(key);
|
|
81
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return;
|
|
82
|
+
const raw = JSON.stringify({ value, expiresAt });
|
|
83
|
+
const size = (key.length + raw.length) * 2;
|
|
84
|
+
if (size > maxBytes) return;
|
|
85
|
+
entries.set(key, raw);
|
|
86
|
+
bytes += size;
|
|
87
|
+
while (bytes > maxBytes) remove(entries.keys().next().value!);
|
|
88
|
+
},
|
|
89
|
+
async delete(key) {
|
|
90
|
+
remove(key);
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Structural binding type; the core has no Cloudflare package dependency. */
|
|
96
|
+
export interface CacheKVNamespace {
|
|
97
|
+
get(key: string): Promise<string | null>;
|
|
98
|
+
put(key: string, value: string, options: { expirationTtl: number }): Promise<void>;
|
|
99
|
+
delete(key: string): Promise<void>;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function createKVCacheStorage(
|
|
103
|
+
kv: CacheKVNamespace,
|
|
104
|
+
prefix = "deco-cache:v1:",
|
|
105
|
+
): CacheStorage {
|
|
106
|
+
const keyFor = async (key: string) => prefix + (await hashCacheKey(key));
|
|
107
|
+
return {
|
|
108
|
+
async get(key) {
|
|
109
|
+
return decode(await kv.get(await keyFor(key)));
|
|
110
|
+
},
|
|
111
|
+
async set(key, value, expiresAt) {
|
|
112
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return;
|
|
113
|
+
const raw = JSON.stringify({ value, expiresAt });
|
|
114
|
+
// Leave space below KV's 25 MiB value limit. Oversized cache entries are optional.
|
|
115
|
+
if (new TextEncoder().encode(raw).byteLength > 25 * 1024 * 1024) return;
|
|
116
|
+
await kv.put(await keyFor(key), raw, {
|
|
117
|
+
expirationTtl: Math.max(60, Math.ceil((expiresAt - Date.now()) / 1000)),
|
|
118
|
+
});
|
|
119
|
+
},
|
|
120
|
+
async delete(key) {
|
|
121
|
+
await kv.delete(await keyFor(key));
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** The app supplies the native cache and its origin; no global API detection in consumers. */
|
|
127
|
+
export function createWebCacheStorage(
|
|
128
|
+
cache: Pick<Cache, "match" | "put" | "delete">,
|
|
129
|
+
origin: string,
|
|
130
|
+
): CacheStorage {
|
|
131
|
+
const requestFor = async (key: string) =>
|
|
132
|
+
new Request(new URL(`/__deco_cache/${await hashCacheKey(key)}`, origin));
|
|
133
|
+
return {
|
|
134
|
+
async get(key) {
|
|
135
|
+
const response = await cache.match(await requestFor(key));
|
|
136
|
+
return decode(response ? await response.text() : null);
|
|
137
|
+
},
|
|
138
|
+
async set(key, value, expiresAt) {
|
|
139
|
+
if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return;
|
|
140
|
+
await cache.put(
|
|
141
|
+
await requestFor(key),
|
|
142
|
+
new Response(JSON.stringify({ value, expiresAt }), {
|
|
143
|
+
headers: {
|
|
144
|
+
"Cache-Control": `public, max-age=${Math.max(1, Math.ceil((expiresAt - Date.now()) / 1000))}`,
|
|
145
|
+
},
|
|
146
|
+
}),
|
|
147
|
+
);
|
|
148
|
+
},
|
|
149
|
+
async delete(key) {
|
|
150
|
+
await cache.delete(await requestFor(key));
|
|
151
|
+
},
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Reject values JSON would silently change, including dates, functions and circular references. */
|
|
156
|
+
function serialize(value: unknown): string | undefined {
|
|
157
|
+
const seen = new Set<object>();
|
|
158
|
+
function check(v: unknown): void {
|
|
159
|
+
if (v === null || typeof v === "string" || typeof v === "boolean") return;
|
|
160
|
+
if (typeof v === "number" && Number.isFinite(v)) return;
|
|
161
|
+
// Optional object fields are common in section props. JSON omits them safely.
|
|
162
|
+
if (v === undefined) return;
|
|
163
|
+
if (typeof v !== "object" || seen.has(v)) throw new Error("Unsupported cached value");
|
|
164
|
+
if (
|
|
165
|
+
!Array.isArray(v) &&
|
|
166
|
+
Object.getPrototypeOf(v) !== Object.prototype &&
|
|
167
|
+
Object.getPrototypeOf(v) !== null
|
|
168
|
+
) {
|
|
169
|
+
throw new Error("Unsupported cached object");
|
|
170
|
+
}
|
|
171
|
+
seen.add(v);
|
|
172
|
+
for (const item of Object.values(v)) check(item);
|
|
173
|
+
seen.delete(v);
|
|
174
|
+
}
|
|
175
|
+
check(value);
|
|
176
|
+
return JSON.stringify(value);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Typed cache with a bounded, decoded memory tier. All remote access uses CacheStorage.
|
|
181
|
+
* Call key() once per operation so a content change cannot redirect an in-flight write.
|
|
182
|
+
* In-flight promises remain in the calling isolate; only completed results are persisted.
|
|
183
|
+
*/
|
|
184
|
+
export function createCacheStore<T>(
|
|
185
|
+
namespace: string,
|
|
186
|
+
maxEntries = 200,
|
|
187
|
+
maxBytes = 4 * 1024 * 1024,
|
|
188
|
+
sizeOf?: (value: T) => number,
|
|
189
|
+
) {
|
|
190
|
+
const local = new Map<string, { value: T; expiresAt: number; bytes: number }>();
|
|
191
|
+
let bytes = 0;
|
|
192
|
+
let generation = 0;
|
|
193
|
+
function remove(key: string) {
|
|
194
|
+
const entry = local.get(key);
|
|
195
|
+
if (entry) bytes -= entry.bytes;
|
|
196
|
+
local.delete(key);
|
|
197
|
+
}
|
|
198
|
+
function remember(key: string, value: T, expiresAt: number) {
|
|
199
|
+
remove(key);
|
|
200
|
+
let size: number;
|
|
201
|
+
try {
|
|
202
|
+
size = sizeOf
|
|
203
|
+
? sizeOf(value)
|
|
204
|
+
: Math.max(512, (key.length + (JSON.stringify(value)?.length ?? 0)) * 2);
|
|
205
|
+
} catch {
|
|
206
|
+
size = 1024;
|
|
207
|
+
}
|
|
208
|
+
if (size > maxBytes) return;
|
|
209
|
+
local.set(key, { value, expiresAt, bytes: size });
|
|
210
|
+
bytes += size;
|
|
211
|
+
while (local.size > 0 && (local.size > maxEntries || bytes > maxBytes))
|
|
212
|
+
remove(local.keys().next().value!);
|
|
213
|
+
}
|
|
214
|
+
function get(key: string): T | undefined {
|
|
215
|
+
if (getCacheStorageContext()?.disabled) return undefined;
|
|
216
|
+
const entry = local.get(key);
|
|
217
|
+
if (!entry) return undefined;
|
|
218
|
+
if (Date.now() >= entry.expiresAt) {
|
|
219
|
+
remove(key);
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
local.delete(key);
|
|
223
|
+
local.set(key, entry);
|
|
224
|
+
return entry.value;
|
|
225
|
+
}
|
|
226
|
+
return {
|
|
227
|
+
key(raw: string): string {
|
|
228
|
+
return JSON.stringify([getCacheStorageContext()?.scope ?? "local", namespace, raw]);
|
|
229
|
+
},
|
|
230
|
+
get,
|
|
231
|
+
async read(key: string): Promise<T | undefined> {
|
|
232
|
+
const hit = get(key);
|
|
233
|
+
if (hit !== undefined) return hit;
|
|
234
|
+
const context = getCacheStorageContext();
|
|
235
|
+
if (!context?.storage || context.disabled) return undefined;
|
|
236
|
+
const gen = generation;
|
|
237
|
+
try {
|
|
238
|
+
const raw = await context.storage.get(key);
|
|
239
|
+
if (gen !== generation) return undefined;
|
|
240
|
+
const concurrent = get(key);
|
|
241
|
+
if (concurrent !== undefined) return concurrent;
|
|
242
|
+
if (raw === null) return undefined;
|
|
243
|
+
const entry = JSON.parse(raw) as { value: T; expiresAt: number };
|
|
244
|
+
if (!Number.isFinite(entry.expiresAt) || Date.now() >= entry.expiresAt) return undefined;
|
|
245
|
+
remember(key, entry.value, entry.expiresAt);
|
|
246
|
+
return entry.value;
|
|
247
|
+
} catch {
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
},
|
|
251
|
+
set(key: string, value: T, expiresAt: number, persist = true): void {
|
|
252
|
+
if (
|
|
253
|
+
getCacheStorageContext()?.disabled ||
|
|
254
|
+
!Number.isFinite(expiresAt) ||
|
|
255
|
+
expiresAt <= Date.now()
|
|
256
|
+
)
|
|
257
|
+
return;
|
|
258
|
+
remember(key, value, expiresAt);
|
|
259
|
+
const storage = getCacheStorageContext()?.storage;
|
|
260
|
+
if (!persist || !storage || !Number.isFinite(expiresAt)) return;
|
|
261
|
+
try {
|
|
262
|
+
const raw = serialize({ value, expiresAt });
|
|
263
|
+
if (raw !== undefined) cacheBackground(storage.set(key, raw, expiresAt));
|
|
264
|
+
} catch {
|
|
265
|
+
/* Non-serializable results remain in the memory tier. */
|
|
266
|
+
}
|
|
267
|
+
},
|
|
268
|
+
delete(key: string): void {
|
|
269
|
+
remove(key);
|
|
270
|
+
},
|
|
271
|
+
/** Local eviction only. Shared invalidation uses a new scope/version or storage.delete(). */
|
|
272
|
+
clear(): void {
|
|
273
|
+
local.clear();
|
|
274
|
+
bytes = 0;
|
|
275
|
+
generation++;
|
|
276
|
+
},
|
|
277
|
+
get size(): number {
|
|
278
|
+
return local.size;
|
|
279
|
+
},
|
|
280
|
+
get estimatedBytes(): number {
|
|
281
|
+
return bytes;
|
|
282
|
+
},
|
|
283
|
+
*entries(): IterableIterator<[string, T]> {
|
|
284
|
+
for (const [key, entry] of local) yield [key, entry.value];
|
|
285
|
+
},
|
|
286
|
+
};
|
|
287
|
+
}
|