@decocms/blocks 8.1.0-next.0 → 8.1.0-next.1

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 (114) hide show
  1. package/package.json +6 -92
  2. package/src/index.ts +2 -12
  3. package/src/protocol/storage/memory.ts +1 -1
  4. package/src/v8/background.ts +3 -3
  5. package/src/v8/builtins/legacy.ts +1 -1
  6. package/src/v8/cli/index.ts +1 -1
  7. package/src/v8/fetch.ts +8 -27
  8. package/src/v8/remoteLoader.ts +1 -1
  9. package/src/v8/telemetry.ts +1 -1
  10. package/src/cms/applySectionConventions.ts +0 -148
  11. package/src/cms/blockSource.ts +0 -228
  12. package/src/cms/client.ts +0 -85
  13. package/src/cms/deferredTrigger.ts +0 -58
  14. package/src/cms/draftSource.ts +0 -476
  15. package/src/cms/index.ts +0 -180
  16. package/src/cms/loadDecofileDirectory.ts +0 -89
  17. package/src/cms/loader.ts +0 -563
  18. package/src/cms/registry.ts +0 -264
  19. package/src/cms/renderJson.ts +0 -179
  20. package/src/cms/resolve.ts +0 -2583
  21. package/src/cms/schema.ts +0 -1219
  22. package/src/cms/sectionLoaderContext.ts +0 -113
  23. package/src/cms/sectionLoaders.ts +0 -686
  24. package/src/cms/sectionMixins.ts +0 -153
  25. package/src/flags/audience.ts +0 -56
  26. package/src/flags/everyone.ts +0 -29
  27. package/src/flags/flag.ts +0 -15
  28. package/src/flags/multivariate/image.ts +0 -11
  29. package/src/flags/multivariate/message.ts +0 -11
  30. package/src/flags/multivariate/page.ts +0 -16
  31. package/src/flags/multivariate/section.ts +0 -16
  32. package/src/flags/multivariate.ts +0 -1
  33. package/src/flags/types.ts +0 -59
  34. package/src/flags/utils/multivariate.ts +0 -20
  35. package/src/hooks/Image.tsx +0 -314
  36. package/src/hooks/JsonLd.tsx +0 -353
  37. package/src/hooks/LazySection.tsx +0 -121
  38. package/src/hooks/LiveControls.tsx +0 -144
  39. package/src/hooks/Picture.tsx +0 -127
  40. package/src/hooks/RenderSection.tsx +0 -91
  41. package/src/hooks/SectionErrorFallback.tsx +0 -97
  42. package/src/hooks/Stats.tsx +0 -134
  43. package/src/hooks/index.ts +0 -35
  44. package/src/hooks/useLoadMore.ts +0 -100
  45. package/src/matchers/builtins.ts +0 -459
  46. package/src/matchers/countryNames.ts +0 -104
  47. package/src/matchers/override.ts +0 -136
  48. package/src/matchers/posthog.ts +0 -154
  49. package/src/middleware/decoState.ts +0 -55
  50. package/src/middleware/healthMetrics.ts +0 -133
  51. package/src/middleware/hydrationContext.ts +0 -79
  52. package/src/middleware/index.ts +0 -88
  53. package/src/middleware/liveness.ts +0 -21
  54. package/src/middleware/observability.ts +0 -800
  55. package/src/middleware/validateSection.ts +0 -100
  56. package/src/preview/DraftPreviewBadge.tsx +0 -306
  57. package/src/preview/decoMark.ts +0 -11
  58. package/src/preview/index.ts +0 -8
  59. package/src/sdk/abTesting.ts +0 -556
  60. package/src/sdk/analytics.ts +0 -147
  61. package/src/sdk/cacheHeaders.ts +0 -633
  62. package/src/sdk/cacheStorage.ts +0 -287
  63. package/src/sdk/cachedLoader.ts +0 -556
  64. package/src/sdk/clx.ts +0 -5
  65. package/src/sdk/cn.ts +0 -28
  66. package/src/sdk/composite.ts +0 -114
  67. package/src/sdk/cookie.ts +0 -129
  68. package/src/sdk/crypto.ts +0 -199
  69. package/src/sdk/csp.ts +0 -59
  70. package/src/sdk/deepOmit.ts +0 -52
  71. package/src/sdk/detectDevice.ts +0 -45
  72. package/src/sdk/djb2.ts +0 -20
  73. package/src/sdk/encoding.ts +0 -44
  74. package/src/sdk/env.ts +0 -54
  75. package/src/sdk/experiments.ts +0 -314
  76. package/src/sdk/fetchCache.ts +0 -269
  77. package/src/sdk/fetchTimeout.ts +0 -58
  78. package/src/sdk/flags.ts +0 -138
  79. package/src/sdk/http.ts +0 -124
  80. package/src/sdk/index.ts +0 -97
  81. package/src/sdk/inflightTimeout.ts +0 -53
  82. package/src/sdk/instrumentedFetch.ts +0 -362
  83. package/src/sdk/invoke.ts +0 -298
  84. package/src/sdk/logger.ts +0 -304
  85. package/src/sdk/mergeCacheControl.ts +0 -150
  86. package/src/sdk/nonce.ts +0 -46
  87. package/src/sdk/normalizeUrls.ts +0 -91
  88. package/src/sdk/observability.ts +0 -116
  89. package/src/sdk/otel.ts +0 -1118
  90. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  91. package/src/sdk/otelAdapters.ts +0 -144
  92. package/src/sdk/otelHttpLog.ts +0 -419
  93. package/src/sdk/otelHttpMeter.ts +0 -532
  94. package/src/sdk/otelHttpTracer.ts +0 -543
  95. package/src/sdk/redirects.ts +0 -336
  96. package/src/sdk/requestContext.ts +0 -281
  97. package/src/sdk/requestContextStorage.browser.ts +0 -43
  98. package/src/sdk/requestContextStorage.ts +0 -35
  99. package/src/sdk/responseCache.ts +0 -82
  100. package/src/sdk/retry.ts +0 -45
  101. package/src/sdk/serverTimings.ts +0 -68
  102. package/src/sdk/signal.ts +0 -42
  103. package/src/sdk/sitemap.ts +0 -160
  104. package/src/sdk/urlRedaction.ts +0 -82
  105. package/src/sdk/urlUtils.ts +0 -183
  106. package/src/sdk/useDevice.ts +0 -89
  107. package/src/sdk/useDeviceContext.tsx +0 -108
  108. package/src/sdk/useId.ts +0 -7
  109. package/src/sdk/useScript.ts +0 -210
  110. package/src/sdk/useSuggestions.ts +0 -188
  111. package/src/sdk/wrapCaughtErrors.ts +0 -107
  112. package/src/setup.ts +0 -120
  113. package/src/types/index.ts +0 -53
  114. package/src/types/widgets.ts +0 -14
