@decocms/blocks 8.5.2 → 8.7.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 (126) hide show
  1. package/dist/async/default.d.ts +10 -0
  2. package/dist/async/default.d.ts.map +1 -0
  3. package/dist/async/default.js +5 -0
  4. package/dist/async/default.js.map +1 -0
  5. package/dist/async/node.d.ts +3 -0
  6. package/dist/async/node.d.ts.map +1 -0
  7. package/dist/async/node.js +11 -0
  8. package/dist/async/node.js.map +1 -0
  9. package/dist/async/types.d.ts +6 -0
  10. package/dist/async/types.d.ts.map +1 -0
  11. package/dist/async/types.js +2 -0
  12. package/dist/async/types.js.map +1 -0
  13. package/dist/index.d.ts +1 -1
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +1 -1
  16. package/dist/index.js.map +1 -1
  17. package/dist/v8/bucketing.d.ts +24 -0
  18. package/dist/v8/bucketing.d.ts.map +1 -0
  19. package/dist/v8/bucketing.js +78 -0
  20. package/dist/v8/bucketing.js.map +1 -0
  21. package/dist/v8/builtins/campaigns.d.ts +36 -0
  22. package/dist/v8/builtins/campaigns.d.ts.map +1 -0
  23. package/dist/v8/builtins/campaigns.js +107 -0
  24. package/dist/v8/builtins/campaigns.js.map +1 -0
  25. package/dist/v8/builtins/data.d.ts +2 -2
  26. package/dist/v8/builtins/data.js +2 -2
  27. package/dist/v8/builtins/experiments.d.ts +27 -0
  28. package/dist/v8/builtins/experiments.d.ts.map +1 -0
  29. package/dist/v8/builtins/experiments.js +62 -0
  30. package/dist/v8/builtins/experiments.js.map +1 -0
  31. package/dist/v8/builtins/index.d.ts.map +1 -1
  32. package/dist/v8/builtins/index.js +7 -2
  33. package/dist/v8/builtins/index.js.map +1 -1
  34. package/dist/v8/builtins/matchers.d.ts +0 -14
  35. package/dist/v8/builtins/matchers.d.ts.map +1 -1
  36. package/dist/v8/builtins/matchers.js +0 -19
  37. package/dist/v8/builtins/matchers.js.map +1 -1
  38. package/dist/v8/cli/builtins.d.ts +6 -0
  39. package/dist/v8/cli/builtins.d.ts.map +1 -1
  40. package/dist/v8/cli/builtins.js +19 -0
  41. package/dist/v8/cli/builtins.js.map +1 -1
  42. package/dist/v8/cli/check/index.d.ts.map +1 -1
  43. package/dist/v8/cli/check/index.js +231 -8
  44. package/dist/v8/cli/check/index.js.map +1 -1
  45. package/dist/v8/cli/schema/builtinSchemas.d.ts.map +1 -1
  46. package/dist/v8/cli/schema/builtinSchemas.js +76 -21
  47. package/dist/v8/cli/schema/builtinSchemas.js.map +1 -1
  48. package/dist/v8/cli/schema/generate.d.ts.map +1 -1
  49. package/dist/v8/cli/schema/generate.js +48 -2
  50. package/dist/v8/cli/schema/generate.js.map +1 -1
  51. package/dist/v8/client.d.ts +25 -0
  52. package/dist/v8/client.d.ts.map +1 -1
  53. package/dist/v8/client.js +58 -10
  54. package/dist/v8/client.js.map +1 -1
  55. package/dist/v8/cms.d.ts.map +1 -1
  56. package/dist/v8/cms.js +113 -44
  57. package/dist/v8/cms.js.map +1 -1
  58. package/dist/v8/content.d.ts +80 -1
  59. package/dist/v8/content.d.ts.map +1 -1
  60. package/dist/v8/content.js +149 -4
  61. package/dist/v8/content.js.map +1 -1
  62. package/dist/v8/current.d.ts +28 -0
  63. package/dist/v8/current.d.ts.map +1 -0
  64. package/dist/v8/current.js +77 -0
  65. package/dist/v8/current.js.map +1 -0
  66. package/dist/v8/draft.d.ts +40 -21
  67. package/dist/v8/draft.d.ts.map +1 -1
  68. package/dist/v8/draft.js +160 -25
  69. package/dist/v8/draft.js.map +1 -1
  70. package/dist/v8/experiments.d.ts +107 -0
  71. package/dist/v8/experiments.d.ts.map +1 -0
  72. package/dist/v8/experiments.js +292 -0
  73. package/dist/v8/experiments.js.map +1 -0
  74. package/dist/v8/hosts.d.ts +3 -2
  75. package/dist/v8/hosts.d.ts.map +1 -1
  76. package/dist/v8/hosts.js +3 -2
  77. package/dist/v8/hosts.js.map +1 -1
  78. package/dist/v8/index.d.ts +7 -5
  79. package/dist/v8/index.d.ts.map +1 -1
  80. package/dist/v8/index.js +6 -4
  81. package/dist/v8/index.js.map +1 -1
  82. package/dist/v8/preview/DraftBadge.d.ts +9 -1
  83. package/dist/v8/preview/DraftBadge.d.ts.map +1 -1
  84. package/dist/v8/preview/DraftBadge.js +42 -2
  85. package/dist/v8/preview/DraftBadge.js.map +1 -1
  86. package/dist/v8/remoteLoader.d.ts.map +1 -1
  87. package/dist/v8/remoteLoader.js +169 -21
  88. package/dist/v8/remoteLoader.js.map +1 -1
  89. package/dist/v8/resolver.d.ts +4 -2
  90. package/dist/v8/resolver.d.ts.map +1 -1
  91. package/dist/v8/resolver.js +11 -3
  92. package/dist/v8/resolver.js.map +1 -1
  93. package/dist/v8/settings.d.ts +16 -4
  94. package/dist/v8/settings.d.ts.map +1 -1
  95. package/dist/v8/settings.js +24 -21
  96. package/dist/v8/settings.js.map +1 -1
  97. package/dist/v8/types.d.ts +162 -22
  98. package/dist/v8/types.d.ts.map +1 -1
  99. package/package.json +35 -1
  100. package/src/async/default.ts +13 -0
  101. package/src/async/node.ts +12 -0
  102. package/src/async/types.ts +5 -0
  103. package/src/index.ts +4 -0
  104. package/src/v8/bucketing.ts +88 -0
  105. package/src/v8/builtins/campaigns.ts +120 -0
  106. package/src/v8/builtins/data.ts +2 -2
  107. package/src/v8/builtins/experiments.ts +72 -0
  108. package/src/v8/builtins/index.ts +7 -2
  109. package/src/v8/builtins/matchers.ts +0 -26
  110. package/src/v8/cli/builtins.ts +23 -0
  111. package/src/v8/cli/check/index.ts +289 -8
  112. package/src/v8/cli/schema/builtinSchemas.ts +82 -22
  113. package/src/v8/cli/schema/generate.ts +48 -3
  114. package/src/v8/client.ts +76 -10
  115. package/src/v8/cms.ts +134 -45
  116. package/src/v8/content.ts +168 -4
  117. package/src/v8/current.ts +98 -0
  118. package/src/v8/draft.ts +170 -30
  119. package/src/v8/experiments.ts +340 -0
  120. package/src/v8/hosts.ts +3 -2
  121. package/src/v8/index.ts +8 -4
  122. package/src/v8/preview/DraftBadge.tsx +72 -2
  123. package/src/v8/remoteLoader.ts +193 -26
  124. package/src/v8/resolver.ts +14 -4
  125. package/src/v8/settings.ts +35 -29
  126. package/src/v8/types.ts +163 -20
