@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
@@ -184,11 +184,23 @@ export function addRedirects(map: RedirectMap, redirects: Redirect[]): void {
184
184
  * typically few patterns exist).
185
185
  */
186
186
  export function matchRedirect(pathname: string, map: RedirectMap): Redirect | null {
187
- const normalized = normalizePath(pathname);
187
+ return matchExactRedirect(pathname, map) ?? matchPatternRedirect(pathname, map);
188
+ }
188
189
 
189
- const exactMatch = map.exact.get(normalized);
190
- if (exactMatch) return exactMatch;
190
+ /**
191
+ * Exact half of `matchRedirect`. Split out because the KV-keyed path has to
192
+ * interleave a third source between the two halves: in-memory exact, then the
193
+ * `redirect:<id>:<path>` KV lookup, then patterns. Collapsing that to
194
+ * "matchRedirect, then KV" would let a glob win over an exact rule, inverting
195
+ * the precedence every other path has.
196
+ */
197
+ export function matchExactRedirect(pathname: string, map: RedirectMap): Redirect | null {
198
+ return map.exact.get(normalizePath(pathname)) ?? null;
199
+ }
191
200
 
201
+ /** Pattern half of `matchRedirect` — ordered prefix scan, `*` suffix carried over. */
202
+ export function matchPatternRedirect(pathname: string, map: RedirectMap): Redirect | null {
203
+ const normalized = normalizePath(pathname);
192
204
  for (const { prefix, redirect } of map.patterns) {
193
205
  if (normalized.startsWith(prefix)) {
194
206
  const suffix = normalized.slice(prefix.length);
@@ -196,15 +208,111 @@ export function matchRedirect(pathname: string, map: RedirectMap): Redirect | nu
196
208
  return { ...redirect, to };
197
209
  }
198
210
  }
199
-
200
211
  return null;
201
212
  }
202
213
 
214
+ // -------------------------------------------------------------------------
215
+ // Splitting exact rules out of the decofile (KV-keyed redirects)
216
+ // -------------------------------------------------------------------------
217
+
218
+ /** One exact rule, ready to be written to its own KV key. */
219
+ export interface ExactRedirect {
220
+ /** Normalized path — the KV key suffix. */
221
+ path: string;
222
+ to: string;
223
+ status: 301 | 302;
224
+ }
225
+
226
+ export interface SplitRedirectsResult {
227
+ /** The blocks map with every EXACT rule removed. Glob rules stay (they can't
228
+ * be addressed by key), and a redirect block left with no entries at all is
229
+ * dropped entirely rather than left as an empty husk. */
230
+ blocks: Record<string, unknown>;
231
+ /** The extracted exact rules, deduped by path (last wins, matching
232
+ * `loadRedirects`, which is last-write-wins over insertion order). */
233
+ exact: ExactRedirect[];
234
+ }
235
+
236
+ /**
237
+ * Split a decofile into "blocks without exact redirects" + "the exact rules".
238
+ *
239
+ * A bulk-migration site can carry tens of thousands of rules. Left inside the
240
+ * decofile they sit in every isolate twice — the parsed snapshot graph and the
241
+ * `RedirectMap` built from it — for data that is consulted at most once per
242
+ * request and usually matches nothing. Moved to one KV key each, the list is
243
+ * never loaded.
244
+ *
245
+ * Read-only over `blocks`: the returned map shares every untouched value and
246
+ * only clones the redirect blocks it had to rewrite.
247
+ */
248
+ const MAX_KV_PATH_BYTES = 400;
249
+ const utf8 = new TextEncoder();
250
+
251
+ export function splitExactRedirects(blocks: Record<string, unknown>): SplitRedirectsResult {
252
+ const exact = new Map<string, ExactRedirect>();
253
+ const out: Record<string, unknown> = {};
254
+
255
+ for (const [key, block] of Object.entries(blocks)) {
256
+ const obj = block && typeof block === "object" ? (block as Record<string, unknown>) : null;
257
+ const resolveType = obj?.__resolveType as string | undefined;
258
+ if (!obj || !resolveType || !REDIRECT_RESOLVE_TYPES.has(resolveType)) {
259
+ out[key] = block;
260
+ continue;
261
+ }
262
+
263
+ const raw = (obj.redirects ?? obj.redirect) as
264
+ | BlockRedirectEntry[]
265
+ | BlockRedirectEntry
266
+ | undefined;
267
+ if (!raw) {
268
+ out[key] = block;
269
+ continue;
270
+ }
271
+
272
+ const kept: BlockRedirectEntry[] = [];
273
+ for (const entry of Array.isArray(raw) ? raw : [raw]) {
274
+ if (!entry?.from || !entry.to) continue;
275
+ const from = normalizePath(entry.from);
276
+ // Globs must be scanned in order against the request path, so they can
277
+ // never be a key lookup — they stay in the decofile.
278
+ // Paths too long for a KV key (512 bytes, minus `redirect:<id>:`) stay
279
+ // in memory too — loadRedirects still serves them from the exact map.
280
+ if (from.includes("*") || utf8.encode(from).length > MAX_KV_PATH_BYTES) {
281
+ kept.push(entry);
282
+ continue;
283
+ }
284
+ exact.set(from, {
285
+ path: from,
286
+ to: entry.to,
287
+ status: entry.type === "permanent" ? 301 : 302,
288
+ });
289
+ }
290
+
291
+ // Nothing left to scan ⇒ drop the block rather than ship an empty husk.
292
+ if (kept.length === 0) continue;
293
+ // Rebuild without `redirect` — a block may have carried the singular form,
294
+ // and leaving it would reintroduce the rule we just extracted.
295
+ const { redirect: _dropped, ...rest } = obj;
296
+ out[key] = { ...rest, redirects: kept };
297
+ }
298
+
299
+ return { blocks: out, exact: [...exact.values()] };
300
+ }
301
+
203
302
  // -------------------------------------------------------------------------
