@decocms/blocks 8.0.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 (220) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +32 -82
  3. package/src/index.ts +35 -8
  4. package/src/protocol/assets.ts +124 -0
  5. package/src/protocol/canonical.ts +7 -0
  6. package/src/protocol/ciphertext.ts +6 -0
  7. package/src/protocol/client.ts +170 -0
  8. package/src/protocol/conformance/cases/assets.ts +81 -0
  9. package/src/protocol/conformance/cases/guards.ts +314 -0
  10. package/src/protocol/conformance/cases/reads.ts +168 -0
  11. package/src/protocol/conformance/cases/types.ts +9 -0
  12. package/src/protocol/conformance/cases/wire.ts +138 -0
  13. package/src/protocol/conformance/cases/writes.ts +345 -0
  14. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  15. package/src/protocol/conformance/context.ts +222 -0
  16. package/src/protocol/conformance/index.ts +140 -0
  17. package/src/protocol/errors.ts +142 -0
  18. package/src/protocol/index.ts +39 -0
  19. package/src/protocol/keys.ts +279 -0
  20. package/src/protocol/params.ts +67 -0
  21. package/src/protocol/secrets.ts +231 -0
  22. package/src/protocol/server/assets.ts +119 -0
  23. package/src/protocol/server/auth.ts +49 -0
  24. package/src/protocol/server/bodyCache.ts +84 -0
  25. package/src/protocol/server/content.ts +175 -0
  26. package/src/protocol/server/core.ts +112 -0
  27. package/src/protocol/server/handler.ts +102 -0
  28. package/src/protocol/server/http.ts +139 -0
  29. package/src/protocol/server/index.ts +11 -0
  30. package/src/protocol/server/methods/apply.ts +341 -0
  31. package/src/protocol/server/methods/read.ts +156 -0
  32. package/src/protocol/server/rpc.ts +136 -0
  33. package/src/protocol/storage/fs/hash.ts +21 -0
  34. package/src/protocol/storage/fs/index.ts +338 -0
  35. package/src/protocol/storage/fs/lock.ts +68 -0
  36. package/src/protocol/storage/fs/transaction.ts +183 -0
  37. package/src/protocol/storage/fs/unsupported.ts +15 -0
  38. package/src/protocol/storage/memory.ts +238 -0
  39. package/src/protocol/storage.ts +182 -0
  40. package/src/protocol/types.ts +172 -0
  41. package/src/v8/analytics.ts +50 -0
  42. package/src/v8/background.ts +107 -0
  43. package/src/v8/builtins/data.ts +23 -0
  44. package/src/v8/builtins/index.ts +26 -0
  45. package/src/v8/builtins/lazy.ts +23 -0
  46. package/src/v8/builtins/legacy.ts +65 -0
  47. package/src/v8/builtins/matchers.ts +31 -0
  48. package/src/v8/builtins/multivariate.ts +25 -0
  49. package/src/v8/builtins/secret.ts +82 -0
  50. package/src/v8/canonical.ts +117 -0
  51. package/src/v8/ciphertext.ts +158 -0
  52. package/src/v8/cli/builtins.ts +20 -0
  53. package/src/v8/cli/check/index.ts +774 -0
  54. package/src/v8/cli/check/messages.ts +168 -0
  55. package/src/v8/cli/content.ts +287 -0
  56. package/src/v8/cli/index.ts +17 -0
  57. package/src/v8/cli/log.ts +18 -0
  58. package/src/v8/cli/main.ts +12 -0
  59. package/src/v8/cli/root.ts +66 -0
  60. package/src/v8/cli/run.ts +236 -0
  61. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  62. package/src/v8/cli/schema/generate.ts +507 -0
  63. package/src/v8/cli/schema/index.ts +63 -0
  64. package/src/v8/cli/schema/tsProgram.ts +497 -0
  65. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  66. package/src/v8/cli/serve/server.ts +303 -0
  67. package/src/v8/cli/watch.ts +86 -0
  68. package/src/v8/client.ts +147 -0
  69. package/src/v8/cms.ts +237 -0
  70. package/src/v8/content.ts +195 -0
  71. package/src/v8/draft.ts +136 -0
  72. package/src/v8/errors.ts +59 -0
  73. package/src/v8/fetch.ts +133 -0
  74. package/src/v8/identity.ts +65 -0
  75. package/src/v8/index.ts +39 -0
  76. package/src/v8/json.ts +74 -0
  77. package/src/v8/matchRoute.ts +204 -0
  78. package/src/v8/remoteLoader.ts +282 -0
  79. package/src/v8/resolver.ts +278 -0
  80. package/src/v8/secrets.ts +17 -0
  81. package/src/v8/telemetry.ts +533 -0
  82. package/src/v8/types.ts +240 -0
  83. package/src/cms/applySectionConventions.ts +0 -124
  84. package/src/cms/blockSource.test.ts +0 -76
  85. package/src/cms/blockSource.ts +0 -191
  86. package/src/cms/client.browserBundle.test.ts +0 -44
  87. package/src/cms/client.ts +0 -80
  88. package/src/cms/draftSource.test.ts +0 -343
  89. package/src/cms/draftSource.ts +0 -362
  90. package/src/cms/index.ts +0 -151
  91. package/src/cms/layoutCacheRace.test.ts +0 -181
  92. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  93. package/src/cms/loadDecofileDirectory.ts +0 -89
  94. package/src/cms/loader.test.ts +0 -200
  95. package/src/cms/loader.ts +0 -304
  96. package/src/cms/registry.test.ts +0 -110
  97. package/src/cms/registry.ts +0 -242
  98. package/src/cms/resolve.test.ts +0 -980
  99. package/src/cms/resolve.ts +0 -2282
  100. package/src/cms/schema.test.ts +0 -356
  101. package/src/cms/schema.ts +0 -1215
  102. package/src/cms/sectionLoaderContext.test.ts +0 -111
  103. package/src/cms/sectionLoaderContext.ts +0 -113
  104. package/src/cms/sectionLoaders.test.ts +0 -533
  105. package/src/cms/sectionLoaders.ts +0 -636
  106. package/src/cms/sectionMixins.test.ts +0 -167
  107. package/src/cms/sectionMixins.ts +0 -153
  108. package/src/cms/stickyFlags.test.ts +0 -117
  109. package/src/flags/audience.ts +0 -56
  110. package/src/flags/everyone.ts +0 -29
  111. package/src/flags/flag.ts +0 -15
  112. package/src/flags/flags.test.ts +0 -148
  113. package/src/flags/multivariate/image.ts +0 -11
  114. package/src/flags/multivariate/message.ts +0 -11
  115. package/src/flags/multivariate/page.ts +0 -16
  116. package/src/flags/multivariate/section.ts +0 -16
  117. package/src/flags/multivariate.ts +0 -1
  118. package/src/flags/types.ts +0 -59
  119. package/src/flags/utils/multivariate.ts +0 -20
  120. package/src/hooks/Image.test.ts +0 -100
  121. package/src/hooks/Image.tsx +0 -250
  122. package/src/hooks/JsonLd.tsx +0 -353
  123. package/src/hooks/LazySection.tsx +0 -121
  124. package/src/hooks/LiveControls.tsx +0 -122
  125. package/src/hooks/Picture.tsx +0 -127
  126. package/src/hooks/RenderSection.test.tsx +0 -81
  127. package/src/hooks/RenderSection.tsx +0 -91
  128. package/src/hooks/SectionErrorFallback.tsx +0 -97
  129. package/src/hooks/index.ts +0 -30
  130. package/src/matchers/builtins.test.ts +0 -318
  131. package/src/matchers/builtins.ts +0 -459
  132. package/src/matchers/countryNames.ts +0 -104
  133. package/src/matchers/override.test.ts +0 -205
  134. package/src/matchers/override.ts +0 -136
  135. package/src/matchers/posthog.ts +0 -154
  136. package/src/middleware/decoState.ts +0 -55
  137. package/src/middleware/healthMetrics.ts +0 -133
  138. package/src/middleware/hydrationContext.test.ts +0 -61
  139. package/src/middleware/hydrationContext.ts +0 -79
  140. package/src/middleware/index.ts +0 -88
  141. package/src/middleware/liveness.ts +0 -21
  142. package/src/middleware/observability.test.ts +0 -242
  143. package/src/middleware/observability.ts +0 -643
  144. package/src/middleware/validateSection.test.ts +0 -147
  145. package/src/middleware/validateSection.ts +0 -100
  146. package/src/sdk/abTesting.test.ts +0 -326
  147. package/src/sdk/abTesting.ts +0 -499
  148. package/src/sdk/analytics.ts +0 -77
  149. package/src/sdk/cacheHeaders.test.ts +0 -115
  150. package/src/sdk/cacheHeaders.ts +0 -433
  151. package/src/sdk/cachedLoader.test.ts +0 -122
  152. package/src/sdk/cachedLoader.ts +0 -503
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/clx.ts +0 -5
  155. package/src/sdk/cn.test.ts +0 -34
  156. package/src/sdk/cn.ts +0 -28
  157. package/src/sdk/composite.test.ts +0 -121
  158. package/src/sdk/composite.ts +0 -114
  159. package/src/sdk/cookie.test.ts +0 -108
  160. package/src/sdk/cookie.ts +0 -129
  161. package/src/sdk/crypto.ts +0 -185
  162. package/src/sdk/csp.ts +0 -59
  163. package/src/sdk/detectDevice.ts +0 -45
  164. package/src/sdk/djb2.ts +0 -20
  165. package/src/sdk/encoding.test.ts +0 -71
  166. package/src/sdk/encoding.ts +0 -47
  167. package/src/sdk/env.test.ts +0 -33
  168. package/src/sdk/env.ts +0 -54
  169. package/src/sdk/flags.test.ts +0 -91
  170. package/src/sdk/flags.ts +0 -108
  171. package/src/sdk/http.test.ts +0 -71
  172. package/src/sdk/http.ts +0 -124
  173. package/src/sdk/index.ts +0 -90
  174. package/src/sdk/inflightTimeout.test.ts +0 -35
  175. package/src/sdk/inflightTimeout.ts +0 -53
  176. package/src/sdk/instrumentedFetch.test.ts +0 -559
  177. package/src/sdk/instrumentedFetch.ts +0 -339
  178. package/src/sdk/invoke.test.ts +0 -115
  179. package/src/sdk/invoke.ts +0 -298
  180. package/src/sdk/logger.test.ts +0 -432
  181. package/src/sdk/logger.ts +0 -304
  182. package/src/sdk/mergeCacheControl.ts +0 -150
  183. package/src/sdk/normalizeUrls.ts +0 -91
  184. package/src/sdk/observability.ts +0 -109
  185. package/src/sdk/otel.test.ts +0 -526
  186. package/src/sdk/otel.ts +0 -1012
  187. package/src/sdk/otelAdapters/clickhouseCollector.ts +0 -65
  188. package/src/sdk/otelAdapters.test.ts +0 -89
  189. package/src/sdk/otelAdapters.ts +0 -144
  190. package/src/sdk/otelHttpLog.test.ts +0 -457
  191. package/src/sdk/otelHttpLog.ts +0 -419
  192. package/src/sdk/otelHttpMeter.test.ts +0 -292
  193. package/src/sdk/otelHttpMeter.ts +0 -506
  194. package/src/sdk/otelHttpTracer.test.ts +0 -474
  195. package/src/sdk/otelHttpTracer.ts +0 -543
  196. package/src/sdk/redirects.ts +0 -228
  197. package/src/sdk/requestContext.ts +0 -281
  198. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  199. package/src/sdk/requestContextStorage.browser.ts +0 -43
  200. package/src/sdk/requestContextStorage.ts +0 -35
  201. package/src/sdk/retry.ts +0 -45
  202. package/src/sdk/serverTimings.ts +0 -68
  203. package/src/sdk/signal.ts +0 -42
  204. package/src/sdk/sitemap.ts +0 -160
  205. package/src/sdk/urlRedaction.test.ts +0 -73
  206. package/src/sdk/urlRedaction.ts +0 -82
  207. package/src/sdk/urlUtils.ts +0 -134
  208. package/src/sdk/useDevice.test.ts +0 -130
  209. package/src/sdk/useDevice.ts +0 -89
  210. package/src/sdk/useDeviceContext.tsx +0 -108
  211. package/src/sdk/useId.ts +0 -7
  212. package/src/sdk/useScript.test.ts +0 -128
  213. package/src/sdk/useScript.ts +0 -210
  214. package/src/sdk/useSuggestions.test.ts +0 -230
  215. package/src/sdk/useSuggestions.ts +0 -188
  216. package/src/sdk/wrapCaughtErrors.ts +0 -107
  217. package/src/setup.ts +0 -120
  218. package/src/types/index.ts +0 -53
  219. package/src/types/widgets.ts +0 -14
  220. package/tsconfig.json +0 -7
