@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.
Files changed (175) hide show
  1. package/bin/deco.js +13 -0
  2. package/package.json +39 -3
  3. package/src/cms/applySectionConventions.ts +26 -2
  4. package/src/cms/blockSource.ts +37 -0
  5. package/src/cms/client.ts +5 -0
  6. package/src/cms/deferredTrigger.ts +58 -0
  7. package/src/cms/draftSource.ts +171 -57
  8. package/src/cms/index.ts +32 -3
  9. package/src/cms/loader.ts +318 -59
  10. package/src/cms/registry.ts +22 -0
  11. package/src/cms/renderJson.ts +179 -0
  12. package/src/cms/resolve.ts +396 -95
  13. package/src/cms/schema.ts +9 -5
  14. package/src/cms/sectionLoaders.ts +106 -56
  15. package/src/hooks/Image.tsx +70 -6
  16. package/src/hooks/LiveControls.tsx +30 -8
  17. package/src/hooks/Stats.tsx +134 -0
  18. package/src/hooks/index.ts +5 -0
  19. package/src/hooks/useLoadMore.ts +100 -0
  20. package/src/index.ts +37 -0
  21. package/src/middleware/observability.ts +173 -16
  22. package/src/preview/DraftPreviewBadge.tsx +306 -0
  23. package/src/preview/decoMark.ts +11 -0
  24. package/src/preview/index.ts +8 -0
  25. package/src/protocol/assets.ts +124 -0
  26. package/src/protocol/canonical.ts +7 -0
  27. package/src/protocol/ciphertext.ts +6 -0
  28. package/src/protocol/client.ts +170 -0
  29. package/src/protocol/conformance/cases/assets.ts +81 -0
  30. package/src/protocol/conformance/cases/guards.ts +314 -0
  31. package/src/protocol/conformance/cases/reads.ts +168 -0
  32. package/src/protocol/conformance/cases/types.ts +9 -0
  33. package/src/protocol/conformance/cases/wire.ts +138 -0
  34. package/src/protocol/conformance/cases/writes.ts +345 -0
  35. package/src/protocol/conformance/contentHashFixtures.ts +79 -0
  36. package/src/protocol/conformance/context.ts +222 -0
  37. package/src/protocol/conformance/index.ts +140 -0
  38. package/src/protocol/errors.ts +142 -0
  39. package/src/protocol/index.ts +39 -0
  40. package/src/protocol/keys.ts +279 -0
  41. package/src/protocol/params.ts +67 -0
  42. package/src/protocol/secrets.ts +231 -0
  43. package/src/protocol/server/assets.ts +119 -0
  44. package/src/protocol/server/auth.ts +49 -0
  45. package/src/protocol/server/bodyCache.ts +84 -0
  46. package/src/protocol/server/content.ts +175 -0
  47. package/src/protocol/server/core.ts +112 -0
  48. package/src/protocol/server/handler.ts +102 -0
  49. package/src/protocol/server/http.ts +139 -0
  50. package/src/protocol/server/index.ts +11 -0
  51. package/src/protocol/server/methods/apply.ts +341 -0
  52. package/src/protocol/server/methods/read.ts +156 -0
  53. package/src/protocol/server/rpc.ts +136 -0
  54. package/src/protocol/storage/fs/hash.ts +21 -0
  55. package/src/protocol/storage/fs/index.ts +338 -0
  56. package/src/protocol/storage/fs/lock.ts +68 -0
  57. package/src/protocol/storage/fs/transaction.ts +183 -0
  58. package/src/protocol/storage/fs/unsupported.ts +15 -0
  59. package/src/protocol/storage/memory.ts +238 -0
  60. package/src/protocol/storage.ts +182 -0
  61. package/src/protocol/types.ts +172 -0
  62. package/src/sdk/abTesting.ts +60 -3
  63. package/src/sdk/analytics.ts +72 -2
  64. package/src/sdk/cacheHeaders.ts +210 -10
  65. package/src/sdk/cacheStorage.ts +287 -0
  66. package/src/sdk/cachedLoader.ts +143 -90
  67. package/src/sdk/crypto.ts +16 -2
  68. package/src/sdk/deepOmit.ts +52 -0
  69. package/src/sdk/encoding.ts +2 -5
  70. package/src/sdk/experiments.ts +314 -0
  71. package/src/sdk/fetchCache.ts +269 -0
  72. package/src/sdk/fetchTimeout.ts +58 -0
  73. package/src/sdk/flags.ts +38 -8
  74. package/src/sdk/index.ts +7 -0
  75. package/src/sdk/instrumentedFetch.ts +25 -2
  76. package/src/sdk/nonce.ts +46 -0
  77. package/src/sdk/normalizeUrls.ts +2 -2
  78. package/src/sdk/observability.ts +8 -1
  79. package/src/sdk/otel.ts +131 -25
  80. package/src/sdk/otelHttpLog.ts +4 -4
  81. package/src/sdk/otelHttpMeter.ts +39 -13
  82. package/src/sdk/otelHttpTracer.ts +4 -4
  83. package/src/sdk/redirects.ts +113 -5
  84. package/src/sdk/responseCache.ts +82 -0
  85. package/src/sdk/urlUtils.ts +49 -0
  86. package/src/sdk/useSuggestions.ts +1 -1
  87. package/src/v8/analytics.ts +50 -0
  88. package/src/v8/background.ts +107 -0
  89. package/src/v8/builtins/data.ts +23 -0
  90. package/src/v8/builtins/index.ts +26 -0
  91. package/src/v8/builtins/lazy.ts +23 -0
  92. package/src/v8/builtins/legacy.ts +65 -0
  93. package/src/v8/builtins/matchers.ts +31 -0
  94. package/src/v8/builtins/multivariate.ts +25 -0
  95. package/src/v8/builtins/secret.ts +82 -0
  96. package/src/v8/canonical.ts +117 -0
  97. package/src/v8/ciphertext.ts +158 -0
  98. package/src/v8/cli/builtins.ts +20 -0
  99. package/src/v8/cli/check/index.ts +774 -0
  100. package/src/v8/cli/check/messages.ts +168 -0
  101. package/src/v8/cli/content.ts +287 -0
  102. package/src/v8/cli/index.ts +17 -0
  103. package/src/v8/cli/log.ts +18 -0
  104. package/src/v8/cli/main.ts +12 -0
  105. package/src/v8/cli/root.ts +66 -0
  106. package/src/v8/cli/run.ts +236 -0
  107. package/src/v8/cli/schema/builtinSchemas.ts +236 -0
  108. package/src/v8/cli/schema/generate.ts +507 -0
  109. package/src/v8/cli/schema/index.ts +63 -0
  110. package/src/v8/cli/schema/tsProgram.ts +497 -0
  111. package/src/v8/cli/schema/typeToSchema.ts +689 -0
  112. package/src/v8/cli/serve/server.ts +303 -0
  113. package/src/v8/cli/watch.ts +86 -0
  114. package/src/v8/client.ts +147 -0
  115. package/src/v8/cms.ts +237 -0
  116. package/src/v8/content.ts +195 -0
  117. package/src/v8/draft.ts +136 -0
  118. package/src/v8/errors.ts +59 -0
  119. package/src/v8/fetch.ts +152 -0
  120. package/src/v8/identity.ts +65 -0
  121. package/src/v8/index.ts +39 -0
  122. package/src/v8/json.ts +74 -0
  123. package/src/v8/matchRoute.ts +204 -0
  124. package/src/v8/remoteLoader.ts +282 -0
  125. package/src/v8/resolver.ts +278 -0
  126. package/src/v8/secrets.ts +17 -0
  127. package/src/v8/telemetry.ts +533 -0
  128. package/src/v8/types.ts +240 -0
  129. package/src/cms/blockSource.test.ts +0 -76
  130. package/src/cms/client.browserBundle.test.ts +0 -44
  131. package/src/cms/draftSource.test.ts +0 -343
  132. package/src/cms/layoutCacheRace.test.ts +0 -181
  133. package/src/cms/loadDecofileDirectory.test.ts +0 -109
  134. package/src/cms/loader.test.ts +0 -200
  135. package/src/cms/registry.test.ts +0 -110
  136. package/src/cms/resolve.test.ts +0 -980
  137. package/src/cms/schema.test.ts +0 -356
  138. package/src/cms/sectionLoaderContext.test.ts +0 -111
  139. package/src/cms/sectionLoaders.test.ts +0 -533
  140. package/src/cms/sectionMixins.test.ts +0 -167
  141. package/src/cms/stickyFlags.test.ts +0 -117
  142. package/src/flags/flags.test.ts +0 -148
  143. package/src/hooks/Image.test.ts +0 -100
  144. package/src/hooks/RenderSection.test.tsx +0 -81
  145. package/src/matchers/builtins.test.ts +0 -318
  146. package/src/matchers/override.test.ts +0 -205
  147. package/src/middleware/hydrationContext.test.ts +0 -61
  148. package/src/middleware/observability.test.ts +0 -242
  149. package/src/middleware/validateSection.test.ts +0 -147
  150. package/src/sdk/abTesting.test.ts +0 -326
  151. package/src/sdk/cacheHeaders.test.ts +0 -115
  152. package/src/sdk/cachedLoader.test.ts +0 -122
  153. package/src/sdk/cachedLoaderModule.test.ts +0 -209
  154. package/src/sdk/cn.test.ts +0 -34
  155. package/src/sdk/composite.test.ts +0 -121
  156. package/src/sdk/cookie.test.ts +0 -108
  157. package/src/sdk/encoding.test.ts +0 -71
  158. package/src/sdk/env.test.ts +0 -33
  159. package/src/sdk/flags.test.ts +0 -91
  160. package/src/sdk/http.test.ts +0 -71
  161. package/src/sdk/inflightTimeout.test.ts +0 -35
  162. package/src/sdk/instrumentedFetch.test.ts +0 -559
  163. package/src/sdk/invoke.test.ts +0 -115
  164. package/src/sdk/logger.test.ts +0 -432
  165. package/src/sdk/otel.test.ts +0 -526
  166. package/src/sdk/otelAdapters.test.ts +0 -89
  167. package/src/sdk/otelHttpLog.test.ts +0 -457
  168. package/src/sdk/otelHttpMeter.test.ts +0 -292
  169. package/src/sdk/otelHttpTracer.test.ts +0 -474
  170. package/src/sdk/requestContextStorage.browser.test.ts +0 -29
  171. package/src/sdk/urlRedaction.test.ts +0 -73
  172. package/src/sdk/useDevice.test.ts +0 -130
  173. package/src/sdk/useScript.test.ts +0 -128
  174. package/src/sdk/useSuggestions.test.ts +0 -230
  175. package/tsconfig.json +0 -7
