@delmaredigital/payload-experiments 0.3.0-rc.4 → 0.4.0-rc.10

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 (658) hide show
  1. package/README.md +293 -688
  2. package/dist/admin/LayerUsage.js +1 -1
  3. package/dist/admin/MetricSourceSelect.js +4 -4
  4. package/dist/admin/PlacementStatus.d.ts +3 -0
  5. package/dist/admin/PlacementStatus.js +54 -0
  6. package/dist/admin/TestsDashboardCards.d.ts +1 -0
  7. package/dist/admin/TestsDashboardCards.js +5 -9
  8. package/dist/admin/TestsNavLink.d.ts +1 -0
  9. package/dist/admin/TestsNavLink.js +5 -11
  10. package/dist/admin/blocks/BlockPanel.d.ts +5 -0
  11. package/dist/admin/blocks/BlockPanel.js +245 -0
  12. package/dist/admin/blocks/TestBlockField.d.ts +5 -0
  13. package/dist/admin/blocks/TestBlockField.js +163 -0
  14. package/dist/admin/blocks/formApi.d.ts +46 -0
  15. package/dist/admin/blocks/formApi.js +159 -0
  16. package/dist/admin/blocks/inject.d.ts +7 -0
  17. package/dist/admin/blocks/inject.js +42 -0
  18. package/dist/admin/blocks/model.d.ts +18 -0
  19. package/dist/admin/blocks/model.js +49 -0
  20. package/dist/admin/blocks/statusCache.d.ts +9 -0
  21. package/dist/admin/blocks/statusCache.js +92 -0
  22. package/dist/admin/blocks/useBlockForm.d.ts +17 -0
  23. package/dist/admin/blocks/useBlockForm.js +46 -0
  24. package/dist/admin/components/RootViewMessage.js +1 -1
  25. package/dist/admin/copy/blocks.d.ts +47 -0
  26. package/dist/admin/copy/blocks.js +72 -0
  27. package/dist/admin/copy/goals.d.ts +8 -1
  28. package/dist/admin/copy/goals.js +14 -4
  29. package/dist/admin/copy/newTest.d.ts +13 -4
  30. package/dist/admin/copy/newTest.js +16 -4
  31. package/dist/admin/goals/XpGoalField.d.ts +4 -0
  32. package/dist/admin/goals/XpGoalField.js +194 -0
  33. package/dist/admin/goals/xpGoalField.css +47 -0
  34. package/dist/admin/pageCollections.d.ts +11 -0
  35. package/dist/admin/pageCollections.js +23 -0
  36. package/dist/admin/paths.d.ts +9 -0
  37. package/dist/admin/paths.js +9 -0
  38. package/dist/admin/placementStatus.model.d.ts +2 -0
  39. package/dist/admin/placementStatus.model.js +19 -0
  40. package/dist/admin/status.model.js +1 -1
  41. package/dist/admin/surface/ResultsRoute.d.ts +2 -1
  42. package/dist/admin/surface/ResultsRoute.js +20 -24
  43. package/dist/admin/surface/SurfaceShell.js +5 -2
  44. package/dist/admin/surface/TestRowMenu.d.ts +6 -0
  45. package/dist/admin/surface/TestRowMenu.js +156 -0
  46. package/dist/admin/surface/TestsHome.d.ts +5 -3
  47. package/dist/admin/surface/TestsHome.js +298 -59
  48. package/dist/admin/surface/TestsSurface.js +13 -8
  49. package/dist/admin/surface/goals/GoalForm.d.ts +1 -1
  50. package/dist/admin/surface/goals/GoalForm.js +159 -85
  51. package/dist/admin/surface/goals/GoalsList.d.ts +1 -1
  52. package/dist/admin/surface/goals/GoalsList.js +7 -6
  53. package/dist/admin/surface/goals/data.js +6 -3
  54. package/dist/admin/surface/goals/goals.css +7 -0
  55. package/dist/admin/surface/goals/goals.model.d.ts +12 -3
  56. package/dist/admin/surface/goals/goals.model.js +43 -2
  57. package/dist/admin/surface/home.model.d.ts +9 -8
  58. package/dist/admin/surface/home.model.js +28 -23
  59. package/dist/admin/surface/newTest/NewTest.d.ts +4 -4
  60. package/dist/admin/surface/newTest/NewTest.js +146 -101
  61. package/dist/admin/surface/newTest/PageWizard.d.ts +8 -0
  62. package/dist/admin/surface/newTest/PageWizard.js +244 -0
  63. package/dist/admin/surface/newTest/newTest.css +28 -9
  64. package/dist/admin/surface/results/ResultsHeader.d.ts +2 -2
  65. package/dist/admin/surface/results/ResultsHeader.js +58 -57
  66. package/dist/admin/surface/surface.css +10 -0
  67. package/dist/admin/surface/test/TestPage.d.ts +1 -2
  68. package/dist/admin/surface/test/TestPage.js +42 -161
  69. package/dist/admin/theme.css +2 -0
  70. package/dist/admin/views/CollectionListRedirect.d.ts +1 -0
  71. package/dist/admin/views/CollectionListRedirect.js +1 -1
  72. package/dist/admin/views/ExperimentsRootView.js +28 -133
  73. package/dist/admin/views/GoalEditRedirect.d.ts +4 -0
  74. package/dist/admin/views/GoalEditRedirect.js +14 -0
  75. package/dist/admin/views/GoalsCollectionListView.d.ts +2 -0
  76. package/dist/admin/views/GoalsCollectionListView.js +4 -0
  77. package/dist/admin/views/TestsCollectionListView.d.ts +2 -0
  78. package/dist/admin/views/TestsCollectionListView.js +4 -0
  79. package/dist/admin/views/TestsNavLinkServer.d.ts +1 -0
  80. package/dist/admin/views/TestsNavLinkServer.js +2 -2
  81. package/dist/admin/views/TestsSurfaceClient.d.ts +3 -0
  82. package/dist/admin/views/TestsSurfaceClient.js +11 -0
  83. package/dist/admin/views/buildSurfaceProps.d.ts +8 -0
  84. package/dist/admin/views/buildSurfaceProps.js +102 -0
  85. package/dist/admin/views/renderCollectionList.d.ts +2 -0
  86. package/dist/admin/views/renderCollectionList.js +34 -0
  87. package/dist/admin/views/renderTestsSurface.d.ts +3 -0
  88. package/dist/admin/views/renderTestsSurface.js +34 -0
  89. package/dist/blocks/bindings.d.ts +3 -0
  90. package/dist/blocks/bindings.js +28 -0
  91. package/dist/blocks/createExperimentBlock.d.ts +6 -0
  92. package/dist/blocks/createExperimentBlock.js +77 -0
  93. package/dist/blocks/formState.d.ts +31 -0
  94. package/dist/blocks/formState.js +146 -0
  95. package/dist/blocks/model.d.ts +41 -0
  96. package/dist/blocks/model.js +34 -0
  97. package/dist/blocks/placementLanguages.d.ts +7 -0
  98. package/dist/blocks/placementLanguages.js +27 -0
  99. package/dist/blocks/placementLocale.d.ts +37 -0
  100. package/dist/blocks/placementLocale.js +270 -0
  101. package/dist/client/ExperimentGroup.d.ts +6 -0
  102. package/dist/client/ExperimentGroup.js +9 -0
  103. package/dist/client/ExperimentsProvider.js +20 -4
  104. package/dist/client/clickGoals.d.ts +4 -0
  105. package/dist/client/clickGoals.js +43 -0
  106. package/dist/collections/experiments/config.js +29 -10
  107. package/dist/collections/experiments/deleteGuard.d.ts +2 -1
  108. package/dist/collections/experiments/deleteGuard.js +14 -3
  109. package/dist/collections/experiments/editability.js +4 -2
  110. package/dist/collections/experiments/lockHook.js +21 -2
  111. package/dist/collections/experiments/pickSlug.d.ts +2 -0
  112. package/dist/collections/experiments/pickSlug.js +10 -0
  113. package/dist/collections/labels.d.ts +3 -0
  114. package/dist/collections/labels.js +20 -0
  115. package/dist/collections/metrics.js +28 -6
  116. package/dist/collections/metricsGuards.js +2 -0
  117. package/dist/collections/phases.js +1 -0
  118. package/dist/collections/serialize.js +12 -4
  119. package/dist/constants.d.ts +1 -0
  120. package/dist/constants.js +1 -0
  121. package/dist/db/adapter.d.ts +9 -1
  122. package/dist/db/adapter.js +77 -1
  123. package/dist/db/appends.d.ts +13 -0
  124. package/dist/db/appends.js +49 -0
  125. package/dist/db/bulkPlacementRemoval.d.ts +30 -0
  126. package/dist/db/bulkPlacementRemoval.js +111 -0
  127. package/dist/db/clickGoals.d.ts +9 -0
  128. package/dist/db/clickGoals.js +22 -0
  129. package/dist/db/delete.d.ts +2 -1
  130. package/dist/db/delete.js +3 -4
  131. package/dist/db/events.d.ts +9 -0
  132. package/dist/db/events.js +42 -8
  133. package/dist/db/executor.d.ts +7 -1
  134. package/dist/db/executor.js +7 -3
  135. package/dist/db/locks.d.ts +8 -0
  136. package/dist/db/locks.js +27 -4
  137. package/dist/db/names.d.ts +4 -0
  138. package/dist/db/names.js +4 -0
  139. package/dist/db/pageBindings.d.ts +4 -0
  140. package/dist/db/pageBindings.js +17 -0
  141. package/dist/db/pageBusy.d.ts +2 -0
  142. package/dist/db/pageBusy.js +10 -0
  143. package/dist/db/pageContent.d.ts +10 -0
  144. package/dist/db/pageContent.js +79 -0
  145. package/dist/db/pageCopies.d.ts +5 -0
  146. package/dist/db/pageCopies.js +31 -0
  147. package/dist/db/placements.d.ts +35 -0
  148. package/dist/db/placements.js +62 -0
  149. package/dist/db/results.d.ts +5 -1
  150. package/dist/db/results.js +21 -5
  151. package/dist/db/slugs.d.ts +8 -0
  152. package/dist/db/slugs.js +40 -0
  153. package/dist/db/snapshots.d.ts +7 -0
  154. package/dist/db/snapshots.js +8 -5
  155. package/dist/endpoints/clickKeys.d.ts +5 -0
  156. package/dist/endpoints/clickKeys.js +17 -0
  157. package/dist/endpoints/contentLocale.d.ts +6 -0
  158. package/dist/endpoints/contentLocale.js +15 -0
  159. package/dist/endpoints/deleteImpact.d.ts +6 -0
  160. package/dist/endpoints/deleteImpact.js +207 -0
  161. package/dist/endpoints/duplicateOriginal.d.ts +38 -0
  162. package/dist/endpoints/duplicateOriginal.js +407 -0
  163. package/dist/endpoints/editorSurface.d.ts +3 -0
  164. package/dist/endpoints/editorSurface.js +31 -0
  165. package/dist/endpoints/events.js +106 -39
  166. package/dist/endpoints/index.js +85 -9
  167. package/dist/endpoints/pages.d.ts +5 -0
  168. package/dist/endpoints/pages.js +303 -0
  169. package/dist/endpoints/placementStatus.d.ts +6 -0
  170. package/dist/endpoints/placementStatus.js +246 -0
  171. package/dist/endpoints/preflight.d.ts +1 -1
  172. package/dist/endpoints/preflight.js +17 -2
  173. package/dist/endpoints/readBody.d.ts +2 -0
  174. package/dist/endpoints/readBody.js +24 -0
  175. package/dist/endpoints/results.d.ts +1 -1
  176. package/dist/endpoints/results.js +10 -2
  177. package/dist/endpoints/routeId.d.ts +2 -2
  178. package/dist/endpoints/routeId.js +11 -5
  179. package/dist/endpoints/summary.js +46 -5
  180. package/dist/endpoints/testVersion.d.ts +2 -0
  181. package/dist/endpoints/testVersion.js +38 -0
  182. package/dist/endpoints/transitions.js +41 -29
  183. package/dist/endpoints/wrapBlock.d.ts +6 -0
  184. package/dist/endpoints/wrapBlock.js +76 -0
  185. package/dist/errors.d.ts +7 -2
  186. package/dist/errors.js +11 -3
  187. package/dist/events/request.d.ts +6 -2
  188. package/dist/events/request.js +35 -8
  189. package/dist/events/rows.d.ts +1 -1
  190. package/dist/events/rows.js +25 -7
  191. package/dist/events/writable.d.ts +9 -0
  192. package/dist/events/writable.js +13 -0
  193. package/dist/exports/adminClient.d.ts +6 -1
  194. package/dist/exports/adminClient.js +6 -1
  195. package/dist/exports/adminRsc.d.ts +3 -0
  196. package/dist/exports/adminRsc.js +3 -0
  197. package/dist/exports/blocks.d.ts +2 -0
  198. package/dist/exports/blocks.js +1 -0
  199. package/dist/exports/client.d.ts +1 -0
  200. package/dist/exports/client.js +1 -0
  201. package/dist/exports/index.d.ts +6 -1
  202. package/dist/exports/index.js +3 -0
  203. package/dist/exports/puck.d.ts +3 -1
  204. package/dist/exports/puck.js +2 -0
  205. package/dist/exports/puckEditor.d.ts +3 -0
  206. package/dist/exports/puckEditor.js +2 -0
  207. package/dist/exports/rsc.d.ts +4 -0
  208. package/dist/exports/rsc.js +3 -0
  209. package/dist/fields/xpGoal.d.ts +3 -0
  210. package/dist/fields/xpGoal.js +16 -0
  211. package/dist/globals/state.js +10 -0
  212. package/dist/goals/cache.d.ts +3 -0
  213. package/dist/goals/cache.js +35 -0
  214. package/dist/goals/fairness.d.ts +40 -0
  215. package/dist/goals/fairness.js +209 -0
  216. package/dist/goals/key.d.ts +4 -0
  217. package/dist/goals/key.js +3 -0
  218. package/dist/goals/picker/clickGoalPicker.model.d.ts +36 -0
  219. package/dist/goals/picker/clickGoalPicker.model.js +63 -0
  220. package/dist/goals/picker/copy.d.ts +20 -0
  221. package/dist/goals/picker/copy.js +24 -0
  222. package/dist/goals/picker/useClickGoalPicker.d.ts +30 -0
  223. package/dist/goals/picker/useClickGoalPicker.js +222 -0
  224. package/dist/goals/validate.d.ts +3 -0
  225. package/dist/goals/validate.js +15 -0
  226. package/dist/hooks/blockRemovalRule.d.ts +30 -0
  227. package/dist/hooks/blockRemovalRule.js +165 -0
  228. package/dist/hooks/hostHook.js +6 -2
  229. package/dist/hooks/pageGuard.d.ts +30 -1
  230. package/dist/hooks/pageGuard.js +337 -107
  231. package/dist/hooks/puckGoals.d.ts +5 -0
  232. package/dist/hooks/puckGoals.js +62 -0
  233. package/dist/hooks/puckNestedTests.d.ts +8 -0
  234. package/dist/hooks/puckNestedTests.js +36 -0
  235. package/dist/hooks/trackPageCopies.d.ts +11 -0
  236. package/dist/hooks/trackPageCopies.js +7 -0
  237. package/dist/lib/fetchAllDocs.d.ts +1 -1
  238. package/dist/lib/placementPages.d.ts +10 -0
  239. package/dist/{admin/previewLinks.model.js → lib/placementPages.js} +10 -5
  240. package/dist/manifest/compile.d.ts +2 -1
  241. package/dist/manifest/compile.js +13 -6
  242. package/dist/onInit.js +65 -0
  243. package/dist/options.d.ts +4 -0
  244. package/dist/options.js +62 -1
  245. package/dist/plugin.js +56 -44
  246. package/dist/proxy/pageNavigation.d.ts +4 -0
  247. package/dist/proxy/pageNavigation.js +28 -0
  248. package/dist/proxy/resolve.js +52 -25
  249. package/dist/puck/ExperimentPicker.d.ts +2 -1
  250. package/dist/puck/ExperimentPicker.js +62 -40
  251. package/dist/puck/ExperimentSlot.js +3 -1
  252. package/dist/puck/copy.d.ts +6 -1
  253. package/dist/puck/copy.js +6 -1
  254. package/dist/puck/editor/ConfigureTestDrawer.d.ts +25 -0
  255. package/dist/puck/editor/ConfigureTestDrawer.js +150 -0
  256. package/dist/puck/editor/CreateExperimentDrawer.d.ts +12 -2
  257. package/dist/puck/editor/CreateExperimentDrawer.js +89 -21
  258. package/dist/puck/editor/EditorControls.d.ts +14 -0
  259. package/dist/puck/editor/EditorControls.js +99 -0
  260. package/dist/puck/editor/ExperimentSlotEditor.js +951 -179
  261. package/dist/puck/editor/LeftoverVersions.d.ts +15 -0
  262. package/dist/puck/editor/LeftoverVersions.js +79 -0
  263. package/dist/puck/editor/PlacementNotice.d.ts +8 -0
  264. package/dist/puck/editor/PlacementNotice.js +22 -0
  265. package/dist/puck/editor/QuickTestActions.d.ts +6 -0
  266. package/dist/puck/editor/QuickTestActions.js +57 -0
  267. package/dist/puck/editor/ResultsReadout.d.ts +2 -1
  268. package/dist/puck/editor/ResultsReadout.js +10 -6
  269. package/dist/puck/editor/VersionBuilder.d.ts +66 -12
  270. package/dist/puck/editor/VersionBuilder.js +554 -231
  271. package/dist/puck/editor/armWrites.d.ts +11 -2
  272. package/dist/puck/editor/armWrites.js +43 -4
  273. package/dist/puck/editor/armsCache.d.ts +3 -1
  274. package/dist/puck/editor/armsCache.js +20 -4
  275. package/dist/puck/editor/blockClipboard.d.ts +16 -0
  276. package/dist/puck/editor/blockClipboard.js +20 -0
  277. package/dist/puck/editor/cloneSlot.d.ts +2 -0
  278. package/dist/puck/editor/cloneSlot.js +7 -0
  279. package/dist/puck/editor/copy.d.ts +64 -19
  280. package/dist/puck/editor/copy.js +72 -20
  281. package/dist/puck/editor/createTest.d.ts +3 -0
  282. package/dist/puck/editor/createTest.js +33 -0
  283. package/dist/puck/editor/editor.chrome.css +192 -19
  284. package/dist/puck/editor/editor.css +329 -24
  285. package/dist/puck/editor/editor.model.d.ts +21 -3
  286. package/dist/puck/editor/editor.model.js +67 -7
  287. package/dist/puck/editor/editorSurface.d.ts +10 -0
  288. package/dist/puck/editor/editorSurface.js +65 -0
  289. package/dist/puck/editor/experimentOutlinePlugin.js +96 -28
  290. package/dist/puck/editor/integration.d.ts +10 -0
  291. package/dist/puck/editor/integration.js +30 -0
  292. package/dist/puck/editor/localPlacements.d.ts +5 -0
  293. package/dist/puck/editor/localPlacements.js +43 -0
  294. package/dist/puck/editor/outlineVersion.d.ts +5 -0
  295. package/dist/puck/editor/outlineVersion.js +36 -0
  296. package/dist/puck/editor/placementsCache.d.ts +60 -0
  297. package/dist/puck/editor/placementsCache.js +263 -0
  298. package/dist/puck/editor/sidebar.d.ts +8 -0
  299. package/dist/puck/editor/sidebar.js +74 -0
  300. package/dist/puck/editor/usePageSaveReadiness.d.ts +6 -0
  301. package/dist/puck/editor/usePageSaveReadiness.js +31 -0
  302. package/dist/puck/editor/usePlacementNotice.d.ts +3 -0
  303. package/dist/puck/editor/usePlacementNotice.js +15 -0
  304. package/dist/puck/editor/xpGoalPuckEditorField.d.ts +7 -0
  305. package/dist/puck/editor/xpGoalPuckEditorField.js +153 -0
  306. package/dist/puck/experimentSlotField.d.ts +3 -0
  307. package/dist/puck/experimentSlotField.js +15 -4
  308. package/dist/puck/experimentSlug.d.ts +2 -0
  309. package/dist/puck/experimentSlug.js +3 -0
  310. package/dist/puck/integration.d.ts +6 -0
  311. package/dist/puck/integration.js +21 -0
  312. package/dist/puck/nestedTestCopy.d.ts +8 -0
  313. package/dist/puck/nestedTestCopy.js +22 -0
  314. package/dist/puck/nestedTests.d.ts +17 -0
  315. package/dist/puck/nestedTests.js +30 -0
  316. package/dist/puck/slotConfig.d.ts +1 -1
  317. package/dist/puck/slotConfig.js +17 -4
  318. package/dist/puck/visibility.d.ts +20 -0
  319. package/dist/puck/visibility.js +81 -0
  320. package/dist/puck/xpGoalField.d.ts +3 -0
  321. package/dist/puck/xpGoalField.js +6 -0
  322. package/dist/results/aggregate.d.ts +6 -3
  323. package/dist/results/aggregate.js +9 -9
  324. package/dist/results/health.d.ts +12 -0
  325. package/dist/results/health.js +55 -0
  326. package/dist/results/identityCredit.d.ts +1 -0
  327. package/dist/results/identityCredit.js +4 -1
  328. package/dist/results/snapshot.js +15 -2
  329. package/dist/results/verdict.js +2 -1
  330. package/dist/runtime/cookie.d.ts +10 -2
  331. package/dist/runtime/cookie.js +38 -6
  332. package/dist/runtime/cookieOptions.d.ts +6 -0
  333. package/dist/runtime/cookieOptions.js +14 -0
  334. package/dist/runtime/proxyRuntime.d.ts +1 -0
  335. package/dist/runtime/proxyRuntime.js +18 -8
  336. package/dist/runtime/signing.d.ts +1 -0
  337. package/dist/runtime/signing.js +5 -0
  338. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  339. package/dist/sanitizeReadinessDetail.js +63 -2
  340. package/dist/server/getAssignments.js +11 -10
  341. package/dist/server/pageKindSeoContract.d.ts +27 -0
  342. package/dist/server/pageKindSeoContract.js +80 -0
  343. package/dist/server/recordContentChange.d.ts +1 -1
  344. package/dist/server/recordContentChange.js +88 -12
  345. package/dist/server/resolveExperimentBlocks.d.ts +5 -0
  346. package/dist/server/resolveExperimentBlocks.js +52 -0
  347. package/dist/server/resolveExperimentData.js +8 -8
  348. package/dist/server/runResults.js +104 -25
  349. package/dist/server/startExperiment.d.ts +20 -0
  350. package/dist/server/startExperiment.js +70 -0
  351. package/dist/server/toClientAssignments.js +2 -1
  352. package/dist/server/trackConversion.js +10 -13
  353. package/dist/{admin → testSurface}/PreviewLinks.d.ts +2 -1
  354. package/dist/{admin → testSurface}/PreviewLinks.js +8 -4
  355. package/dist/testSurface/actions/DecideDialog.d.ts +16 -0
  356. package/dist/{admin → testSurface}/actions/DecideDialog.js +79 -56
  357. package/dist/testSurface/actions/LifecycleAction.d.ts +16 -0
  358. package/dist/testSurface/actions/LifecycleAction.js +105 -0
  359. package/dist/{admin → testSurface}/actions/MakeContentResult.d.ts +4 -3
  360. package/dist/{admin → testSurface}/actions/MakeContentResult.js +10 -2
  361. package/dist/{admin → testSurface}/actions/actions.model.d.ts +13 -5
  362. package/dist/testSurface/actions/actions.model.js +122 -0
  363. package/dist/testSurface/api.d.ts +60 -0
  364. package/dist/testSurface/api.js +167 -0
  365. package/dist/testSurface/contentLocaleURL.d.ts +2 -0
  366. package/dist/testSurface/contentLocaleURL.js +3 -0
  367. package/dist/{admin → testSurface}/copy/actions.d.ts +30 -8
  368. package/dist/{admin → testSurface}/copy/actions.js +40 -11
  369. package/dist/{admin → testSurface}/copy/common.d.ts +13 -4
  370. package/dist/{admin → testSurface}/copy/common.js +18 -8
  371. package/dist/testSurface/copy/languages.d.ts +12 -0
  372. package/dist/testSurface/copy/languages.js +8 -0
  373. package/dist/{admin → testSurface}/copy/metrics.d.ts +1 -0
  374. package/dist/{admin → testSurface}/copy/metrics.js +1 -0
  375. package/dist/testSurface/copy/pages.d.ts +84 -0
  376. package/dist/testSurface/copy/pages.js +90 -0
  377. package/dist/{admin → testSurface}/copy/readiness.d.ts +59 -6
  378. package/dist/testSurface/copy/readiness.js +136 -0
  379. package/dist/{admin → testSurface}/copy/results.d.ts +7 -3
  380. package/dist/{admin → testSurface}/copy/results.js +7 -3
  381. package/dist/{admin → testSurface}/copy/review.d.ts +1 -1
  382. package/dist/{admin → testSurface}/copy/review.js +1 -1
  383. package/dist/{admin → testSurface}/copy/surface.d.ts +11 -2
  384. package/dist/{admin → testSurface}/copy/surface.js +13 -10
  385. package/dist/{admin → testSurface}/copy/testPage.d.ts +56 -7
  386. package/dist/testSurface/copy/testPage.js +165 -0
  387. package/dist/testSurface/format/adminURL.d.ts +7 -0
  388. package/dist/testSurface/format/adminURL.js +9 -0
  389. package/dist/{admin → testSurface}/metricSource.model.d.ts +2 -0
  390. package/dist/{admin → testSurface}/metricSource.model.js +4 -0
  391. package/dist/testSurface/placementLabel.d.ts +8 -0
  392. package/dist/testSurface/placementLabel.js +24 -0
  393. package/dist/testSurface/placements/placementLabels.d.ts +13 -0
  394. package/dist/testSurface/placements/placementLabels.js +22 -0
  395. package/dist/testSurface/placements/placementLabels.model.d.ts +13 -0
  396. package/dist/testSurface/placements/placementLabels.model.js +12 -0
  397. package/dist/testSurface/placements/usePlacementLabels.d.ts +12 -0
  398. package/dist/testSurface/placements/usePlacementLabels.js +102 -0
  399. package/dist/{admin → testSurface}/previewLinks.model.d.ts +1 -6
  400. package/dist/testSurface/previewLinks.model.js +4 -0
  401. package/dist/testSurface/readPreflight.d.ts +13 -0
  402. package/dist/testSurface/readPreflight.js +44 -0
  403. package/dist/testSurface/readinessRead.d.ts +53 -0
  404. package/dist/testSurface/readinessRead.js +50 -0
  405. package/dist/{admin → testSurface}/results/DataQualityPanel.js +4 -1
  406. package/dist/{admin → testSurface}/results/VerdictHero.d.ts +2 -1
  407. package/dist/{admin → testSurface}/results/VerdictHero.js +5 -1
  408. package/dist/testSurface/results/results.css +64 -0
  409. package/dist/{admin → testSurface}/results/results.model.d.ts +3 -0
  410. package/dist/{admin → testSurface}/results/results.model.js +14 -6
  411. package/dist/{admin → testSurface}/surface/contracts.d.ts +23 -8
  412. package/dist/testSurface/surface/editorPlacement.d.ts +26 -0
  413. package/dist/testSurface/surface/editorPlacement.js +78 -0
  414. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +9 -0
  415. package/dist/{admin → testSurface}/surface/pageBlock/parts.js +39 -11
  416. package/dist/testSurface/surface/pagePicker/CopyRoute.d.ts +13 -0
  417. package/dist/testSurface/surface/pagePicker/CopyRoute.js +273 -0
  418. package/dist/testSurface/surface/pagePicker/PageCombobox.d.ts +21 -0
  419. package/dist/testSurface/surface/pagePicker/PageCombobox.js +503 -0
  420. package/dist/testSurface/surface/pagePicker/pagePicker.css +73 -0
  421. package/dist/testSurface/surface/pagePicker/pagePicker.model.d.ts +29 -0
  422. package/dist/testSurface/surface/pagePicker/pagePicker.model.js +40 -0
  423. package/dist/{admin → testSurface}/surface/readiness/ActionDialogs.d.ts +8 -4
  424. package/dist/testSurface/surface/readiness/ActionDialogs.js +351 -0
  425. package/dist/{admin → testSurface}/surface/readiness/Banner.d.ts +2 -3
  426. package/dist/testSurface/surface/readiness/Banner.js +187 -0
  427. package/dist/testSurface/surface/readiness/BlockerList.d.ts +11 -0
  428. package/dist/testSurface/surface/readiness/BlockerList.js +31 -0
  429. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +10 -0
  430. package/dist/testSurface/surface/readiness/SaveStatus.js +66 -0
  431. package/dist/{admin → testSurface}/surface/readiness/parts.js +0 -2
  432. package/dist/testSurface/surface/readiness/readiness.model.d.ts +57 -0
  433. package/dist/testSurface/surface/readiness/readiness.model.js +377 -0
  434. package/dist/testSurface/surface/readiness/useTransition.d.ts +16 -0
  435. package/dist/testSurface/surface/readiness/useTransition.js +141 -0
  436. package/dist/testSurface/surface/results/ReleasePages.d.ts +19 -0
  437. package/dist/{admin → testSurface}/surface/results/ReleasePages.js +43 -47
  438. package/dist/{admin → testSurface}/surface/results/ResultsBody.d.ts +7 -3
  439. package/dist/{admin → testSurface}/surface/results/ResultsBody.js +129 -46
  440. package/dist/{admin → testSurface}/surface/results/useResults.d.ts +36 -9
  441. package/dist/{admin → testSurface}/surface/results/useResults.js +3 -2
  442. package/dist/{admin → testSurface}/surface/setting/parts.js +58 -18
  443. package/dist/testSurface/surface/setting/setting.css +17 -0
  444. package/dist/testSurface/surface/test/AdvancedSection.js +169 -0
  445. package/dist/testSurface/surface/test/DeleteTest.d.ts +23 -0
  446. package/dist/testSurface/surface/test/DeleteTest.js +270 -0
  447. package/dist/testSurface/surface/test/GoalSection.d.ts +4 -0
  448. package/dist/testSurface/surface/test/GoalSection.js +341 -0
  449. package/dist/testSurface/surface/test/LengthSection.d.ts +2 -0
  450. package/dist/{admin → testSurface}/surface/test/LengthSection.js +6 -2
  451. package/dist/testSurface/surface/test/PageHoldout.d.ts +3 -0
  452. package/dist/testSurface/surface/test/PageHoldout.js +70 -0
  453. package/dist/{admin → testSurface}/surface/test/Rail.js +7 -4
  454. package/dist/{admin → testSurface}/surface/test/ReadinessBar.d.ts +1 -0
  455. package/dist/{admin → testSurface}/surface/test/ReadinessBar.js +2 -3
  456. package/dist/{admin → testSurface}/surface/test/Section.d.ts +3 -1
  457. package/dist/testSurface/surface/test/Section.js +80 -0
  458. package/dist/{admin → testSurface}/surface/test/TargetingSection.js +82 -12
  459. package/dist/testSurface/surface/test/TestSurface.d.ts +19 -0
  460. package/dist/testSurface/surface/test/TestSurface.js +265 -0
  461. package/dist/testSurface/surface/test/VersionsSection.d.ts +5 -0
  462. package/dist/{admin → testSurface}/surface/test/VersionsSection.js +81 -40
  463. package/dist/{admin → testSurface}/surface/test/fields.d.ts +40 -8
  464. package/dist/testSurface/surface/test/fields.js +306 -0
  465. package/dist/{admin → testSurface}/surface/test/jumpToSection.d.ts +1 -1
  466. package/dist/{admin → testSurface}/surface/test/jumpToSection.js +4 -3
  467. package/dist/testSurface/surface/test/pageParts.d.ts +5 -0
  468. package/dist/testSurface/surface/test/pageParts.js +106 -0
  469. package/dist/testSurface/surface/test/testPage.css +103 -0
  470. package/dist/{admin → testSurface}/surface/test/testPage.model.d.ts +1 -0
  471. package/dist/{admin → testSurface}/surface/test/testPage.model.js +6 -0
  472. package/dist/{admin → testSurface}/surface/testDocument.model.d.ts +4 -0
  473. package/dist/{admin → testSurface}/surface/testDocument.model.js +6 -2
  474. package/dist/testSurface/surface/useTestDocument.d.ts +60 -0
  475. package/dist/testSurface/surface/useTestDocument.js +782 -0
  476. package/dist/testSurface/surface/watchTestDocument.d.ts +15 -0
  477. package/dist/testSurface/surface/watchTestDocument.js +181 -0
  478. package/dist/testSurface/surfaceUrls.d.ts +7 -0
  479. package/dist/testSurface/surfaceUrls.js +19 -0
  480. package/dist/testSurface/useApi.d.ts +60 -0
  481. package/dist/testSurface/useApi.js +8 -0
  482. package/dist/testSurface/useOnTestReturn.d.ts +2 -0
  483. package/dist/testSurface/useOnTestReturn.js +27 -0
  484. package/dist/testSurface/useReadinessPolling.d.ts +3 -0
  485. package/dist/testSurface/useReadinessPolling.js +26 -0
  486. package/dist/transitions/addMetric.d.ts +4 -6
  487. package/dist/transitions/addMetric.js +33 -2
  488. package/dist/transitions/allocate.d.ts +2 -2
  489. package/dist/transitions/allocate.js +3 -1
  490. package/dist/transitions/archive.d.ts +1 -1
  491. package/dist/transitions/archive.js +3 -2
  492. package/dist/transitions/checkStart.d.ts +18 -1
  493. package/dist/transitions/checkStart.js +207 -9
  494. package/dist/transitions/contentFields.js +9 -5
  495. package/dist/transitions/decide.d.ts +1 -1
  496. package/dist/transitions/decide.js +30 -3
  497. package/dist/transitions/deleteExperiment.d.ts +5 -3
  498. package/dist/transitions/deleteExperiment.js +43 -7
  499. package/dist/transitions/kernel.d.ts +4 -0
  500. package/dist/transitions/kernel.js +13 -4
  501. package/dist/transitions/makeContent.d.ts +7 -1
  502. package/dist/transitions/makeContent.js +74 -22
  503. package/dist/transitions/nestedPlacementNames.d.ts +5 -0
  504. package/dist/transitions/nestedPlacementNames.js +32 -0
  505. package/dist/transitions/pageAddress.d.ts +6 -0
  506. package/dist/transitions/pageAddress.js +71 -0
  507. package/dist/transitions/pageCollection.d.ts +10 -0
  508. package/dist/transitions/pageCollection.js +20 -0
  509. package/dist/transitions/pageVersions.d.ts +10 -0
  510. package/dist/transitions/pageVersions.js +46 -0
  511. package/dist/transitions/phaseRecord.d.ts +3 -0
  512. package/dist/transitions/phaseRecord.js +5 -0
  513. package/dist/transitions/placementInteractions.d.ts +40 -0
  514. package/dist/transitions/placementInteractions.js +98 -0
  515. package/dist/transitions/placements.d.ts +58 -4
  516. package/dist/transitions/placements.js +391 -21
  517. package/dist/transitions/preflightData.d.ts +7 -5
  518. package/dist/transitions/preflightData.js +269 -40
  519. package/dist/transitions/releaseHoldout.d.ts +2 -1
  520. package/dist/transitions/releaseHoldout.js +3 -1
  521. package/dist/transitions/releasePages.d.ts +2 -1
  522. package/dist/transitions/releasePages.js +3 -1
  523. package/dist/transitions/resolveCaps.d.ts +3 -4
  524. package/dist/transitions/resolveCaps.js +6 -2
  525. package/dist/transitions/start.d.ts +6 -8
  526. package/dist/transitions/start.js +112 -31
  527. package/dist/transitions/startReads.d.ts +7 -0
  528. package/dist/transitions/startReads.js +28 -0
  529. package/dist/transitions/stop.d.ts +2 -1
  530. package/dist/transitions/stop.js +3 -2
  531. package/dist/types/admin.d.ts +1 -1
  532. package/dist/types/assignments.d.ts +1 -0
  533. package/dist/types/contracts.d.ts +30 -3
  534. package/dist/types/endpoints.d.ts +204 -13
  535. package/dist/types/index.d.ts +3 -0
  536. package/dist/types/puck.d.ts +8 -1
  537. package/dist/types/runtime.d.ts +15 -9
  538. package/dist/types/snapshot.d.ts +19 -4
  539. package/dist/types/surface.d.ts +20 -7
  540. package/dist/ui/Button.js +2 -2
  541. package/dist/ui/Card.d.ts +2 -1
  542. package/dist/ui/Card.js +4 -4
  543. package/dist/ui/ChipsInput.d.ts +8 -1
  544. package/dist/ui/ChipsInput.js +17 -4
  545. package/dist/ui/Dialog.d.ts +24 -2
  546. package/dist/ui/Dialog.js +116 -6
  547. package/dist/ui/Drawer.d.ts +10 -0
  548. package/dist/ui/Drawer.js +29 -0
  549. package/dist/ui/Inputs.d.ts +4 -3
  550. package/dist/ui/Inputs.js +7 -4
  551. package/dist/ui/SelectControl.d.ts +33 -0
  552. package/dist/ui/SelectControl.js +504 -0
  553. package/dist/ui/Tabs.d.ts +4 -4
  554. package/dist/ui/Tabs.js +35 -32
  555. package/dist/ui/ui.css +49 -5
  556. package/package.json +9 -1
  557. package/dist/admin/actions/ConfirmDialog.d.ts +0 -18
  558. package/dist/admin/actions/ConfirmDialog.js +0 -149
  559. package/dist/admin/actions/DecideDialog.d.ts +0 -9
  560. package/dist/admin/actions/actions.model.js +0 -70
  561. package/dist/admin/api.d.ts +0 -38
  562. package/dist/admin/api.js +0 -99
  563. package/dist/admin/copy/readiness.js +0 -71
  564. package/dist/admin/copy/testPage.js +0 -100
  565. package/dist/admin/results/results.css +0 -64
  566. package/dist/admin/styles.css +0 -10
  567. package/dist/admin/styles.d.ts +0 -2
  568. package/dist/admin/styles.js +0 -3
  569. package/dist/admin/surface/pageBlock/pageBlock.model.js +0 -8
  570. package/dist/admin/surface/readiness/ActionDialogs.js +0 -302
  571. package/dist/admin/surface/readiness/Banner.js +0 -166
  572. package/dist/admin/surface/readiness/SaveStatus.d.ts +0 -5
  573. package/dist/admin/surface/readiness/SaveStatus.js +0 -53
  574. package/dist/admin/surface/readiness/readiness.model.d.ts +0 -24
  575. package/dist/admin/surface/readiness/readiness.model.js +0 -123
  576. package/dist/admin/surface/readiness/useTransition.d.ts +0 -11
  577. package/dist/admin/surface/readiness/useTransition.js +0 -35
  578. package/dist/admin/surface/results/ReleasePages.d.ts +0 -14
  579. package/dist/admin/surface/setting/setting.css +0 -17
  580. package/dist/admin/surface/test/AdvancedSection.js +0 -160
  581. package/dist/admin/surface/test/GoalSection.d.ts +0 -2
  582. package/dist/admin/surface/test/GoalSection.js +0 -228
  583. package/dist/admin/surface/test/LengthSection.d.ts +0 -2
  584. package/dist/admin/surface/test/Section.js +0 -47
  585. package/dist/admin/surface/test/VersionsSection.d.ts +0 -4
  586. package/dist/admin/surface/test/fields.js +0 -184
  587. package/dist/admin/surface/test/pageParts.d.ts +0 -2
  588. package/dist/admin/surface/test/pageParts.js +0 -45
  589. package/dist/admin/surface/test/testPage.css +0 -90
  590. package/dist/admin/surface/useTestDocument.d.ts +0 -23
  591. package/dist/admin/surface/useTestDocument.js +0 -377
  592. package/dist/admin/useApi.d.ts +0 -35
  593. package/dist/admin/useApi.js +0 -10
  594. /package/dist/{admin → testSurface}/actions/decide.model.d.ts +0 -0
  595. /package/dist/{admin → testSurface}/actions/decide.model.js +0 -0
  596. /package/dist/{admin → testSurface}/allocation.model.d.ts +0 -0
  597. /package/dist/{admin → testSurface}/allocation.model.js +0 -0
  598. /package/dist/{admin → testSurface}/arms/arms.model.d.ts +0 -0
  599. /package/dist/{admin → testSurface}/arms/arms.model.js +0 -0
  600. /package/dist/{admin → testSurface}/arms/pageTarget.model.d.ts +0 -0
  601. /package/dist/{admin → testSurface}/arms/pageTarget.model.js +0 -0
  602. /package/dist/{admin → testSurface}/arms/params.model.d.ts +0 -0
  603. /package/dist/{admin → testSurface}/arms/params.model.js +0 -0
  604. /package/dist/{admin → testSurface}/copy/advanced.d.ts +0 -0
  605. /package/dist/{admin → testSurface}/copy/advanced.js +0 -0
  606. /package/dist/{admin → testSurface}/copy/arms.d.ts +0 -0
  607. /package/dist/{admin → testSurface}/copy/arms.js +0 -0
  608. /package/dist/{admin → testSurface}/copy/audience.d.ts +0 -0
  609. /package/dist/{admin → testSurface}/copy/audience.js +0 -0
  610. /package/dist/{admin → testSurface}/copy/recommendation.d.ts +0 -0
  611. /package/dist/{admin → testSurface}/copy/recommendation.js +0 -0
  612. /package/dist/{admin → testSurface}/copy/setting.d.ts +0 -0
  613. /package/dist/{admin → testSurface}/copy/setting.js +0 -0
  614. /package/dist/{admin → testSurface}/format/date.d.ts +0 -0
  615. /package/dist/{admin → testSurface}/format/date.js +0 -0
  616. /package/dist/{admin → testSurface}/labels.d.ts +0 -0
  617. /package/dist/{admin → testSurface}/labels.js +0 -0
  618. /package/dist/{admin → testSurface}/lockedNotice.model.d.ts +0 -0
  619. /package/dist/{admin → testSurface}/lockedNotice.model.js +0 -0
  620. /package/dist/{admin → testSurface}/reload.d.ts +0 -0
  621. /package/dist/{admin → testSurface}/reload.js +0 -0
  622. /package/dist/{admin → testSurface}/results/CappedCell.d.ts +0 -0
  623. /package/dist/{admin → testSurface}/results/CappedCell.js +0 -0
  624. /package/dist/{admin → testSurface}/results/CiChart.d.ts +0 -0
  625. /package/dist/{admin → testSurface}/results/CiChart.js +0 -0
  626. /package/dist/{admin → testSurface}/results/DataQualityPanel.d.ts +0 -0
  627. /package/dist/{admin → testSurface}/results/DataTable.d.ts +0 -0
  628. /package/dist/{admin → testSurface}/results/DataTable.js +0 -0
  629. /package/dist/{admin → testSurface}/results/StatTile.d.ts +0 -0
  630. /package/dist/{admin → testSurface}/results/StatTile.js +0 -0
  631. /package/dist/{admin → testSurface}/results/chart.model.d.ts +0 -0
  632. /package/dist/{admin → testSurface}/results/chart.model.js +0 -0
  633. /package/dist/{admin → testSurface}/results/format.d.ts +0 -0
  634. /package/dist/{admin → testSurface}/results/format.js +0 -0
  635. /package/dist/{admin → testSurface}/results/legacy.d.ts +0 -0
  636. /package/dist/{admin → testSurface}/results/legacy.js +0 -0
  637. /package/dist/{admin → testSurface}/results/releasePages.model.d.ts +0 -0
  638. /package/dist/{admin → testSurface}/results/releasePages.model.js +0 -0
  639. /package/dist/{admin → testSurface}/results/snapshot.d.ts +0 -0
  640. /package/dist/{admin → testSurface}/results/snapshot.js +0 -0
  641. /package/dist/{admin → testSurface}/review/review.model.d.ts +0 -0
  642. /package/dist/{admin → testSurface}/review/review.model.js +0 -0
  643. /package/dist/{admin → testSurface}/surface/contracts.js +0 -0
  644. /package/dist/{admin → testSurface}/surface/pageBlock/pageBlock.model.d.ts +0 -0
  645. /package/dist/{admin → testSurface}/surface/pageBlock/parts.d.ts +0 -0
  646. /package/dist/{admin → testSurface}/surface/readiness/parts.d.ts +0 -0
  647. /package/dist/{admin → testSurface}/surface/results/recommendation.model.d.ts +0 -0
  648. /package/dist/{admin → testSurface}/surface/results/recommendation.model.js +0 -0
  649. /package/dist/{admin → testSurface}/surface/setting/parts.d.ts +0 -0
  650. /package/dist/{admin → testSurface}/surface/setting/setting.model.d.ts +0 -0
  651. /package/dist/{admin → testSurface}/surface/setting/setting.model.js +0 -0
  652. /package/dist/{admin → testSurface}/surface/test/AdvancedSection.d.ts +0 -0
  653. /package/dist/{admin → testSurface}/surface/test/Rail.d.ts +0 -0
  654. /package/dist/{admin → testSurface}/surface/test/TargetingSection.d.ts +0 -0
  655. /package/dist/{admin → testSurface}/targeting/targeting.model.d.ts +0 -0
  656. /package/dist/{admin → testSurface}/targeting/targeting.model.js +0 -0
  657. /package/dist/{admin → testSurface}/theme.d.ts +0 -0
  658. /package/dist/{admin → testSurface}/theme.js +0 -0