@@ -1,362 +0,0 @@
1
- /**
2
- * Draft preview — pull-based decofile override.
3
- *
4
- * A Studio preview serves the working-tree draft at
5
- * `GET <origin>/_sandbox/decofile`; a production site pulls it and renders its
6
- * own real pages against it. This replaces pushing the decofile into a POST
7
- * body, which only deco's own runtime honours — Next.js and most frameworks
8
- * render on GET only.
9
- *
10
- * This module is the framework-agnostic half: token parsing, origin
11
- * validation, fetching, and version caching. Binding a resolved draft to a
12
- * request is framework-specific (see `@decocms/nextjs`'s draft wiring) and
13
- * reaches this module through {@link setDraftOverrideGetter} — the same
14
- * dependency-injection shape as `setFastDeployKVGetter`, so `blocks` keeps its
15
- * zero-dependency direction.
16
- *
17
- * Inert unless `DECO_ALLOWED_PREVIEW_HOSTS` names the request's host: upgrading
18
- * the package must never be enough to start fetching from the network and
19
- * rendering unpublished content. Host-scoping (rather than a boolean) exists
20
- * because one deployment commonly serves several domains — the preview domain
21
- * may render drafts while the production domain, on the same build, must
22
- * ignore a `?__draft=` entirely.
23
- */
24
-
25
- /**
26
- * A parsed `?__draft=` token: `<host[:port]>@<version>`.
27
- *
28
- * The token carries the AUTHORITY of the draft content API, never a scheme or
29
- * path — a full URL would be an SSRF vector, and the scheme is derived from
30
- * the matched domain instead. Reserved evolution: a future signed token uses a
31
- * distinguishable prefix (e.g. `s1.`), so this strict two-part parse rejects
32
- * it cleanly rather than half-reading it.
33
- */
34
- export interface DraftPointer {
35
- /** Content-API authority, e.g. `abc.preview-studio.decocms.com` or `abc.localhost:60534`. */
36
- host: string;
37
- /** Opaque content version (the server's ETag). Immutable → safe cache key. */
38
- version: string;
39
- }
40
-
41
- /** Lowercase DNS hostname, at least two labels (a bare label can't match any domain). */
42
- const HOST_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)+$/;
43
- const PORT_RE = /^[0-9]{1,5}$/;
44
- const VERSION_RE = /^[A-Za-z0-9._-]{1,64}$/;
45
-
46
- /**
47
- * Parse `<host[:port]>@<version>`. Null on anything unexpected — callers fall
48
- * back to published content. Requires EXACTLY one `@`: a naive split accepts
49
- * `a@b@c` and silently uses the first two segments.
50
- */
51
- export function parseDraftPointer(raw: string | null | undefined): DraftPointer | null {
52
- if (!raw) return null;
53
- const parts = raw.split("@");
54
- if (parts.length !== 2) return null;
55
- const [authority, version] = parts;
56
- if (!authority || !version || !VERSION_RE.test(version)) return null;
57
-
58
- const [host, port, extra] = authority.toLowerCase().split(":");
59
- if (extra !== undefined) return null;
60
- if (!host || !HOST_RE.test(host)) return null;
61
- if (port !== undefined && !PORT_RE.test(port)) return null;
62
-
63
- return { host: port === undefined ? host : `${host}:${port}`, version };
64
- }
65
-
66
- /**
67
- * Domains the draft content API may live under — deco-operated, so shipping
68
- * them as defaults adds no SSRF surface. `DECO_PREVIEW_API_DOMAINS` overrides
69
- * the whole list when set. Entries are dot-prefixed suffixes, which guarantees
70
- * a label boundary on match (`evil-preview-studio.decocms.com` cannot pass).
71
- */
72
- export const DEFAULT_PREVIEW_API_DOMAINS = [
73
- ".preview-studio.decocms.com",
74
- ".local.studio.decocms.com",
75
- ".localhost",
76
- ];
77
-
78
- function readApiDomains(env: Record<string, string | undefined>): string[] {
79
- const configured = (env.DECO_PREVIEW_API_DOMAINS ?? "")
80
- .split(",")
81
- .map((s) => s.trim().toLowerCase())
82
- .filter(Boolean);
83
- return configured.length > 0 ? configured : DEFAULT_PREVIEW_API_DOMAINS;
84
- }
85
-
86
- /**
87
- * Validate the token's authority against the configured domains and derive the
88
- * fetch origin, or null if no domain admits it.
89
- *
90
- * The token proposes, configuration disposes: only the hostname-suffix match
91
- * decides, so a caller can steer WHICH label under your domains, never which
92
- * domains. Scheme is derived — http for localhost-ish domains, https
93
- * otherwise — and an explicit port is allowed only there, so a public-domain
94
- * token cannot aim at odd ports.
95
- */
96
- export function previewApiOriginForHost(
97
- authority: string,
98
- env?: Record<string, string | undefined>,
99
- ): string | null {
100
- const [host, port] = authority.toLowerCase().split(":");
101
- if (!host) return null;
102
- const domain = readApiDomains(envOrProcess(env)).find(
103
- (d) => host.length > d.length && host.endsWith(d),
104
- );
105
- if (!domain) return null;
106
- const local = domain.includes("localhost");
107
- if (port !== undefined && !local) return null;
108
- return `${local ? "http" : "https"}://${host}${port === undefined ? "" : `:${port}`}`;
109
- }
110
-
111
- /**
112
- * Hosts declared by the site itself (the global `site` block's `previewHosts`),
113
- * installed once at setup time by the framework binding.
114
- *
115
- * MUST be fed from the setup-time base blocks, never from `loadBlocks()` at
116
- * request time: the request path merges the draft override, and an allowlist
117
- * readable through the override could be rewritten by the very draft it gates.
118
- */
119
- // globalThis-backed, like the block loader itself: bundlers can duplicate
120
- // this module across graphs, and a plain module variable set in one instance
121
- // is invisible to the others. (The MIDDLEWARE runtime is a separate world
122
- // even so — which is why the page-side gate is the authoritative one and the
123
- // middleware only hard-gates when the env override is present.)
124
- const G = globalThis as { __decoDraftHosts?: string[] };
125
-
126
- /** Install the site-declared preview hosts. Called by the framework binding at setup. */
127
- export function setDraftPreviewHosts(hosts: readonly unknown[]): void {
128
- G.__decoDraftHosts = hosts
129
- .filter((h): h is string => typeof h === "string")
130
- .map((h) => h.trim().toLowerCase())
131
- .filter(Boolean);
132
- }
133
-
134
- /**
135
- * Hosts allowed to render drafts.
136
- *
137
- * The site block is the expected source — the opt-in lives in the repo,
138
- * reviewed in a PR, versioned with branches. `DECO_ALLOWED_PREVIEW_HOSTS`
139
- * REPLACES it when set: an operational escape hatch (kill a bad value without
140
- * a deploy, add a machine-specific port) — not the primary configuration.
141
- */
142
- function readAllowedHosts(env: Record<string, string | undefined>): string[] {
143
- const fromEnv = (env.DECO_ALLOWED_PREVIEW_HOSTS ?? "")
144
- .split(",")
145
- .map((s) => s.trim().toLowerCase())
146
- .filter(Boolean);
147
- return fromEnv.length > 0 ? fromEnv : (G.__decoDraftHosts ?? []);
148
- }
149
-
150
- /**
151
- * Whether `host` (as seen on the request) may render drafts.
152
- *
153
- * Compared against `DECO_ALLOWED_PREVIEW_HOSTS` verbatim, port included —
154
- * local dev is `localhost:3100`, not `localhost`. The header is spoofable by a
155
- * direct-to-origin request, but the draft id is the actual capability;
156
- * host-scoping bounds blast radius (production domains stay inert), it is not
157
- * a secret.
158
- */
159
- export function isDraftHostAllowed(
160
- host: string | null | undefined,
161
- env?: Record<string, string | undefined>,
162
- ): boolean {
163
- if (!host) return false;
164
- return readAllowedHosts(envOrProcess(env)).includes(host.trim().toLowerCase());
165
- }
166
-
167
- /**
168
- * True when any host is allowed to preview. A plain env read — callers use it
169
- * to gate BEFORE touching dynamic APIs (`cookies()`/`headers()`), so an
170
- * unconfigured site never loses static/ISR rendering. The per-request host
171
- * match happens later, in `isDraftHostAllowed`.
172
- */
173
- export function isDraftPreviewEnabled(env?: Record<string, string | undefined>): boolean {
174
- return readAllowedHosts(envOrProcess(env)).length > 0;
175
- }
176
-
177
- function envOrProcess(
178
- env?: Record<string, string | undefined>,
179
- ): Record<string, string | undefined> {
180
- return (
181
- env ??
182
- (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env ??
183
- {}
184
- );
185
- }
186
-
187
- /**
188
- * Version cache. Bounded on purpose: a decofile is routinely multi-megabyte,
189
- * so an unbounded map keyed by version would grow with every save until the
190
- * process died. Content-addressed, so a hit is always correct.
191
- */
192
- const MAX_CACHED_VERSIONS = 3;
193
- const byVersion = new Map<string, Record<string, unknown>>();
194
-
195
- function cacheDraft(version: string, blocks: Record<string, unknown>): void {
196
- byVersion.delete(version);
197
- byVersion.set(version, blocks);
198
- while (byVersion.size > MAX_CACHED_VERSIONS) {
199
- const oldest = byVersion.keys().next().value;
200
- if (oldest === undefined) break;
201
- byVersion.delete(oldest);
202
- }
203
- }
204
-
205
- /** Test seam — drops every cached version. */
206
- export function clearDraftCache(): void {
207
- byVersion.clear();
208
- }
209
-
210
- export interface ResolveDraftOptions {
211
- /** Raw `<host[:port]>@<version>` token from the request. */
212
- pointer: string | null | undefined;
213
- /** Defaults to `process.env`. */
214
- env?: Record<string, string | undefined>;
215
- /** Defaults to global `fetch`. Injected in tests. */
216
- fetchImpl?: typeof fetch;
217
- }
218
-
219
- /**
220
- * Resolve a draft token to a decofile, or null to render published content.
221
- *
222
- * Null on every failure path — disabled, malformed token, disallowed origin,
223
- * unreachable, non-2xx — because a draft that cannot be resolved must degrade
224
- * to published rather than break the page.
225
- */
226
- export async function resolveDraftDecofile(
227
- options: ResolveDraftOptions,
228
- ): Promise<Record<string, unknown> | null> {
229
- const env = envOrProcess(options.env);
230
- if (readAllowedHosts(env).length === 0) return null;
231
-
232
- const parsed = parseDraftPointer(options.pointer);
233
- if (!parsed) return null;
234
-
235
- const cached = byVersion.get(parsed.version);
236
- if (cached) return cached;
237
-
238
- const origin = previewApiOriginForHost(parsed.host, env);
239
- if (!origin) return null;
240
-
241
- const doFetch = options.fetchImpl ?? fetch;
242
- let res: Response;
243
- try {
244
- res = await doFetch(`${origin}/_sandbox/decofile`, { cache: "no-store" });
245
- } catch {
246
- return null;
247
- }
248
- if (!res.ok) return null;
249
-
250
- let blocks: Record<string, unknown>;
251
- try {
252
- blocks = (await res.json()) as Record<string, unknown>;
253
- } catch {
254
- return null;
255
- }
256
-
257
- cacheDraft(parsed.version, blocks);
258
- return blocks;
259
- }
260
-
261
- // ---------------------------------------------------------------------------
262
- // Request-level resolution (framework-agnostic; for secondary endpoints)
263
- // ---------------------------------------------------------------------------
264
-
265
- /**
266
- * Cookie the draft pointer travels in across navigation. The Next binding's
267
- * middleware sets it on entry; a SECONDARY endpoint that must honour the same
268
- * draft — `/deco/invoke`, which is a separate request from the page render —
269
- * reads it back off the raw Request here.
270
- *
271
- * Duplicated (as a plain literal) in `@decocms/nextjs`'s client-safe
272
- * `draftConstants`, because the client badge cannot import this server-only
273
- * module. A parity test keeps the two in lock-step.
274
- */
275
- export const DRAFT_COOKIE_NAME = "__deco_draft";
276
- /** Query param that enters draft mode; `off` leaves it. */
277
- export const DRAFT_QUERY_PARAM = "__draft";
278
-
279
- /** Read one cookie value out of a raw `Cookie:` header. */
280
- function readCookieValue(cookieHeader: string | null | undefined, name: string): string | null {
281
- if (!cookieHeader) return null;
282
- for (const part of cookieHeader.split(";")) {
283
- const eq = part.indexOf("=");
284
- if (eq === -1) continue;
285
- if (part.slice(0, eq).trim() === name) {
286
- return decodeURIComponent(part.slice(eq + 1).trim());
287
- }
288
- }
289
- return null;
290
- }
291
-
292
- /**
293
- * The draft pointer a raw Request is carrying: `?__draft=` wins, the cookie
294
- * carries navigation, `off` exits. Same precedence as the Next binding's
295
- * page-side `selectDraftPointer`, but reads straight off the Request so it
296
- * works in a plain route handler (no `next/headers`, no React scope).
297
- */
298
- export function draftPointerFromRequest(request: Request): string | null {
299
- const url = new URL(request.url);
300
- const param = url.searchParams.get(DRAFT_QUERY_PARAM);
301
- if (param === "off") return null;
302
- if (param) return param;
303
- return readCookieValue(request.headers.get("cookie"), DRAFT_COOKIE_NAME);
304
- }
305
-
306
- export interface ResolveDraftForRequestOptions {
307
- env?: Record<string, string | undefined>;
308
- fetchImpl?: typeof fetch;
309
- }
310
-
311
- /**
312
- * Resolve the draft decofile a raw Request is asking for, or null to fall back
313
- * to published blocks.
314
- *
315
- * Applies the SAME gate as the page path — allowlist non-empty, request host
316
- * allowed, pointer valid, origin allowed, fetch OK — so a secondary endpoint
317
- * can bind the identical draft the page is rendering instead of silently
318
- * serving published content. Wrap the endpoint's work in
319
- * `withBlocksOverride(blocks, ...)` with the result; null means "don't wrap".
320
- *
321
- * This is what lets `/deco/invoke` (client-fetched lazy sections, self-fetched
322
- * section loaders) honour a draft: the draft binding lives in per-request state
323
- * that does not travel across an HTTP hop, so the endpoint must re-resolve it
324
- * from the request it received.
325
- */
326
- export async function resolveDraftForRequest(
327
- request: Request,
328
- options: ResolveDraftForRequestOptions = {},
329
- ): Promise<Record<string, unknown> | null> {
330
- const env = envOrProcess(options.env);
331
- if (readAllowedHosts(env).length === 0) return null;
332
- const pointer = draftPointerFromRequest(request);
333
- if (!pointer) return null;
334
- const host = request.headers.get("x-forwarded-host") ?? request.headers.get("host");
335
- if (!isDraftHostAllowed(host, env)) return null;
336
- return resolveDraftDecofile({ pointer, env, fetchImpl: options.fetchImpl });
337
- }
338
-
339
- // ---------------------------------------------------------------------------
340
- // Request binding (dependency-injected by the framework binding)
341
- // ---------------------------------------------------------------------------
342
-
343
- type DraftOverrideGetter = () => Record<string, unknown> | null | undefined;
344
-
345
- let getDraftOverride: DraftOverrideGetter = () => undefined;
346
-
347
- /**
348
- * Inject the request-scoped draft getter.
349
- *
350
- * Binding a value to "the current request" is framework-specific and `blocks`
351
- * must not know about any framework: `@decocms/nextjs` backs this with React
352
- * `cache()` (App Router has no AsyncLocalStorage request scope of its own).
353
- * Never called → returns undefined → `loadBlocks()` behaves exactly as before.
354
- */
355
- export function setDraftOverrideGetter(getter: DraftOverrideGetter): void {
356
- getDraftOverride = getter;
357
- }
358
-
359
- /** The current request's draft blocks, if a binding registered one. */
360
- export function getRequestDraftOverride(): Record<string, unknown> | null | undefined {
361
- return getDraftOverride();
362
- }
package/src/cms/index.ts DELETED
@@ -1,151 +0,0 @@
1
- export type { ApplySectionConventionsInput, SectionMetaEntry } from "./applySectionConventions";
2
- export { applySectionConventions } from "./applySectionConventions";
3
- export type { BlockSnapshot, BlockSource, KVNamespace } from "./blockSource";
4
- export {
5
- BUILD_HASH_ENV,
6
- BundledBlockSource,
7
- computeRevision,
8
- DEPLOYMENT_ID_ENV,
9
- DEPLOYMENTS_KEY,
10
- getDeploymentId,
11
- LIVE_KEY,
12
- revisionKey,
13
- snapshotKey,
14
- } from "./blockSource";
15
- export type {
16
- DraftPointer,
17
- ResolveDraftForRequestOptions,
18
- ResolveDraftOptions,
19
- } from "./draftSource";
20
- export {
21
- clearDraftCache,
22
- DEFAULT_PREVIEW_API_DOMAINS,
23
- DRAFT_COOKIE_NAME,
24
- DRAFT_QUERY_PARAM,
25
- draftPointerFromRequest,
26
- getRequestDraftOverride,
27
- isDraftHostAllowed,
28
- isDraftPreviewEnabled,
29
- parseDraftPointer,
30
- previewApiOriginForHost,
31
- resolveDraftDecofile,
32
- resolveDraftForRequest,
33
- setDraftOverrideGetter,
34
- setDraftPreviewHosts,
35
- } from "./draftSource";
36
- export type { DecoPage, Resolvable } from "./loader";
37
- export {
38
- findPageByPath,
39
- getAllPages,
40
- getRevision,
41
- getSiteSeo,
42
- loadBlocks,
43
- onChange,
44
- setBlocks,
45
- withBlocksOverride,
46
- } from "./loader";
47
- export type { OnBeforeResolveProps, SectionModule, SectionOptions } from "./registry";
48
- export {
49
- getResolvedComponent,
50
- getSection,
51
- getSectionOptions,
52
- getSectionRegistry,
53
- getSyncComponent,
54
- listRegisteredSections,
55
- preloadSectionComponents,
56
- preloadSectionModule,
57
- registerOnBeforeResolveProps,
58
- registerSection,
59
- registerSections,
60
- registerSectionsSync,
61
- setResolvedComponent,
62
- } from "./registry";
63
- export type {
64
- AsyncRenderingConfig,
65
- CommerceLoader,
66
- DanglingReferenceHandler,
67
- DecoPageResult,
68
- DeferredSection,
69
- MatcherContext,
70
- PageSeo,
71
- ResolvedSection,
72
- ResolveErrorHandler,
73
- } from "./resolve";
74
- export {
75
- addSkipResolveType,
76
- cacheDeferredRawProps,
77
- clearCommerceLoaders,
78
- evaluateMatcher,
79
- extractSeoFromProps,
80
- extractSeoFromSections,
81
- getAsyncRenderingConfig,
82
- getDeferredRawProps,
83
- isBot,
84
- isEagerRequest,
85
- isSeoSection,
86
- onBeforeResolve,
87
- reExtractRawProps,
88
- registerBotPattern,
89
- registerCommerceLoader,
90
- registerCommerceLoaders,
91
- registerEagerSections,
92
- registerMatcher,
93
- registerNeverDeferSections,
94
- registerSeoSections,
95
- resolveDecoPage,
96
- resolveDeferredSection,
97
- resolveDeferredSectionFull,
98
- resolvePageSections,
99
- resolvePageSeoBlock,
100
- resolveValue,
101
- setAsyncRenderingConfig,
102
- setDanglingReferenceHandler,
103
- setResolveErrorHandler,
104
- unregisterCommerceLoader,
105
- WELL_KNOWN_TYPES,
106
- } from "./resolve";
107
- export type {
108
- ActionConfig,
109
- AppSchemas,
110
- BlockPropsSchema,
111
- LoaderConfig,
112
- MatcherConfig,
113
- MetaResponse,
114
- } from "./schema";
115
- export {
116
- composeMeta,
117
- getRegisteredLoaders,
118
- getRegisteredMatchers,
119
- inferLoaderTags,
120
- registerActionSchema,
121
- registerActionSchemas,
122
- registerAppSchemas,
123
- registerLoaderSchema,
124
- registerLoaderSchemas,
125
- registerMatcherSchema,
126
- registerMatcherSchemas,
127
- } from "./schema";
128
- export type { SectionLoaderContext } from "./sectionLoaderContext";
129
- export { buildSectionLoaderContext } from "./sectionLoaderContext";
130
- export type { SectionLoaderFn } from "./sectionLoaders";
131
- export {
132
- getDegradedSections,
133
- isCriticalSection,
134
- isLayoutSection,
135
- markSectionDegraded,
136
- registerCacheableSections,
137
- registerLayoutSections,
138
- registerNonCriticalSections,
139
- registerSectionLoader,
140
- registerSectionLoaders,
141
- runSectionLoaders,
142
- runSingleSectionLoader,
143
- unregisterLayoutSections,
144
- } from "./sectionLoaders";
145
- export {
146
- compose,
147
- withDevice,
148
- withMobile,
149
- withSearchParam,
150
- withSectionLoader,
151
- } from "./sectionMixins";
@@ -1,181 +0,0 @@
1
- import { describe, expect, it } from "vitest";
2
- import {
3
- registerLayoutSections,
4
- registerSectionLoader,
5
- registerSections,
6
- resolveDecoPage,
7
- runSectionLoaders,
8
- setBlocks,
9
- unregisterLayoutSections,
10
- } from "./index";
11
-
12
- /**
13
- * Regression test for the layout-cache index-corruption bug that shipped in
14
- * @decocms/start@6.12.1 and was fixed in 6.12.2 (blocks commit 73d4f19,
15
- * "fix(cms): don't mutate shared cached section objects when stamping
16
- * index"). Two live production sites (casaevideo-tanstack, bagaggio-tanstack)
17
- * hit this in the wild as an intermittent "footer renders above other
18
- * sections" bug under concurrent traffic.
19
- *
20
- * Mechanism: resolveDecoPage caches a layout section's (Header/Footer)
21
- * resolved output in a module-level Map, shared across every request that
22
- * references the same layout block — and dedupes concurrent in-flight
23
- * resolutions to the same shared Promise. Each request then stamps its own
24
- * page's flat position onto `.index` so mergeSections can sort eager +
25
- * deferred sections back into CMS order. If two concurrent requests need the
26
- * SAME cached layout section at DIFFERENT flat positions (e.g. page A has
27
- * Footer at index 0, page B has Footer at index 2), and stamping mutates the
28
- * shared cached object in place, whichever request's stamp lands last wins —
29
- * and both requests then see that same (possibly wrong-for-them) index.
30
- *
31
- * The fix clones the wrapper object before stamping, so each caller gets its
32
- * own `{ ...section, index }` and the shared cache/in-flight objects are
33
- * never touched.
34
- */
35
- describe("resolveDecoPage — layout section cache does not leak `.index` across concurrent requests", () => {
36
- it("gives each page its own correct Footer index when resolved concurrently", async () => {
37
- const FOOTER_TYPE = "site/sections/RaceFooter.tsx";
38
- const FILLER_TYPE = "site/sections/RaceFiller.tsx";
39
-
40
- // A controllable delay on Footer's resolver forces both concurrent
41
- // resolveDecoPage() calls to land on the SAME in-flight promise
42
- // (resolvedLayoutInflight), reproducing the exact shared-object window
43
- // the original bug required — without this, the two calls might resolve
44
- // sequentially and never actually share state.
45
- let releaseFooter: () => void = () => {};
46
- const footerGate = new Promise<void>((resolve) => {
47
- releaseFooter = resolve;
48
- });
49
-
50
- registerSections({
51
- [FOOTER_TYPE]: async () => {
52
- await footerGate;
53
- return { default: () => null };
54
- },
55
- [FILLER_TYPE]: async () => ({ default: () => null }),
56
- });
57
- registerLayoutSections([FOOTER_TYPE]);
58
-
59
- setBlocks({
60
- "pages-race-a": {
61
- path: "/race-a",
62
- // Footer at flat index 0 for this page.
63
- sections: [{ __resolveType: FOOTER_TYPE }, { __resolveType: FILLER_TYPE }],
64
- },
65
- "pages-race-b": {
66
- path: "/race-b",
67
- // Same Footer, but at flat index 2 for this page.
68
- sections: [
69
- { __resolveType: FILLER_TYPE },
70
- { __resolveType: FILLER_TYPE },
71
- { __resolveType: FOOTER_TYPE },
72
- ],
73
- },
74
- });
75
-
76
- try {
77
- const pending = Promise.all([resolveDecoPage("/race-a"), resolveDecoPage("/race-b")]);
78
-
79
- // Let both resolveDecoPage() calls start and reach the shared
80
- // in-flight Footer promise before releasing it — this is what forces
81
- // them onto the SAME cached/in-flight object rather than resolving
82
- // one after the other.
83
- await new Promise((r) => setTimeout(r, 10));
84
- releaseFooter();
85
-
86
- const [pageA, pageB] = await pending;
87
-
88
- const footerA = pageA?.resolvedSections.find((s) => s.component === FOOTER_TYPE);
89
- const footerB = pageB?.resolvedSections.find((s) => s.component === FOOTER_TYPE);
90
-
91
- expect(footerA).toBeDefined();
92
- expect(footerB).toBeDefined();
93
-
94
- // The bug: mutating a shared cached object in place means both pages
95
- // would observe whichever index was stamped last (either both 0 or
96
- // both 2), not their own correct position.
97
- expect(footerA?.index).toBe(0);
98
- expect(footerB?.index).toBe(2);
99
-
100
- // The fix clones the wrapper before stamping — each page's Footer
101
- // section must be its own object, not the same shared reference.
102
- expect(footerA).not.toBe(footerB);
103
- } finally {
104
- unregisterLayoutSections([FOOTER_TYPE]);
105
- }
106
- });
107
-
108
- it("does not leak index across sequential requests when the result is already in the TTL cache", async () => {
109
- // This covers the scenario missing from the concurrent test above:
110
- // Page A is fully served first (result lands in layoutCache), then Page B
111
- // arrives and hits the cache — it must get its own index, not Page A's.
112
- const FOOTER_KEY = "site/sections/SeqCacheFooter.tsx";
113
-
114
- registerLayoutSections([FOOTER_KEY]);
115
- registerSectionLoader(FOOTER_KEY, async (props) => props);
116
-
117
- const req = new Request("https://example.com/");
118
- const makeSection = (index: number) => ({
119
- component: FOOTER_KEY,
120
- props: {},
121
- key: `${FOOTER_KEY}-${index}`,
122
- index,
123
- });
124
-
125
- try {
126
- // First request: populate the TTL cache with index 2.
127
- const [sectionA] = await runSectionLoaders([makeSection(2)], req);
128
-
129
- // Second request: hits the TTL cache — must get index 7, not 2.
130
- const [sectionB] = await runSectionLoaders([makeSection(7)], req);
131
-
132
- expect(sectionA?.index).toBe(2);
133
- expect(sectionB?.index).toBe(7);
134
- // Must be separate objects — the cached entry must never carry an index.
135
- expect(sectionA).not.toBe(sectionB);
136
- } finally {
137
- unregisterLayoutSections([FOOTER_KEY]);
138
- }
139
- });
140
-
141
- it("mechanism check: mutating a shared object in place under concurrent stamping loses one side's index (isolated, framework-independent)", async () => {
142
- // This isolates the exact bug mechanism from the diff that shipped in
143
- // 6.12.1 and was reverted after the rollback, independent of the CMS
144
- // registry/cache machinery — proof that the failure mode is a plain JS
145
- // shared-mutable-object race, not something specific to this framework's
146
- // plumbing.
147
- type Wrapper = { component: string; index?: number };
148
-
149
- const sharedCached: Wrapper[] = [{ component: "Footer" }];
150
-
151
- // Old (buggy) behavior: mutate the shared array's objects in place.
152
- function stampBuggy(indexForThisCaller: number): Promise<Wrapper[]> {
153
- return Promise.resolve(sharedCached).then((sections) => {
154
- for (const s of sections) s.index = indexForThisCaller;
155
- return sections;
156
- });
157
- }
158
-
159
- // New (fixed) behavior: clone before stamping.
160
- function stampFixed(indexForThisCaller: number): Promise<Wrapper[]> {
161
- return Promise.resolve(sharedCached).then((sections) =>
162
- sections.map((s) => ({ ...s, index: indexForThisCaller })),
163
- );
164
- }
165
-
166
- // Two "requests" concurrently want different indices for the same
167
- // shared cached object. With the buggy stamper, whichever `.then()`
168
- // callback runs last (caller B, since microtasks run in scheduling
169
- // order) overwrites the object caller A already received a *reference*
170
- // to — so caller A's array ends up reporting caller B's index too.
171
- const [buggyA, buggyB] = await Promise.all([stampBuggy(0), stampBuggy(2)]);
172
- expect(buggyA[0].index).toBe(2); // <- corrupted: A wanted 0, sees 2
173
- expect(buggyB[0].index).toBe(2);
174
- expect(buggyA[0]).toBe(buggyB[0]); // same object reference — the bug
175
-
176
- const [fixedA, fixedB] = await Promise.all([stampFixed(0), stampFixed(2)]);
177
- expect(fixedA[0].index).toBe(0); // <- correct
178
- expect(fixedB[0].index).toBe(2); // <- correct
179
- expect(fixedA[0]).not.toBe(fixedB[0]); // independent objects — the fix
180
- });
181
- });