package/src/v8/draft.ts CHANGED
@@ -1,15 +1,30 @@
1
1
  /**
2
2
  * Draft pointers (see /next/api-reference#draft-pointers): the string
3
3
  * `<host[:port]><path[?query]>@<version>` that names a draft, and what
4
- * `cms.draftPointer` and `cms.draftCookie` read and write to carry one from a
5
- * `?__draft=` link into a cookie. The host check against the preview hosts is
6
- * the CMS's: these read the request only.
4
+ * `cms.readVersion` and `cms.draftCookie` read and write to carry one (or a
5
+ * published release's commit SHA) from a `?__draft=` link into a cookie. The
6
+ * host check against the preview hosts is the CMS's: these read the request
7
+ * only.
7
8
  *
8
- * The query's reserved `__variant` parameters are the variants a preview
9
- * forces (`<block>@<path>=<index>`, URL-encoded, one per multivariate); the
10
- * parser lifts them out of `path` into `variants`.
9
+ * A version is a draft pointer or a release's commit SHA, nothing else. A
10
+ * pointer's query may force variants, which are part of the draft it names:
11
+ *
12
+ * - `__variant=<block>@<path>=<index>`: a variant the preview forces, one per
13
+ * multivariate (`variants`).
14
+ *
15
+ * A Studio preview link carries more than the version: the moment it shows
16
+ * and the tests and campaigns it switches on or off. They ride in the same
17
+ * query (a pointer's, or after a SHA: `<sha>?__at=…&__test=…`), and
18
+ * `parseVersion` lifts them out into the client's other options:
19
+ *
20
+ * - `__at=<ISO date-time with offset>`: the client's `date`.
21
+ * - `__test=<name>=on|off`: a test in the client's `experiments`.
22
+ * - `__campaign=<name>=on|off`: a campaign in the client's `campaigns`.
23
+ *
24
+ * Each value is URL-encoded.
11
25
  */
12
- import type { DraftPointer, ForcedVariant, RequestLike } from "./types.ts";
26
+ import type { Assignments } from "./experiments.ts";
27
+ import type { DraftPointer, ForcedVariant, RequestLike, RequestVersion } from "./types.ts";
13
28
 
14
29
  /** The draft cookie's name. Not exported from the package: reading it directly would skip the host check. */
15
30
  const DRAFT_COOKIE = "__deco_draft";
@@ -26,13 +41,108 @@ const VERSION_RE = /^[A-Za-z0-9._-]{1,64}$/;
26
41
  const PATH_RE = /^\/[A-Za-z0-9/_.%~=&?-]*$/;
27
42
  const MAX_POINTER_LENGTH = 4096;
28
43
  const VARIANT_PARAM = "__variant=";