@@ -1,476 +0,0 @@
1
- /**
2
- * Draft preview — pull-based decofile snapshot.
3
- *
4
- * Studio serves the draft decofile (the merged `.deco/blocks/*.json` at the
5
- * branch head) from its decofile API
6
- * (`GET <origin>/api/<org>/decofile/<virtualMcpId>/<branch>?token=…`); a
7
- * production site pulls it and renders its own real pages against it. This
8
- * replaces pushing the decofile into a POST body, which only deco's own
9
- * runtime honours — Next.js and most frameworks render on GET only.
10
- *
11
- * This module is the framework-agnostic half: token parsing, origin
12
- * validation, fetching, and version caching. Binding a resolved draft to a
13
- * request is framework-specific (see `@decocms/nextjs`'s draft wiring) and
14
- * reaches this module through {@link setDraftOverrideGetter} — the same
15
- * dependency-injection shape as `setFastDeployKVGetter`, so `blocks` keeps its
16
- * zero-dependency direction.
17
- *
18
- * Inert unless `DECO_ALLOWED_PREVIEW_HOSTS` names the request's host: upgrading
19
- * the package must never be enough to start fetching from the network and
20
- * rendering unpublished content. Host-scoping (rather than a boolean) exists
21
- * because one deployment commonly serves several domains — the preview domain
22
- * may render drafts while the production domain, on the same build, must
23
- * ignore a `?__draft=` entirely.
24
- */
25
-
26
- /**
27
- * A parsed `?__draft=` token: `<host[:port]><path[?query]>@<version>`.
28
- *
29
- * The token carries the AUTHORITY + PATH of the draft content API, never a
30
- * scheme — a full URL would be an SSRF vector, and the scheme is derived from
31
- * the matched domain instead. The path is REQUIRED and typically addresses
32
- * Studio's decofile API (`/api/<org>/decofile/<virtualMcpId>/<branch>?token=…`);
33
- * its query carries the signed draft grant.
34
- */
35
- export interface DraftPointer {
36
- /** Content-API authority, e.g. `studio.decocms.com` or `localhost:4000`. */
37
- host: string;
38
- /** Path (+ query) on that authority serving the decofile JSON. */
39
- path: string;
40
- /** Opaque content version (the branch head sha / server ETag). Immutable → safe cache key. */
41
- version: string;
42
- }
43
-
44
- /** Lowercase DNS hostname. A single label is allowed — exact-host domain
45
- * entries (`localhost`, `local.studio.decocms.com`) can admit it. */
46
- const HOST_RE =
47
- /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/;
48
- const PORT_RE = /^[0-9]{1,5}$/;
49
- const VERSION_RE = /^[A-Za-z0-9._-]{1,64}$/;
50
- /** Rooted path with an optional query; conservative charset, no `@`/`#`/space. */
51
- const PATH_RE = /^\/[A-Za-z0-9/_.%~=&?-]*$/;
52
-
53
- /**
54
- * Parse `<host[:port]><path>@<version>`. Null on anything unexpected — callers
55
- * fall back to published content. Splits on the LAST `@` (neither the path
56
- * charset nor a signed token may contain one, so a stray `@` fails validation
57
- * rather than being half-read).
58
- */
59
- export function parseDraftPointer(
60
- raw: string | null | undefined,
61
- ): DraftPointer | null {
62
- if (!raw) return null;
63
- const at = raw.lastIndexOf("@");
64
- if (at <= 0 || at === raw.length - 1) return null;
65
- const authorityAndPath = raw.slice(0, at);
66
- const version = raw.slice(at + 1);
67
- if (!VERSION_RE.test(version)) return null;
68
-
69
- const slash = authorityAndPath.indexOf("/");
70
- if (slash === -1) return null;
71
- const authority = authorityAndPath.slice(0, slash).toLowerCase();
72
- const path = authorityAndPath.slice(slash);
73
- if (!PATH_RE.test(path)) return null;
74
-
75
- const [host, port, extra] = authority.split(":");
76
- if (extra !== undefined) return null;
77
- if (!host || !HOST_RE.test(host)) return null;
78
- if (port !== undefined && !PORT_RE.test(port)) return null;
79
-
80
- return {
81
- host: port === undefined ? host : `${host}:${port}`,
82
- path,
83
- version,
84
- };
85
- }
86
-
87
- /**
88
- * Domains the draft content API may live under — deco-operated, so shipping
89
- * them as defaults adds no SSRF surface. `DECO_PREVIEW_API_DOMAINS` overrides
90
- * the whole list when set.
91
- *
92
- * Two entry shapes: a dot-prefixed entry is a suffix match with a guaranteed
93
- * label boundary (`evil-decocms.com` cannot pass `.decocms.com`); a bare entry
94
- * is an exact-host match (needed for `localhost` and dev origins, which no
95
- * suffix can admit). Order matters only for the local/port rule: the first
96
- * matching entry decides whether a port and `http` are allowed.
97
- */
98
- export const DEFAULT_PREVIEW_API_DOMAINS = [
99
- "local.studio.decocms.com", // native/web dev origin (http, explicit port)
100
- "localhost",
101
- "127.0.0.1", // loopback dev — `localhost` can resolve to a different (IPv6) server
102
- ".localhost",
103
- ".decocms.com", // hosted Studio (decofile API) + preview daemons
104
- ];
105
-
106
- function readApiDomains(env: Record<string, string | undefined>): string[] {
107
- const configured = (env.DECO_PREVIEW_API_DOMAINS ?? "")
108
- .split(",")
109
- .map((s) => s.trim().toLowerCase())
110
- .filter(Boolean);
111
- return configured.length > 0 ? configured : DEFAULT_PREVIEW_API_DOMAINS;
112
- }
113
-
114
- /**
115
- * Validate the token's authority against the configured domains and derive the
116
- * fetch origin, or null if no domain admits it.
117
- *
118
- * The token proposes, configuration disposes: only the hostname-suffix match
119
- * decides, so a caller can steer WHICH label under your domains, never which
120
- * domains. Scheme is derived — http for localhost-ish domains, https
121
- * otherwise — and an explicit port is allowed only there, so a public-domain
122
- * token cannot aim at odd ports.
123
- */
124
- export function previewApiOriginForHost(
125
- authority: string,
126
- env?: Record<string, string | undefined>,
127
- ): string | null {
128
- const [host, port] = authority.toLowerCase().split(":");
129
- if (!host) return null;
130
- const domain = readApiDomains(envOrProcess(env)).find((d) =>
131
- d.startsWith(".") ? host.length > d.length && host.endsWith(d) : host === d,
132
- );
133
- if (!domain) return null;
134
- // Local entries may carry an explicit port; public domains may not (a
135
- // public-domain token must not steer the fetch at odd ports).
136
- const local =
137
- domain === "localhost" ||
138
- domain === "127.0.0.1" ||
139
- domain.endsWith(".localhost") ||
140
- domain === "local.studio.decocms.com";
141
- if (port !== undefined && !local) return null;
142
- // Scheme is derived, never taken from the token. Plain-loopback dev hosts
143
- // are http; local.studio.decocms.com is the native app's TLS dev origin
144
- // (locally-trusted cert), so it — like every public domain — is https.
145
- const insecure =
146
- domain === "localhost" ||
147
- domain === "127.0.0.1" ||
148
- domain.endsWith(".localhost");
149
- return `${insecure ? "http" : "https"}://${host}${port === undefined ? "" : `:${port}`}`;
150
- }
151
-
152
- /**
153
- * Hosts declared by the site itself (the global `site` block's `previewHosts`),
154
- * installed once at setup time by the framework binding.
155
- *
156
- * MUST be fed from the setup-time base blocks, never from `loadBlocks()` at
157
- * request time: the request path merges the draft override, and an allowlist
158
- * readable through the override could be rewritten by the very draft it gates.
159
- */
160
- // globalThis-backed, like the block loader itself: bundlers can duplicate
161
- // this module across graphs, and a plain module variable set in one instance
162
- // is invisible to the others. (The MIDDLEWARE runtime is a separate world
163
- // even so — which is why the page-side gate is the authoritative one and the
164
- // middleware only hard-gates when the env override is present.)
165
- const G = globalThis as { __decoDraftHosts?: string[]; __decoSite?: string };
166
-
167
- /** Install the site-declared preview hosts. Called by the framework binding at setup. */
168
- export function setDraftPreviewHosts(hosts: readonly unknown[]): void {
169
- G.__decoDraftHosts = hosts
170
- .filter((h): h is string => typeof h === "string")
171
- .map((h) => h.trim().toLowerCase())
172
- .filter(Boolean);
173
- }
174
-
175
- /**
176
- * Register the resolved site name (`DECO_SITE_NAME` / an explicit setup
177
- * option, resolved by the framework binding at setup). deco-operated preview
178
- * hosts are derived from it, both exact:
179
- *
180
- * - `<site>.deco.site` — the stable deco-hosted domain.
181
- * - `<site>.deco-cx.workers.dev` — the workers.dev deploy URL
182
- * (e.g. `acme-tanstack.deco-cx.workers.dev`).
183
- *
184
- * Both are MERGED with the site-block/env list rather than replacing it: they
185
- * are deco-operated infra, so a signed draft grant can preview there out of the
186
- * box, while a custom production domain — never inferred here — stays inert.
187
- * Fed from the trusted setup-time site name, never from the request or a draft.
188
- *
189
- * Threat model, now that a named site is no longer inert by default: the
190
- * request host is spoofable on a direct-to-origin request (the edge is trusted
191
- * to set `x-forwarded-host`), so for a named site the SIGNED `?__draft=` grant
192
- * is the sole remaining gate — host-scoping only bounds blast radius. Set
193
- * `DECO_ALLOWED_PREVIEW_HOSTS=none` to kill preview entirely, including these
194
- * inferred hosts, without a deploy.
195
- */
196
- export function setDecoSiteHost(site: string | null | undefined): void {
197
- const s = (site ?? "").trim().toLowerCase();
198
- G.__decoSite = s || undefined;
199
- }
200
-
201
- /**
202
- * Hosts allowed to render drafts.
203
- *
204
- * The site block is the expected source — the opt-in lives in the repo,
205
- * reviewed in a PR, versioned with branches. `DECO_ALLOWED_PREVIEW_HOSTS`
206
- * REPLACES it when set: an operational escape hatch (kill a bad value without
207
- * a deploy, add a machine-specific port) — not the primary configuration.
208
- *
209
- * The deco-hosted domains inferred from the site name (via `setDecoSiteHost`)
210
- * are always ADDED on top, so a signed draft grant can preview on
211
- * deco-operated infra without any per-site config.
212
- *
213
- * The sentinel `DECO_ALLOWED_PREVIEW_HOSTS=none` is a KILL SWITCH: it disables
214
- * preview entirely — the inferred hosts and the site block included — so a bad
215
- * rollout can be stopped without a deploy. It must win over every other source.
216
- */
217
- function readAllowedHosts(env: Record<string, string | undefined>): string[] {
218
- const fromEnv = (env.DECO_ALLOWED_PREVIEW_HOSTS ?? "")
219
- .split(",")
220
- .map((s) => s.trim().toLowerCase())
221
- .filter(Boolean);
222
- if (fromEnv.includes("none")) return [];
223
- const configured = fromEnv.length > 0 ? fromEnv : (G.__decoDraftHosts ?? []);
224
- const site = G.__decoSite;
225
- if (!site) return configured;
226
- const inferred = [`${site}.deco.site`, `${site}.deco-cx.workers.dev`].filter(
227
- (h) => !configured.includes(h),
228
- );
229
- return inferred.length > 0 ? [...configured, ...inferred] : configured;
230
- }
231
-
232
- /**
233
- * Whether `host` (as seen on the request) may render drafts.
234
- *
235
- * Compared against the allowlist verbatim, port included — local dev is
236
- * `localhost:3100`, not `localhost`. The header is spoofable by a
237
- * direct-to-origin request, but the draft id is the actual capability;
238
- * host-scoping bounds blast radius (production domains stay inert), it is not
239
- * a secret.
240
- */
241
- export function isDraftHostAllowed(
242
- host: string | null | undefined,
243
- env?: Record<string, string | undefined>,
244
- ): boolean {
245
- if (!host) return false;
246
- return readAllowedHosts(envOrProcess(env)).includes(
247
- host.trim().toLowerCase(),
248
- );
249
- }
250
-
251
- /**
252
- * True when any host is allowed to preview. A plain env read — callers use it
253
- * to gate BEFORE touching dynamic APIs (`cookies()`/`headers()`), so an
254
- * unconfigured site never loses static/ISR rendering. A site with no config
255
- * but a resolved name is now enabled here (its inferred `<site>.deco.site` /
256
- * `<site>.deco-cx.workers.dev` hosts); `DECO_ALLOWED_PREVIEW_HOSTS=none`
257
- * forces it back to fully inert. The per-request host match happens later, in
258
- * `isDraftHostAllowed`.
259
- */
260
- export function isDraftPreviewEnabled(
261
- env?: Record<string, string | undefined>,
262
- ): boolean {
263
- return readAllowedHosts(envOrProcess(env)).length > 0;
264
- }
265
-
266
- function envOrProcess(
267
- env?: Record<string, string | undefined>,
268
- ): Record<string, string | undefined> {
269
- return (
270
- env ??
271
- (globalThis as { process?: { env?: Record<string, string | undefined> } })
272
- .process?.env ??
273
- {}
274
- );
275
- }
276
-
277
- /**
278
- * Version cache. Bounded on purpose: a decofile is routinely multi-megabyte,
279
- * so an unbounded map keyed by version would grow with every save until the
280
- * process died. Content-addressed, so a hit is always correct.
281
- */
282
- const MAX_CACHED_VERSIONS = 3;
283
- const byVersion = new Map<string, Record<string, unknown>>();
284
-
285
- function cacheDraft(version: string, blocks: Record<string, unknown>): void {
286
- byVersion.delete(version);
287
- byVersion.set(version, blocks);
288
- while (byVersion.size > MAX_CACHED_VERSIONS) {
289
- const oldest = byVersion.keys().next().value;
290
- if (oldest === undefined) break;
291
- byVersion.delete(oldest);
292
- }
293
- }
294
-
295
- /** Test seam — drops every cached version. */
296
- export function clearDraftCache(): void {
297
- byVersion.clear();
298
- }
299
-
300
- export interface ResolveDraftOptions {
301
- /** Raw `<host[:port]><path>@<version>` token from the request. */
302
- pointer: string | null | undefined;
303
- /** Defaults to `process.env`. */
304
- env?: Record<string, string | undefined>;
305
- /** Defaults to global `fetch`. Injected in tests. */
306
- fetchImpl?: typeof fetch;
307
- }
308
-
309
- /**
310
- * Resolve a draft token to a decofile, or null to render published content.
311
- *
312
- * Null on every failure path — disabled, malformed token, disallowed origin,
313
- * unreachable, non-2xx — because a draft that cannot be resolved must degrade
314
- * to published rather than break the page.
315
- */
316
- export async function resolveDraftDecofile(
317
- options: ResolveDraftOptions,
318
- ): Promise<Record<string, unknown> | null> {
319
- const env = envOrProcess(options.env);
320
- if (!isDraftPreviewEnabled(env)) return null;
321
-
322
- const parsed = parseDraftPointer(options.pointer);
323
- if (!parsed) return null;
324
-
325
- // Origin validation BEFORE the cache: a cached version must never be served
326
- // for a pointer whose authority the configuration would reject.
327
- const origin = previewApiOriginForHost(parsed.host, env);
328
- if (!origin) return null;
329
-
330
- const cached = byVersion.get(parsed.version);
331
- if (cached) return cached;
332
-
333
- const doFetch = options.fetchImpl ?? fetch;
334
- // The pointer's version rides along as `v=`, making the fetch URL fully
335
- // content-addressed (path + token + version). Today the server serves it
336
- // no-store either way — token-protected drafts are deliberately NOT
337
- // shared-cacheable (edge caches can't re-validate the grant, so revocation
338
- // wouldn't propagate). The param still earns its place: version-tagged
339
- // access logs, and it's the prerequisite for edge-validated caching later
340
- // (a CDN worker checking the token per request, keyed on path+version)
341
- // without another runtime deploy.
342
- const url = new URL(parsed.path, origin);
343
- url.searchParams.append("v", parsed.version);
344
- let res: Response;
345
- try {
346
- res = await doFetch(url.toString(), { cache: "no-store" });
347
- } catch {
348
- return null;
349
- }
350
- if (!res.ok) return null;
351
-
352
- let blocks: Record<string, unknown>;
353
- try {
354
- blocks = (await res.json()) as Record<string, unknown>;
355
- } catch {
356
- return null;
357
- }
358
-
359
- cacheDraft(parsed.version, blocks);
360
- return blocks;
361
- }
362
-
363
- // ---------------------------------------------------------------------------
364
- // Request-level resolution (framework-agnostic; for secondary endpoints)
365
- // ---------------------------------------------------------------------------
366
-
367
- /**
368
- * Cookie the draft pointer travels in across navigation. The Next binding's
369
- * middleware sets it on entry; a SECONDARY endpoint that must honour the same
370
- * draft — `/deco/invoke`, which is a separate request from the page render —
371
- * reads it back off the raw Request here.
372
- *
373
- * Duplicated (as a plain literal) in `@decocms/nextjs`'s client-safe
374
- * `draftConstants`, because the client badge cannot import this server-only
375
- * module. A parity test keeps the two in lock-step.
376
- */
377
- export const DRAFT_COOKIE_NAME = "__deco_draft";
378
- /** Query param that enters draft mode; `off` leaves it. */
379
- export const DRAFT_QUERY_PARAM = "__draft";
380
-
381
- /** Read one cookie value out of a raw `Cookie:` header. */
382
- function readCookieValue(
383
- cookieHeader: string | null | undefined,
384
- name: string,
385
- ): string | null {
386
- if (!cookieHeader) return null;
387
- for (const part of cookieHeader.split(";")) {
388
- const eq = part.indexOf("=");
389
- if (eq === -1) continue;
390
- if (part.slice(0, eq).trim() === name) {
391
- return decodeURIComponent(part.slice(eq + 1).trim());
392
- }
393
- }
394
- return null;
395
- }
396
-
397
- /**
398
- * The draft pointer a raw Request is carrying: `?__draft=` wins, the cookie
399
- * carries navigation, `off` exits. Same precedence as the Next binding's
400
- * page-side `selectDraftPointer`, but reads straight off the Request so it
401
- * works in a plain route handler (no `next/headers`, no React scope).
402
- */
403
- export function draftPointerFromRequest(request: Request): string | null {
404
- const url = new URL(request.url);
405
- const param = url.searchParams.get(DRAFT_QUERY_PARAM);
406
- if (param === "off") return null;
407
- if (param) return param;
408
- return readCookieValue(request.headers.get("cookie"), DRAFT_COOKIE_NAME);
409
- }
410
-
411
- export interface ResolveDraftForRequestOptions {
412
- env?: Record<string, string | undefined>;
413
- fetchImpl?: typeof fetch;
414
- }
415
-
416
- /**
417
- * Resolve the draft decofile a raw Request is asking for, or null to fall back
418
- * to published blocks.
419
- *
420
- * Applies the SAME gate as the page path — allowlist non-empty, request host
421
- * allowed, pointer valid, origin allowed, fetch OK — so a secondary endpoint
422
- * can bind the identical draft the page is rendering instead of silently
423
- * serving published content. Wrap the endpoint's work in
424
- * `withBlocksOverride(blocks, ...)` with the result; null means "don't wrap".
425
- *
426
- * This is what lets `/deco/invoke` (client-fetched lazy sections, self-fetched
427
- * section loaders) honour a draft: the draft binding lives in per-request state
428
- * that does not travel across an HTTP hop, so the endpoint must re-resolve it
429
- * from the request it received.
430
- */
431
- export async function resolveDraftForRequest(
432
- request: Request,
433
- options: ResolveDraftForRequestOptions = {},
434
- ): Promise<Record<string, unknown> | null> {
435
- const env = envOrProcess(options.env);
436
- if (!isDraftPreviewEnabled(env)) return null;
437
- const pointer = draftPointerFromRequest(request);
438
- if (!pointer) return null;
439
- const host =
440
- request.headers.get("x-forwarded-host") ?? request.headers.get("host");
441
- if (!isDraftHostAllowed(host, env)) return null;
442
- return resolveDraftDecofile({ pointer, env, fetchImpl: options.fetchImpl });
443
- }
444
-
445
- // ---------------------------------------------------------------------------
446
- // Request binding (dependency-injected by the framework binding)
447
- // ---------------------------------------------------------------------------
448
-
449
- type DraftOverrideGetter = () => Record<string, unknown> | null | undefined;
450
-
451
- // globalThis-backed like the hosts above: bundlers can duplicate this module
452
- // across graphs (nested node_modules installs, RSC layer splits), and a getter
453
- // registered on one instance's module variable is invisible to the copy
454
- // `loadBlocks()` imports — the framework binding then resolves the draft while
455
- // the render silently serves published content.
456
- const GG = globalThis as { __decoDraftOverrideGetter?: DraftOverrideGetter };
457
-
458
- /**
459
- * Inject the request-scoped draft getter.
460
- *
461
- * Binding a value to "the current request" is framework-specific and `blocks`
462
- * must not know about any framework: `@decocms/nextjs` backs this with React
463
- * `cache()` (App Router has no AsyncLocalStorage request scope of its own).
464
- * Never called → returns undefined → `loadBlocks()` behaves exactly as before.
465
- */
466
- export function setDraftOverrideGetter(getter: DraftOverrideGetter): void {
467
- GG.__decoDraftOverrideGetter = getter;
468
- }
469
-
470
- /** The current request's draft blocks, if a binding registered one. */
471
- export function getRequestDraftOverride():
472
- | Record<string, unknown>
473
- | null
474
- | undefined {
475
- return GG.__decoDraftOverrideGetter?.();
476
- }
package/src/cms/index.ts DELETED
@@ -1,180 +0,0 @@
1
- export type {
2
- ApplySectionConventionsInput,
3
- SectionMetaEntry,
4
- } from "./applySectionConventions";
5
- export { applySectionConventions } from "./applySectionConventions";
6
- export type { BlockSnapshot, BlockSource, KVNamespace, StoredRedirect } from "./blockSource";
7
- export {
8
- BUILD_HASH_ENV,
9
- BundledBlockSource,
10
- computeRevision,
11
- DEPLOYMENT_ID_ENV,
12
- DEPLOYMENTS_KEY,
13
- getDeploymentId,
14
- LIVE_KEY,
15
- redirectKey,
16
- redirectPrefix,
17
- revisionKey,
18
- snapshotKey,
19
- } from "./blockSource";
20
- export type { DeferredTrigger } from "./deferredTrigger";
21
- export { DEFAULT_DEFERRED_TRIGGER, getDeferredTrigger } from "./deferredTrigger";
22
- export type {
23
- DraftPointer,
24
- ResolveDraftForRequestOptions,
25
- ResolveDraftOptions,
26
- } from "./draftSource";
27
- export {
28
- clearDraftCache,
29
- DEFAULT_PREVIEW_API_DOMAINS,
30
- DRAFT_COOKIE_NAME,
31
- DRAFT_QUERY_PARAM,
32
- draftPointerFromRequest,
33
- getRequestDraftOverride,
34
- isDraftHostAllowed,
35
- isDraftPreviewEnabled,
36
- parseDraftPointer,
37
- previewApiOriginForHost,
38
- resolveDraftDecofile,
39
- resolveDraftForRequest,
40
- setDecoSiteHost,
41
- setDraftOverrideGetter,
42
- setDraftPreviewHosts,
43
- } from "./draftSource";
44
- export type { DecoPage, Resolvable } from "./loader";
45
- export {
46
- findPageByPath,
47
- getAllPages,
48
- getRevision,
49
- getSiteSeo,
50
- loadBlocks,
51
- onChange,
52
- setBlocks,
53
- withBlocksOverride,
54
- withDraftBlocks,
55
- } from "./loader";
56
- export type {
57
- OnBeforeResolveProps,
58
- SectionModule,
59
- SectionOptions,
60
- } from "./registry";
61
- export {
62
- getResolvedComponent,
63
- getSection,
64
- getSectionOptions,
65
- getSectionRegistry,
66
- getSyncComponent,
67
- listRegisteredSections,
68
- preloadSectionComponents,
69
- preloadSectionModule,
70
- registerOnBeforeResolveProps,
71
- registerSection,
72
- registerSections,
73
- registerSectionsSync,
74
- setResolvedComponent,
75
- setSectionRenderJson,
76
- } from "./registry";
77
- export type {
78
- DeferredRef,
79
- RenderJson,
80
- RenderJsonModule,
81
- SerializableSection,
82
- SerializedSection,
83
- SerializeOptions,
84
- } from "./renderJson";
85
- export { isSecretValue, serializeRenderJson, stringifyWithoutSecrets } from "./renderJson";
86
- export type {
87
- AsyncRenderingConfig,
88
- CommerceLoader,
89
- DanglingReferenceHandler,
90
- DecoPageResult,
91
- Deferred,
92
- DeferredSection,
93
- MatcherContext,
94
- PageSeo,
95
- ResolvedSection,
96
- ResolveErrorHandler,
97
- } from "./resolve";
98
- export {
99
- addSkipResolveType,
100
- asResolved,
101
- BOT_UA_SUBSTRINGS,
102
- cacheDeferredRawProps,
103
- clearCommerceLoaders,
104
- evaluateMatcher,
105
- extractSeoFromProps,
106
- extractSeoFromSections,
107
- getAsyncRenderingConfig,
108
- getDeferredRawProps,
109
- isBot,
110
- isDeferred,
111
- isEagerRequest,
112
- isSeoSection,
113
- onBeforeResolve,
114
- readDeferredRawProps,
115
- reExtractRawProps,
116
- registerBotPattern,
117
- registerCommerceLoader,
118
- registerCommerceLoaders,
119
- registerEagerSections,
120
- registerMatcher,
121
- registerNeverDeferSections,
122
- registerSeoSections,
123
- resolveDecoPage,
124
- resolveDeferred,
125
- resolveDeferredSection,
126
- resolveDeferredSectionFull,
127
- resolvePageSections,
128
- resolvePageSeoBlock,
129
- resolveValue,
130
- setAsyncRenderingConfig,
131
- setDanglingReferenceHandler,
132
- setResolveErrorHandler,
133
- unregisterCommerceLoader,
134
- WELL_KNOWN_TYPES,
135
- } from "./resolve";
136
- export type {
137
- ActionConfig,
138
- AppSchemas,
139
- BlockPropsSchema,
140
- LoaderConfig,
141
- MatcherConfig,
142
- MetaResponse,
143
- } from "./schema";
144
- export {
145
- composeMeta,
146
- getRegisteredLoaders,
147
- getRegisteredMatchers,
148
- inferLoaderTags,
149
- registerActionSchema,
150
- registerActionSchemas,
151
- registerAppSchemas,
152
- registerLoaderSchema,
153
- registerLoaderSchemas,
154
- registerMatcherSchema,
155
- registerMatcherSchemas,
156
- } from "./schema";
157
- export type { SectionLoaderContext } from "./sectionLoaderContext";
158
- export { buildSectionLoaderContext } from "./sectionLoaderContext";
159
- export type { SectionLoaderFn } from "./sectionLoaders";
160
- export {
161
- getDegradedSections,
162
- isCriticalSection,
163
- isLayoutSection,
164
- markSectionDegraded,
165
- registerCacheableSections,
166
- registerLayoutSections,
167
- registerNonCriticalSections,
168
- registerSectionLoader,
169
- registerSectionLoaders,
170
- runSectionLoaders,
171
- runSingleSectionLoader,
172
- unregisterLayoutSections,
173
- } from "./sectionLoaders";
174
- export {
175
- compose,
176
- withDevice,
177
- withMobile,
178
- withSearchParam,
179
- withSectionLoader,
180
- } from "./sectionMixins";