204
303
  // Helpers
205
304
  // -------------------------------------------------------------------------
206
305
 
207
- function normalizePath(path: string): string {
306
+ /**
307
+ * Canonical redirect-path form: origin stripped, leading slash forced, trailing
308
+ * slash dropped, lower-cased.
309
+ *
310
+ * Exported because it is the KV key contract for `redirect:<id>:<path>` — the
311
+ * sync script that WRITES the keys and the worker that READS them must agree
312
+ * byte for byte, or a rule is stored under a key nothing ever asks for. Never
313
+ * inline a different normalization on either side.
314
+ */
315
+ export function normalizePath(path: string): string {
208
316
  let p = path.trim();
209
317
 
210
318
  // If the "from" is a full URL, extract just the pathname
@@ -0,0 +1,82 @@
1
+ import type { CacheStorage } from "./cacheStorage";
2
+ import { decodeBase64 } from "./encoding";
3
+
4
+ interface StoredResponse {
5
+ status: number;
6
+ statusText: string;
7
+ headers: [string, string][];
8
+ body: string;
9
+ }
10
+
11
+ /** HTTP serialization belongs to the cache consumer, independent of its storage adapter. */
12
+ export function createResponseCache(storage: CacheStorage, scope: string) {
13
+ const keyFor = (request: Request) => JSON.stringify([scope, "responses", request.url]);
14
+ return {
15
+ async match(request: Request): Promise<Response | undefined> {
16
+ const raw = await storage.get(keyFor(request));
17
+ if (raw === null) return undefined;
18
+ try {
19
+ const stored = JSON.parse(raw) as StoredResponse;
20
+ // Uint8Array.from(string, mapper) creates a large temporary iterable array.
21
+ // Decode straight into the byte buffer to keep cache hits proportional to body size.
22
+ const body = decodeBase64(stored.body);
23
+ return new Response([204, 205, 304].includes(stored.status) ? null : body, {
24
+ status: stored.status,
25
+ statusText: stored.statusText,
26
+ headers: stored.headers,
27
+ });
28
+ } catch {
29
+ return undefined;
30
+ }
31
+ },
32
+ async put(request: Request, response: Response): Promise<void> {
33
+ const cc = response.headers.get("Cache-Control") ?? "";
34
+ const ttl = Number(/(?:^|[,\s])max-age=(\d+)/i.exec(cc)?.[1] ?? 0);
35
+ if (!ttl || /(?:private|no-store|no-cache)/i.test(cc) || response.headers.has("set-cookie"))
36
+ return;
37
+ const expiresAt = Date.now() + ttl * 1000;
38
+ // Bound buffering before serialization; an oversized page can still stream to its caller.
39
+ const chunks: Uint8Array[] = [];
40
+ let size = 0;
41
+ const reader = response.body?.getReader();
42
+ if (reader) {
43
+ while (true) {
44
+ const { done, value } = await reader.read();
45
+ if (done) break;
46
+ size += value.byteLength;
47
+ if (size > 8 * 1024 * 1024) {
48
+ void reader.cancel().catch(() => {});
49
+ return;
50
+ }
51
+ chunks.push(value);
52
+ }
53
+ }
54
+ const bytes = new Uint8Array(size);
55
+ let offset = 0;
56
+ for (const chunk of chunks) {
57
+ bytes.set(chunk, offset);
58
+ offset += chunk.byteLength;
59
+ }
60
+ let binary = "";
61
+ for (let i = 0; i < bytes.length; i += 8192) {
62
+ binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
63
+ }
64
+ const value: StoredResponse = {
65
+ status: response.status,
66
+ statusText: response.statusText,
67
+ headers: [...response.headers.entries()],
68
+ body: btoa(binary),
69
+ };
70
+ try {
71
+ await storage.set(keyFor(request), JSON.stringify(value), expiresAt);
72
+ } catch {
73
+ /* Cache writes must not fail the response or its waitUntil task. */
74
+ }
75
+ },
76
+ async delete(request: Request): Promise<boolean> {
77
+ // KV deletion has no "existed" result. Report an accepted deletion, avoiding an extra read.
78
+ await storage.delete(keyFor(request));
79
+ return true;
80
+ },
81
+ };
82
+ }
@@ -25,6 +25,27 @@ const UTM_PARAMS = new Set([
25
25
  "mc_eid",
26
26
  "ttclid",
27
27
  "srsltid",
28
+ // GA4's newer campaign params. The five classic `utm_*` above predate them,
29
+ // so a GA4-tagged campaign was still fragmenting the cache key.
30
+ "utm_id",
31
+ "utm_source_platform",
32
+ "utm_creative_format",
33
+ "utm_marketing_tactic",
34
+ // Google Ads click ids that replaced bare `gclid` for privacy-restricted
35
+ // traffic (iOS/Safari), plus the source tag now appended to essentially every
36
+ // Google Ads click. Measured on a production storefront: each of these missed
37
+ // the edge cache on 3/3 routes probed, deterministically.
38
+ "gad_source",
39
+ "gad_campaignid",
40
+ "gbraid",
41
+ "wbraid",
42
+ // Google Analytics cross-domain linker. Sites already strip this by hand in
43
+ // client code, which is the tell that it shows up in real URLs.
44
+ "_gl",
45
+ "igshid",
46
+ "epik",
47
+ "mkt_tok",
48
+ "yclid",
28
49
  ]);
29
50
 
30
51
  /**
@@ -44,6 +65,17 @@ export function registerTrackingParams(params: string[]): void {
44
65
  }
45
66
  }
46
67
 
68
+ /**
69
+ * Whether a search param is a known tracking/attribution param.
70
+ *
71
+ * Exposed so cache-key builders can filter params in place without having to
72
+ * round-trip through a `URL` (server-fn payloads carry bare relative paths) and
73
+ * without keeping a second copy of the list.
74
+ */
75
+ export function isTrackingParam(param: string): boolean {
76
+ return UTM_PARAMS.has(param.toLowerCase());
77
+ }
78
+
47
79
  /**
48
80
  * Strip UTM and tracking parameters from a URL.
49
81
  *
@@ -118,6 +150,23 @@ export function canonicalUrl(request: Request, baseUrl?: string): string {
118
150
  return `${origin}${path}`;
119
151
  }
120
152
 
153
+ /**
154
+ * Extract the pathname from an absolute or relative URL, stripping query
155
+ * string and hash. Falls back to manual slicing when `new URL()` would
156
+ * throw (relative URL without a base). Used by operation routers that
157
+ * need to match against URL structure without caring about the host.
158
+ */
159
+ export function extractPathname(url: string): string {
160
+ try {
161
+ return new URL(url).pathname;
162
+ } catch {
163
+ const qs = url.indexOf("?");
164
+ const hash = url.indexOf("#");
165
+ const end = [qs, hash].filter((i) => i >= 0).sort((a, b) => a - b)[0];
166
+ return end === undefined ? url : url.slice(0, end);
167
+ }
168
+ }
169
+
121
170
  /**
122
171
  * Check if a URL has any tracking/UTM parameters.
123
172
  */
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * Search-suggestions hook factory.
3
3
  *
4
- * Both casaevideo-storefront and baggagio-tanstack independently
4
+ * Two production storefronts independently
5
5
  * invented the same shape for autocomplete-style suggestions:
6
6
  *
7
7
  * - module-level signal for the current payload + loading flag
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `@decocms/blocks/analytics`: cookie-free page views in the One Dollar Stats
3
+ * tracker's wire format. See /next/analytics and
4
+ * /next/telemetry-internals#analytics-events.
5
+ *
6
+ * `AnalyticsScript` renders one small inline script with the resolved
7
+ * `analytics` block's settings. In the browser it sends a page view on load
8
+ * (once the page is visible, so prerendered pages don't count) and on every
9
+ * navigation that changes the path, and exposes the sender `track` uses.
10
+ *
11
+ * Wire format (pinned against onedollarstats' stonks.js tracker):
12
+ * `{ u, e: [{ t, h, r, p }], debug }`, where `u` is the page URL without its
13
+ * query string, hash or trailing slash, `t` the event type (`PageView` or a
14
+ * custom name), `h` hash routing (always false), `r` a referrer from another
15
+ * host and `p` the event's properties. Sent as `GET <collector>?data=<base64
16
+ * of the UTF-8 JSON>` when that's at most 1500 characters, otherwise with
17
+ * `navigator.sendBeacon` or a `POST`.
18
+ */
19
+ import { createElement, type ReactNode } from "react";
20
+ import { HOSTED_ANALYTICS_COLLECTOR } from "./builtins/data";
21
+ import type { Analytics } from "./types";
22
+
23
+ const GLOBAL = "__decoAnalytics";
24
+
25
+ /** The browser tracker. Static: the collector reaches it through `data-url`, never string-built. */
26
+ const TRACKER = `(function(){var s=document.currentScript,c=s&&s.getAttribute("data-url");if(!c||window.${GLOBAL})return;var last;function post(b){if(navigator.sendBeacon&&navigator.sendBeacon(c,b))return;fetch(c,{method:"POST",body:b,headers:{"Content-Type":"application/json"},keepalive:true}).catch(function(){})}function send(t,p){var u=new URL(location.href);u.search="";u.hash="";var r;try{if(document.referrer){var f=new URL(document.referrer);if(f.hostname!==u.hostname){f.search="";f.hash="";r=f.href}}}catch(e){}var b=JSON.stringify({u:u.href.replace(/\\/$/,""),e:[{t:t,h:false,r:r,p:p}],debug:false});var d=btoa(String.fromCharCode.apply(null,Array.from(new TextEncoder().encode(b))));if(d.length<=1500){new Image(1,1).src=c+"?data="+d}else post(b)}function view(){if(location.pathname===last)return;last=location.pathname;send("PageView")}window.${GLOBAL}={track:function(n,p){send(n,p)}};var h=history.pushState;history.pushState=function(){h.apply(this,arguments);requestAnimationFrame(view)};addEventListener("popstate",function(){requestAnimationFrame(view)});if(document.visibilityState==="visible")view();else document.addEventListener("visibilitychange",function v(){if(document.visibilityState==="visible"){document.removeEventListener("visibilitychange",v);view()}})})();`;
27
+
28
+ /**
29
+ * The tracking script. Render it in your root layout with the resolved
30
+ * `analytics` block's settings; renders nothing when `enabled` is false.
31
+ */
32
+ export function AnalyticsScript(props: Analytics = {}): ReactNode | null {
33
+ if (props.enabled === false) return null;
34
+ return createElement("script", {
35
+ "data-url": props.collector ?? HOSTED_ANALYTICS_COLLECTOR,
36
+ dangerouslySetInnerHTML: { __html: TRACKER },
37
+ });
38
+ }
39
+
40
+ /**
41
+ * Sends your own event from the browser, through the script `AnalyticsScript`
42
+ * renders. Does nothing without it (and on the server).
43
+ */
44
+ export function track(name: string, props?: Record<string, string | number | boolean>): void {
45
+ const tracker =
46
+ typeof window === "undefined"
47
+ ? undefined
48
+ : (window as unknown as Record<string, { track?: typeof track } | undefined>)[GLOBAL];
49
+ tracker?.track?.(name, props);
50
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Work that runs beside requests, never in front of them: release checks and
3
+ * telemetry batches (see /next/hosted-releases-internals and
4
+ * /next/telemetry-internals#sending-in-the-background).
5
+ *
6
+ * Where it runs, in order:
7
+ * - a host hook a framework binding installs under {@link BACKGROUND_HOOK};
8
+ * - on Cloudflare Workers, which run no timers between requests, the
9
+ * platform's `waitUntil` (from `cloudflare:workers`), so the task runs
10
+ * after the response with no binding and no user code: the core installs
11
+ * that hook itself;
12
+ * - `requestIdleCallback` (browsers, React Native);
13
+ * - `scheduler.postTask({ priority: "background" })`;
14
+ * - an unref'd `setTimeout` (so Node never stays alive for it), then
15
+ * `setImmediate` where it exists.
16
+ *
17
+ * A task never throws into its caller: errors and rejections are swallowed.
18
+ */
19
+
20
+ /** Where a binding installs `(task) => void` to run background work its own way. */
21
+ const BACKGROUND_HOOK = Symbol.for("decocms.blocks.background");
22
+
23
+ type Task = () => unknown;
24
+
25
+ type WaitUntil = (promise: Promise<unknown>) => void;
26
+
27
+ /** Workers identify themselves in `navigator.userAgent`. */
28
+ function onWorkers(): boolean {
29
+ return (
30
+ (globalThis as { navigator?: { userAgent?: string } }).navigator?.userAgent ===
31
+ "Cloudflare-Workers"
32
+ );
33
+ }
34
+
35
+ /**
36
+ * `cloudflare:workers`, loaded once. The specifier is computed so bundlers
37
+ * for other targets (browsers, Node) never try to resolve it.
38
+ */
39
+ let workers: Promise<WaitUntil | undefined> | undefined;
40
+ function workersWaitUntil(): Promise<WaitUntil | undefined> {
41
+ const specifier = ["cloudflare", "workers"].join(":");
42
+ workers ??= import(/* @vite-ignore */ /* webpackIgnore: true */ specifier).then(
43
+ (mod: { waitUntil?: WaitUntil }) =>
44
+ typeof mod.waitUntil === "function" ? mod.waitUntil : undefined,
45
+ () => undefined,
46
+ );
47
+ return workers;
48
+ }
49
+
50
+ interface BackgroundGlobals {
51
+ [BACKGROUND_HOOK]?: (task: () => Promise<void>) => void;
52
+ requestIdleCallback?: (callback: () => void) => unknown;
53
+ scheduler?: {
54
+ postTask?: (callback: () => void, options: { priority: string }) => Promise<unknown>;
55
+ };
56
+ setImmediate?: (callback: () => void) => unknown;
57
+ }
58
+
59
+ export function runInBackground(task: Task): void {
60
+ const run = async (): Promise<void> => {
61
+ try {
62
+ await task();
63
+ } catch {
64
+ // Background work fails quietly; nothing reaches a request.
65
+ }
66
+ };
67
+ const g = globalThis as BackgroundGlobals;
68
+ const hook = g[BACKGROUND_HOOK];
69
+ if (typeof hook === "function") {
70
+ hook(run);
71
+ return;
72
+ }
73
+ if (onWorkers()) {
74
+ void workersWaitUntil().then((waitUntil) => {
75
+ if (waitUntil === undefined) return void run();
76
+ // From now on, hand every task straight to the platform.
77
+ if (typeof g[BACKGROUND_HOOK] !== "function") {
78
+ g[BACKGROUND_HOOK] = (next) => waitUntil(next());
79
+ }
80
+ g[BACKGROUND_HOOK]?.(run);
81
+ });
82
+ return;
83
+ }
84
+ if (typeof g.requestIdleCallback === "function") {
85
+ g.requestIdleCallback(() => void run());
86
+ return;
87
+ }
88
+ if (typeof g.scheduler?.postTask === "function") {
89
+ g.scheduler.postTask(() => void run(), { priority: "background" }).catch(() => {});
90
+ return;
91
+ }
92
+ later(0, () => {
93
+ if (typeof g.setImmediate === "function") g.setImmediate(() => void run());
94
+ else void run();
95
+ });
96
+ }
97
+
98
+ /** `setTimeout` that never keeps a Node process alive. */
99
+ export function later(ms: number, callback: () => void): void {
100
+ const timer = setTimeout(callback, ms) as unknown as { unref?: () => void };
101
+ timer?.unref?.();
102
+ }
103
+
104
+ /** Whether a binding installed a background hook (then batches go out after each response). */
105
+ export function hasBackgroundHook(): boolean {
106
+ return typeof (globalThis as BackgroundGlobals)[BACKGROUND_HOOK] === "function";
107
+ }
@@ -0,0 +1,23 @@
1
+ import type { Analytics, Redirect, Telemetry } from "../types";
2
+
3
+ /** The hosted Deco CMS collector: where page views go when `collector` is left out. */
4
+ export const HOSTED_ANALYTICS_COLLECTOR = "https://d.lilstts.com/events";
5
+
6
+ /**
7
+ * `page`: its inputs are already resolved (`seo` and every block in
8
+ * `sections`), so the page is its input.
9
+ */
10
+ export const page = <P>(props: P): P => props;
11
+
12
+ /** `redirect`: returns its arguments as saved. */
13
+ export const redirect = (props: Redirect): Redirect => props;
14
+
15
+ /** `telemetry`: the type of the well-known `Telemetry` saved block; returns its arguments. */
16
+ export const telemetry = (props: Telemetry = {}): Telemetry => props;
17
+
18
+ /** `analytics`: returns its input with the defaults filled in. */
19
+ export const analytics = (props: Analytics = {}): Required<Analytics> => ({
20
+ ...props,
21
+ collector: props.collector ?? HOSTED_ANALYTICS_COLLECTOR,
22
+ enabled: props.enabled ?? true,
23
+ });
@@ -0,0 +1,26 @@
1
+ import type { BlockFunction } from "../types";
2
+ import { analytics, page, redirect, telemetry } from "./data";
3
+ import { lazy } from "./lazy";
4
+ import { always, date, never } from "./matchers";
5
+ import { multivariate } from "./multivariate";
6
+ import { secretBlock } from "./secret";
7
+
8
+ /**
9
+ * The built-in blocks every block map gets. `secret` here has no key, so it
10
+ * always fails; each CMS replaces it with one holding its `secrets.key`.
11
+ */
12
+ export const builtIns: Readonly<Record<string, BlockFunction>> = Object.freeze({
13
+ lazy,
14
+ multivariate,
15
+ always,
16
+ never,
17
+ date,
18
+ page,
19
+ redirect,
20
+ telemetry,
21
+ analytics,
22
+ secret: secretBlock(),
23
+ });
24
+
25
+ /** Names no saved block can take (see /next/saved-blocks#names). */
26
+ export const RESERVED_NAMES: ReadonlySet<string> = new Set(Object.keys(builtIns));
@@ -0,0 +1,23 @@
1
+ import type { Lazy } from "../types";
2
+
3
+ /** Marks the built-in `lazy` function, the resolver's one special case. */
4
+ const LAZY_BLOCK: unique symbol = Symbol.for("decocms.blocks.v8.lazy");
5
+
6
+ /**
7
+ * The built-in `lazy` block. The resolver never calls it: it sees the marker
8
+ * and hands the parent a memoized `() => Promise<T>` that resolves `value`
9
+ * only when called. Called directly (outside the resolver), it wraps an
10
+ * already-resolved value, so it still honours the `Lazy<T>` contract.
11
+ */
12
+ export const lazy = Object.assign(
13
+ <T>({ value }: { value: T }): Lazy<T> =>
14
+ () =>
15
+ Promise.resolve(value),
16
+ { [LAZY_BLOCK]: true as const },
17
+ );
18
+
19
+ export function isLazyBuiltin(fn: unknown): boolean {
20
+ return (
21
+ typeof fn === "function" && (fn as unknown as Record<symbol, unknown>)[LAZY_BLOCK] === true
22
+ );
23
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The legacy alias bridge: the well-known Fresh/Deno and v7 type names the
3
+ * site editor still writes, mapped to the built-ins, so v7 content resolves
4
+ * without a block-map entry (see /next/studio-compatibility#well-known-types-and-the-alias-table
5
+ * and /next/renames-and-migrations#rename-a-type-with-an-alias).
6
+ *
7
+ * A snapshot's own `aliases` (the table `deco content` writes) win over these, and a key in the block map wins over
8
+ * both, so a site can still register a legacy name itself.
9
+ *
10
+ * - Redirects keep v7's nested shape: `redirect` returns its arguments as
11
+ * saved, and `matchRoute` accepts both shapes.
12
+ * - `website/loaders/secret.ts` resolves as `secret`, which needs the
13
+ * `ciphertext` the one-time re-encryption writes (see
14
+ * /next/renames-and-migrations#secrets); a v7 `encrypted` value fails that
15
+ * block with `BLOCK_FAILED`.
16
+ * - Legacy variants are saved as plain values; on the way to `multivariate`
17
+ * each one is wrapped in a `lazy` block, so only the chosen one runs.
18
+ */
19
+ import { isPlainObject, type JsonObject } from "../json";
20
+
21
+ /**
22
+ * Legacy type name → built-in. The one table: the runtime falls back to it,
23
+ * and `deco schema` / `deco content` write it into the schema and the content
24
+ * module. Exactly the names the site editor's special screens look for
25
+ * (/next/studio-compatibility#well-known-types-and-the-alias-table); other
26
+ * legacy names (`$live/…`, the per-kind multivariate files, the date
27
+ * matcher) are rewritten to these by the one-time migration
28
+ * (`@decocms/blocks-migrate`), and types with no built-in counterpart are
29
+ * left to the site's block map.
30
+ */
31
+ export const LEGACY_ALIASES: Readonly<Record<string, string>> = Object.freeze({
32
+ "website/pages/Page.tsx": "page",
33
+ "$live/pages/LivePage.tsx": "page",
34
+ "website/flags/multivariate.ts": "multivariate",
35
+ "website/flags/multivariate/section.ts": "multivariate",
36
+ "website/matchers/always.ts": "always",
37
+ "website/matchers/never.ts": "never",
38
+ "website/loaders/redirect.ts": "redirect",
39
+ "website/loaders/secret.ts": "secret",
40
+ });
41
+
42
+ /**
43
+ * Whether a legacy name stores its variants' values plain (every legacy name
44
+ * for `multivariate`); under the short name each value carries a `lazy`.
45
+ */
46
+ export function storesPlainVariants(type: string): boolean {
47
+ return Object.hasOwn(LEGACY_ALIASES, type) && LEGACY_ALIASES[type] === "multivariate";
48
+ }
49
+
50
+ /**
51
+ * A legacy variants block with each plain `value` wrapped in `lazy`; any
52
+ * other block as is. A value that already is a `lazy` block stays one.
53
+ */
54
+ export function wrapLegacyVariants(type: string, node: JsonObject): JsonObject {
55
+ if (!storesPlainVariants(type) || !Array.isArray(node.variants)) return node;
56
+ return {
57
+ ...node,
58
+ variants: node.variants.map((variant) =>
59
+ isPlainObject(variant) &&
60
+ !(isPlainObject(variant.value) && variant.value.__resolveType === "lazy")
61
+ ? { ...variant, value: { __resolveType: "lazy", value: variant.value } }
62
+ : variant,
63
+ ),
64
+ };
65
+ }
@@ -0,0 +1,31 @@
1
+ /** `always`: the fallback rule. */
2
+ export const always = (): boolean => true;
3
+
4
+ /** `never`: the rule the site editor uses to hide a block. */
5
+ export const never = (): boolean => false;
6
+
7
+ /** Inputs of the built-in `date` matcher: ISO 8601 strings, both optional. */
8
+ interface DateProps {
9
+ /** Inclusive. */
10
+ start?: string;
11
+ /** Exclusive: `end` itself doesn't match. */
12
+ end?: string;
13
+ }
14
+
15
+ /**
16
+ * `date`: `true` from `start` (inclusive) until `end` (exclusive). A date
17
+ * without a time means midnight UTC. An unparseable bound never matches, so a
18
+ * typo can't switch a campaign on.
19
+ */
20
+ export const date = ({ start, end }: DateProps = {}): boolean => {
21
+ const now = Date.now();
22
+ if (start !== undefined && start !== null && start !== "") {
23
+ const from = Date.parse(start);
24
+ if (Number.isNaN(from) || now < from) return false;
25
+ }
26
+ if (end !== undefined && end !== null && end !== "") {
27
+ const until = Date.parse(end);
28
+ if (Number.isNaN(until) || now >= until) return false;
29
+ }
30
+ return true;
31
+ };
@@ -0,0 +1,25 @@
1
+ import type { Variant } from "../types";
2
+
3
+ interface MultivariateProps<T> {
4
+ variants?: Variant<T>[];
5
+ /** The stable ID of an A/B test; results are kept per ID. */
6
+ experiment?: string;
7
+ }
8
+
9
+ /**
10
+ * `multivariate`: runs the first variant whose rule is `true` and returns its
11
+ * value, or `undefined` when no rule is. Only the chosen variant runs, because
12
+ * each `value` is a `Lazy<T>`. A value saved without the `lazy` wrapper (which
13
+ * `deco check` flags) is returned as is rather than failing the page.
14
+ */
15
+ export const multivariate = async <T>({
16
+ variants,
17
+ }: MultivariateProps<T> = {}): Promise<T | undefined> => {
18
+ if (!Array.isArray(variants)) return undefined;
19
+ for (const variant of variants) {
20
+ if (variant?.rule !== true) continue;
21
+ const value = variant.value as unknown;
22
+ return typeof value === "function" ? await (value as () => Promise<T>)() : (value as T);
23
+ }
24
+ return undefined;
25
+ };