44
+ const AT_PARAM = "__at=";
45
+ const TEST_PARAM = "__test=";
46
+ const CAMPAIGN_PARAM = "__campaign=";
47
+ /** The parameters of a preview link that aren't part of the version. */
48
+ const PREVIEW_PARAMS = [AT_PARAM, TEST_PARAM, CAMPAIGN_PARAM];
49
+ /** An ISO 8601 date-time with its offset (`Z` or `±hh:mm`): the moment a preview shows. */
50
+ const AT_RE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d{1,9})?)?(Z|[+-]\d{2}:\d{2})$/;
29
51
  const INDEX_RE = /^(0|[1-9][0-9]{0,3})$/;
52
+ /** A published release: its git commit SHA (SHA-1, 40 lowercase hex). */
53
+ const REVISION_RE = /^[0-9a-f]{40}$/;
54
+
55
+ /** A version, read: a published release (by its commit SHA) or a draft. */
56
+ type ClientVersion = { kind: "revision"; sha: string } | { kind: "draft"; pointer: DraftPointer };
57
+
58
+ /**
59
+ * What `cms.client({ version })` reads: a published release's commit SHA (40
60
+ * lowercase hex, nothing after it) or a draft pointer. `null` for anything
61
+ * else, a preview link's `__at`, `__test` or `__campaign` included: those
62
+ * are the client's `date`, `experiments` and `campaigns` (`parseVersion`).
63
+ */
64
+ export function parseClientVersion(value: string): ClientVersion | null {
65
+ if (REVISION_RE.test(value)) return { kind: "revision", sha: value };
66
+ const pointer = parseDraftPointer(value);
67
+ return pointer === null ? null : { kind: "draft", pointer };
68
+ }
69
+
70
+ /**
71
+ * A Studio link's value (what `?__draft=` and the draft cookie carry): the
72
+ * version, a draft pointer or a published release's commit SHA, and the
73
+ * preview's moment and switched tests and campaigns, lifted out of its query
74
+ * as the client's `date`, `experiments` and `campaigns`. `null` for a value
75
+ * that is neither, or whose preview parameters don't parse (a second `__at`,
76
+ * a state other than `on` or `off`). The last `__test` or `__campaign` for a
77
+ * name wins. Spread it into `cms.client()`.
78
+ */
79
+ export function parseVersion(value: string | null | undefined): RequestVersion | null {
80
+ if (typeof value !== "string" || value.length === 0 || value.length > MAX_POINTER_LENGTH) {
81
+ return null;
82
+ }
83
+ const head = value.indexOf("?");
84
+ if (REVISION_RE.test(head === -1 ? value : value.slice(0, head))) {
85
+ if (head === -1) return { version: value };
86
+ const preview = liftPreview(value.slice(head + 1));
87
+ // After a SHA, only the preview's own parameters.
88
+ if (preview === null || preview.kept.length > 0) return null;
89
+ return { version: value.slice(0, head), ...preview.options };
90
+ }
91
+ const at = value.lastIndexOf("@");
92
+ if (at <= 0) return null;
93
+ const location = value.slice(0, at);
94
+ const q = location.indexOf("?");
95
+ if (q === -1) return parseDraftPointer(value) === null ? null : { version: value };
96
+ const preview = liftPreview(location.slice(q + 1));
97
+ if (preview === null) return null;
98
+ const query = preview.kept.length === 0 ? "" : `?${preview.kept.join("&")}`;
99
+ const version = `${location.slice(0, q)}${query}${value.slice(at)}`;
100
+ return parseDraftPointer(version) === null ? null : { version, ...preview.options };
101
+ }
102
+
103
+ /** A query's preview parameters, read, and the other parameters, kept as they are. */
104
+ function liftPreview(query: string): {
105
+ kept: string[];
106
+ options: Omit<RequestVersion, "version">;
107
+ } | null {
108
+ const kept: string[] = [];
109
+ let at: string | undefined;
110
+ let experiments: Assignments | undefined;
111
+ let campaigns: Assignments | undefined;
112
+ for (const param of query.split("&")) {
113
+ if (param.startsWith(AT_PARAM)) {
114
+ const value = decodeParam(param.slice(AT_PARAM.length));
115
+ if (at !== undefined || value === null || !AT_RE.test(value)) return null;
116
+ if (Number.isNaN(Date.parse(value))) return null;
117
+ at = value;
118
+ } else if (param.startsWith(TEST_PARAM)) {
119
+ const test = decodeSwitch(param.slice(TEST_PARAM.length));
120
+ if (test === null) return null;
121
+ experiments ??= Object.create(null) as Assignments;
122
+ experiments[test.name] = test.on;
123
+ } else if (param.startsWith(CAMPAIGN_PARAM)) {
124
+ const campaign = decodeSwitch(param.slice(CAMPAIGN_PARAM.length));
125
+ if (campaign === null) return null;
126
+ campaigns ??= Object.create(null) as Assignments;
127
+ campaigns[campaign.name] = campaign.on;
128
+ } else if (param !== "") {
129
+ kept.push(param);
130
+ }
131
+ }
132
+ const options: Omit<RequestVersion, "version"> = {};
133
+ if (at !== undefined) options.date = new Date(Date.parse(at));
134
+ if (experiments !== undefined) options.experiments = experiments;
135
+ if (campaigns !== undefined) options.campaigns = campaigns;
136
+ return { kept, options };
137
+ }
30
138
 
