@delmaredigital/payload-experiments 0.4.0-rc.7 → 0.4.0-rc.9

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 (221) hide show
  1. package/README.md +12 -12
  2. package/dist/admin/blocks/model.js +2 -2
  3. package/dist/admin/copy/blocks.js +1 -1
  4. package/dist/admin/surface/ResultsRoute.js +17 -11
  5. package/dist/admin/surface/TestsHome.js +53 -20
  6. package/dist/admin/surface/newTest/PageWizard.js +8 -2
  7. package/dist/admin/surface/results/ResultsHeader.js +11 -6
  8. package/dist/admin/surface/test/TestPage.js +3 -3
  9. package/dist/blocks/formState.js +1 -1
  10. package/dist/collections/experiments/config.js +8 -3
  11. package/dist/collections/experiments/deleteGuard.js +2 -2
  12. package/dist/collections/experiments/lockHook.js +21 -2
  13. package/dist/collections/experiments/pickSlug.js +2 -0
  14. package/dist/collections/metricsGuards.js +2 -0
  15. package/dist/collections/serialize.js +5 -4
  16. package/dist/constants.d.ts +1 -0
  17. package/dist/constants.js +1 -0
  18. package/dist/db/adapter.d.ts +9 -1
  19. package/dist/db/adapter.js +77 -1
  20. package/dist/db/delete.d.ts +1 -1
  21. package/dist/db/delete.js +2 -4
  22. package/dist/db/events.d.ts +9 -0
  23. package/dist/db/events.js +42 -8
  24. package/dist/db/executor.d.ts +7 -1
  25. package/dist/db/executor.js +7 -3
  26. package/dist/db/results.d.ts +5 -1
  27. package/dist/db/results.js +21 -5
  28. package/dist/db/snapshots.d.ts +1 -0
  29. package/dist/endpoints/deleteImpact.js +2 -1
  30. package/dist/endpoints/events.js +103 -39
  31. package/dist/endpoints/index.js +2 -8
  32. package/dist/endpoints/placementStatus.js +7 -4
  33. package/dist/endpoints/results.d.ts +1 -1
  34. package/dist/endpoints/results.js +6 -2
  35. package/dist/endpoints/routeId.d.ts +2 -2
  36. package/dist/endpoints/routeId.js +11 -5
  37. package/dist/endpoints/summary.js +46 -12
  38. package/dist/endpoints/transitions.js +37 -24
  39. package/dist/errors.d.ts +4 -0
  40. package/dist/errors.js +6 -0
  41. package/dist/events/request.d.ts +6 -2
  42. package/dist/events/request.js +35 -8
  43. package/dist/events/rows.d.ts +1 -1
  44. package/dist/events/rows.js +24 -8
  45. package/dist/events/writable.d.ts +9 -0
  46. package/dist/events/writable.js +13 -0
  47. package/dist/exports/index.d.ts +1 -1
  48. package/dist/exports/rsc.d.ts +1 -0
  49. package/dist/exports/rsc.js +1 -0
  50. package/dist/goals/fairness.js +2 -2
  51. package/dist/hooks/hostHook.js +6 -2
  52. package/dist/hooks/pageGuard.js +4 -0
  53. package/dist/lib/fetchAllDocs.d.ts +1 -1
  54. package/dist/manifest/compile.js +8 -5
  55. package/dist/onInit.js +14 -0
  56. package/dist/options.js +5 -0
  57. package/dist/proxy/pageNavigation.d.ts +4 -0
  58. package/dist/proxy/pageNavigation.js +28 -0
  59. package/dist/proxy/resolve.js +52 -25
  60. package/dist/puck/editor/ConfigureTestDrawer.js +5 -4
  61. package/dist/puck/editor/ExperimentSlotEditor.js +182 -58
  62. package/dist/puck/editor/QuickTestActions.d.ts +5 -2
  63. package/dist/puck/editor/QuickTestActions.js +16 -4
  64. package/dist/puck/editor/ResultsReadout.d.ts +2 -1
  65. package/dist/puck/editor/ResultsReadout.js +2 -1
  66. package/dist/puck/editor/VersionBuilder.d.ts +13 -2
  67. package/dist/puck/editor/VersionBuilder.js +133 -49
  68. package/dist/puck/editor/armWrites.js +1 -1
  69. package/dist/puck/editor/armsCache.js +1 -3
  70. package/dist/puck/editor/copy.d.ts +4 -1
  71. package/dist/puck/editor/copy.js +4 -1
  72. package/dist/puck/editor/editor.chrome.css +1 -0
  73. package/dist/puck/editor/editor.css +1 -0
  74. package/dist/puck/editor/editor.model.d.ts +1 -0
  75. package/dist/puck/editor/placementsCache.d.ts +5 -1
  76. package/dist/puck/editor/placementsCache.js +17 -9
  77. package/dist/puck/editor/usePageSaveReadiness.d.ts +9 -0
  78. package/dist/puck/editor/usePageSaveReadiness.js +34 -0
  79. package/dist/puck/editor/usePlacementNotice.d.ts +2 -2
  80. package/dist/puck/editor/usePlacementNotice.js +5 -4
  81. package/dist/results/aggregate.d.ts +6 -3
  82. package/dist/results/aggregate.js +9 -9
  83. package/dist/results/health.d.ts +8 -0
  84. package/dist/results/health.js +28 -0
  85. package/dist/results/identityCredit.d.ts +1 -0
  86. package/dist/results/identityCredit.js +4 -1
  87. package/dist/results/verdict.js +2 -1
  88. package/dist/runtime/cookie.d.ts +10 -2
  89. package/dist/runtime/cookie.js +38 -6
  90. package/dist/runtime/cookieOptions.d.ts +6 -0
  91. package/dist/runtime/cookieOptions.js +14 -0
  92. package/dist/runtime/proxyRuntime.d.ts +1 -0
  93. package/dist/runtime/proxyRuntime.js +18 -8
  94. package/dist/runtime/signing.d.ts +1 -0
  95. package/dist/runtime/signing.js +5 -0
  96. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  97. package/dist/sanitizeReadinessDetail.js +20 -2
  98. package/dist/server/getAssignments.js +11 -10
  99. package/dist/server/recordContentChange.d.ts +1 -1
  100. package/dist/server/recordContentChange.js +11 -2
  101. package/dist/server/resolveExperimentBlocks.js +2 -4
  102. package/dist/server/resolveExperimentData.js +2 -5
  103. package/dist/server/runResults.js +52 -14
  104. package/dist/server/startExperiment.d.ts +20 -0
  105. package/dist/server/startExperiment.js +70 -0
  106. package/dist/server/trackConversion.js +10 -13
  107. package/dist/testSurface/actions/DecideDialog.d.ts +4 -1
  108. package/dist/testSurface/actions/DecideDialog.js +32 -14
  109. package/dist/testSurface/actions/MakeContentResult.d.ts +4 -3
  110. package/dist/testSurface/actions/MakeContentResult.js +9 -1
  111. package/dist/testSurface/api.d.ts +5 -5
  112. package/dist/testSurface/api.js +21 -9
  113. package/dist/testSurface/copy/actions.d.ts +1 -0
  114. package/dist/testSurface/copy/actions.js +1 -0
  115. package/dist/testSurface/copy/common.d.ts +3 -1
  116. package/dist/testSurface/copy/common.js +4 -2
  117. package/dist/testSurface/copy/languages.d.ts +1 -0
  118. package/dist/testSurface/copy/languages.js +1 -0
  119. package/dist/testSurface/copy/metrics.d.ts +1 -0
  120. package/dist/testSurface/copy/metrics.js +1 -0
  121. package/dist/testSurface/copy/readiness.d.ts +12 -1
  122. package/dist/testSurface/copy/readiness.js +18 -1
  123. package/dist/testSurface/copy/results.d.ts +5 -2
  124. package/dist/testSurface/copy/results.js +5 -2
  125. package/dist/testSurface/copy/testPage.d.ts +20 -2
  126. package/dist/testSurface/copy/testPage.js +34 -3
  127. package/dist/testSurface/readPreflight.d.ts +5 -0
  128. package/dist/testSurface/readPreflight.js +7 -0
  129. package/dist/testSurface/readinessRead.d.ts +3 -0
  130. package/dist/testSurface/readinessRead.js +4 -0
  131. package/dist/testSurface/results/VerdictHero.d.ts +2 -1
  132. package/dist/testSurface/results/VerdictHero.js +5 -1
  133. package/dist/testSurface/results/results.model.d.ts +1 -1
  134. package/dist/testSurface/results/results.model.js +6 -2
  135. package/dist/testSurface/surface/contracts.d.ts +8 -1
  136. package/dist/testSurface/surface/editorPlacement.d.ts +2 -2
  137. package/dist/testSurface/surface/editorPlacement.js +1 -1
  138. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +2 -2
  139. package/dist/testSurface/surface/pagePicker/PageCombobox.js +20 -6
  140. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +4 -2
  141. package/dist/testSurface/surface/readiness/ActionDialogs.js +39 -34
  142. package/dist/testSurface/surface/readiness/Banner.js +23 -12
  143. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +4 -3
  144. package/dist/testSurface/surface/readiness/SaveStatus.js +15 -15
  145. package/dist/testSurface/surface/readiness/readiness.model.d.ts +6 -1
  146. package/dist/testSurface/surface/readiness/readiness.model.js +108 -11
  147. package/dist/testSurface/surface/readiness/useTransition.d.ts +4 -4
  148. package/dist/testSurface/surface/readiness/useTransition.js +12 -10
  149. package/dist/testSurface/surface/results/ReleasePages.d.ts +4 -2
  150. package/dist/testSurface/surface/results/ReleasePages.js +5 -4
  151. package/dist/testSurface/surface/results/ResultsBody.d.ts +4 -2
  152. package/dist/testSurface/surface/results/ResultsBody.js +86 -43
  153. package/dist/testSurface/surface/results/useResults.d.ts +7 -6
  154. package/dist/testSurface/surface/results/useResults.js +3 -2
  155. package/dist/testSurface/surface/setting/parts.js +58 -18
  156. package/dist/testSurface/surface/test/AdvancedSection.js +1 -0
  157. package/dist/testSurface/surface/test/DeleteTest.d.ts +6 -2
  158. package/dist/testSurface/surface/test/DeleteTest.js +145 -54
  159. package/dist/testSurface/surface/test/GoalSection.js +7 -3
  160. package/dist/testSurface/surface/test/LengthSection.js +3 -0
  161. package/dist/testSurface/surface/test/PageHoldout.js +4 -1
  162. package/dist/testSurface/surface/test/ReadinessBar.js +1 -1
  163. package/dist/testSurface/surface/test/TargetingSection.js +77 -12
  164. package/dist/testSurface/surface/test/TestSurface.js +81 -19
  165. package/dist/testSurface/surface/test/VersionsSection.js +56 -29
  166. package/dist/testSurface/surface/test/fields.d.ts +29 -4
  167. package/dist/testSurface/surface/test/fields.js +159 -39
  168. package/dist/testSurface/surface/test/pageParts.js +14 -5
  169. package/dist/testSurface/surface/test/testPage.model.d.ts +1 -0
  170. package/dist/testSurface/surface/test/testPage.model.js +6 -0
  171. package/dist/testSurface/surface/testDocument.model.d.ts +3 -0
  172. package/dist/testSurface/surface/testDocument.model.js +4 -1
  173. package/dist/testSurface/surface/useTestDocument.d.ts +22 -4
  174. package/dist/testSurface/surface/useTestDocument.js +407 -160
  175. package/dist/testSurface/useApi.d.ts +5 -5
  176. package/dist/testSurface/useOnTestReturn.d.ts +2 -0
  177. package/dist/testSurface/useOnTestReturn.js +27 -0
  178. package/dist/testSurface/useReadinessPolling.js +3 -1
  179. package/dist/transitions/addMetric.d.ts +1 -4
  180. package/dist/transitions/allocate.d.ts +2 -2
  181. package/dist/transitions/allocate.js +3 -1
  182. package/dist/transitions/archive.d.ts +1 -1
  183. package/dist/transitions/archive.js +3 -2
  184. package/dist/transitions/checkStart.d.ts +1 -0
  185. package/dist/transitions/checkStart.js +17 -6
  186. package/dist/transitions/decide.d.ts +1 -1
  187. package/dist/transitions/decide.js +5 -3
  188. package/dist/transitions/deleteExperiment.d.ts +2 -2
  189. package/dist/transitions/deleteExperiment.js +17 -7
  190. package/dist/transitions/kernel.d.ts +2 -0
  191. package/dist/transitions/kernel.js +9 -4
  192. package/dist/transitions/makeContent.d.ts +2 -1
  193. package/dist/transitions/makeContent.js +12 -8
  194. package/dist/transitions/nestedPlacementNames.d.ts +2 -2
  195. package/dist/transitions/nestedPlacementNames.js +4 -5
  196. package/dist/transitions/phaseRecord.d.ts +2 -0
  197. package/dist/transitions/phaseRecord.js +5 -0
  198. package/dist/transitions/placementInteractions.d.ts +3 -3
  199. package/dist/transitions/placementInteractions.js +8 -7
  200. package/dist/transitions/placements.d.ts +2 -0
  201. package/dist/transitions/placements.js +5 -5
  202. package/dist/transitions/preflightData.d.ts +3 -2
  203. package/dist/transitions/preflightData.js +67 -41
  204. package/dist/transitions/releaseHoldout.d.ts +2 -1
  205. package/dist/transitions/releaseHoldout.js +3 -1
  206. package/dist/transitions/releasePages.d.ts +2 -1
  207. package/dist/transitions/releasePages.js +3 -1
  208. package/dist/transitions/resolveCaps.d.ts +2 -4
  209. package/dist/transitions/start.d.ts +6 -8
  210. package/dist/transitions/start.js +67 -34
  211. package/dist/transitions/startReads.d.ts +7 -0
  212. package/dist/transitions/startReads.js +28 -0
  213. package/dist/transitions/stop.d.ts +2 -1
  214. package/dist/transitions/stop.js +3 -2
  215. package/dist/types/contracts.d.ts +6 -3
  216. package/dist/types/endpoints.d.ts +52 -9
  217. package/dist/types/runtime.d.ts +15 -9
  218. package/dist/types/snapshot.d.ts +2 -0
  219. package/dist/ui/ChipsInput.d.ts +8 -1
  220. package/dist/ui/ChipsInput.js +17 -4
  221. package/package.json +2 -2