package/README.md CHANGED
@@ -1,52 +1,59 @@
1
1
  # @delmaredigital/payload-experiments
2
2
 
3
- > ⚠️ Upgrading to 0.3? For 0.3.0-rc.1, every `linkIdentity` call must supply `verified`; it now returns an outcome. Run `payload migrate:create` for the nullable `xp_identities.verified_at` column and `user_id` index, plus the release-pages columns listed in the CHANGELOG (`decision_pages_released_at` / `decision_pages_released_by` on `xp_experiments` and their `version_` counterparts on `_xp_experiments_v`). Existing identity links become unverified; see the CHANGELOG for optional backfill.
3
+ A/B testing for Payload CMS and Next.js, from the content you already manage. Test a block on a page, a whole page against another page, or a setting your developer makes testable. Pick a goal, including click goals you name and attach to buttons and links, then compare the Original with your new versions. Results appear in the admin: they count only people who actually saw the content, warn when traffic looks wrong, and check guardrail goals (goals you don't want to hurt). You pick a winner and can make it permanent. Your data stays in your own Postgres database. There is no vendor.
4
4
 
5
- > ⚠️ Upgrading to 0.2? After upgrading, run `payload generate:importmap`: the Tests surface is registered through admin.dependencies, and without it the Tests routes show a 'not installed' message instead of the Tests screen. In 0.2.0-rc.2, the Tests server views moved from `/rsc` to `/admin/rsc`, so the import map must be regenerated when upgrading from rc.1 too. The old experiments edit-form components are gone from `/admin/client`, and the `xp-experiments` admin list and edit views now redirect to the Tests surface.
5
+ > ⚠️ Upgrading from 0.4.0-rc.9 to rc.10? Update exhaustive TypeScript switches and records over `RefusalCode`. If you mount `TestsSurface` directly with the `pages` prop, replace it with `blockPageCollections`. If you filter or rate-limit `/api/xp/*` upstream, allow the new version check at its polling cadence. See the [rc.10 upgrade steps](https://plugins.delmaredigital.com/docs/experiments/upgrading#from-040-rc9-to-rc10).
6
6
 
7
- A/B testing for Payload CMS and Next.js, with results inside the admin and data
8
- in your own Postgres database. Editors can test blocks, whole pages and
9
- registered flag points, choose a winner, and make it the permanent content.
10
- Results count people who actually saw the content, with checks for traffic
11
- imbalances and metrics that must not get worse. Puck support is optional.
7
+ > ⚠️ Upgrading from 0.4.0-rc.8 to rc.9? Set `events.rateLimit` and `rateLimitUnit`, or explicitly use `false` for requests you limit upstream. Use signing keys of at least 32 characters, including previous rotation keys. Serve events on the page's origin, preserve `Sec-Fetch-Site`, `Origin`, and `Referer`, and configure the public origin in `events.origin` or Payload's `serverURL`. If you use a reverse proxy, forward the browser-facing host and protocol. Set `skipProxyUrlNormalize: true` and keep full prefetch off experiment routes. Use matching cookie settings in the proxy and event handler and cap `cookie.maxAgeDays` at 400. Deploy proxies and event handlers together because an older proxy can reissue IDs. Pre-rc.9 IDs expire on January 7, 2028 at 00:00 UTC by default. Drain older `trackConversion` writers before upgraded writers use the same event table. Update exhaustive TypeScript switches and records over `SnapshotHealth` and `RefusalCode`. See the [rc.9 upgrade steps](https://plugins.delmaredigital.com/docs/experiments/upgrading#from-040-rc7-or-rc8-to-rc9).
12
8
 
13
- ```sh
9
+ > ⚠️ Upgrading from 0.4.0-rc.7? Apply the rc.9 runtime steps above and set the Postgres adapter's `transactionOptions.isolationLevel` to `'read committed'` or remove the override if the database has a supported default. PostgreSQL treats `READ UNCOMMITTED` as `READ COMMITTED`, so both are supported. The app refuses to start with other levels. If your client expects HTTP `403` when a manager deletes a running, stopped, or decided test by ID, handle HTTP `409` with code `invalid-status` and ask the manager to archive the test first. See the [rc.8 release notes](https://github.com/delmaredigital/payload-experiments/blob/main/CHANGELOG.md#040-rc8---2026-12-01).
10
+
11
+ > ⚠️ Upgrading to 0.4 from 0.3? Run `payload migrate:create` for four nullable plugin columns (`xp_experiments.page_collection`, `_xp_experiments_v.version_page_collection`, `xp_phases.placement_docs`, and `xp_state.retired_slugs`), plus the Experiment block and `xpGoal` changes if you adopt them. Apply the migration and run `payload generate:importmap`. Use PostgreSQL `READ COMMITTED` for default and guarded host transactions. PostgreSQL's `READ UNCOMMITTED` is equivalent. Update clients that expect HTTP `403` when a manager deletes a running, stopped, or decided test by ID. Handle HTTP `409` with code `invalid-status` and ask the manager to archive first. Registered page and block saves can be refused with `page-busy` or `interacting-tests`. Publish draft-only placements before starting a test, and publish the Original and winning pages before deciding a stopped whole-page test. Reserve `click:` for click goals and update `admin.editorUrl` for its required `editor` argument. Apply the runtime requirements in the rc.9 callout above. See the [full 0.4 upgrade steps](https://plugins.delmaredigital.com/docs/experiments/upgrading#to-04).
12
+
13
+ ## Install
14
+
15
+ ```bash
14
16
  pnpm add @delmaredigital/payload-experiments
15
17
  ```
16
18
 
17
- ## Setup
19
+ ### Requirements
18
20
 
19
- Requires Node.js `>=22.23.4`, Next.js App Router, and Postgres through
20
- `@payloadcms/db-postgres` with transactions enabled. Other database adapters
21
- are not supported. Install the peers used by your host:
21
+ Use Node.js `>=22.23.4`, the Next.js App Router, and Postgres through `@payloadcms/db-postgres` with transactions enabled and `READ COMMITTED` (or its PostgreSQL equivalent, `READ UNCOMMITTED`) as the default isolation level. Puck is optional. Install the peers your application uses:
22
22
 
23
- | Peer | Range |
23
+ | Peer | Version |
24
24
  | --- | --- |
25
25
  | `payload`, `@payloadcms/db-postgres`, `@payloadcms/next`, `@payloadcms/ui` | `>=3.90.0 <4` |
26
26
  | `next` | `>=16.4.1 <17` |
27
27
  | `react`, `react-dom` | `>=19.2.1 <20` |
28
28
  | `pg` | `>=8.13.0 <9` |
29
- | `@puckeditor/core` (optional, for Puck integration) | `>=0.24.0` |
29
+ | `@puckeditor/core` (optional) | `>=0.24.0` |
30
+
31
+ ## Quick Start
30
32
 
31
- Create one proxy runtime, then a server runtime shared by your Payload config
32
- and server readers. Keep Payload imports lazy so the proxy stays independent
33
- of Payload, React and Puck:
33
+ These examples use your existing Payload app and Pages collection. Imports starting with `@/` are files you supply; the rendering example uses Puck.
34
+
35
+ ### 1. Set a secret and create the runtimes
36
+
37
+ Set a private `XP_SECRET` of at least 32 characters in your server environment. Use the shared Postgres pool from the [rate limiter example](https://plugins.delmaredigital.com/docs/experiments/installation#rate-limit-browser-traffic).
34
38
 
35
39
  ```ts
36
- // experiments/proxyRuntime.ts
40
+ // src/experiments/proxyRuntime.ts
37
41
  import {
38
42
  defineExperimentsProxyRuntime,
39
43
  createPostgresManifestLoader,
40
44
  } from '@delmaredigital/payload-experiments/runtime/proxy'
41
- import { manifestPool } from '@/db/manifestPool' // host-owned pg Pool
45
+ import { allowNewVisitor, pool } from '@/experiments/rateLimit'
42
46
 
43
47
  export const proxyRuntime = defineExperimentsProxyRuntime({
44
48
  secret: process.env.XP_SECRET!,
45
- apiRoute: '/api', // match Payload's config.routes.api
46
- loadManifest: createPostgresManifestLoader({ pool: manifestPool }),
49
+ apiRoute: '/api', // match Payload's routes.api
50
+ rateLimitUnit: allowNewVisitor,
51
+ loadManifest: createPostgresManifestLoader({ pool }),
47
52
  })
53
+ ```
48
54
 
49
- // experiments/serverRuntime.ts
55
+ ```ts
56
+ // src/experiments/serverRuntime.ts
50
57
  import { defineExperimentsServerRuntime } from
51
58
  '@delmaredigital/payload-experiments/runtime/server'
52
59
  import { proxyRuntime } from './proxyRuntime'
@@ -58,760 +65,358 @@ export const serverRuntime = defineExperimentsServerRuntime(proxyRuntime, {
58
65
  return getPayload({ config })
59
66
  },
60
67
  })
68
+ ```
69
+
70
+ Keep the secret private and stable across deployments and instances. To rotate it, pass `secret: [newSecret, previousSecret]`, newest first. For a custom Postgres schema, pass the loader's `schemaName`.
71
+
72
+ ### 2. Add the plugin
61
73
 
62
- // In payload.config.ts
74
+ Add this to your existing `payload.config.ts` plugins array. Your permission check must return a boolean; grant it to the staff who will manage tests.
75
+
76
+ ```ts
63
77
  import { createExperimentsPlugin } from '@delmaredigital/payload-experiments'
64
78
  import { serverRuntime } from '@/experiments/serverRuntime'
65
- import { canManageExperiments } from '@/access/experiments' // host permission check
79
+ import { canManageTests } from '@/access/tests'
80
+ import { allowExperimentEvents } from '@/experiments/rateLimit'
66
81
 
67
- // Add to buildConfig({ plugins: [...] })
68
82
  createExperimentsPlugin({
69
83
  runtime: serverRuntime,
70
- access: { manage: canManageExperiments },
71
- puck: {
72
- enabled: true,
73
- collections: ['pages', { slug: 'templates', field: 'content' }],
74
- },
84
+ access: { manage: canManageTests },
85
+ events: { rateLimit: allowExperimentEvents },
75
86
  })
76
87
  ```
77
88
 
78
- `secret` is required on `defineExperimentsProxyRuntime`, not a top-level plugin
79
- option. Use a stable, private secret shared by all instances. For rotation, pass
80
- an array with the newest secret first; older entries verify existing signatures.
81
- Set a finite `connectionTimeoutMillis` on the host's manifest pool to bound
82
- connection acquisition. `createPostgresManifestLoader` also accepts `schemaName`
83
- when Payload uses a custom Postgres schema. It reads the private compiled
84
- manifest directly, avoiding HTTP calls back into your deployment.
85
-
86
- `createExperimentsPlugin` requires `runtime` and `access.manage`. The permission
87
- callback receives `{ req }` and must return a boolean (or a promise of one);
88
- permission is granted only for `true`. Optional `access.admin` and
89
- `access.readResults` default to `manage`; `access.readIdentities` defaults to
90
- `admin`. Use `admin` for code experiments and changing the analysis method.
91
- Other plugin options are `flagPoints`, `metricSources`, `eventSources`,
92
- `attributeKeys`, `pages`, `puck` and `events`:
93
-
94
- - `attributeKeys` declares targeting attributes as `{ type, values? }`, with
95
- `type` one of `string`, `number`, `boolean`; optional string `values` supplies
96
- an admin select. Pass only non-identifying attributes.
97
- - `puck.collections` registers existing host collections for placement discovery,
98
- content-change markers and making winners permanent. A slug string uses the
99
- `puckData` JSON field; `{ slug, field }` names another field. `puck.enabled`
100
- defaults to `true` when this list is non-empty; set it explicitly in TypeScript
101
- config (the current public type requires it). `false` disables the installed
102
- content-change hook.
103
- - `events.retentionDays` defaults to `180`; `events.maxBodyBytes` to `8192`.
104
- Both must be positive integers. `events.rateLimit` is an optional host adapter,
105
- called with `{ req, unitId }`; return `true` to permit or `false` to drop.
106
- - `events.dimensions` (optional, default none) names up to 8 request attributes
107
- to record on each exposure for later analysis, for example `['loggedIn']`.
108
- Values come only from the attributes the server computes for that request
109
- (`path`, `loggedIn`, `staff` and your `getUnit` attributes), never from what a
110
- browser sends; only strings (first 64 characters), numbers and booleans are
111
- kept. Names that identify a person (such as `userId`, `email` or `ip`) are
112
- refused at startup, but whether an attribute you add yourself identifies
113
- someone is your responsibility. For client-reported exposures `path` is the
114
- page path from the request's `Referer`. Reporting by dimension is not yet
115
- available.
116
- Supply a shared limiter suitable for your deployment; there is no built-in
117
- in-memory limiter.
118
-
119
- The plugin adds `xp-experiments`, `xp-phases`, `xp-layers`, `xp-metrics`,
120
- `xp-events`, `xp-identities`, `xp-results-snapshots` and the `xp-state` global.
121
- The host owns their migrations. After registering the plugin, generate and
122
- review a migration, then apply it in the host:
123
-
124
- ```sh
89
+ Use shared rate limiters keyed by a trusted client address. `events.rateLimit` receives `{ req, unitId }`, with `unitId` available as context only. `rateLimitUnit` receives the `NextRequest` before a new visitor cookie is issued. Each adapter returns `true` to allow the operation. Set either option to `false` only when a firewall or equivalent upstream control limits the corresponding events or page requests, since doing so disables the plugin's rate limit for that traffic. Serve the browser events route on the same origin as your pages and set `events.origin` or Payload's `serverURL` to that public origin. See the [shared rate limiter example](https://plugins.delmaredigital.com/docs/experiments/installation#rate-limit-browser-traffic).
90
+ Keep identifying attributes out of `events.dimensions`. Use the proxy runtime's `cookie.consent` to enrol only after consent (`ExperimentsProxyRuntimeOptions`); `eraseUser(payload, { userId })` from `/rsc` handles privacy erasure (typed by that exported function).
91
+
92
+ ### 3. Run migrations and generate the import map
93
+
94
+ Generate and review the migration in your host app, then apply it. Regenerate the import map so the Tests screens and goal pickers are available.
95
+
96
+ ```bash
125
97
  pnpm exec payload migrate:create
126
98
  pnpm exec payload migrate
99
+ pnpm exec payload generate:importmap
127
100
  ```
128
101
 
129
- ## Next.js proxy
102
+ ### 4. Wire the Next.js proxy
130
103
 
131
- For a standalone proxy, export the wrapper from your host's `proxy.ts`:
104
+ Create your app's `proxy.ts`. This assigns the version to show and handles
105
+ whole-page rewrites.
132
106
 
133
107
  ```ts
108
+ // src/proxy.ts
134
109
  import { createExperimentProxy } from '@delmaredigital/payload-experiments/proxy'
135
110
  import { proxyRuntime } from '@/experiments/proxyRuntime'
136
111
 
137
112
  export const proxy = createExperimentProxy(proxyRuntime)
138
113
  ```
139
114
 
140
- To compose with other proxy logic, call `resolveExperiments` and forward its
141
- request headers on **both** the normal response and any page rewrite. Then call
142
- `applyExperiments` to attach response cookies and headers:
115
+ ### 5. Add a results cron route
116
+
117
+ Your host schedules and authenticates this route. Choose a budget below your platform's route timeout, and schedule regular calls so results refresh.
143
118
 
144
119
  ```ts
145
- import { NextResponse, type NextRequest } from 'next/server'
146
- import { resolveExperiments, applyExperiments } from
147
- '@delmaredigital/payload-experiments/proxy'
148
- import { proxyRuntime } from '@/experiments/proxyRuntime'
120
+ // src/app/api/cron/xp-results/route.ts
121
+ import { runResults } from '@delmaredigital/payload-experiments/rsc'
122
+ import { serverRuntime } from '@/experiments/serverRuntime'
123
+ import { isAuthorizedCronRequest } from '@/auth/cron'
149
124
 
150
- export async function proxy(request: NextRequest) {
151
- const result = await resolveExperiments(request, proxyRuntime)
152
- const options = { request: { headers: result.requestHeaders } }
153
- const response = result.rewrite
154
- ? NextResponse.rewrite(result.rewrite, options)
155
- : NextResponse.next(options)
156
- return applyExperiments(response, result)
125
+ export async function GET(request: Request) {
126
+ if (!(await isAuthorizedCronRequest(request))) {
127
+ return new Response('Unauthorized', { status: 401 })
128
+ }
129
+ const payload = await serverRuntime.getPayload()
130
+ const result = await runResults(payload, { budgetMs: 20_000 })
131
+ return Response.json(result, { headers: { 'Cache-Control': 'no-store' } })
157
132
  }
158
133
  ```
159
134
 
160
- The default `xp_id` cookie is a signed opaque visitor id: HttpOnly,
161
- SameSite=Lax, Secure on HTTPS, path `/`, lifetime 365 days. Runtime `cookie`
162
- options are `name`, `maxAgeDays`, `domain` and `consent`. A newly minted cookie
163
- is forwarded into the same request, so server readers see it immediately.
164
- Inbound `x-xp-*` headers are removed before any skip check. The proxy writes
165
- signed `x-xp-assignments` (at most 1 KB) and `x-xp-request` (method, path/search
166
- and consent, at most 2048 bytes). Server readers verify these; unsigned or
167
- changed values are ignored, with a safe fallback when context is missing.
168
-
169
- `cookie.consent(request)` must read **cookies and headers only**: server
170
- conversion and identity helpers call it with a placeholder URL. When it returns
171
- `false`, nobody is enrolled, including signed-in users; no visitor id is minted
172
- or honoured, and an existing unit cookie is removed from the forwarded request.
173
- Running tests show the Original. Decided winners without an active holdout
174
- round still serve the decided content subject to targeting. Archived page
175
- rewrites serve shipped content by path alone. Neither records exposure.
176
- `linkIdentity` and `trackConversion`
177
- also become no-ops when consent is declined. Omitting `consent` permits cookies
178
- and enrolment.
179
-
180
- Optional runtime `getUnit(request)` returns `{ userId?, attributes,
181
- sessionUnknown? }`, synchronously or asynchronously. Use opaque user ids. With
182
- no session token, return known logged-out attributes such as
183
- `{ loggedIn: false, staff: false }`. With a verified session cache, return the
184
- known user and attributes; with an unresolved session, set `sessionUnknown:
185
- true`. User-unit experiments and session-dependent targeting can then be
186
- resolved on the server through `getUser`. Server runtime options `userIdOf`
187
- (default `String(user.id)`) and `attributesOf` map the host user to the unit id
188
- and targeting attributes; server attributes take precedence. `attributesOf`
189
- defaults to `{ loggedIn: Boolean(user) }`. If you declare `staff` in
190
- `attributeKeys`, pass your own `attributesOf` that identifies staff to
191
- `defineExperimentsServerRuntime`; the plugin refuses to start otherwise. The plugin owns the
192
- normalized `path` attribute (no search, no trailing slash except `/`).
193
-
194
- Staff, bots detected by the built-in user-agent list, preview renders and `HEAD`
195
- requests produce no exposures. A signed `xp_preview` token can select a group
196
- for review without counting it; preview responses are not cached. The plugin
197
- skips admin, API, Next internals and asset paths. Host editor renders must also
198
- remain outside exposure recording.
199
-
200
- Whole-page experiments use visitor units only. Requests to any target path are
201
- rewritten to the assigned group's page; a holdout sees the Original page. After
202
- a winner is made permanent, losing paths keep rewriting to the winner while
203
- the archived experiment record exists. A live experiment targeting a path takes
204
- precedence. Decided winners remain subject to targeting.
205
-
206
- ## Server components (`/rsc`)
207
-
208
- Import server helpers from `@delmaredigital/payload-experiments/rsc`.
209
- `getAssignments(serverRuntime, { user? })` reads and verifies request context,
210
- resolves deferred users, and recomputes stale or missing assignments using the
211
- signed cookie and manifest. It is memoised per request. It reads dynamic Next
212
- headers: call it inside `<Suspense>` under Cache Components, outside
213
- `'use cache'`.
214
-
215
- For Puck content, resolve before rendering and record only the returned
216
- `rendered` list after the response. Capture all request values before `after()`:
135
+ ### 6. Render the assigned version
136
+
137
+ For Puck pages, resolve the saved content before rendering it. Your page loader and render config stay in your app; add the [Puck integration](#puck-optional). For a Payload blocks field, see [Payload blocks (without Puck)](#payload-blocks-without-puck).
217
138
 
218
139
  ```tsx
140
+ // src/components/TestedPage.tsx
219
141
  import { after } from 'next/server'
220
- import { getAssignments, resolveExperimentData, recordExposures } from
221
- '@delmaredigital/payload-experiments/rsc'
142
+ import { Render } from '@puckeditor/core'
143
+ import {
144
+ getAssignments, resolveExperimentData, recordExposures,
145
+ } from '@delmaredigital/payload-experiments/rsc'
222
146
  import { serverRuntime } from '@/experiments/serverRuntime'
223
-
224
- // Inside your async Server Component, after loading the host page:
225
- const assignments = await getAssignments(serverRuntime)
226
- const { data, rendered } = resolveExperimentData(page.puckData, assignments)
227
- after(() => recordExposures(serverRuntime, rendered, assignments))
228
- // Render `data` with your host's Puck render config.
147
+ import { loadPage } from '@/pages/loadPage'
148
+ import { renderConfig } from '@/puck/renderConfig'
149
+
150
+ export async function TestedPage({ path }: { path: string }) {
151
+ const page = await loadPage(path)
152
+ const assignments = await getAssignments(serverRuntime)
153
+ const { data, rendered } = resolveExperimentData(page.puckData, assignments)
154
+ after(() => recordExposures(serverRuntime, rendered, assignments))
155
+ return <Render config={renderConfig} data={data} />
156
+ }
229
157
  ```
230
158
 
231
- **Exposure is the denominator.** Reading an assignment is not an exposure.
232
- `resolveExperimentData` removes unselected content and returns only block
233
- experiments actually present with the `render` policy. Pass that list to
234
- `recordExposures(serverRuntime, rendered, assignments)`, never the full
235
- assignment map. Only schedule it when you render that resolved content.
236
- Viewport and pageview exposures come from the client; manual flag/code
237
- exposures require an explicit host call. Non-enrolled units see the Original
238
- without being counted. Same-unit exposures to multiple groups in a round are
239
- excluded and reported.
240
-
241
- Next's default prefetch does not render the dynamic subtree in `<Suspense>`.
242
- Full prefetch (`<Link prefetch={true}>` or full `router.prefetch`) of pages with
243
- `render`-policy slots is unsupported: it would record content before a visit.
244
-
245
- `toClientAssignments(assignments, { pathname, apiRoute?, flagPoints?,
246
- experiments? })` creates the provider value without visitor identifiers. Both
247
- allow-lists default to empty. Use the served page's pathname for pageview
248
- logging; see the client integration below.
249
-
250
- `getFlagPoint(serverRuntime, id, { user? })` returns `arm`, `params`, `source`
251
- (`experiment` or `default`), optional `experiment`/`experimentId`, and
252
- `expose(renderedArm)`. Bind host code to the registered point id. It uses the
253
- live experiment, then saved winner defaults, then the point's `defaultParams`.
254
- Render the returned settings and call `await point.expose(point.arm)` only
255
- when that arm's content is actually delivered; this records only the manual
256
- exposure policy. Nothing is exposed by reading the point.
257
-
258
- Other server integrations:
259
-
260
- - `trackConversion(serverRuntime, { eventName, value?, idempotencyKey, userId?,
261
- headers? })` records a server event (default value `1`). Use a stable, globally
262
- unique idempotency key for each business event. Pass request headers when
263
- outside a Next request; a user-only server conversion can supply `userId`.
264
- Record revenue through trusted server code or a metric source, never a client
265
- beacon.
266
- - `linkIdentity(serverRuntime, { headers, userId, verified })` belongs on every
267
- user-creation and proving sign-in path; see Identity linking below.
268
- - `eraseUser(payload, { userId })` deletes the user's identities and associated
269
- events transactionally and returns `{ identities, events }` counts. Call it
270
- from the host's authorized user-erasure flow.
271
- - `recordContentChange({ doc, previousDoc, req, collection })` can be called
272
- from a host collection's `afterChange` for content tagged with the arm-select
273
- field; for a collection with drafts, also add `captureContentBaseline` to its
274
- `beforeChange` hooks so the previously published content can be compared.
275
- Collections without drafts can also add `captureContentBaseline` for an exact
276
- raw comparison; without it, the helper normalises relationships to ids. No host
277
- change is required for collections without drafts. Supply that hook's transaction request. Puck collections get the hook
278
- automatically when enabled. Markers compare published content; drafts and
279
- autosaves do not add markers (collections without drafts record on save).
280
- Neither the helper nor the installed hooks ever throw into your save: a
281
- failure is logged and the content save proceeds.
282
- - `experimentMetadata(serverRuntime, path)` returns metadata to merge into the
283
- page's Next metadata: live variant targets get noindex and an Original
284
- canonical; archived losing paths point canonically to the winner. It reads
285
- the signed request context via `headers()`, so it decides from the URL the
286
- visitor requested, not the rewritten route, and the Original's URL is never
287
- noindex. While a test is live the Original's URL also gets a canonical to
288
- itself, even when it is served with a variant's route: merge this result after
289
- your own metadata so its `alternates.canonical` wins over one derived from the
290
- rendered route. Call it only from a dynamic `generateMetadata`, never inside
291
- `'use cache'`; `path` is the fallback when the proxy did not run.
292
- `experimentSitemapFilter(path, manifest)` is a synchronous build-time filter:
293
- pass a privately server-loaded manifest and keep paths for which it returns
294
- `true`, excluding live variants and archived losing paths.
295
-
296
- ## Identity linking
297
-
298
- Call `linkIdentity(serverRuntime, { headers, userId, verified })` on every
299
- user-creation and proving sign-in path. It links the signed anonymous cookie
300
- to an opaque user id on its own connection and never throws into sign-in.
301
- `verified` is required. Pass `true` only when **this request proves, in this
302
- browser, that the person owns the account**: a magic-link or one-time-code
303
- callback, password sign-in, or OAuth callback. It does not mean "a session
304
- exists" or "the account's email is verified". Registration alone uses `false`.
159
+ Render this async component inside `<Suspense>` and outside `'use cache'`.
160
+ Only record the returned `rendered` list when you deliver that content. Keep
161
+ editor and preview renders out of this path. Use Next's default prefetch;
162
+ full prefetch of pages that count content on server render is unsupported.
163
+
164
+ ## Running a test
165
+
166
+ 1. Start from the content: add an **Experiment block** (in Puck's **A/B tests** category),
167
+ or open **Tests** in the admin to test whole pages or a registered setting.
168
+ 2. Keep the **Original**, use **Copy Original here** in Puck to make a version,
169
+ and make your changes. For whole pages, use Payload's **Duplicate** action, give the
170
+ copy its own address, publish it, then choose it as a version in the test.
171
+ 3. Pick a **goal**: a signup, purchase, or a named click goal on a button or
172
+ link. Add guardrail goals for outcomes you don't want to hurt.
173
+ 4. Save, follow the setup checks, preview each version ([wire preview links](#preview-and-editor-links)), and **Start**. The
174
+ results explain whether to keep running or choose a winner.
175
+ 5. Use **Decide** to pick the winner, then **Make it the content** to make it permanent.
176
+ You can also **Stop** to show everyone the Original; starting again begins
177
+ a new round with fresh results.
178
+
179
+ A click tells you someone took an action; it doesn't prove they completed a purchase or signup. Use the outcome itself as a goal when you can measure it.
180
+
181
+ ## What your app wires
182
+
183
+ ### Proxy
184
+
185
+ Keep the [proxy from step 4](#4-wire-the-nextjs-proxy) on your public routes.
186
+ If you already have a proxy, compose with `resolveExperiments` and
187
+ `applyExperiments` from `/proxy`: forward the returned `requestHeaders` on
188
+ both normal responses and rewrites, then apply the returned cookies and headers.
189
+
190
+ ### Whole-page tests
191
+
192
+ Add this to the plugin from step 2 for a drafts-enabled Pages collection:
305
193
 
306
194
  ```ts
307
- // Registration, before proof of account ownership:
308
- await linkIdentity(serverRuntime, { headers, userId, verified: false })
309
- // After successful magic-link/code verification in this browser:
310
- await linkIdentity(serverRuntime, { headers, userId, verified: true })
311
- // After a successful password sign-in (or OAuth callback):
312
- await linkIdentity(serverRuntime, { headers, userId, verified: true })
195
+ pages: { collections: [{
196
+ slug: 'pages',
197
+ pathOf: doc => typeof doc.slug === 'string' ? `/${doc.slug}` : null,
198
+ findByPath: async (path, req) => {
199
+ const { docs } = await req.payload.find({
200
+ collection: 'pages', req, overrideAccess: false, draft: false, depth: 0, limit: 1,
201
+ where: { and: [
202
+ { slug: { equals: path.slice(1) } },
203
+ { _status: { equals: 'published' } },
204
+ ] },
205
+ })
206
+ return docs[0] ? { id: docs[0].id, published: true } : null
207
+ },
208
+ }] }
313
209
  ```
314
210
 
315
- An auth "after" hook that fires whenever a new session cookie is set also
316
- fires on routine session refreshes; pass `verified: true` only from proving
317
- sign-in paths, never from a refresh.
318
-
319
- The result is `'linked'` for an inserted link, `'verified'` for an upgraded
320
- unverified link, `'skipped'` for no consent, no valid unit cookie or an existing
321
- link with nothing to change, and `'failed'` for an error (safely logged).
322
- First link per browser wins; a different account never replaces it.
323
-
324
- For visitor experiments with user-keyed events, verified links are always
325
- eligible. Unverified links are eligible only before the first verification
326
- across all of that user's browsers, or indefinitely if nobody ever verifies.
327
- Each event goes to the earliest exposed eligible visitor. Eligible links
328
- spanning groups are reported as a diagnostic. User-keyed CUPED covariates use
329
- the same eligibility rule at each visitor's first exposure and credit one
330
- aggregate value to the earliest eligible visitor per user.
331
-
332
- Accepted limits:
333
-
334
- - Cross-device: register in A, verify on B, keep using A. A's events after B's
335
- proof are not credited until a proving sign-in on A upgrades A. Events before
336
- B's proof, including the registration funnel, remain credited. Once A is
337
- upgraded, its link is verified and eligible for all its events, so the next
338
- results run also credits A's events from between B's proof and the upgrade.
339
- - Password set before verification: a later password sign-in is proof the
340
- plugin accepts. Whether unverified registration may set a password is a host
341
- authentication concern.
342
- - Shared device: a different user's verified sign-in never relinks an already
343
- linked browser and returns `'skipped'`; that user's events get no credit
344
- through that browser.
345
- - If someone registers another person's email from their own browser and that
346
- person never signs in, a later user-keyed event the host records against that
347
- account (for example an offline gift) is credited to the registering browser.
348
- It needs a deliberate registration of someone else's email plus an event
349
- matched to that account, and it moves one unit's value, never assignment.
350
- There is no time window, so recurring gifts from never-signed-in donors keep
351
- counting.
352
-
353
- ## Results
354
-
355
- The host owns scheduling and authentication. Call
356
- `runResults(payload, { budgetMs })` in-process from your cron route; no Payload
357
- jobs queue or HTTP call back into the application is needed:
211
+ Adapt both callbacks for your homepage. Add `contentOf: doc => doc.layout` to select content for comparison. Keep shipped winner pages published at the same address.
212
+ In dynamic `generateMetadata`, merge `await experimentMetadata(serverRuntime, path)` from `/rsc` **after** your own metadata so its canonical and robots settings win; keep it outside `'use cache'`. Use `experimentSitemapFilter` from `/rsc` in your sitemap.
358
213
 
359
- ```ts
360
- // app/api/cron/xp-results/route.ts
361
- import { runResults } from '@delmaredigital/payload-experiments/rsc'
362
- import { serverRuntime } from '@/experiments/serverRuntime'
363
- import { isAuthorizedCronRequest } from '@/auth/cron' // host-owned auth
214
+ ### Preview and editor links
364
215
 
365
- export async function GET(request: Request) {
366
- if (!(await isAuthorizedCronRequest(request))) {
367
- return new Response('Unauthorized', { status: 401 })
368
- }
369
- const payload = await serverRuntime.getPayload()
370
- const result = await runResults(payload, { budgetMs: 20_000 })
371
- return Response.json(result, { headers: { 'Cache-Control': 'no-store' } })
216
+ The setup checks in [Running a test, step 4](#running-a-test) get their preview links from `admin.previewUrl`. Add these options to the plugin, adapting the routes to your app:
217
+
218
+ ```ts
219
+ admin: {
220
+ previewUrl: ({ collection, slug }) => collection === 'pages' && slug !== undefined
221
+ ? (slug === 'home' ? '/' : `/${slug}`) : null,
222
+ editorUrl: ({ collection, id, editor }) => editor === 'puck'
223
+ ? `/admin/puck-editor/${encodeURIComponent(collection)}/${encodeURIComponent(String(id))}`
224
+ : `/admin/collections/${encodeURIComponent(collection)}/${encodeURIComponent(String(id))}`,
372
225
  }
373
226
  ```
374
227
 
375
- The default budget is 20 seconds. Choose a budget below the host route's timeout.
376
- The runner prioritizes the oldest snapshots, checks the remaining budget before
377
- metrics, bounds waiting for host `query`/`covariate` promises and database
378
- connections, and applies a remaining-budget SQL statement timeout. Hung work
379
- cannot keep the runner waiting beyond that budget. Source failures mark that
380
- metric unavailable. A timed-out source is reported in `unavailableMetrics`;
381
- that experiment's new snapshots are not written, its previous snapshots remain,
382
- and `budgetExhausted` signals the cutoff. Racing a host promise does not cancel
383
- its underlying work: give your own source clients appropriate timeouts too.
384
- The returned summary also includes `ran`, `skipped`, `swept`, `sweepAttempted` and `processedIds`.
385
- Optional `experimentId` limits analysis to one experiment; `sweep: false`
386
- disables retention for that call.
387
-
388
- Analysis uses each round's frozen config and actual exposures. Its window ends
389
- at `endedAt`; later exposures and conversions are excluded. Finished rounds
390
- have a **24-hour late-beacon grace** before their final snapshot freezes: once
391
- a snapshot has been computed after that grace, later runs leave it unchanged.
392
- This does not extend the attribution window beyond the round's end.
393
-
394
- Event retention defaults to **180 days after the experiment's final round
395
- ends**, configurable with `events.retentionDays`. No experiment events are
396
- swept while any of its rounds is open, including a long-lived holdout round.
397
- The runner reserves part of its budget for the batched retention sweep.
398
-
399
- Routes below are relative to Payload's `config.routes.api` (normally `/api`):
400
-
401
- | Endpoint | Permission and response |
402
- | --- | --- |
403
- | `GET /xp/experiments/:id/results?phase=1&series=1` | `access.readResults`; round summaries, newest selected-round `snapshot` (`null` before a run), optional `decisionSnapshot` and requested time series. Without `phase`, a decided experiment opens on its decision round. |
404
- | `GET /xp/experiments/summary?ids=...` | `access.readResults`; map of experiment ids to exposures, days and verdict summary. Encode each id individually, comma-join, and request at most 100 ids. |
405
- | `POST /xp/experiments/:id/recompute` | `access.manage`; runs results for one experiment without sweeping and returns `{ snapshotId }`. Failed or budget-exhausted work returns an error. Frozen rounds stay frozen. |
228
+ `previewUrl` receives `PreviewPlacement`: `collection`, `id`, `title`, `published`, and optional `slug` from the published page (absent for unpublished pages). Return `null` to hide preview. `editorUrl` receives `collection`, `id`, optional `draft` and `doc`, and `editor: 'puck' | 'blocks' | 'page'` to choose the editor route.
406
229
 
407
- ## Flag points and metric sources
230
+ ### Results schedule
231
+
232
+ The [route in step 5](#5-add-a-results-cron-route) runs results in your app.
233
+ On Vercel, add it to your cron configuration and check its authentication.
234
+ The host owns the schedule; the plugin does not use Payload jobs.
235
+
236
+ ### Migrations
408
237
 
409
- Register stable host integration points in `flagPoints`. `defineFlagPoint` and
410
- `defineMetricSource` are optional typed identity helpers from the root export;
411
- the root also exports the `FlagPoint`, `ParamField` and `MetricSource` types.
412
-
413
- A `FlagPoint` has `id`, `label`, `params` and `defaultParams`. `params` maps
414
- setting names to `ParamField` definitions: `{ type, label, required?, options?,
415
- min?, max? }`. Supported types are `text`, `textarea`, `number`, `checkbox`,
416
- `select`; select options are `{ label, value }`. Keep defaults valid for that
417
- schema. Optional callbacks integrate host-owned content:
418
-
419
- - `placements({ experimentId, arms, req })` returns
420
- `[{ arm, ok, detail? }]` for the required content groups at Start. Holdouts
421
- use Original content and are not passed as required placements.
422
- - `makeContent({ experimentId, winner: { arm, params }, req })` runs when the
423
- chosen settings are made permanent. Match host tags on both experiment id
424
- and arm. Use the manager's `req` and `overrideAccess: false` for host-document
425
- writes. The plugin saves the winning settings as defaults for the point.
426
-
427
- A `MetricSource`, registered in `metricSources`, has `id`, `label`,
428
- `kind: 'binomial' | 'count' | 'revenue'`, and `keyedBy: 'visitor' | 'user'`.
429
- `clientWritable` optionally permits client conversions (revenue is always
430
- server-only). `query({ from, to, unitIds? })` returns a promise of
431
- `[{ unitId, value, ts }]`, **one row per event**, with `ts` a `Date`; use the
432
- same opaque ids as assignment or identity linking. A user experiment requires
433
- a user-keyed source. Visitor experiments can use a user-keyed source through
434
- linked identities.
435
-
436
- Optional `covariate({ units: [{ unitId, firstExposureTs }], lookbackDays })`
437
- returns `[{ unitId, value }]`, one aggregate value per unit for pre-exposure
438
- CUPED adjustment (the plugin asks for a 14-day lookback). Percentile
439
- revenue capping reuses `query` over the 90 days before Start; the resolved cap
440
- is frozen for the round. Capping affects decision statistics, while results
441
- also show uncapped totals. Count and binomial metrics are never capped.
442
-
443
- For simple yes/no outcomes, list names in `eventSources`, for example
444
- `eventSources: ['signup']`. A bare string allows client writes; the object form
445
- sets that permission explicitly:
238
+ The schema belongs to your app. Repeat [step 3](#3-run-migrations-and-generate-the-import-map) after every upgrade that changes it, including fields you add to host blocks.
239
+
240
+ ### Signing users in
241
+
242
+ If your site has logins, extend the [server runtime in step 1](#1-set-a-secret-and-create-the-runtimes)
243
+ with `getUser` for your session lookup and `attributesOf` for non-identifying
244
+ attributes such as `loggedIn` and `staff`. Identify staff so their visits don't
245
+ count. In the proxy runtime, supply `getUnit`: return `{ userId, attributes }`
246
+ from a verified session, with `loggedIn` and `staff` in `attributes`; return
247
+ known logged-out attributes when there is no session token, or set
248
+ `sessionUnknown: true` when a token still needs checking on the server.
249
+ Declare `staff: { type: 'boolean' }` in the plugin's `attributeKeys`.
250
+ Call `linkIdentity` at registration and after a successful sign-in:
446
251
 
447
252
  ```ts
448
- eventSources: ['signup', { name: 'donation_completed', clientWritable: false }]
253
+ import { linkIdentity } from '@delmaredigital/payload-experiments/rsc'
254
+ import { serverRuntime } from '@/experiments/serverRuntime'
255
+
256
+ // In your successful password, magic-link/code, or OAuth callback:
257
+ await linkIdentity(serverRuntime, { headers: request.headers, userId, verified: true })
449
258
  ```
450
259
 
451
- Names must match `/^[a-z0-9_]+$/` and be unique across both forms. Editors can
452
- choose `events:signup` or `events:donation_completed` as binomial sources backed
453
- by stored conversions with the corresponding `eventName`. Writable sources
454
- accept both `trackConversion` and `trackConversionBeacon`; server-only sources
455
- are recorded with `trackConversion`. Beacon conversions for a non-writable name
456
- are dropped silently. Only listed names become `events:<name>` sources. They
457
- support visitor and user units and do not represent counts or revenue in v1.
260
+ `verified` is required: use `true` only when this request proves ownership of
261
+ the account in this browser. Registration without that proof uses `false`.
262
+ A session refresh or an account's verified-email flag is not proof here.
458
263
 
459
- ### Whole-page options
264
+ ### Erasing a user
460
265
 
461
- | Option | Purpose |
462
- | --- | --- |
463
- | `pages.collections` | Optional array of `{ slug, pathOf, findByPath }`. `pathOf(doc)` derives a public path from the slug (used to protect live test paths); `findByPath(path, req)` resolves a published page to `{ id, published: true }`, or returns `null`. Start and readiness check every non-holdout version, including the Original. Registered collections must exist when this plugin runs. Localized publication status and field-level `beforeChange` hooks that rewrite paths after the collection guard are unsupported; derive paths from fields finalized before collection hooks. Without this option, readiness warns that pages are unchecked and Start keeps its existing behaviour. |
266
+ When you erase a user, call `eraseUser(payload, { userId })` from `/rsc` so their test data goes too; see the [full reference](https://github.com/delmaredigital/payload-experiments/blob/main/packages/plugin/REFERENCE.md#server-components-rsc).
464
267
 
465
- Do not swallow errors from nested updates of guarded page collections inside host hooks: a swallowed error leaves the guard's operation frame in place for the rest of the request because Payload's Local API does not call `afterError`.
268
+ ### Puck (optional)
466
269
 
467
- For a collection with drafts enabled, use a published-only slug lookup with the
468
- manager's request and `overrideAccess: false`:
270
+ For [steps 2](#2-add-the-plugin) and [6](#6-render-the-assigned-version), add
271
+ `puck: { enabled: true, collections: ['pages'] }` to the plugin. A collection
272
+ slug uses its `puckData` field; use `{ slug: 'pages', field: 'content' }` for another.
273
+ Works with `@delmaredigital/payload-puck >=0.10.3` and experiments `>=0.4.0`.
469
274
 
470
- ```ts
471
- pages: {
472
- collections: [{
473
- slug: 'pages',
474
- pathOf: doc => typeof doc.slug === 'string' ? `/${doc.slug}` : null,
475
- findByPath: async (path, req) => {
476
- const { docs } = await req.payload.find({
477
- collection: 'pages', req, overrideAccess: false, draft: false, depth: 0, limit: 1,
478
- where: { and: [
479
- { slug: { equals: path.slice(1) } },
480
- { _status: { equals: 'published' } },
481
- ] },
482
- })
483
- return docs[0] ? { id: docs[0].id, published: true } : null
484
- },
485
- }],
486
- },
275
+ In your render config, import `experimentsPuck` from `/puck` and pass
276
+ `integrations: [experimentsPuck()]` to payload-puck's `extendConfig`. In a
277
+ `'use client'` editor module, import `experimentsPuckEditor` from `/puck/editor`,
278
+ create `const integrations = [experimentsPuckEditor()]` once at module scope,
279
+ and pass it to `PuckConfigProvider`. Pass your custom `routes` to both helpers.
280
+ Load this in your iframe stylesheet, after Tailwind if you use it, and list that stylesheet's URL in payload-puck's `editorStylesheets`:
281
+
282
+ ```css
283
+ @import "@delmaredigital/payload-experiments/puck/editor.css";
487
284
  ```
488
285
 
489
- Adapt both callbacks for the site's homepage path. These checks run before Start;
490
- they do not protect pages from later deletion, unpublishing or renaming. Keep an
491
- archived winner published at the same address: archived test URLs still point to it.
492
- No migration is needed.
286
+ ### Payload blocks (without Puck)
493
287
 
494
- ### `admin` options
288
+ Add `blocks: { collections: [{ slug: 'pages', field: 'layout' }] }` to the plugin from step 2. Add the wrapper to your host's blocks field, then repeat step 3:
495
289
 
496
- Host links and kind descriptions are optional. For a host using payload-puck's
497
- editor route, public pages and a `puck-templates` collection:
290
+ ```ts
291
+ import { createExperimentBlock } from '@delmaredigital/payload-experiments'
292
+ import { contentBlocks } from '@/blocks'
498
293
 
499
- | Option | Signature and behavior |
500
- | --- | --- |
501
- | `admin.previewUrl` | `(placement: PreviewPlacement) => string \| null \| undefined \| Promise<string \| null \| undefined>`. Receives `collection`, `id`, `title`, `published`, and optional `slug`. May be async; return `null` to hide preview for that placement. Each call has a 2 s limit, with at most 8 lookups awaited concurrently. |
294
+ // In the Pages collection's fields array:
295
+ { name: 'layout', type: 'blocks', blocks: [
296
+ ...contentBlocks, createExperimentBlock({ blocks: contentBlocks }),
297
+ ] }
298
+ ```
502
299
 
503
- For example, pass:
300
+ Resolve before rendering, as in step 6:
504
301
 
505
302
  ```ts
506
- admin: {
507
- editorUrl: ({ collection, id, draft }) =>
508
- `/admin/puck-editor/${encodeURIComponent(collection)}/${encodeURIComponent(String(id))}`,
509
- previewUrl: async ({ collection, slug }) => {
510
- if (collection !== 'pages' || slug === undefined) return null
511
- // Match the site's public page routing, including its homepage convention.
512
- return slug === 'home' ? '/' : `/${slug}`
513
- },
514
- descriptions: {
515
- block: 'Try different content on a landing page.',
516
- document: 'Try different versions of a donation ask.',
517
- setting: 'Try a different signup or donation prompt.',
518
- },
519
- }
303
+ import { after } from 'next/server'
304
+ import { getAssignments, resolveExperimentBlocks, recordExposures } from
305
+ '@delmaredigital/payload-experiments/rsc'
306
+
307
+ const assignments = await getAssignments(serverRuntime)
308
+ const { blocks, rendered } = resolveExperimentBlocks(page.layout, assignments)
309
+ after(() => recordExposures(serverRuntime, rendered, assignments))
310
+ // Render `blocks` with your host's block renderer.
520
311
  ```
521
312
 
522
- `PreviewPlacement` is exported from the package root and `/rsc`. Its `slug` is
523
- the published main row's string slug, including for a placement found in a newer
524
- draft with a different slug. It is absent for unpublished documents. `published`
525
- describes the placement's version; the callback receives no other document fields.
526
- An async callback can also look up the public path by `collection` and `id` using
527
- the host's own data access. The old `({ collection, id }) => string` form still works.
528
-
529
- Preflight resolves the URL callbacks on the server for block placements and sends
530
- only URL strings to the client. A null/undefined result, a non-string, an exception,
531
- a rejected promise or a timeout leaves preview hidden for that placement. When an
532
- editor URL exists, the admin offers "Edit on page"; when neither URL exists, it
533
- omits the row. Timed-out host work cannot be cancelled and keeps its concurrency
534
- slot until it settles; if all 8 slots remain occupied, further preview lookups
535
- are skipped for that preflight. Kind descriptions are available to the server views through
536
- `config.custom.xp`.
537
-
538
- A flag point can also declare `description?: string` to explain the setting below its label.
539
-
540
- ## Security
541
-
542
- The unit cookie, assignments header, request-context header and preview tokens
543
- are HMAC-SHA256 signed with purpose-separated inputs and constant-time
544
- verification. Signing prevents a browser from choosing a trusted identity,
545
- assigned arm, request context or preview group by editing a value. The manifest
546
- is private. Store no PII beyond opaque unit ids: keep names, emails and other
547
- identifying values out of attributes, params and event data.
548
-
549
- Every collection/global access operation is explicit: create, read, update,
550
- delete, readVersions and unlock. Managers operate experiments, layers and
551
- metrics; results and identity reads have separate permissions. Internal event,
552
- identity, round, snapshot and state writes are denied through ordinary
553
- collection/global access. Every Payload Local API call declares
554
- `overrideAccess`; request handlers and views pass `req` and
555
- `overrideAccess: false`. The enumerated privileged operations are the events
556
- insert and assignment lookup, `recordExposures`, server `trackConversion`,
557
- `linkIdentity`, manifest reads, transition writes to plugin collections/state,
558
- content-change markers, results writes and retention sweep, and `eraseUser`.
559
- Host content writes when making a winner permanent still use the manager's
560
- access. Privileged side effects follow their authorized operation in the same
561
- transaction; identity linking deliberately uses its own insert-ignore connection
562
- so duplicate links cannot abort sign-in.
563
-
564
- `POST /xp/events` requires a valid signed unit cookie, reads a streamed body
565
- with an **8192-byte default limit**, and accepts at most **20 events** per body.
566
- It parses JSON regardless of content type for beacon compatibility. Exposure
567
- beacons must name the current round, policy and the arm actually rendered;
568
- the server recomputes assignment and drops mismatches while counting them
569
- separately. Only manual, viewport and pageview exposure policies are accepted.
570
- Conversions require a client-writable source, never revenue; client values are
571
- stored as `1`, attributes are allow-listed, and the host's `events.rateLimit`
572
- adapter runs when supplied. Accepted and dropped events both return `202 {}`;
573
- malformed requests can return errors.
574
-
575
- **The real bound on slow or method-override bodies is the host firewall/platform
576
- timeout.** A stream under the byte limit can remain open, and Payload can read
577
- an `X-HTTP-Method-Override` body before the plugin's streamed cap runs. Apply
578
- host firewall rules and platform request timeouts at that boundary.
579
-
580
- Static checks enforce explicit access and keep raw SQL in the database modules,
581
- but have accepted gaps: extracting a Payload method with a computed property
582
- in destructuring; reflection through `Object.getOwnPropertyNames`,
583
- `Object.getOwnPropertyDescriptor` or `Reflect.ownKeys`; capturing a computed
584
- method from an unknown receiver and calling it later; `payload.jobs.*` calls
585
- (the jobs queue is not used or supported here); lowercase SQL through `pg`;
586
- and aliases changed through `let` reassignment. **Code review is the backstop**
587
- for these patterns.
588
-
589
- ## Admin and client
590
-
591
- The sidebar includes a **Tests** group with **All tests** and **Goals**. The
592
- dashboard also includes **Tests** and **Goals** cards above its widgets. Goals
593
- appears only for users who can manage tests. Both additions follow the host's
594
- admin route and keep host-provided navigation and dashboard entries first.
595
- After upgrading, run `payload generate:importmap` to register the dashboard card
596
- component and the server nav wrapper.
597
- A host nav group also labelled "Tests" shares Payload's NavGroup DOM id and open-state preference with the plugin's group, so pick another label.
598
-
599
- ### Client assignments and exposure
600
-
601
- Read assignments on the server and pass them to `ExperimentsProvider` from
602
- `@delmaredigital/payload-experiments/client`. Build its `value` with
603
- `toClientAssignments` from `@delmaredigital/payload-experiments/rsc`:
313
+ Use the same Suspense, preview and prefetch rules as step 6; record only `rendered` when delivering the content.
314
+
315
+ ### Click goals on your blocks
316
+
317
+ After [step 2](#2-add-the-plugin), add a goal picker to your button or link block,
318
+ then repeat [step 3](#3-run-migrations-and-generate-the-import-map):
604
319
 
605
320
  ```tsx
606
- <ExperimentsProvider value={toClientAssignments(assignments, {
607
- pathname,
608
- flagPoints: ['signup-form'],
609
- experiments: ['welcome-copy'],
610
- })}>
611
- {children}
612
- </ExperimentsProvider>
321
+ import { xpGoalField } from '@delmaredigital/payload-experiments'
322
+
323
+ // Add xpGoalField() to the host block's fields array.
324
+ // In that block's renderer, put the saved value on the actual button or link:
325
+ <a href={href} data-xp-goal={xpGoal}>{label}</a>
613
326
  ```
614
327
 
615
- `flagPoints` and `experiments` are allow-lists: both default to none. Include
616
- only the flag points and experiments that the client needs. The provider value
617
- contains no visitor identifier. Use **one `apiRoute` for every provider on a
618
- page**, including nested providers; it is the API base, such as `/api`. When the
619
- API isn't at `/api`, set that shared route through
620
- `toClientAssignments(assignments, { pathname, apiRoute })`.
621
-
622
- `useFlagPoint(id)` reads the current group and settings at a registered flag
623
- point. `useExperiment(slug)` reads an allow-listed experiment. An unlisted flag
624
- point or experiment slug throws in development and returns the Original with
625
- one console error in production. Neither hook records exposure automatically.
626
- For manual exposure, call
627
- `expose(renderedArm)` only when that group's content actually showed, passing
628
- the group key you rendered. Reading an assignment alone does not count as
629
- seeing content. `expose()` sends only for experiments using the manual exposure
630
- policy.
631
-
632
- On each whole-page experiment target, render a nested `ExperimentsProvider`
633
- whose value is built for **that page's pathname**, and put
634
- `<ExperimentPageview />` inside it. This component reads from the nearest
635
- provider and records the page that appeared, including after navigation.
636
-
637
- Every page that renders Puck viewport slots also needs a provider. A
638
- layout-level provider with empty allow-lists is enough:
639
- `toClientAssignments(assignments, { pathname })`. Without a provider, viewport
640
- exposures cannot be sent.
641
-
642
- For a client-writable conversion, call
643
- `trackConversionBeacon(eventName, { idempotencyKey })`. Pass a stable key for
644
- conversions that matter, so retries count as the same conversion. It sends
645
- nothing without a mounted provider. The server accepts only conversion sources
646
- configured to allow client writes; record revenue on the server.
647
-
648
- ### Puck render and editor configs
649
-
650
- Register the factories from `/puck` and `/puck/editor`, using the same
651
- `ExperimentSlot` component name in both configs. Pass the host's Payload routes:
328
+ For Puck components, use `xpGoalPuckField()` from `/puck` in the render fields
329
+ and `xpGoalPuckEditorField()` from `/puck/editor` in the editor fields; pass custom `routes` as
330
+ `xpGoalPuckEditorField({ routes })`. Editors name click goals in **Goals** or the picker. Mount the provider described below
331
+ to count clicks; put the main goal and guardrail goals in every version or
332
+ outside all tested content.
652
333
 
653
- ```ts
654
- import { createExperimentSlot } from '@delmaredigital/payload-experiments/puck'
655
- import { createExperimentSlotEditor, experimentOutlinePlugin } from '@delmaredigital/payload-experiments/puck/editor'
334
+ ## How it fits a typical site
656
335
 
657
- const routes = { admin: '/manage', api: '/content-api' } // Same as Payload config.routes
658
- const accent = '#1f3a68' // Same as the plugin's theme.accent
336
+ For a site with Puck Pages, signed-in users, a Vercel cron and staff who manage tests, the pieces usually live here:
659
337
 
660
- // Render config
661
- components: { ExperimentSlot: createExperimentSlot({ routes }) }
338
+ | File | What belongs there |
339
+ | --- | --- |
340
+ | `src/experiments/proxyRuntime.ts` | Private secret, manifest pool and API route |
341
+ | `src/experiments/serverRuntime.ts` | Lazy Payload loader, session lookup and staff attributes |
342
+ | `src/payload.config.ts` | Plugin, staff permissions, shared limiter and Pages registration |
343
+ | `src/proxy.ts` | Version selection and whole-page rewrites |
344
+ | `src/app/api/cron/xp-results/route.ts`, `vercel.json` | Authenticated results route and schedule |
345
+ | `src/components/TestedPage.tsx` | Resolve Puck content and render the assigned version |
346
+ | `src/puck/renderConfig.ts`, `src/puck/EditorProvider.tsx` | Render/editor integrations and iframe CSS |
347
+ | `src/auth/callbacks.ts` | Identity linking after registration and proving sign-in |
348
+ | `src/blocks/Button.ts` and its renderer | Click-goal picker and button/link attribute |
662
349
 
663
- // Editor config
664
- components: { ExperimentSlot: createExperimentSlotEditor({ routes, accent }) }
665
- ```
350
+ ## Flag points and metric sources
666
351
 
667
- Add `experimentOutlinePlugin()` to Puck's `plugins` alongside this block config
668
- (with payload-puck, use its `plugins` option). It composes with the host's outline
669
- override and hides empty version slots that the block's test doesn't use. Content
670
- in an unused slot stays visible in the outline and gets a warning in the block.
352
+ Register a stable point once; editors can run new tests on it without changing
353
+ your code. Add this option to the plugin from step 2:
671
354
 
672
355
  ```ts
673
- plugins: [experimentOutlinePlugin()]
356
+ flagPoints: [{
357
+ id: 'signup-prompt', label: 'Signup prompt',
358
+ params: { heading: { type: 'text', label: 'Heading', required: true } },
359
+ defaultParams: { heading: 'Start learning' },
360
+ }]
674
361
  ```
675
362
 
676
- Routes default to Payload's `/admin` and `/api` when omitted. The existing
677
- `ExperimentSlot` and `ExperimentSlotEditor` exports remain available with these
678
- defaults. Hosts on non-default routes switch to the factories. The standalone
679
- `createExperimentSlotField({ routes })` also accepts the host's routes.
363
+ Read it with `getFlagPoint(serverRuntime, 'signup-prompt')` from `/rsc`, render
364
+ its `params`, and call `await point.expose(point.arm)` only when you deliver
365
+ that version. Bind code to the point id. For simple outcome goals, register
366
+ `eventSources: [{ name: 'signup', clientWritable: false }]` and call
367
+ `trackConversion` from `/rsc` with `eventName`, a stable `idempotencyKey` and,
368
+ when needed, `userId` or request `headers`. Editors see **signup** in the goal picker.
369
+ For existing business data, supply `metricSources` adapters with `id`, `label`,
370
+ `kind`, `keyedBy` and `query`, returning one `{ unitId, value, ts: Date }` row
371
+ per event. Revenue belongs in trusted server code, never a browser beacon.
680
372
 
681
- Pass the same accent as the plugin's `theme.accent`: the editor cannot read
682
- Payload config. Both use the same validator and report the same error for an
683
- invalid colour. Without an accent the editor uses the neutral palette.
684
-
685
- Load the editor stylesheet inside the Puck iframe. With Tailwind v4, add the
686
- package import **after** Tailwind in the CSS that builds your editor iframe
687
- stylesheet (the stylesheet listed in payload-puck's `editorStylesheets`):
688
-
689
- ```css
690
- @import "tailwindcss";
691
- @import "@delmaredigital/payload-experiments/puck/editor.css";
692
- ```
373
+ ## Client counting for viewport and pageview tests
693
374
 
694
- Alternatively, serve the exported `puck/editor.css` file from a public URL and
695
- append that URL to payload-puck's `editorStylesheets`, after the host stylesheet.
696
- The editor CSS includes its own light and dark palette, selected by
697
- `data-theme="dark"` or the `dark` class on the iframe's `<html>`. The client component's CSS import alone
698
- does not reach an iframe configured with `syncHostStyles: false`.
375
+ Pass server assignments through a provider around the rendered content:
699
376
 
700
- If Puck runs outside Payload's admin, the page needs Payload's admin styles (the plugin's tokens map onto them) and the plugin's admin styles, plus `data-theme="light"` or `data-theme="dark"` on `<html>`. Inside the admin all of this is already in place:
377
+ ```tsx
378
+ import { ExperimentsProvider, ExperimentPageview } from
379
+ '@delmaredigital/payload-experiments/client'
380
+ import { toClientAssignments } from '@delmaredigital/payload-experiments/rsc'
701
381
 
702
- ```css
703
- @import "@payloadcms/next/css";
704
- @import "@payloadcms/ui/styles.css";
705
- @import "@delmaredigital/payload-experiments/admin/theme.css";
706
- @import "@delmaredigital/payload-experiments/admin/ui.css";
382
+ <ExperimentsProvider value={toClientAssignments(assignments, { pathname })}>
383
+ <ExperimentPageview />
384
+ {children}
385
+ </ExperimentsProvider>
707
386
  ```
708
387
 
709
- Resolve the Puck data on the server with `resolveExperimentData` before
710
- rendering it. The render component shows only the selected group's slot. The
711
- editor lets you select a block experiment, edit each group's content, copy the
712
- Original into a variant, or create an experiment. It warns when edits would
713
- change content during a running test. `createExperimentSlotField` is available
714
- from `/puck` if you need the experiment picker in another custom component.
715
-
716
- The picker lists the 100 most recently updated block experiments.
717
- Viewport exposure watches a fixed, invisible **100 px sentinel**
718
- at the top of the slot and counts it when at least half is visible. The
719
- sentinel stays the same size for short and tall content.
720
-
721
- ### Tag host content with a group
722
-
723
- Add `createArmSelectField({ flagPoint: 'signup-form' })` from
724
- `@delmaredigital/payload-experiments` to a host collection's fields. By default
725
- the field is named `experimentArm`; it stores
726
- `{ experiment: String(experimentId), arm }`.
727
-
728
- Match host content on **`String(experimentId)` plus the arm key**, never on
729
- the experiment slug. The field shows group labels, leaves out the holdout,
730
- warns about tags from an earlier experiment, and lets you clear them. A running
731
- experiment shows a warning before you change its content.
732
-
733
- ### Inside the admin
734
-
735
- The experiment's edit tabs guide setup:
736
-
737
- - **What:** what you are testing and why, including the flag point when needed.
738
- - **Who:** who takes part, targeting, allocation, and space in a layer.
739
- - **Groups:** the Original, variants and optional holdout, their percentages,
740
- settings, or page paths.
741
- - **Metrics:** the main outcome, supporting metrics, guardrails, and planned
742
- duration.
743
- - **Review:** saved setup checks, placements and preview links, recent traffic,
744
- and a duration estimate when enough information is available. Apply copies
745
- the suggested duration and sensitivity into the form; save before you start.
746
-
747
- The **Results** view lets you select a round, read the verdict, compare groups,
748
- check data quality, and see results over time with content-change markers.
749
- Holdouts are measured without being compared during the test. Revenue results
750
- show uncapped totals alongside any capped decision statistic. Recompute
751
- requests fresh results. The experiment list shows status and a results summary;
752
- round history and layer usage provide context in the admin.
753
-
754
- Actions depend on the experiment's status and your permissions. **Unsaved
755
- changes block actions**; save first so they use the saved experiment.
756
-
757
- - **Start** runs a draft. **Start a new round** after stopping warns:
758
- “Starting again begins a new round; results restart.”
759
- - **Stop** says: “Everyone will see the Original. Starting again begins a new
760
- round; results restart.”
761
- - **Raise allocation** adds people without changing the group of anyone
762
- already taking part. Lowering allocation needs a new round.
763
- - **Add a metric** adds a supporting metric or guardrail to a running test.
764
- - **Decide** starts with the recommended group. Choosing the Original says
765
- “Everyone will see the Original.” Choosing a variant says everyone will see
766
- it, except an existing holdout, which keeps seeing the Original so you can
767
- measure the shipped change. When results need caution or you choose against
768
- the recommendation, enter a note and type the chosen group's label.
769
- - **Release holdout** says the holdout will see the winner too and measuring
770
- since shipping ends.
771
- - **Make it the content** copies the winner into page content or saves its
772
- settings as defaults, then archives the experiment. Failed page updates are
773
- listed with Retry. **Finish archiving** completes archiving when the content
774
- has already been updated.
775
- - **Archive** closes a stopped experiment. **Discard winner** says: “Everyone
776
- goes back to the Original. The decision note is kept.” It requires typed
777
- confirmation. For code experiments, the action confirming that the developer
778
- has hard-coded the winner also requires typed confirmation before archiving.
779
-
780
- ### Known limitations (v1)
781
-
782
- - Preview links open after a token request, so Safari's popup blocker may block
783
- them. Allow popups for the admin.
784
- - “Raise allocation” is offered even at 100%.
785
- - The metric picker in “Add a metric” lists 100 metrics.
786
- - The Puck picker lists 100 experiments.
787
- - The Puck experiment picker always calls `/api`; hosts with a custom API route
788
- see an empty picker.
789
- - Content-change markers are recorded on publish only (on save for collections
790
- without drafts).
791
- - Results cover the whole round; breakdowns by segment or dimension are not
792
- available in v1.
793
-
794
- ### Limits
795
-
796
- | Capability | Limit |
797
- |---|---|
798
- | Make it the content: localized collections | not supported yet |
799
- | Make it the content: field defaults | An update-denied field empty in both versions may publish its default because Payload applies defaults when reading. |
388
+ Use the served page's own pathname, including after a rewrite. Puck viewport
389
+ blocks count when visible; whole-page tests need `ExperimentPageview` on each
390
+ target page. The provider also enables click goals. Pass `apiRoute` if yours
391
+ isn't `/api`. Client readers need explicit `flagPoints` or `experiments`
392
+ allow-lists in `toClientAssignments`; reading alone never counts a visit.
800
393
 
801
394
  ## Theme
802
395
 
803
- The admin inherits Payload's neutral palette by default. Set one host accent:
396
+ The admin follows Payload's light and dark themes. To use your own accent, add:
804
397
 
805
398
  ```ts
806
399
  theme: { accent: '#1f3a68' }
807
400
  ```
808
401
 
809
- `theme.accent` accepts `#rgb` or `#rrggbb`; empty or undefined uses the default.
810
- The plugin derives darker hover/active fills (clamped to keep text contrast), a
811
- contrasting focus ring, and an opaque 8% subtle tint.
812
- In dark mode it raises HSL lightness when needed to reach 3:1 against the
813
- reference dark surface, then selects white or near-black foreground text.
814
- The WCAG 2.x gate requires at least 4.5:1 **foreground text on the accent fill**
815
- in each theme (the accent is used as a fill, not as page text). A failing
816
- colour is refused with its ratio. Status chips retain Payload semantic colours.
817
- `deriveAccent` is also exported from `/puck/editor` for editor integrations.
402
+ Use a hex colour with three or six digits; colours without enough contrast are refused. Pass the same `accent` to `experimentsPuckEditor` for Puck.
403
+
404
+ ## Access options
405
+
406
+ Callbacks receive `{ req }` and return a boolean or a promise of one.
407
+
408
+ | Option | Who it permits | Default |
409
+ | --- | --- | --- |
410
+ | `manage` | Create and run tests, manage goals and choose winners | Required |
411
+ | `admin` | Code tests and analysis-method changes | `manage` |
412
+ | `readResults` | Read results | `manage` |
413
+ | `readIdentities` | Read identity links | `admin` |
414
+
415
+ ## Full reference (until the docs site)
416
+
417
+ The longer option-by-option reference from before this rewrite is in [REFERENCE.md](https://github.com/delmaredigital/payload-experiments/blob/main/packages/plugin/REFERENCE.md) until the documentation site exists.
418
+
419
+ ## License
420
+
421
+ [MIT](https://github.com/delmaredigital/payload-experiments/blob/main/LICENSE).
422
+ See the [statistics engine README](https://github.com/delmaredigital/payload-experiments/blob/main/packages/stats/README.md) for the methods behind the results.