31
139
  /**
32
140
  * Parses a pointer, strictly: `null` on a scheme, a stray `@`, an unrooted
33
- * path, an odd character in the host or version, or a port out of range. The
34
- * host is lowercased (DNS names are case-insensitive); path and version are
35
- * kept as they are.
141
+ * path, an odd character in the host or version, a port out of range, or a
142
+ * preview link's `__at`, `__test` or `__campaign` left in its query (they
143
+ * aren't part of a version: `parseVersion` lifts them out). The host is
144
+ * lowercased (DNS names are case-insensitive); path and version are kept as
145
+ * they are.
36
146
  */
37
147
  export function parseDraftPointer(raw: string | null | undefined): DraftPointer | null {
38
148
  if (typeof raw !== "string" || raw.length === 0 || raw.length > MAX_POINTER_LENGTH) return null;
@@ -51,9 +161,9 @@ export function parseDraftPointer(raw: string | null | undefined): DraftPointer
51
161
  if (host === null) return null;
52
162
  const split = splitVariants(path);
53
163
  if (split === null) return null;
54
- return split.variants.length === 0
55
- ? { host, path, version }
56
- : { host, path: split.path, version, variants: split.variants };
164
+ const pointer: DraftPointer = { host, path: split.path, version };
165
+ if (split.variants.length > 0) pointer.variants = split.variants;
166
+ return pointer;
57
167
  }
58
168
 