package/src/cms/schema.ts CHANGED
@@ -882,7 +882,11 @@ function buildFrameworkSections(sectionAnyOf: any[], loaderUnion: any[]) {
882
882
  type: "object",
883
883
  title: "Structured Data",
884
884
  properties: {
885
- removeVideos: { type: "boolean", title: "Remove videos" },
885
+ removeVideos: {
886
+ type: "boolean",
887
+ title: "Remove videos (deprecated)",
888
+ description: "No effect: listing structured data is an ItemList, which carries no videos.",
889
+ },
886
890
  ignoreStructuredData: {
887
891
  type: "boolean",
888
892
  title: "Ignore Structured Data",
@@ -1104,9 +1108,9 @@ export function composeMeta(siteMeta: MetaResponse, options?: ComposeMetaOptions
1104
1108
  // Idempotency guard. composeMeta is NOT structurally idempotent — it appends
1105
1109
  // the framework section refs to `root.sections.anyOf` (and `__SECTION_REF__`),
1106
1110
  // so composing an already-composed meta a second time duplicates those refs.
1107
- // Since self-contained meta.gen.json is now baked at generation time (via the
1108
- // CLI's --compose), the tanstack runtime re-runs composeMeta on the file it
1109
- // loads from disk. A composed meta always carries a top-level `framework`
1111
+ // Since self-contained meta.gen.json is now baked at generation time (the CLI
1112
+ // always composes before writing), the tanstack runtime re-runs composeMeta
1113
+ // on the file it loads from disk. A composed meta always carries a `framework`
1110
1114
  // field, which raw generateMeta() output never sets — use it as the sentinel
1111
1115
  // and return the already-composed meta unchanged. Raw metas (framework unset,
1112
1116
  // e.g. sites generated by an older CLI) still compose normally, so this stays
@@ -1141,7 +1145,7 @@ export function composeMeta(siteMeta: MetaResponse, options?: ComposeMetaOptions
1141
1145
  const seenLoaderRefs = new Set<string>(loaders.loaderAnyOf.map((r: any) => r.$ref));
1142
1146
  const loaderUnion = [
1143
1147
  ...loaders.loaderAnyOf,
1144
- ...siteLoaderRefs.filter((r) => !seenLoaderRefs.has(r.$ref)),
1148
+ ...siteLoaderRefs.filter((r: { $ref: string }) => !seenLoaderRefs.has(r.$ref)),
1145
1149
  ];
1146
1150
 
1147
1151
  const fwSections = buildFrameworkSections(siteAnyOf, loaderUnion);
@@ -11,7 +11,8 @@
11
11
 
12
12
  import { RequestContext } from "@decocms/blocks/sdk/requestContext";
13
13
  import { getCacheProfile } from "../sdk/cacheHeaders";
14
- import { djb2 } from "../sdk/djb2";
14
+ import { cacheBackground, createCacheStore, getCacheStorageContext } from "../sdk/cacheStorage";
15
+ import { detectDevice } from "../sdk/detectDevice";
15
16
  import { withInflightTimeout } from "../sdk/inflightTimeout";
16
17
  import { withTracing } from "../sdk/observability";
17
18
  import type { ResolvedSection } from "./resolve";
@@ -90,6 +91,8 @@ export function getDegradedSections(): string[] {
90
91
 
91
92
  interface CacheableSectionConfig {
92
93
  maxAge: number;
94
+ /** Bounded stale window in milliseconds. Default: 5 minutes. */
95
+ staleWhileRevalidate?: number;
93
96
  }
94
97
 
95
98
  export type CacheableSectionInput =
@@ -112,19 +115,10 @@ interface SectionCacheEntry {
112
115
  refreshing: boolean;
113
116
  }
114
117
 
115
- const sectionLoaderCache = new Map<string, SectionCacheEntry>();
118
+ const sectionLoaderCache = createCacheStore<SectionCacheEntry>("sections");
116
119
  const sectionLoaderInflight = new Map<string, Promise<ResolvedSection>>();
117
- const MAX_SECTION_CACHE_ENTRIES = 200;
118
-
119
- function evictSectionCacheIfNeeded() {
120
- if (sectionLoaderCache.size <= MAX_SECTION_CACHE_ENTRIES) return;
121
- const oldest = [...sectionLoaderCache.entries()].sort((a, b) => a[1].createdAt - b[1].createdAt);
122
- const toDelete = oldest.slice(0, sectionLoaderCache.size - MAX_SECTION_CACHE_ENTRIES);
123
- for (const [key] of toDelete) sectionLoaderCache.delete(key);
124
- }
125
-
126
120
  function sectionCacheKey(component: string, props: Record<string, unknown>): string {
127
- return `${component}::${djb2(JSON.stringify(props))}`;
121
+ return `${component}::${JSON.stringify(props)}`;
128
122
  }
129
123
 
130
124
  /**
@@ -141,18 +135,24 @@ export function registerCacheableSections(configs: Record<string, CacheableSecti
141
135
  }
142
136
  }
143
137
 
144
- function runCacheableSectionLoader(
138
+ async function runCacheableSectionLoader(
145
139
  section: ResolvedSection,
146
140
  loader: SectionLoaderFn,
147
141
  request: Request,
148
142
  config: CacheableSectionConfig,
149
143
  ): Promise<ResolvedSection> {
150
- const key = sectionCacheKey(section.component, section.props as Record<string, unknown>);
144
+ const key = sectionLoaderCache.key(
145
+ sectionCacheKey(section.component, section.props as Record<string, unknown>),
146
+ );
151
147
 
152
148
  const existing = sectionLoaderInflight.get(key);
153
149
  if (existing) return existing;
154
150
 
155
- const entry = sectionLoaderCache.get(key);
151
+ const entry = getCacheStorageContext()?.storage
152
+ ? await sectionLoaderCache.read(key)
153
+ : sectionLoaderCache.get(key);
154
+ const pending = sectionLoaderInflight.get(key);
155
+ if (pending) return pending;
156
156
  const now = Date.now();
157
157
  const isStale = entry ? now - entry.createdAt > config.maxAge : true;
158
158
 
@@ -162,18 +162,25 @@ function runCacheableSectionLoader(
162
162
 
163
163
  if (entry && isStale && !entry.refreshing) {
164
164
  entry.refreshing = true;
165
- void Promise.resolve(loader(section.props as Record<string, unknown>, request))
166
- .then((enrichedProps) => {
167
- const enriched = { ...section, props: enrichedProps };
168
- sectionLoaderCache.set(key, {
169
- section: enriched,
170
- createdAt: Date.now(),
171
- refreshing: false,
172
- });
173
- })
174
- .catch(() => {
175
- entry.refreshing = false;
176
- });
165
+ cacheBackground(
166
+ Promise.resolve()
167
+ .then(() => loader(section.props as Record<string, unknown>, request))
168
+ .then((enrichedProps) => {
169
+ const enriched = { ...section, props: enrichedProps };
170
+ sectionLoaderCache.set(
171
+ key,
172
+ {
173
+ section: enriched,
174
+ createdAt: Date.now(),
175
+ refreshing: false,
176
+ },
177
+ Date.now() + config.maxAge + (config.staleWhileRevalidate ?? 300_000),
178
+ );
179
+ })
180
+ .catch(() => {
181
+ entry.refreshing = false;
182
+ }),
183
+ );
177
184
  return Promise.resolve(entry.section);
178
185
  }
179
186
 
@@ -183,12 +190,15 @@ function runCacheableSectionLoader(
183
190
  (async () => {
184
191
  const enrichedProps = await loader(section.props as Record<string, unknown>, request);
185
192
  const enriched = { ...section, props: enrichedProps };
186
- sectionLoaderCache.set(key, {
187
- section: enriched,
188
- createdAt: Date.now(),
189
- refreshing: false,
190
- });
191
- evictSectionCacheIfNeeded();
193
+ sectionLoaderCache.set(
194
+ key,
195
+ {
196
+ section: enriched,
197
+ createdAt: Date.now(),
198
+ refreshing: false,
199
+ },
200
+ Date.now() + config.maxAge + (config.staleWhileRevalidate ?? 300_000),
201
+ );
192
202
  return enriched;
193
203
  })(),
194
204
  `sectionLoader ${key}`,
@@ -212,10 +222,15 @@ export function registerSectionLoader(sectionKey: string, loader: SectionLoaderF
212
222
  *
213
223
  * Dev-only diagnostic: when a request-dependent loader (one built from
214
224
  * `withDevice`/`withMobile`/`withSearchParam`, possibly through `compose`)
215
- * is registered for a section that's also in `layoutSections`, the layout
216
- * cache will serve the first visitor's variant to every viewer for
217
- * `LAYOUT_CACHE_TTL` (5 min). We log a loud warning explaining the
218
- * remediation options. See #206.
225
+ * is registered for a section that's also in `layoutSections`, the layout cache
226
+ * may serve the first visitor's variant to every viewer for
227
+ * `LAYOUT_CACHE_TTL` (5 min). See #206.
228
+ *
229
+ * DEVICE is now segmented in the key ({@link layoutLoaderCacheKey}), so
230
+ * `withDevice`/`withMobile` are safe. The warning stays because
231
+ * `__requestDependent` is a single boolean and does not say WHICH signal the
232
+ * loader reads — a `withSearchParam` layout loader still contaminates, and we
233
+ * would rather warn on a safe case than stay silent on an unsafe one.
219
234
  */
220
235
  export function registerSectionLoaders(loaders: Record<string, SectionLoaderFn>): void {
221
236
  for (const [key, loader] of Object.entries(loaders)) {
@@ -228,9 +243,11 @@ export function registerSectionLoaders(loaders: Record<string, SectionLoaderFn>)
228
243
  if (requestDependent && layoutSections.has(key)) {
229
244
  console.warn(
230
245
  `[SectionLoaders] "${key}" is registered as a layout section ` +
231
- `(cached for 5min by component path) but its loader is request-` +
232
- `dependent (withDevice/withMobile/withSearchParam). The first ` +
233
- `visitor's variant will be served to all users for 5min. Fix: ` +
246
+ `(cached for 5min by component path + device) but its loader is ` +
247
+ `request-dependent (withDevice/withMobile/withSearchParam). ` +
248
+ `withDevice/withMobile are safe — device is in the key. If it ` +
249
+ `reads a search param, cookie or geo, the first visitor's variant ` +
250
+ `will be served to all users for 5min. Fix: ` +
234
251
  `(1) remove "export const layout = true" from the section, ` +
235
252
  `(2) call unregisterLayoutSections(["${key}"]) in setup.ts ` +
236
253
  `after applySectionConventions, or (3) move the request-` +
@@ -259,7 +276,7 @@ interface CachedSection {
259
276
  expiresAt: number;
260
277
  }
261
278
 
262
- const layoutCache = new Map<string, CachedSection>();
279
+ const layoutCache = createCacheStore<CachedSection>("layout-loaders");
263
280
  const layoutInflight = new Map<string, Promise<ResolvedSection>>();
264
281
 
265
282
  /**
@@ -267,10 +284,11 @@ const layoutInflight = new Map<string, Promise<ResolvedSection>>();
267
284
  * Layout sections (Header, Footer, etc.) are cached server-side
268
285
  * for LAYOUT_CACHE_TTL to avoid redundant enrichment on every navigation.
269
286
  *
270
- * The cache key is the component path only — it does NOT include UA,
271
- * cookies, or geo. Sections whose loader depends on those signals must
272
- * not be layout-cached: see {@link unregisterLayoutSections} to opt a
273
- * section out of the auto-discovery done by `applySectionConventions`.
287
+ * The cache key is the component path plus the DEVICE (see
288
+ * {@link layoutLoaderCacheKey}) — it does NOT include cookies, geo or search
289
+ * params. A section whose loader depends on THOSE must not be layout-cached:
290
+ * see {@link unregisterLayoutSections} to opt a section out of the
291
+ * auto-discovery done by `applySectionConventions`.
274
292
  */
275
293
  export function registerLayoutSections(keys: string[]): void {
276
294
  for (const key of keys) {
@@ -299,32 +317,64 @@ export function isLayoutSection(key: string): boolean {
299
317
  return layoutSections.has(key);
300
318
  }
301
319
 
302
- function getCachedLayout(component: string): ResolvedSection | null {
303
- const entry = layoutCache.get(component);
320
+ /**
321
+ * Cache key for a layout section's LOADER OUTPUT, segmented by device.
322
+ *
323
+ * This is the cache that actually carried the device leak, and it is a
324
+ * different one from `resolvedLayoutCache` in `cms/resolve.ts` — that one holds
325
+ * the CMS prop resolution, which never sees `isMobile`. `isMobile` is produced
326
+ * HERE, by the section's own loader (`ctx.device`, or a loader composed with
327
+ * `withDevice`/`withMobile`), and this cache stored it under the component path
328
+ * alone. Measured on a real store's PDP with Header/Footer layout-cached: the
329
+ * first request decided the variant for everyone — desktop first and a mobile
330
+ * visitor got `h-[90px]`; mobile first and a desktop visitor got
331
+ * `id="header-mobile-menu"`.
332
+ *
333
+ * Device is the right default axis because it is the one signal the framework
334
+ * itself injects into every section loader, so a layout section can depend on it
335
+ * without the site opting into anything. A layout whose output does not vary by
336
+ * device just gets up to 3 identical entries.
337
+ *
338
+ * Still NOT covered, and still the reason the `registerSectionLoaders` warning
339
+ * below exists: a layout loader that varies on a search param, a cookie or geo.
340
+ * Those are site-specific; such a section belongs outside `layoutSections`.
341
+ *
342
+ * Exported for unit testing.
343
+ */
344
+ export function layoutLoaderCacheKey(component: string, request?: Request): string {
345
+ return `${component}::${detectDevice(request?.headers?.get?.("user-agent") ?? "")}`;
346
+ }
347
+
348
+ async function getCachedLayout(cacheKey: string): Promise<ResolvedSection | null> {
349
+ const entry = await layoutCache.read(cacheKey);
304
350
  if (!entry) return null;
305
351
  if (Date.now() > entry.expiresAt) {
306
- layoutCache.delete(component);
352
+ layoutCache.delete(cacheKey);
307
353
  return null;
308
354
  }
309
355
  return entry.section;
310
356
  }
311
357
 
312
- function setCachedLayout(component: string, section: ResolvedSection): void {
313
- layoutCache.set(component, {
314
- section,
315
- expiresAt: Date.now() + LAYOUT_CACHE_TTL,
316
- });
358
+ function setCachedLayout(cacheKey: string, section: ResolvedSection): void {
359
+ layoutCache.set(
360
+ cacheKey,
361
+ {
362
+ section,
363
+ expiresAt: Date.now() + LAYOUT_CACHE_TTL,
364
+ },
365
+ Date.now() + LAYOUT_CACHE_TTL,
366
+ );
317
367
  }
318
368
 
319
369
  /**
320
370
  * Run a layout section's loader with in-flight dedup + TTL cache.
321
371
  */
322
- function resolveLayoutSection(
372
+ async function resolveLayoutSection(
323
373
  section: ResolvedSection,
324
374
  loader: SectionLoaderFn,
325
375
  request: Request,
326
376
  ): Promise<ResolvedSection> {
327
- const key = section.component;
377
+ const key = layoutCache.key(layoutLoaderCacheKey(section.component, request));
328
378
  const { index } = section;
329
379
 
330
380
  // Re-apply the caller's page-specific index onto a fresh object so the
@@ -332,7 +382,7 @@ function resolveLayoutSection(
332
382
  const withIndex = (s: ResolvedSection): ResolvedSection =>
333
383
  index !== undefined ? { ...s, index } : s;
334
384
 
335
- const cached = getCachedLayout(key);
385
+ const cached = await getCachedLayout(key);
336
386
  if (cached) return Promise.resolve(withIndex(cached));
337
387
 
338
388
  const existing = layoutInflight.get(key);
@@ -5,21 +5,28 @@ import { forwardRef } from "react";
5
5
  // Known asset prefixes that get stripped to produce a relative src path
6
6
  // -------------------------------------------------------------------------
7
7
 
8
- const DECO_CACHE_URL = "https://assets.decocache.com/";
9
- const S3_URL = "https://deco-sites-assets.s3.sa-east-1.amazonaws.com/";
8
+ // Anchored: only a leading host is stripped.
9
+ const DECO_ASSET_PREFIX_RE =
10
+ /^https:\/\/(?:assets\.decocache\.com|deco-sites-assets\.s3\.sa-east-1\.amazonaws\.com)\//;
11
+ // decoims.com — the legacy default image CDN (pre-#495). Decofiles are full of
12
+ // these URLs; passing one as `src=` to a Cloudflare Deco CDN makes it fetch
13
+ // itself → 508 Loop Detected. Azion CDNs (edgedeco/decoazn) fetch it fine but
14
+ // may 404 on the relative path, so only strip it for the Cloudflare ones.
15
+ const DECOIMS_PREFIX_RE = /^https:\/\/decoims\.com\//;
16
+ const CLOUDFLARE_CDNS = new Set(["assets.decocms.com", "decoims.com"]);
10
17
 
11
18
  // -------------------------------------------------------------------------
12
19
  // Configurable CDN domain
13
20
  // -------------------------------------------------------------------------
14
21
 
15
- let imageCdnDomain = "decoims.com";
22
+ let imageCdnDomain = "assets.decocms.com";
16
23
 
17
24
  /**
18
25
  * Register the image CDN domain used by `getOptimizedMediaUrl`.
19
26
  * Call once in your site's setup.ts before any page loads.
20
27
  *
21
28
  * Available domains:
22
- * - `decoims.com` (Cloudflare, default — best compression, same edge as Workers)
29
+ * - `assets.decocms.com` (Cloudflare, default — best compression, same edge as Workers)
23
30
  * - `deco-assets.edgedeco.com` (Azion IMS)
24
31
  * - `deco-assets.decoazn.com` (Azion IMS, legacy)
25
32
  */
@@ -31,6 +38,61 @@ export function getImageCdnDomain(): string {
31
38
  return imageCdnDomain;
32
39
  }
33
40
 
41
+ // -------------------------------------------------------------------------
42
+ // Configurable image quality
43
+ // -------------------------------------------------------------------------
44
+
45
+ /**
46
+ * Quality levels the Deco image CDN accepts as a site-wide default.
47
+ *
48
+ * The CDN maps these to 60% / 70% / 80%. It also accepts `original` (100%),
49
+ * deliberately excluded here: a global 100% default hurts performance on
50
+ * every page, which is the same call `DefaultQualityOptions` makes in the
51
+ * Fresh implementation this file was ported from (deco-cx/apps,
52
+ * website/components/Image.tsx).
53
+ *
54
+ * A union rather than `string` because the CDN **fails silently** on
55
+ * anything else: it answers 200 and serves its 60% default. So the obvious
56
+ * `registerImageQuality("80")` — quality means 1-100 in Cloudflare Images,
57
+ * next/image and imgix — would quietly serve the LOWEST quality while
58
+ * changing the cache key on every image. Measured against production
59
+ * decoims.com on one asset: no param 2911 B, `low` 2911, `medium` 3235,
60
+ * `high` 5189, and `"80"` / `"HIGH"` / garbage all 2911.
61
+ */
62
+ export type ImageQuality = "low" | "medium" | "high";
63
+
64
+ let imageQuality: ImageQuality | undefined;
65
+
66
+ /**
67
+ * Register the quality level `getOptimizedMediaUrl` asks the image CDN for.
68
+ *
69
+ * Call once at module scope in your site's setup, NOT from a loader, action or
70
+ * anything else on the request path. This is module-level state shared by every
71
+ * request in a Worker isolate: setting it per-request would leak across
72
+ * concurrent requests, and setting it on only one of the SSR/hydration paths
73
+ * would produce mismatched `src`/`srcSet` and re-download every image.
74
+ *
75
+ * Unset by default, which emits no `quality` param and leaves the CDN on its
76
+ * 60% default — so existing sites are byte-for-byte unaffected and no CDN
77
+ * cache is invalidated. Set it when a site's art direction needs fidelity over
78
+ * bytes: on fashion/editorial catalogues the default compression visibly
79
+ * softens fabric texture and print detail.
80
+ *
81
+ * Applies to every URL built by `getOptimizedMediaUrl` — `Image`, `getSrcSet`
82
+ * and also `Video` when it is given `forceOptimizedSrc`. It does NOT apply to
83
+ * VTEX- or Shopify-hosted sources: those are resized through their own native
84
+ * URL syntax (`optimizeVTEX` / `optimizeShopify`), which returns before the
85
+ * query-param block. On a VTEX storefront that means product imagery is
86
+ * untouched and only CMS/banner assets are affected.
87
+ */
88
+ export function registerImageQuality(quality: ImageQuality | undefined) {
89
+ imageQuality = quality || undefined;
90
+ }
91
+
92
+ export function getImageQuality(): ImageQuality | undefined {
93
+ return imageQuality;
94
+ }
95
+
34
96
  // -------------------------------------------------------------------------
35
97
  // Fit options & optimization types
36
98
  // -------------------------------------------------------------------------
@@ -77,7 +139,7 @@ function optimizeShopify(originalSrc: string, width: number, height?: number): s
77
139
  /**
78
140
  * Builds an optimized image URL.
79
141
  *
80
- * For Deco-hosted images (decocache / S3), strips the known prefix and
142
+ * For Deco-hosted images (decocache / S3 / decoims), strips the known prefix and
81
143
  * routes through the Deco image CDN for edge resize + format conversion.
82
144
  *
83
145
  * For platform-specific images (VTEX, Shopify), rewrites the URL using
@@ -114,7 +176,8 @@ export function getOptimizedMediaUrl(opts: OptimizationOptions): string {
114
176
  return optimizeShopify(originalSrc, width, height);
115
177
  }
116
178
 
117
- let imageSource = originalSrc.replace(DECO_CACHE_URL, "").replace(S3_URL, "").split("?")[0];
179
+ let imageSource = originalSrc.replace(DECO_ASSET_PREFIX_RE, "").split("?")[0];
180
+ if (CLOUDFLARE_CDNS.has(imageCdnDomain)) imageSource = imageSource.replace(DECOIMS_PREFIX_RE, "");
118
181
 
119
182
  // Already on the image CDN — strip the host so we don't proxy through ourselves.
120
183
  const cdnPrefix = `https://${imageCdnDomain}/`;
@@ -126,6 +189,7 @@ export function getOptimizedMediaUrl(opts: OptimizationOptions): string {
126
189
  params.set("fit", fit);
127
190
  params.set("width", `${width}`);
128
191
  if (height) params.set("height", `${height}`);
192
+ if (imageQuality) params.set("quality", imageQuality);
129
193
 
130
194
  return `https://${imageCdnDomain}/image?${params}&src=${imageSource}`;
131
195
  }
@@ -1,4 +1,7 @@
1
- import React from "react";
1
+ "use client";
2
+
3
+ import React, { useEffect } from "react";
4
+ import { getRequestNonce } from "../sdk/nonce";
2
5
 
3
6
  interface LiveControlsProps {
4
7
  site?: string;
@@ -15,6 +18,21 @@ interface LiveControlsProps {
15
18
  * 3. "." opens admin in same tab, Ctrl/Cmd+"." opens in new tab, Ctrl+Shift+E also works
16
19
  */
17
20
  export function LiveControls({ site, page, flags }: LiveControlsProps) {
21
+ // Keep `window.LIVE.page` in sync with the CURRENT page across SPA
22
+ // navigations. The bootstrap script below reads __DECO_STATE only once (on
23
+ // initial load), so without this effect a client-side navigation would leave
24
+ // window.LIVE.page pointing at the first page rendered — and the "." shortcut
25
+ // would send that page's pathTemplate/id (or the "/*" fallback) instead of the
26
+ // route the user is actually looking at.
27
+ useEffect(() => {
28
+ if (typeof window === "undefined") return;
29
+ const w = window as unknown as { LIVE?: Record<string, unknown> };
30
+ w.LIVE = w.LIVE || {};
31
+ w.LIVE.page = page || {};
32
+ w.LIVE.site = { name: site || "storefront" };
33
+ // eslint-disable-next-line react-hooks/exhaustive-deps
34
+ }, [site, page?.id, page?.pathTemplate]);
35
+
18
36
  return (
19
37
  <>
20
38
  <script
@@ -39,10 +57,11 @@ function LiveControlsScript() {
39
57
  if (window.__DECO_LIVE_CONTROLS__) return;
40
58
  window.__DECO_LIVE_CONTROLS__ = true;
41
59
 
42
- var TRUSTED_ORIGINS = ["https://deco.cx", "https://admin.deco.cx", "https://play.deco.cx"];
60
+ var TRUSTED_ORIGINS = ["https://deco.cx", "https://admin.deco.cx", "https://play.deco.cx", "https://decocms.com", "https://studio.decocms.com"];
43
61
  function isTrustedOrigin(origin) {
44
62
  return TRUSTED_ORIGINS.indexOf(origin) !== -1 ||
45
63
  (origin.startsWith("https://") && origin.endsWith(".deco.cx")) ||
64
+ (origin.startsWith("https://") && origin.endsWith(".decocms.com")) ||
46
65
  origin === window.location.origin;
47
66
  }
48
67
 
@@ -85,8 +104,9 @@ function LiveControlsScript() {
85
104
  });
86
105
 
87
106
  if (window.self === window.top) {
88
- document.body.addEventListener("keydown", function(e) {
89
- if (e.target !== document.body) return;
107
+ document.addEventListener("keydown", function(e) {
108
+ var t = e.target;
109
+ if (t && (t.tagName === "INPUT" || t.tagName === "TEXTAREA" || t.tagName === "SELECT" || t.isContentEditable)) return;
90
110
  if (e.defaultPrevented) return;
91
111
 
92
112
  if (
@@ -100,12 +120,12 @@ function LiveControlsScript() {
100
120
  var pageId = (window.LIVE.page && window.LIVE.page.id) || "";
101
121
  var pathTemplate = (window.LIVE.page && window.LIVE.page.pathTemplate) || "/*";
102
122
 
103
- var href = new URL("/choose-editor", "https://admin.deco.cx");
123
+ var href = new URL("/choose-editor", "https://studio.decocms.com");
104
124
  href.searchParams.set("site", siteName);
105
125
  href.searchParams.set("domain", window.location.origin);
106
126
  if (pageId) href.searchParams.set("pageId", pageId);
107
- href.searchParams.set("path", encodeURIComponent(window.location.pathname + window.location.search));
108
- href.searchParams.set("pathTemplate", encodeURIComponent(pathTemplate));
127
+ href.searchParams.set("path", window.location.pathname + window.location.search);
128
+ href.searchParams.set("pathTemplate", pathTemplate);
109
129
 
110
130
  if ((e.ctrlKey || e.metaKey) && e.key === ".") {
111
131
  window.open(href.toString(), "_blank");
@@ -118,5 +138,7 @@ function LiveControlsScript() {
118
138
  })();
119
139
  `;
120
140
 
121
- return <script type="module" dangerouslySetInnerHTML={{ __html: script }} />;
141
+ return (
142
+ <script type="module" nonce={getRequestNonce()} dangerouslySetInnerHTML={{ __html: script }} />
143
+ );
122
144
  }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Stats — deco's first-party analytics collector.
3
+ *
4
+ * MOUNTED BY THE FRAMEWORK. `DecoRootLayout` renders it, so a site turns analytics on with an
5
+ * environment variable and no code change — the same ergonomics the Fresh side already has,
6
+ * where `website/pages/Page.tsx` renders it for every page.
7
+ *
8
+ * It lives in `@decocms/blocks` rather than in `@decocms/apps-website` because of what it is:
9
+ * twenty lines of a `<link>` and a `<script>` driven by environment variables, pointing at our
10
+ * own collector. `OneDollarStats` belongs among the apps because it is a VENDOR integration —
11
+ * it wraps `history`, decodes a cookie and feeds a third party\'s SDK. This is framework
12
+ * infrastructure, and putting it here is also what lets `@decocms/tanstack` mount it without
13
+ * importing from an apps package, which would be a new edge in a dependency graph the repo
14
+ * keeps one-way on purpose.
15
+ *
16
+ * `@decocms/apps-website/components/Stats` re-exports it, so anything importing the old path
17
+ * keeps working.
18
+ *
19
+ * ## Why this is twenty lines and OneDollarStats is three hundred
20
+ *
21
+ * Not because it does less — because the work is on the other side. The lilstts SDK
22
+ * has no notion of SPA navigation the way this app routes, no notion of the
23
+ * `deco_segment` cookie, and no notion of `window.DECO.events`, so the component has
24
+ * to wrap `history.pushState`, poll for globals, read and decode the cookie, and
25
+ * forward every commerce event by hand.
26
+ *
27
+ * The deco collector's own bundle already does all of it, and is tested doing it:
28
+ * the core module takes the first pageview through the prerender guard, wraps
29
+ * `pushState`, `replaceState` and `popstate`, and flushes on `pagehide` and
30
+ * `visibilitychange`; the deco module reads `deco_segment` into experiment
31
+ * assignments and subscribes to `window.DECO.events`, mapping the commerce
32
+ * vocabulary. None of that belongs in a component that would then be a second
33
+ * implementation of it, drifting from the first.
34
+ *
35
+ * So there is no `useEffect` here, and that is the point. Nothing to hydrate, no
36
+ * readiness polling, no module-level guard against StrictMode double-mounting —
37
+ * because there is no client state to guard.
38
+ *
39
+ * ## data- attributes, not a global
40
+ *
41
+ * `dev` and `debug` are read off the tag rather than from `window.__dq`, and this is
42
+ * load-bearing on exactly this framework. TanStack hoists `<script async>` into
43
+ * `<head>` ABOVE any inline configuration block — measured at byte 190 against byte
44
+ * 1108 on a real site. A component that set a global and expected the collector to
45
+ * find it would boot into silence here, with no error: the collector would see a
46
+ * development host, skip, and say nothing. Attributes cannot lose that race because
47
+ * they are on the element that is executing.
48
+ *
49
+ * ## Off by default
50
+ *
51
+ * `DECO_ANALYTICS_ENABLED` must be set to `true`. This is the inverse of
52
+ * `ONEDOLLAR_ENABLED`, which defaults to on, and the asymmetry is deliberate: one is
53
+ * the incumbent and the other is being introduced. The two gates are also
54
+ * independent, so a site can run both during a shadow comparison and neither gate
55
+ * can turn the other off.
56
+ */
57
+
58
+ export interface Props {
59
+ /**
60
+ * Where the collector is published. Empty means same-origin, which is the
61
+ * intended deployment: the script and the beacon are served from the site's own
62
+ * hostname so no third-party request is involved and nothing is blocked.
63
+ */
64
+ origin?: string;
65
+ /**
66
+ * The site's public key, for sites NOT served through our CDN.
67
+ *
68
+ * Sites behind our edge are identified by the `Host` header, which a visitor
69
+ * cannot forge; those must leave this unset. A key travels in the page source
70
+ * where anyone can read and reuse it, so a key-identified site is recorded with
71
+ * `site_id_source = tag` and is never billed from.
72
+ */
73
+ siteKey?: string;
74
+ /** `defer` instead of `async`. Only for a page that needs strict ordering. */
75
+ defer?: boolean;
76
+ /**
77
+ * Collect from localhost. The collector refuses local and private hostnames by
78
+ * default, which is why a developer sees nothing until this is on.
79
+ */
80
+ dev?: boolean;
81
+ /** Log every queued and flushed batch to the console. */
82
+ debug?: boolean;
83
+ }
84
+
85
+ /** Same-origin. See {@link Props.origin}. */
86
+ export const DEFAULT_ORIGIN = "";
87
+
88
+ /**
89
+ * Opt-in, and independent of `ONEDOLLAR_ENABLED` so both can run at once.
90
+ */
91
+ const DECO_ANALYTICS_ENABLED = process.env.DECO_ANALYTICS_ENABLED === "true";
92
+ const DECO_ANALYTICS_ORIGIN = process.env.DECO_ANALYTICS_ORIGIN;
93
+ const DECO_ANALYTICS_SITE_KEY = process.env.DECO_ANALYTICS_SITE_KEY;
94
+
95
+ function Stats({ origin, siteKey, defer, dev, debug }: Props) {
96
+ if (!DECO_ANALYTICS_ENABLED) return null;
97
+
98
+ const base = origin ?? DECO_ANALYTICS_ORIGIN ?? DEFAULT_ORIGIN;
99
+ const key = siteKey ?? DECO_ANALYTICS_SITE_KEY;
100
+
101
+ return (
102
+ <>
103
+ {/*
104
+ * Only when the collector is on another origin. A `preconnect` to the page's
105
+ * own origin is a wasted hint at best, and on some browsers it is a second
106
+ * connection opened for nothing.
107
+ */}
108
+ {base ? <link rel="preconnect" href={base} crossOrigin="anonymous" /> : null}
109
+ <script
110
+ id="deco-analytics"
111
+ async={!defer}
112
+ defer={defer}
113
+ // THE KEY GOES IN THE URL, not in a `data-` attribute. The collector resolves the
114
+ // site server-side while RENDERING the bundle -- it reads `?k=` and writes the
115
+ // resolved config into the script it returns -- so a key on the element arrives
116
+ // far too late to matter. It is also never read: the bundle only looks at
117
+ // `data-dev` and `data-debug`.
118
+ //
119
+ // This was `data-site` and it would have failed the way this project's failures
120
+ // always do: the collector resolves nothing, serves the `s:"unknown"` fallback,
121
+ // and the site collects exactly zero with no error anywhere. Same shape as the
122
+ // bug that once made the entire self-serve tier silent.
123
+ src={`${base}/_dq/a.js${key ? `?k=${encodeURIComponent(key)}` : ""}`}
124
+ // Rendered only when true. `data-dev="false"` and an absent attribute mean
125
+ // the same thing to the collector, and the absent one cannot be mistaken
126
+ // for a deliberate setting by someone reading the page source.
127
+ data-dev={dev ? "true" : undefined}
128
+ data-debug={debug ? "true" : undefined}
129
+ />
130
+ </>
131
+ );
132
+ }
133
+
134
+ export default Stats;
@@ -1,5 +1,6 @@
1
1
  export { isBelowFold, LazySection, type LazySectionProps } from "./LazySection";
2
2
  export { LiveControls } from "./LiveControls";
3
+ export { default as Stats, DEFAULT_ORIGIN as STATS_DEFAULT_ORIGIN, type Props as StatsProps } from "./Stats";
3
4
  export { SectionErrorBoundary } from "./SectionErrorFallback";
4
5
  export { default as RenderSection } from "./RenderSection";
5
6
 
@@ -8,13 +9,17 @@ export {
8
9
  default as Image,
9
10
  registerImageCdnDomain,
10
11
  getImageCdnDomain,
12
+ registerImageQuality,
13
+ getImageQuality,
11
14
  getOptimizedMediaUrl,
12
15
  getSrcSet,
13
16
  FACTORS,
14
17
  type ImageProps,
18
+ type ImageQuality,
15
19
  type FitOptions,
16
20
  } from "./Image";
17
21
  export { Picture, Source, type PictureProps, type SourceProps } from "./Picture";
22
+ export { useLoadMore } from "./useLoadMore";
18
23
  export {
19
24
  ProductJsonLd,
20
25
  PLPJsonLd,