@@ -21,24 +21,23 @@ import { XpAnalysisError } from '../errors.js';
21
21
  const ts = timestampMs(row.ts);
22
22
  if (ts >= end || excluded.has(row.unitId)) continue;
23
23
  const unit = first.get(row.unitId);
24
- if (!unit) first.set(row.unitId, {
25
- arm: row.arm,
26
- firstTs: ts
27
- });
28
- else if (unit.arm !== row.arm) {
24
+ if (unit && unit.arm !== row.arm) {
29
25
  first.delete(row.unitId);
30
26
  excluded.add(row.unitId);
31
- } else if (ts < unit.firstTs) {
27
+ } else if (!unit || ts < unit.firstTs) {
32
28
  first.set(row.unitId, {
33
29
  arm: row.arm,
34
- firstTs: ts
30
+ firstTs: ts,
31
+ ...row.unitAgeMs === undefined ? {} : {
32
+ unitAgeMs: row.unitAgeMs
33
+ }
35
34
  });
36
35
  }
37
36
  }
38
37
  const units = new Map();
39
38
  for (const [unitId, unit] of first){
40
39
  units.set(unitId, {
41
- arm: unit.arm,
40
+ ...unit,
42
41
  firstTs: new Date(unit.firstTs)
43
42
  });
44
43
  }