59
169
  /**
@@ -80,25 +190,49 @@ export function formatDraftPointer(pointer: DraftPointer): string {
80
190
  return `${parsed.host}${path}@${parsed.version}`;
81
191
  }
82
192
 
83
- /** The path without its `__variant` parameters, and the variants they force; `null` on a bad one. */
193
+ /**
194
+ * The path without its `__variant` parameters, and the variants they force.
195
+ * `null` on one that doesn't parse, or on a preview link's `__at`, `__test`
196
+ * or `__campaign`.
197
+ */
84
198
  function splitVariants(path: string): { path: string; variants: ForcedVariant[] } | null {
85
199
  const q = path.indexOf("?");
86
200
  if (q === -1) return { path, variants: [] };
87
201
  const kept: string[] = [];
88
202
  const variants: ForcedVariant[] = [];
89
203
  for (const param of path.slice(q + 1).split("&")) {
90
- if (!param.startsWith(VARIANT_PARAM)) {
204
+ if (param.startsWith(VARIANT_PARAM)) {
205
+ const variant = decodeVariant(param.slice(VARIANT_PARAM.length));
206
+ if (variant === null) return null;
207
+ variants.push(variant);
208
+ } else if (PREVIEW_PARAMS.some((prefix) => param.startsWith(prefix))) {
209
+ return null;
210
+ } else {
91
211
  kept.push(param);
92
- continue;
93
212
  }
94
- const variant = decodeVariant(param.slice(VARIANT_PARAM.length));
95
- if (variant === null) return null;
96
- variants.push(variant);
97
213
  }
98
214
  const base = path.slice(0, q);
99
215
  return { path: kept.length === 0 ? base : `${base}?${kept.join("&")}`, variants };
100
216
  }
101
217
 
218
+ /** `<name>=on|off`: the state after the last `=`, the test's or campaign's name before it. */
219
+ function decodeSwitch(encoded: string): { name: string; on: boolean } | null {
220
+ const raw = decodeParam(encoded);
221
+ if (raw === null) return null;
222
+ const eq = raw.lastIndexOf("=");
223
+ const state = raw.slice(eq + 1);
224
+ if (eq <= 0 || (state !== "on" && state !== "off")) return null;
225
+ return { name: raw.slice(0, eq), on: state === "on" };
226
+ }
227
+
228
+ function decodeParam(encoded: string): string | null {
229
+ try {
230
+ return decodeURIComponent(encoded);
231
+ } catch {
232
+ return null;
233
+ }
234
+ }
235
+
102
236
  /** `<block>@<path>=<index>`: the index after the last `=`, the block before the last `@`. */
103
237
  function decodeVariant(encoded: string): ForcedVariant | null {
104
238
  let raw: string;
@@ -117,8 +251,12 @@ function decodeVariant(encoded: string): ForcedVariant | null {
117
251
  }
118
252
 
119
253
  function encodeVariant({ block, path, index }: ForcedVariant): string {
254
+ return encodeParam(`${block}@${path}=${index}`);
255
+ }
256
+
257
+ function encodeParam(value: string): string {
120
258
  // encodeURIComponent leaves !'()* as they are; the pointer's path doesn't allow them.
121
- return encodeURIComponent(`${block}@${path}=${index}`).replace(
259
+ return encodeURIComponent(value).replace(
122
260
  /[!'()*]/g,
123
261
  (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`,
124
262
  );
@@ -157,23 +295,25 @@ function normalizeIPv6Host(authority: string): string | null {
157
295
  }
158
296
 
159
297
  /**
160
- * The draft pointer a request carries: `?__draft=` from the URL first, then
161
- * the `__deco_draft` cookie. `null` when neither is present, or when the URL
162
- * says `?__draft=off`. A value that doesn't parse is ignored, as if it were
298
+ * The version a request carries (a draft pointer, or a published release's
299
+ * commit SHA) with its preview's date, tests and campaigns (`parseVersion`):
300
+ * `?__draft=` from the URL first, then the `__deco_draft`
301
+ * cookie. `null` when neither is present, or when the URL says
302
+ * `?__draft=off`. A value that doesn't parse is ignored, as if it were
163
303
  * absent: a stray `?__draft=junk` link or a mangled cookie gets the release,
164
- * never an error from `cms.forDraft`.
304
+ * never an error from `cms.client`.
165
305
  */
166
- export function readDraftPointer(request: RequestLike): string | null {
306
+ export function readVersion(request: RequestLike): RequestVersion | null {
167
307
  const param = draftParam(request);
168
308
  if (param === DRAFT_OFF) return null;
169
- if (param && parseDraftPointer(param) !== null) return param;
170
- const cookie = readCookie(request.headers.get("cookie"), DRAFT_COOKIE);
171
- return cookie && parseDraftPointer(cookie) !== null ? cookie : null;
309
+ const fromLink = param ? parseVersion(param) : null;
310
+ if (fromLink !== null) return fromLink;
311
+ return parseVersion(readCookie(request.headers.get("cookie"), DRAFT_COOKIE));
172
312
  }
173
313
 
174
314
  /**
175
315
  * The `Set-Cookie` value for a request whose URL carries `?__draft=`: one that
176
- * stores the pointer, or one that expires the cookie when the value is `off`
316
+ * stores the version (a draft pointer or a release's commit SHA), or one that expires the cookie when the value is `off`
177
317
  * (how the site editor ends a preview). `null` on every other request, and for
178
318
  * a pointer that doesn't parse, so garbage never lands in the cookie.
179
319
  *
@@ -185,7 +325,7 @@ export function draftCookieFor(request: RequestLike): string | null {
185
325
  const param = draftParam(request);
186
326
  if (!param) return null;
187
327
  if (param === DRAFT_OFF) return serializeCookie("", ["Max-Age=0"]);
188
- if (parseDraftPointer(param) === null) return null;
328
+ if (parseVersion(param) === null) return null;
189
329
  return serializeCookie(encodeURIComponent(param), []);
190
330
  }
191
331
 
@@ -0,0 +1,340 @@
1
+ /**
2
+ * `@decocms/blocks/experiments`: who is in which A/B test, decided the same
3
+ * way on a server, in a browser and in a mobile app.
4
+ *
5
+ * The percentages are content (the saved block `experiments`, of the built-in
6
+ * type `split-traffic`); a decision is arithmetic over the visitor's id. What
7
+ * a visitor gets is never stored: it is recomputed from the percentage and the
8
+ * id, so one id serves every test (each roll hashes `name:id`), a new test
9
+ * needs no new state and two tests are independent.
10
+ *
11
+ * Pure functions over values and strings: no React, no framework, no module
12
+ * state, no environment reads, no network. Nothing here is called for you:
13
+ * the app reads the visitor its own way (`readVisitor` on the web, device
14
+ * storage in an app) and hands it to `cms.client({ visitor })`; the built-in
15
+ * `split-traffic` calls `assign` with it.
16
+ *
17
+ * The stored form is v7's `deco_segment` (the same fields and encoding; names
18
+ * sorted by code unit rather than v7's `localeCompare`) plus an `id`, so a
19
+ * visitor carried over from v7 keeps the group v7 put them in and analytics
20
+ * keeps reading the cookie it already reads. A visitor is written once, when
21
+ * it has no id; v7's stored assignments are read and honoured, never rewritten.
22
+ */
23
+
24
+ import { newId, roll } from "./bucketing.ts";
25
+
26
+ /** The saved block `experiments`: each test's name and the whole percentage of visitors in it, 0–100. */
27
+ export type Experiments = Record<string, number>;
28
+
29
+ /** What a visitor got: each test's name and whether they are in it. */
30
+ export type Assignments = Record<string, boolean>;
31
+
32
+ /**
33
+ * Who is visiting: an id every assignment is computed from, plus the
34
+ * assignments v7 stored (`active`, `inactiveDrawn`, `pct`, `exp`), which are honoured and
35
+ * carried, never rewritten.
36
+ */
37
+ export interface Visitor {
38
+ /**
39
+ * 16 random bytes as 22 base64url characters, drawn once per visitor. `""`
40
+ * for a visitor with no id of its own (one built from a cache key's
41
+ * assignments), which is in only the tests `active` names.
42
+ */
43
+ id: string;
44
+ /** Tests v7 put this visitor in. */
45
+ active: string[];
46
+ /** Tests v7 left this visitor out of. */
47
+ inactiveDrawn: string[];
48
+ /** The percentage each of v7's decisions was made at. */
49
+ pct: Record<string, number>;
50
+ /** v7's N-way decisions. Never read; carried as they are. */
51
+ exp?: Record<string, string>;
52
+ }
53
+
54
+ /** What `readVisitor` answers. */
55
+ export interface VisitorFromRequest {
56
+ /** The request's visitor, or a new one when it had none. */
57
+ visitor: Visitor;
58
+ /**
59
+ * The `Set-Cookie` line to send when the visitor had no id (a first visit,
60
+ * or a v7 visitor getting theirs); `null` otherwise. Never send it from a
61
+ * preview.
62
+ */
63
+ cookie: string | null;
64
+ }
65
+
66
+ /** The fields of a request `readVisitor` reads: a `Request`, or anything with its `headers`. */
67
+ interface RequestWithHeaders {
68
+ url?: string;
69
+ headers: { get(name: string): string | null };
70
+ }
71
+
72
+ /** The visitor's stored form, v7's name for it. */
73
+ const VISITOR_COOKIE = "deco_segment";
74
+
75
+ /** One year: the id is the visitor, and it should outlive any single test. */
76
+ const VISITOR_COOKIE_MAX_AGE = 60 * 60 * 24 * 365;
77
+
78
+ /**
79
+ * A cookie over this stays out of every request. An id plus 50 of v7's
80
+ * decisions fits well under it; past it, `serializeVisitor` drops entries,
81
+ * the ones the id reproduces first.
82
+ */
83
+ const COOKIE_BUDGET = 2048;
84
+
85
+ const ID_RE = /^[A-Za-z0-9_-]{22}$/;
86
+
87
+ /** A stored visitor before it is known to have an id. */
88
+ type Stored = Omit<Visitor, "id"> & { id?: string };
89
+
90
+ /**
91
+ * A record with no prototype, so a name such as `__proto__` is an ordinary
92
+ * key: decided, written and read back like any other.
93
+ */
94
+ function record<T>(): Record<string, T> {
95
+ return Object.create(null) as Record<string, T>;
96
+ }
97
+
98
+ function emptyStored(): Stored {
99
+ return { active: [], inactiveDrawn: [], pct: record() };
100
+ }
101
+
102
+ function stringList(value: unknown): string[] {
103
+ if (!Array.isArray(value)) return [];
104
+ return value.filter((entry): entry is string => typeof entry === "string");
105
+ }
106
+
107
+ function pctRecord(value: unknown): Record<string, number> {
108
+ const out = record<number>();
109
+ if (typeof value !== "object" || value === null) return out;
110
+ for (const [name, pct] of Object.entries(value as Record<string, unknown>)) {
111
+ if (typeof pct === "number" && Number.isFinite(pct)) out[name] = pct;
112
+ }
113
+ return out;
114
+ }
115
+
116
+ function expRecord(value: unknown): Record<string, string> | undefined {
117
+ if (typeof value !== "object" || value === null) return undefined;
118
+ const out = record<string>();
119
+ for (const [name, variant] of Object.entries(value as Record<string, unknown>)) {
120
+ if (typeof variant === "string") out[name] = variant;
121
+ }
122
+ return Object.keys(out).length > 0 ? out : undefined;
123
+ }
124
+
125
+ /**
126
+ * A stored value, with or without an id; `null` when it doesn't read. Never
127
+ * throws. The value may arrive percent-encoded (some cookie APIs encode what
128
+ * they write; base64 never holds a `%`, so decoding first is always safe).
129
+ * Entries of the wrong type are dropped, and an id that is not 22 base64url
130
+ * characters is treated as absent.
131
+ */
132
+ function parseStored(text: string | null | undefined): Stored | null {
133
+ if (typeof text !== "string" || text === "") return null;
134
+ try {
135
+ const parsed: unknown = JSON.parse(decodeURIComponent(atob(decodeURIComponent(text.trim()))));
136
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null;
137
+ const body = parsed as Record<string, unknown>;
138
+ const stored: Stored = {
139
+ active: stringList(body.active),
140
+ inactiveDrawn: stringList(body.inactiveDrawn),
141
+ pct: pctRecord(body.pct),
142
+ };
143
+ if (typeof body.id === "string" && ID_RE.test(body.id)) stored.id = body.id;
144
+ const exp = expRecord(body.exp);
145
+ if (exp) stored.exp = exp;
146
+ return stored;
147
+ } catch {
148
+ return null;
149
+ }
150
+ }
151
+
152
+ /** A new visitor: a fresh id and nothing else. */
153
+ export function newVisitor(): Visitor {
154
+ return { id: newId(), active: [], inactiveDrawn: [], pct: record() };
155
+ }
156
+
157
+ /**
158
+ * A visitor out of its stored form (what `serializeVisitor` wrote, the value
159
+ * of the `deco_segment` cookie). `null` when the text is missing, doesn't
160
+ * read, or holds no id (a v7 value: `readVisitor` gives it one, keeping its
161
+ * decisions). Never throws.
162
+ */
163
+ export function parseVisitor(text: string | null | undefined): Visitor | null {
164
+ const stored = parseStored(text);
165
+ return stored?.id === undefined ? null : (stored as Visitor);
166
+ }
167
+
168
+ /**
169
+ * The visitor's stored form: v7's `btoa(encodeURIComponent(JSON.stringify(...)))`,
170
+ * with a fixed key order and names sorted, so two equal visitors give
171
+ * byte-equal values. Under 2KB: past it, v7's entries are dropped, first the
172
+ * ones the id reproduces anyway.
173
+ */
174
+ export function serializeVisitor(visitor: Visitor): string {
175
+ const active = [...visitor.active].sort();
176
+ const inactiveDrawn = [...visitor.inactiveDrawn].sort();
177
+ const dropped = new Set<string>();
178
+
179
+ const encode = (): string => {
180
+ const stillActive = active.filter((name) => !dropped.has(name));
181
+ const stillInactive = inactiveDrawn.filter((name) => !dropped.has(name));
182
+ const pct = record<number>();
183
+ for (const name of Object.keys(visitor.pct).sort()) {
184
+ // v7 kept a `pct` beside its N-way names too, and `exp` is carried
185
+ // untouched, so their fingerprint is carried with it.
186
+ const listed =
187
+ stillActive.includes(name) ||
188
+ stillInactive.includes(name) ||
189
+ (visitor.exp !== undefined && Object.hasOwn(visitor.exp, name));
190
+ if (listed) pct[name] = visitor.pct[name] as number;
191
+ }
192
+ const body: Record<string, unknown> = {
193
+ active: stillActive,
194
+ inactiveDrawn: stillInactive,
195
+ pct,
196
+ };
197
+ if (visitor.id !== undefined) body.id = visitor.id;
198
+ if (visitor.exp !== undefined) body.exp = visitor.exp;
199
+ return btoa(encodeURIComponent(JSON.stringify(body)));
200
+ };
201
+
202
+ let value = encode();
203
+ if (value.length <= COOKIE_BUDGET) return value;
204
+
205
+ // Over budget. A dropped entry is decided by the roll from then on, which
206
+ // keeps the decision only when the stored one already agrees with the roll.
207
+ // So drop those first, and the others only if the value is still too big.
208
+ const reproducible = (name: string): boolean => {
209
+ const pct = visitor.pct[name];
210
+ if (typeof pct !== "number") return false;
211
+ return active.includes(name) === roll(name, visitor.id) < pct;
212
+ };
213
+ for (const name of [
214
+ ...inactiveDrawn.filter(reproducible),
215
+ ...active.filter(reproducible),
216
+ ...inactiveDrawn.filter((name) => !reproducible(name)),
217
+ ...active.filter((name) => !reproducible(name)),
218
+ ]) {
219
+ if (value.length <= COOKIE_BUDGET) break;
220
+ dropped.add(name);
221
+ value = encode();
222
+ }
223
+ return value;
224
+ }
225
+
226
+ /** The raw `deco_segment` value out of a `Cookie` header. */
227
+ function readCookie(cookies: string | null): string | undefined {
228
+ if (!cookies) return undefined;
229
+ for (const part of cookies.split(";")) {
230
+ const eq = part.indexOf("=");
231
+ if (eq < 0) continue;
232
+ if (part.slice(0, eq).trim() !== VISITOR_COOKIE) continue;
233
+ return part.slice(eq + 1).trim();
234
+ }
235
+ return undefined;
236
+ }
237
+
238
+ /** Whether a request came over plain http (localhost), where a `Secure` cookie isn't stored. */
239
+ function isPlainHttp(url: string | undefined): boolean {
240
+ if (typeof url !== "string") return false;
241
+ try {
242
+ return new URL(url).protocol === "http:";
243
+ } catch {
244
+ return false;
245
+ }
246
+ }
247
+
248
+ /**
249
+ * The web helper: the visitor out of a request's `deco_segment` cookie, and
250
+ * the `Set-Cookie` line to send back when it had no id (a first visit, or a
251
+ * v7 visitor, whose decisions are kept). The cookie isn't `HttpOnly` (the
252
+ * analytics script reads it, as in v7) and is `Secure` unless the request
253
+ * came over plain http. Never throws.
254
+ */
255
+ export function readVisitor(request: RequestWithHeaders): VisitorFromRequest {
256
+ let header: string | null = null;
257
+ try {
258
+ header = request.headers.get("cookie");
259
+ } catch {
260
+ header = null;
261
+ }
262
+ const stored = parseStored(readCookie(header));
263
+ if (stored?.id !== undefined) return { visitor: stored as Visitor, cookie: null };
264
+ const visitor: Visitor = { ...(stored ?? emptyStored()), id: newId() };
265
+ const parts = [
266
+ `${VISITOR_COOKIE}=${serializeVisitor(visitor)}`,
267
+ "Path=/",
268
+ `Max-Age=${VISITOR_COOKIE_MAX_AGE}`,
269
+ "SameSite=Lax",
270
+ ];
271
+ if (!isPlainHttp(request.url)) parts.push("Secure");
272
+ return { visitor, cookie: parts.join("; ") };
273
+ }
274
+
275
+ function roundPct(allocation: number): number {
276
+ return Math.round(Math.min(100, Math.max(0, allocation)));
277
+ }
278
+
279
+ /**
280
+ * A v7 decision after the percentage moved: raising a percentage never
281
+ * removes anyone v7 put in, and lowering it never adds anyone v7 left out.
282
+ * Otherwise the roll decides, as for any visitor.
283
+ */
284
+ function keptFromV7(stored: boolean, from: number, to: number): boolean | undefined {
285
+ if (to === from) return stored;
286
+ if (stored && to > from) return true;
287
+ if (!stored && to < from) return false;
288
+ return undefined;
289
+ }
290
+
291
+ /**
292
+ * This visitor's answer for every test: `true` when they are in it.
293
+ *
294
+ * A visitor is in a test when their roll for it (a fixed number in [0, 100)
295
+ * from the test's name and their id) is under its percentage, so 0 puts
296
+ * nobody in, 100 everybody, and raising a percentage only adds people. A
297
+ * fractional percentage is rounded. An assignment v7 stored is honoured while
298
+ * the percentage it was made at holds (a missing or `-1` percentage, v7's
299
+ * "any", included); once it moves, a v7 visitor in a test that grows stays
300
+ * in and one out of a test that shrinks stays out. Without a visitor every
301
+ * test is `false`. A visitor without an id (`""`, as a page built from a
302
+ * cache key's assignments gives one) has no roll: it is in exactly the tests
303
+ * its stored `active` and `pct` keep it in. Entries that aren't finite numbers are
304
+ * left out. Pure; never throws.
305
+ */
306
+ export function assign(
307
+ experiments: Experiments | null | undefined,
308
+ visitor: Visitor | null | undefined,
309
+ ): Assignments {
310
+ const assignments = record<boolean>();
311
+ if (typeof experiments !== "object" || experiments === null) return assignments;
312
+ const id = visitor !== null && typeof visitor === "object" ? visitor.id : undefined;
313
+ const known = typeof id === "string" && ID_RE.test(id);
314
+ const v: Partial<Visitor> = visitor !== null && typeof visitor === "object" ? visitor : {};
315
+ for (const name of Object.keys(experiments).sort()) {
316
+ const allocation = experiments[name];
317
+ if (typeof allocation !== "number" || !Number.isFinite(allocation)) continue;
318
+ const pct = roundPct(allocation);
319
+ const stored = list(v.active).includes(name)
320
+ ? true
321
+ : list(v.inactiveDrawn).includes(name)
322
+ ? false
323
+ : undefined;
324
+ // v7 wrote `round(traffic * 100)` here, and its own reader treated a
325
+ // missing or negative entry as "matches anything".
326
+ const raw = isRecord(v.pct) && Object.hasOwn(v.pct, name) ? v.pct[name] : undefined;
327
+ const from = typeof raw === "number" && Number.isFinite(raw) && raw >= 0 ? roundPct(raw) : pct;
328
+ const kept = stored === undefined ? undefined : keptFromV7(stored, from, pct);
329
+ assignments[name] = kept ?? (known && roll(name, id as string) < pct);
330
+ }
331
+ return assignments;
332
+ }
333
+
334
+ function list(value: unknown): string[] {
335
+ return Array.isArray(value) ? value : [];
336
+ }
337
+
338
+ function isRecord(value: unknown): value is Record<string, unknown> {
339
+ return typeof value === "object" && value !== null;
340
+ }
package/src/v8/hosts.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  /**
2
- * Host patterns (see /next/api-reference#host-patterns): the format of
3
- * `preview.hosts`, in `createCMS` and in the `CMS` block.
2
+ * Host patterns (see /next/api-reference#host-patterns): the format of a
3
+ * release's `previewHosts` (Studio writes them into the release metadata)
4
+ * and of `createCMS`'s `preview.hosts`.
4
5
  *
5
6
  * - Hostnames and patterns are compared lowercase, with one trailing dot
6
7
  * removed; names outside ASCII in their punycode form.
package/src/v8/index.ts CHANGED
@@ -1,11 +1,13 @@
1
1
  /**
2
- * The next-major (v8) core SDK: `createCMS`, the clients, the built-in blocks,
3
- * `matchRoute` and the draft pointer helpers (`cms.draftPointer` and
4
- * `cms.draftCookie` are methods: they check the preview hosts). Re-exported from the package root, where
2
+ * The next-major (v8) core SDK: `createCMS`, the clients, `currentClient`,
3
+ * the built-in blocks, `matchRoute` and the draft pointer helpers
4
+ * (`cms.readVersion` and `cms.draftCookie` are methods: they check the
5
+ * preview hosts). Re-exported from the package root, where
5
6
  * these names are the documented ones; see /next/api-reference.
6
7
  */
7
8
  export { createCMS, resetForTests } from "./cms.ts";
8
- export { formatDraftPointer, parseDraftPointer } from "./draft.ts";
9
+ export { currentClient } from "./current.ts";
10
+ export { formatDraftPointer, parseDraftPointer, parseVersion } from "./draft.ts";
9
11
  export { matchRoute } from "./matchRoute.ts";
10
12
  export { remoteLoader } from "./remoteLoader.ts";
11
13
  export type {
@@ -14,6 +16,7 @@ export type {
14
16
  BlockFunction,
15
17
  Blocks,
16
18
  Client,
19
+ ClientOptions,
17
20
  CMS,
18
21
  CMSError,
19
22
  CMSSettings,
@@ -26,6 +29,7 @@ export type {
26
29
  Page,
27
30
  Redirect,
28
31
  RequestLike,
32
+ RequestVersion,
29
33
  Result,
30
34
  Route,
31
35
  Secret,