@@ -47,7 +46,7 @@ import { XpAnalysisError } from '../errors.js';
47
46
  excludedMultiArm: excluded.size
48
47
  };
49
48
  }
50
- /** Spec §7.6/§8.2: zero-filled outcomes over each exposed unit's half-open window. */ export function perUnitValues(units, events, { kind, windowHours, endedAt }) {
49
+ /** Spec §7.6/§8.2: zero-filled outcomes over each exposed unit's half-open window. */ export function perUnitValues(units, events, { kind, windowHours, endedAt, onAttributed }) {
51
50
  const values = new Map();
52
51
  const starts = new Map();
53
52
  const duration = windowMs(windowHours);
@@ -61,6 +60,7 @@ import { XpAnalysisError } from '../errors.js';
61
60
  const start = starts.get(event.unitId);
62
61
  if (start === undefined) continue;
63
62
  if (ts < start || ts >= Math.min(start + duration, phaseEnd)) continue;
63
+ onAttributed?.(event, ts);
64
64
  values.set(event.unitId, kind === 'binomial' ? 1 : values.get(event.unitId) + (kind === 'count' ? 1 : event.value));
65
65
  }
66
66
  return values;
@@ -1,4 +1,12 @@
1
1
  import type { Snapshot, SnapshotHealth } from '../types/snapshot.js';
2
+ /** A diagnostic for a large difference in rapid activity, not an inference test.
3
+ * Compare only arms with enough observations and age coverage. Ordinary
4
+ * same-speed activity (including immediate pageviews) should not warn.
5
+ */
6
+ export declare function rapidBrowserEvents(arms: ReadonlySet<string>, units: Iterable<{
7
+ arm: string;
8
+ unitAgeMs?: number;
9
+ }>): boolean;
2
10
  /** Refresh page health while retaining health produced by other checks. */
3
11
  export declare function mergePageHealth(previous: readonly SnapshotHealth[], pages: readonly SnapshotHealth[]): SnapshotHealth[];
4
12
  export declare function canonicalHealth(snapshot: Pick<Snapshot, 'health' | 'goalFairnessNotice'>, ignoreUncheckedPlacements?: boolean): string;
@@ -1,3 +1,31 @@
1
+ const rapidAgeMs = 5_000;
2
+ const minimumKnownPerArm = 30;
3
+ /** A diagnostic for a large difference in rapid activity, not an inference test.
4
+ * Compare only arms with enough observations and age coverage. Ordinary
5
+ * same-speed activity (including immediate pageviews) should not warn.
6
+ */ export function rapidBrowserEvents(arms, units) {
7
+ const counts = new Map();
8
+ for (const { arm, unitAgeMs } of units){
9
+ if (!arms.has(arm)) continue;
10
+ const count = counts.get(arm) ?? {
11
+ total: 0,
12
+ known: 0,
13
+ rapid: 0
14
+ };
15
+ count.total++;
16
+ if (unitAgeMs !== undefined) {
17
+ count.known++;
18
+ if (unitAgeMs <= rapidAgeMs) count.rapid++;
19
+ }
20
+ counts.set(arm, count);
21
+ }
22
+ const usable = [
23
+ ...counts.values()
24
+ ].filter((count)=>count.known >= minimumKnownPerArm && 2 * count.known >= count.total);
25
+ // A fast arm needs ≥25% rapid activity and a gap of ≥20 percentage points.
26
+ // Compare counts directly so exact boundaries don't depend on rounding.
27
+ return usable.some((high)=>4 * high.rapid >= high.known && usable.some((low)=>5 * (high.rapid * low.known - low.rapid * high.known) >= high.known * low.known));
28
+ }
1
29
  const healthKey = (row)=>JSON.stringify(row.code === 'placement-unchecked' ? [
2
30
  row.code,
3
31
  row.detail.collection ?? '',
@@ -18,6 +18,7 @@ export declare function creditUserEvents(units: ReadonlyMap<string, ExposedUnit>
18
18
  userId: string;
19
19
  value: number;
20
20
  ts: Timestamp;
21
+ unitAgeMs?: number;
21
22
  }[], onConflict?: (userId: string) => void): {
22
23
  events: MetricEvent[];
23
24
  conflicts: number;
@@ -31,7 +31,10 @@ import { timestampMs } from './aggregate.js';
31
31
  events.push({
32
32
  unitId: eligible[0].anonymousId,
33
33
  value: event.value,
34
- ts: event.ts
34
+ ts: event.ts,
35
+ ...event.unitAgeMs === undefined ? {} : {
36
+ unitAgeMs: event.unitAgeMs
37
+ }
35
38
  });
36
39
  if (new Set(eligible.map((link)=>units.get(link.anonymousId).arm)).size > 1) {
37
40
  conflicts.add(event.userId);
@@ -1,4 +1,5 @@
1
1
  import { ARM_LABELS } from '../labels/arms.js';
2
+ import { RESULTS_COPY } from '../testSurface/copy/results.js';
2
3
  function percent(value) {
3
4
  if (value === null) return '…';
4
5
  const rounded = Math.round(value * 100);
@@ -44,7 +45,7 @@ function chance(value) {
44
45
  return make(rollout ? 'R1' : 1, 'unavailable', `Results unavailable: ${input.primary.name} could not be read.`, 'Recompute; if it persists, contact a developer.', 'The main outcome could not be loaded.', null);
45
46
  }
46
47
  if (input.srm.flagged || input.exposures.multiArmShare >= 0.01) {
47
- return make(rollout ? 'R1' : 2, 'data-problem', "Data problem: traffic isn't splitting as set.", "Don't trust these results. Check for caching or a page placed twice; contact a developer.", 'The people counted do not match the expected split.', null);
48
+ return make(rollout ? 'R1' : 2, 'data-problem', "Data problem: traffic isn't splitting as set.", input.srm.flagged ? RESULTS_COPY.srmAction : "Don't trust these results. Ask a developer to check for caching or a page placed twice.", 'The people counted do not match the expected split.', null);
48
49
  }
49
50
  const compared = input.exposures.perArm.filter((item)=>rollout || item.kind !== 'holdout');
50
51
  const minimum = compared.length ? Math.min(...compared.map((item)=>item.n)) : 0;
@@ -1,10 +1,17 @@
1
1
  import { NextRequest } from 'next/server.js';
2
2
  import type { ExperimentsProxyRuntime } from '../types/runtime.js';
3
3
  export declare function mintUnitId(): string;
4
- export declare function encodeUnitCookie(unitId: string, secrets: readonly string[]): string;
5
- export declare function verifyUnitCookie(cookie: string | undefined, secrets: readonly string[]): string | null;
4
+ export declare function encodeUnitCookie(unitId: string, secrets: readonly string[], issuedAtMs?: number | 'legacy', renewedAtMs?: number): string;
5
+ interface SignedUnit {
6
+ unitId: string;
7
+ issuedAtMs: number | 'legacy';
8
+ renewedAtMs: number | null;
9
+ }
10
+ export declare function verifySignedUnit(cookie: string | undefined, secrets: readonly string[], maxAgeMs: number, now?: number, legacyCutoffMs?: number): SignedUnit | null;
11
+ export declare function unitCookieMaxAgeMs(runtime: Pick<ExperimentsProxyRuntime, 'cookie'>): number;
6
12
  /** Use Next's cookie selection everywhere: the last cookie of a given name wins. */
7
13
  export declare function readUnitCookie(input: Headers | NextRequest, runtime: Pick<ExperimentsProxyRuntime, 'cookie' | 'secrets'>): string | null;
14
+ export declare function readSignedUnit(input: Headers | NextRequest, runtime: Pick<ExperimentsProxyRuntime, 'cookie' | 'secrets'>, now?: number): SignedUnit | null;
8
15
  export declare function cookieAttributes(runtime: Pick<ExperimentsProxyRuntime, 'cookie'>, { https }: {
9
16
  https: boolean;
10
17
  }): {
@@ -15,3 +22,4 @@ export declare function cookieAttributes(runtime: Pick<ExperimentsProxyRuntime,
15
22
  path: string;
16
23
  maxAge: number;
17
24
  };
25
+ export {};
@@ -1,30 +1,62 @@
1
1
  import { randomBytes } from 'node:crypto';
2
2
  import { NextRequest } from 'next/server.js';
3
+ import { DAY_MS, LEGACY_COOKIE_CUTOFF_MS } from './cookieOptions.js';
3
4
  import { sign, verify } from './signing.js';
4
5
  export function mintUnitId() {
5
6
  return randomBytes(16).toString('base64url');
6
7
  }
7
- export function encodeUnitCookie(unitId, secrets) {
8
+ export function encodeUnitCookie(unitId, secrets, issuedAtMs = Date.now(), renewedAtMs = issuedAtMs === 'legacy' ? Date.now() : issuedAtMs) {
8
9
  if (!/^[A-Za-z0-9_-]+$/.test(unitId)) throw new Error('Invalid unit id');
9
- return `${unitId}.${sign(`xp:unit:${unitId}`, secrets)}`;
10
+ if (!validTimes(issuedAtMs, renewedAtMs)) throw new Error('Invalid unit cookie time');
11
+ const payload = `${unitId}.${issuedAtMs}.${renewedAtMs}`;
12
+ return `v2.${payload}.${sign(`xp:unit:v2:${payload}`, secrets)}`;
10
13
  }
11
- export function verifyUnitCookie(cookie, secrets) {
14
+ function validTimes(issuedAtMs, renewedAtMs) {
15
+ return Number.isSafeInteger(renewedAtMs) && renewedAtMs >= 0 && (issuedAtMs === 'legacy' || Number.isSafeInteger(issuedAtMs) && issuedAtMs >= 0 && issuedAtMs <= renewedAtMs);
16
+ }
17
+ export function verifySignedUnit(cookie, secrets, maxAgeMs, now = Date.now(), legacyCutoffMs = LEGACY_COOKIE_CUTOFF_MS) {
12
18
  if (typeof cookie !== 'string') return null;
19
+ const acceptsLegacy = now < Math.min(legacyCutoffMs, LEGACY_COOKIE_CUTOFF_MS);
20
+ const timed = /^v2\.(([A-Za-z0-9_-]+)\.(legacy|0|[1-9][0-9]{0,15})\.(0|[1-9][0-9]{0,15}))\.([A-Za-z0-9_-]{43})$/.exec(cookie);
21
+ if (timed) {
22
+ const payload = timed[1], unitId = timed[2], time = timed[3], renewal = timed[4], mac = timed[5];
23
+ const issuedAtMs = time === 'legacy' ? time : Number(time);
24
+ const renewedAtMs = Number(renewal);
25
+ if (issuedAtMs === 'legacy' && !acceptsLegacy) return null;
26
+ return validTimes(issuedAtMs, renewedAtMs) && now - renewedAtMs < maxAgeMs && verify(`xp:unit:v2:${payload}`, mac, secrets) ? {
27
+ unitId,
28
+ issuedAtMs,
29
+ renewedAtMs
30
+ } : null;
31
+ }
32
+ if (!acceptsLegacy) return null;
13
33
  const match = /^([A-Za-z0-9_-]+)\.([A-Za-z0-9_-]{43})$/.exec(cookie);
14
- return match && verify(`xp:unit:${match[1]}`, match[2], secrets) ? match[1] : null;
34
+ return match && verify(`xp:unit:${match[1]}`, match[2], secrets) ? {
35
+ unitId: match[1],
36
+ issuedAtMs: 'legacy',
37
+ renewedAtMs: null
38
+ } : null;
39
+ }
40
+ export function unitCookieMaxAgeMs(runtime) {
41
+ // Set-Cookie's Max-Age is an integer number of seconds. Verify the same lifetime.
42
+ return Math.floor(runtime.cookie.maxAgeDays * (DAY_MS / 1000)) * 1000;
15
43
  }
16
44
  /** Use Next's cookie selection everywhere: the last cookie of a given name wins. */ export function readUnitCookie(input, runtime) {
45
+ return readSignedUnit(input, runtime)?.unitId ?? null;
46
+ }
47
+ export function readSignedUnit(input, runtime, now = Date.now()) {
17
48
  const request = input instanceof Headers ? new NextRequest('https://xp.invalid/', {
18
49
  headers: input
19
50
  }) : input;
20
- return verifyUnitCookie(request.cookies.get(runtime.cookie.name)?.value, runtime.secrets);
51
+ const cutoff = runtime.cookie.legacyCutoff;
52
+ return verifySignedUnit(request.cookies.get(runtime.cookie.name)?.value, runtime.secrets, unitCookieMaxAgeMs(runtime), now, cutoff === undefined ? undefined : Date.parse(cutoff));
21
53
  }
22
54
  export function cookieAttributes(runtime, { https }) {
23
55
  return {
24
56
  httpOnly: true,
25
57
  sameSite: 'lax',
26
58
  path: '/',
27
- maxAge: runtime.cookie.maxAgeDays * 86400,
59
+ maxAge: unitCookieMaxAgeMs(runtime) / 1000,
28
60
  ...https ? {
29
61
  secure: true
30
62
  } : {},
@@ -0,0 +1,6 @@
1
+ export declare const LEGACY_COOKIE_CUTOFF_MS: number;
2
+ export declare const DAY_MS = 86400000;
3
+ export declare function assertCookieOptions({ maxAgeDays, legacyCutoff }: {
4
+ maxAgeDays: number;
5
+ legacyCutoff?: string;
6
+ }): void;
@@ -0,0 +1,14 @@
1
+ // 400 days after the end of the December 2, 2026 rollout day (UTC).
2
+ export const LEGACY_COOKIE_CUTOFF_MS = Date.UTC(2028, 0, 7);
3
+ export const DAY_MS = 86_400_000;
4
+ export function assertCookieOptions({ maxAgeDays, legacyCutoff }) {
5
+ if (!Number.isFinite(maxAgeDays) || maxAgeDays * DAY_MS < 1000 || maxAgeDays > 400) {
6
+ throw new Error('Experiments cookie.maxAgeDays must be a number from one second in days (1/86400) through 400.');
7
+ }
8
+ if (legacyCutoff !== undefined) {
9
+ const cutoff = typeof legacyCutoff === 'string' && /^\d{4}-\d{2}-\d{2}$/.test(legacyCutoff) ? Date.parse(legacyCutoff) : NaN;
10
+ if (!Number.isFinite(cutoff) || cutoff > LEGACY_COOKIE_CUTOFF_MS || new Date(cutoff).toISOString().slice(0, 10) !== legacyCutoff) {
11
+ throw new Error('Experiments cookie.legacyCutoff must be a UTC date (YYYY-MM-DD) on or before 2028-01-07.');
12
+ }
13
+ }
14
+ }
@@ -1,2 +1,3 @@
1
1
  import type { ExperimentsProxyRuntime, ExperimentsProxyRuntimeOptions } from '../types/runtime.js';
2
+ export declare function assertUnitRateLimit(rateLimitUnit: unknown): void;
2
3
  export declare function defineExperimentsProxyRuntime(opts: ExperimentsProxyRuntimeOptions): ExperimentsProxyRuntime;
@@ -1,22 +1,32 @@
1
1
  import { XP_COOKIE } from '../constants.js';
2
+ import { assertSigningSecrets } from './signing.js';
3
+ import { assertCookieOptions } from './cookieOptions.js';
4
+ export function assertUnitRateLimit(rateLimitUnit) {
5
+ if (rateLimitUnit !== false && typeof rateLimitUnit !== 'function') {
6
+ throw new Error('Experiments requires rateLimitUnit to be a client-address rate limiter, or false if you rate-limit unit issuance upstream.');
7
+ }
8
+ }
2
9
  export function defineExperimentsProxyRuntime(opts) {
3
10
  const secrets = typeof opts.secret === 'string' ? [
4
11
  opts.secret
5
- ] : [
6
- ...opts.secret
7
- ];
8
- if (!secrets.length || secrets.some((secret)=>!secret.trim())) throw new Error('At least one non-empty secret is required');
12
+ ] : opts.secret;
13
+ assertSigningSecrets(secrets);
14
+ assertUnitRateLimit(opts.rateLimitUnit);
15
+ const maxAgeDays = opts.cookie?.maxAgeDays;
9
16
  const cookie = Object.freeze({
10
17
  ...opts.cookie,
11
18
  name: opts.cookie?.name ?? XP_COOKIE,
12
- maxAgeDays: opts.cookie?.maxAgeDays ?? 365
19
+ maxAgeDays: maxAgeDays === undefined ? 365 : maxAgeDays
13
20
  });
14
- Object.freeze(secrets);
21
+ assertCookieOptions(cookie);
15
22
  return Object.freeze({
16
- secrets,
23
+ secrets: Object.freeze([
24
+ ...secrets
25
+ ]),
17
26
  apiRoute: opts.apiRoute,
18
27
  cookie,
19
28
  loadManifest: opts.loadManifest,
20
- getUnit: opts.getUnit
29
+ getUnit: opts.getUnit,
30
+ rateLimitUnit: opts.rateLimitUnit
21
31
  });
22
32
  }
@@ -1,3 +1,4 @@
1
+ export declare function assertSigningSecrets(secrets: readonly string[]): void;
1
2
  /** New signatures use the first key; verification accepts the entire rotation. */
2
3
  export declare function sign(value: string, secrets: readonly string[]): string;
3
4
  export declare function verify(value: string, mac: string, secrets: readonly string[]): boolean;
@@ -1,4 +1,9 @@
1
1
  import { createHmac, timingSafeEqual } from 'node:crypto';
2
+ export function assertSigningSecrets(secrets) {
3
+ if (!Array.isArray(secrets) || !secrets.length || Array.from(secrets).some((secret)=>typeof secret !== 'string' || secret.trim().length < 32)) {
4
+ throw new Error('Experiments requires at least one signing secret. Each signing secret must contain at least 32 characters.');
5
+ }
6
+ }
2
7
  /** New signatures use the first key; verification accepts the entire rotation. */ export function sign(value, secrets) {
3
8
  if (!secrets.length || !secrets[0]) throw new Error('A signing secret is required');
4
9
  return createHmac('sha256', secrets[0]).update(value).digest('base64url');
@@ -2,6 +2,6 @@ import type { ReadinessCode } from './types/endpoints.js';
2
2
  /** Summary details contain identifiers only. Project known shapes rather than
3
3
  * recursively copying host objects: titles, messages and placement detail are text.
4
4
  * Other checks use authored client fallbacks and need no detail (including slot
5
- * counts and layer capacity, which are not identifiers).
5
+ * counts and layer capacity, which are not identifiers). Empty slots carry only version keys.
6
6
  */
7
- export declare function sanitizeReadinessDetail(code: ReadinessCode, detail: unknown): unknown;
7
+ export declare function sanitizeReadinessDetail(code: ReadinessCode, detail: unknown, draftReadySlots?: readonly string[]): unknown;
@@ -13,8 +13,8 @@ const failure = (value)=>value === 'placements-failed' || value === 'forbidden'
13
13
  /** Summary details contain identifiers only. Project known shapes rather than
14
14
  * recursively copying host objects: titles, messages and placement detail are text.
15
15
  * Other checks use authored client fallbacks and need no detail (including slot
16
- * counts and layer capacity, which are not identifiers).
17
- */ export function sanitizeReadinessDetail(code, detail) {
16
+ * counts and layer capacity, which are not identifiers). Empty slots carry only version keys.
17
+ */ export function sanitizeReadinessDetail(code, detail, draftReadySlots = []) {
18
18
  switch(code){
19
19
  case 'goal-in-some-versions':
20
20
  {
@@ -63,6 +63,24 @@ const failure = (value)=>value === 'placements-failed' || value === 'forbidden'
63
63
  } : undefined;
64
64
  case 'no-placements':
65
65
  return failure(detail) ? detail : undefined;
66
+ case 'empty-slot':
67
+ {
68
+ const rows = (Array.isArray(detail) ? detail : [
69
+ detail
70
+ ]).filter(object);
71
+ const missing = [
72
+ ...new Set(rows.flatMap((row)=>Array.isArray(row.missing) ? row.missing : []).filter((value)=>arm(value) && value !== 'holdout'))
73
+ ];
74
+ if (!missing.length) return undefined;
75
+ const reportedReady = object(detail) && Array.isArray(detail.draftReady) ? detail.draftReady : draftReadySlots;
76
+ const draftReady = missing.filter((slot)=>reportedReady.includes(slot));
77
+ return {
78
+ missing,
79
+ ...draftReady.length ? {
80
+ draftReady
81
+ } : {}
82
+ };
83
+ }
66
84
  case 'placement-removed':
67
85
  return undefined;
68
86
  case 'page-in-use':
@@ -53,7 +53,8 @@ async function readAssignments(runtime, suppliedUser) {
53
53
  sessionUnknown: unit.sessionUnknown
54
54
  };
55
55
  let user = consent === false ? null : suppliedUser;
56
- const canResolveUser = consent !== false && (suppliedUser !== undefined || Boolean(runtime.getUser));
56
+ const canAssignUser = consent !== false && (hasContext || Boolean(visitorId));
57
+ const canResolveUser = canAssignUser && (suppliedUser !== undefined || Boolean(runtime.getUser));
57
58
  let userFailed = false;
58
59
  const resolveUser = async ()=>{
59
60
  if (user !== undefined) return user;
@@ -68,14 +69,14 @@ async function readAssignments(runtime, suppliedUser) {
68
69
  };
69
70
  const value = requestHeaders.get(XP_HEADER);
70
71
  // Consent-false proxy headers are signed without either identity.
71
- let headerUserId = visitorId ? unit.userId : undefined;
72
+ let headerUserId = canAssignUser ? unit.userId : undefined;
72
73
  const authenticate = (userId)=>verifiedHeaderRevision(value, {
73
74
  secrets: proxy.secrets,
74
75
  visitorId,
75
76
  userId
76
77
  });
77
78
  let revision = authenticate(headerUserId);
78
- if (revision === null && visitorId && value && (runtime.getUser || suppliedUser)) {
79
+ if (revision === null && value && canResolveUser) {
79
80
  const resolved = await resolveUser();
80
81
  if (resolved) {
81
82
  const resolvedId = runtime.userIdOf(resolved);
@@ -108,13 +109,14 @@ async function readAssignments(runtime, suppliedUser) {
108
109
  userFailed = true;
109
110
  }
110
111
  }
111
- const userId = visitorId ? user === undefined ? unit.userId : user ? runtime.userIdOf(user) : undefined : undefined;
112
+ const userId = canAssignUser ? user === undefined ? unit.userId : user ? runtime.userIdOf(user) : undefined : undefined;
113
+ const token = hasContext ? verifyPreviewToken(request.nextUrl.searchParams.get('xp_preview') ?? '', proxy.secrets) : null;
112
114
  const context = {
113
115
  visitorId,
114
116
  userId,
115
117
  staff: decoded?.staff === true || unit.attributes.staff === true || attributes.staff === true,
116
118
  bot: decoded?.bot === true || isBot(requestHeaders.get('user-agent')),
117
- preview: decoded?.preview ?? false,
119
+ preview: decoded?.preview === true || !visitorId && token !== null,
118
120
  sessionUnknown: needsUser && canResolveUser && !userFailed ? false : decoded?.sessionUnknown ?? unit.sessionUnknown ?? false,
119
121
  method: request.method
120
122
  };
@@ -159,10 +161,10 @@ async function readAssignments(runtime, suppliedUser) {
159
161
  }
160
162
  };
161
163
  const slugs = new Set(hasContext ? decoded.deferred : []);
162
- if (visitorId && user !== undefined && userId !== headerUserId) {
164
+ if (canAssignUser && user !== undefined && userId !== headerUserId) {
163
165
  for (const e of manifest.experiments)if (e.unitType === 'user') slugs.add(e.slug);
164
166
  }
165
- if (visitorId && slugs.size && canResolveUser && !userFailed) {
167
+ if (slugs.size && canResolveUser && !userFailed) {
166
168
  try {
167
169
  const resolved = assign(manifest, {
168
170
  visitorId,
@@ -179,7 +181,7 @@ async function readAssignments(runtime, suppliedUser) {
179
181
  userFailed = true;
180
182
  }
181
183
  }
182
- } else if (!visitorId || !hasContext) result = controlAssignments(manifest, context);
184
+ } else if (!visitorId && !userId || !hasContext) result = controlAssignments(manifest, context);
183
185
  else {
184
186
  try {
185
187
  result = assign(manifest, {
@@ -202,7 +204,6 @@ async function readAssignments(runtime, suppliedUser) {
202
204
  }
203
205
  fillFlagPoints(result, manifest);
204
206
  fillHostDefaults(result);
205
- const token = hasContext ? verifyPreviewToken(request.nextUrl.searchParams.get('xp_preview') ?? '', proxy.secrets) : null;
206
207
  if (token && visitorId && payload) {
207
208
  const live = manifest.experiments.find((e)=>e.id === token.e && e.phase === token.p && e.arms.some((a)=>a.key === token.a));
208
209
  if (live) {
@@ -219,7 +220,7 @@ async function readAssignments(runtime, suppliedUser) {
219
220
  fillFlagPoints(result, manifest);
220
221
  } else await previewDraft(payload, await resolveUser(), token, result, requestHeaders);
221
222
  }
222
- if (suppressExposure(result) || !hasContext || !visitorId || payloadFailed || userFailed || mustResolveStaff && !runtime.getUser && suppliedUser === undefined) {
223
+ if (suppressExposure(result) || !hasContext || payloadFailed || userFailed || mustResolveStaff && !runtime.getUser && suppliedUser === undefined) {
223
224
  for (const assignment of Object.values(result.bySlug))assignment.exposable = false;
224
225
  for (const point of Object.values(result.flagPoints))point.exposable = false;
225
226
  }
@@ -2,6 +2,6 @@ import type { CollectionAfterChangeHook, CollectionBeforeChangeHook } from 'payl
2
2
  /** Paired raw beforeChange capture: previousDoc may be an autosaved draft. */
3
3
  export declare function capturePublishedContent({ req, collection, originalDoc, operation }: Parameters<CollectionBeforeChangeHook>[0]): Promise<void>;
4
4
  type ContentChangeArgs = Pick<Parameters<CollectionAfterChangeHook>[0], 'doc' | 'previousDoc' | 'req' | 'collection'>;
5
- /** Publish-only host helper. Audit failures are logged, never thrown into saves. */
5
+ /** Publish-only host helper. Audit failures are logged after savepoint recovery. */
6
6
  export declare function recordContentChange(args: ContentChangeArgs): Promise<void>;
7
7
  export {};
@@ -4,6 +4,7 @@ import { puckVisibility } from '../puck/visibility.js';
4
4
  import { EXPERIMENT_BLOCK_SLUG, hostBlocks } from '../blocks/model.js';
5
5
  import { safeError } from '../log.js';
6
6
  import { isDeepStrictEqual } from 'node:util';
7
+ import { XpTransactionIsolationError } from '../db/adapter.js';
7
8
  import { appendContentChange, contentChangeSavepoint, previousPublishedContent, runningContentExperiment, storedContent } from '../db/appends.js';
8
9
  import { txExecutor } from '../db/executor.js';
9
10
  import { pageContentBindings } from '../db/pageBindings.js';
@@ -81,11 +82,17 @@ const baselineKey = (collection, id)=>`${collection}:${id}`;
81
82
  doc: audit.result
82
83
  };
83
84
  }
84
- /** Publish-only host helper. Audit failures are logged, never thrown into saves. */ export async function recordContentChange(args) {
85
+ /** Publish-only host helper. Audit failures are logged after savepoint recovery. */ export async function recordContentChange(args) {
85
86
  try {
86
87
  await auditContentChange(args);
87
88
  } catch (error) {
88
- console.error('[payload-experiments] contentChanges failed; the document was saved without it', safeError(error));
89
+ try {
90
+ // The isolation check already logged the reason once for this transaction.
91
+ if (error instanceof XpTransactionIsolationError) return;
92
+ } catch {}
93
+ try {
94
+ console.error('[payload-experiments] contentChanges failed; the document was saved without it', safeError(error));
95
+ } catch {}
89
96
  }
90
97
  }
91
98
  async function auditContentChange({ doc, previousDoc, req, collection }) {
@@ -203,6 +210,8 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
203
210
  bump: false,
204
211
  audit: true
205
212
  }, async ({ exec })=>{
213
+ // Keep the recheck and append on the executor. A failed nested Local API
214
+ // call would kill the host transaction before the savepoint could recover.
206
215
  const experiment = await runningContentExperiment(exec, {
207
216
  field: 'id',
208
217
  value: experimentId
@@ -1,5 +1,5 @@
1
1
  import { BLOCK_SLOTS, EXPERIMENT_BLOCK_SLUG, hostBlocks, slotBlocks } from '../blocks/model.js';
2
- import { manifestOf, suppressExposure } from './context.js';
2
+ import { suppressExposure } from './context.js';
3
3
  export function resolveExperimentBlocks(blocks, assignments, { blockSlug = EXPERIMENT_BLOCK_SLUG } = {}) {
4
4
  const result = {
5
5
  blocks: [],
@@ -18,10 +18,8 @@ export function resolveExperimentBlocks(blocks, assignments, { blockSlug = EXPER
18
18
  }
19
19
  const slug = typeof block.experiment === 'string' ? block.experiment : '';
20
20
  const assignment = Object.hasOwn(assignments.bySlug, slug) ? assignments.bySlug[slug] : undefined;
21
- const experiment = manifestOf(assignments)?.experiments.find((e)=>e.slug === slug);
22
- const arm = experiment?.arms.find((a)=>a.key === assignment?.arm);
23
21
  const archived = Object.hasOwn(assignments.archivedWinners, slug) ? assignments.archivedWinners[slug] : undefined;
24
- const slot = assignment ? assignment.arm === 'holdout' ? 'control' : arm?.slot ?? assignment.arm : archived ?? 'control';
22
+ const slot = assignment ? assignment.arm === 'holdout' ? 'control' : assignment.arm : archived ?? 'control';
25
23
  const selected = BLOCK_SLOTS.includes(slot) ? slotBlocks(block, slot) : [];
26
24
  const content = selected.length ? selected : slotBlocks(block, 'control');
27
25
  const group = {
@@ -1,6 +1,6 @@
1
1
  import { puckExperimentSlug } from '../puck/experimentSlug.js';
2
2
  import { puckVisibility } from '../puck/visibility.js';
3
- import { manifestOf, suppressExposure } from './context.js';
3
+ import { suppressExposure } from './context.js';
4
4
  export function resolveExperimentData(puckData, assignments) {
5
5
  const visibility = puckVisibility(puckData);
6
6
  const rendered = new Map();
@@ -10,7 +10,6 @@ export function resolveExperimentData(puckData, assignments) {
10
10
  'variantB',
11
11
  'variantC'
12
12
  ];
13
- const manifest = manifestOf(assignments);
14
13
  function walk(value) {
15
14
  if (Array.isArray(value)) return value.map(walk).filter((item)=>item !== undefined);
16
15
  if (!value || typeof value !== 'object') return value;
@@ -30,10 +29,8 @@ export function resolveExperimentData(puckData, assignments) {
30
29
  delete clean.xpExpose;
31
30
  const slug = puckExperimentSlug(props.experiment);
32
31
  const assignment = slug && Object.hasOwn(assignments.bySlug, slug) ? assignments.bySlug[slug] : undefined;
33
- const experiment = manifest?.experiments.find((e)=>e.slug === slug);
34
- const arm = experiment?.arms.find((a)=>a.key === assignment?.arm);
35
32
  const archived = slug && Object.hasOwn(assignments.archivedWinners, slug) ? assignments.archivedWinners[slug] : undefined;
36
- const selected = assignment ? assignment.arm === 'holdout' ? 'control' : arm?.slot ?? assignment.arm : archived ?? 'control';
33
+ const selected = assignment ? assignment.arm === 'holdout' ? 'control' : assignment.arm : archived ?? 'control';
37
34
  const slot = slots.includes(selected) ? selected : 'control';
38
35
  clean.xpSlot = slot;
39
36
  if (assignment) {