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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (367) hide show
  1. package/README.md +9 -15
  2. package/dist/admin/MetricSourceSelect.js +10 -3
  3. package/dist/admin/armSelect/armSelect.model.d.ts +1 -1
  4. package/dist/admin/blocks/BlockPanel.d.ts +1 -0
  5. package/dist/admin/blocks/BlockPanel.js +75 -29
  6. package/dist/admin/blocks/model.js +7 -6
  7. package/dist/admin/copy/blocks.d.ts +14 -11
  8. package/dist/admin/copy/blocks.js +33 -22
  9. package/dist/admin/copy/goals.d.ts +15 -8
  10. package/dist/admin/copy/goals.js +18 -8
  11. package/dist/admin/copy/newTest.d.ts +10 -7
  12. package/dist/admin/copy/newTest.js +14 -7
  13. package/dist/admin/copy/status.d.ts +1 -1
  14. package/dist/admin/copy/status.js +2 -1
  15. package/dist/admin/pageCollections.d.ts +1 -0
  16. package/dist/admin/pageCollections.js +3 -0
  17. package/dist/admin/placementStatus.model.js +5 -3
  18. package/dist/admin/status.model.d.ts +1 -0
  19. package/dist/admin/status.model.js +2 -1
  20. package/dist/admin/surface/ResultsRoute.js +12 -10
  21. package/dist/admin/surface/SurfaceShell.d.ts +4 -2
  22. package/dist/admin/surface/SurfaceShell.js +28 -3
  23. package/dist/admin/surface/TestRowMenu.d.ts +13 -0
  24. package/dist/admin/surface/TestRowMenu.js +163 -0
  25. package/dist/admin/surface/TestsHome.d.ts +4 -3
  26. package/dist/admin/surface/TestsHome.js +224 -52
  27. package/dist/admin/surface/TestsSurface.js +2 -1
  28. package/dist/admin/surface/goals/DeleteGoalDialog.d.ts +7 -0
  29. package/dist/admin/surface/goals/DeleteGoalDialog.js +42 -0
  30. package/dist/admin/surface/goals/GoalForm.d.ts +1 -0
  31. package/dist/admin/surface/goals/GoalForm.js +280 -198
  32. package/dist/admin/surface/goals/GoalsList.js +102 -33
  33. package/dist/admin/surface/goals/data.d.ts +2 -0
  34. package/dist/admin/surface/goals/data.js +9 -0
  35. package/dist/admin/surface/goals/goals.css +3 -2
  36. package/dist/admin/surface/goals/goals.model.d.ts +2 -2
  37. package/dist/admin/surface/goals/goals.model.js +7 -12
  38. package/dist/admin/surface/home.model.d.ts +15 -8
  39. package/dist/admin/surface/home.model.js +22 -18
  40. package/dist/admin/surface/newTest/NewTest.d.ts +3 -3
  41. package/dist/admin/surface/newTest/NewTest.js +156 -96
  42. package/dist/admin/surface/newTest/PageWizard.d.ts +4 -1
  43. package/dist/admin/surface/newTest/PageWizard.js +99 -68
  44. package/dist/admin/surface/newTest/newTest.css +28 -11
  45. package/dist/admin/surface/results/ResultsHeader.d.ts +1 -1
  46. package/dist/admin/surface/results/ResultsHeader.js +98 -66
  47. package/dist/admin/surface/surface.css +29 -0
  48. package/dist/admin/surface/test/TestPage.js +46 -38
  49. package/dist/admin/surface/useXpStepNav.d.ts +11 -0
  50. package/dist/admin/surface/useXpStepNav.js +14 -0
  51. package/dist/admin/views/TestsSurfaceClient.js +27 -3
  52. package/dist/admin/views/buildSurfaceProps.js +18 -66
  53. package/dist/arms/copy.d.ts +13 -3
  54. package/dist/arms/copy.js +5 -4
  55. package/dist/blocks/createExperimentBlock.js +1 -1
  56. package/dist/blocks/formState.js +2 -2
  57. package/dist/collections/experiments/armInvariants.js +8 -5
  58. package/dist/collections/experiments/config.js +8 -3
  59. package/dist/collections/experiments/deleteGuard.js +2 -2
  60. package/dist/collections/experiments/lockHook.js +21 -2
  61. package/dist/collections/experiments/pickSlug.js +2 -0
  62. package/dist/collections/metrics.js +12 -5
  63. package/dist/collections/metricsGuards.js +2 -0
  64. package/dist/collections/serialize.js +8 -6
  65. package/dist/constants.d.ts +1 -0
  66. package/dist/constants.js +1 -0
  67. package/dist/db/adapter.d.ts +9 -1
  68. package/dist/db/adapter.js +77 -1
  69. package/dist/db/delete.d.ts +1 -1
  70. package/dist/db/delete.js +2 -4
  71. package/dist/db/events.d.ts +9 -0
  72. package/dist/db/events.js +42 -8
  73. package/dist/db/executor.d.ts +7 -1
  74. package/dist/db/executor.js +7 -3
  75. package/dist/db/pageCopies.d.ts +5 -0
  76. package/dist/db/pageCopies.js +31 -0
  77. package/dist/db/results.d.ts +5 -1
  78. package/dist/db/results.js +21 -5
  79. package/dist/db/snapshots.d.ts +2 -0
  80. package/dist/endpoints/deleteImpact.js +2 -1
  81. package/dist/endpoints/duplicateOriginal.d.ts +38 -0
  82. package/dist/endpoints/duplicateOriginal.js +414 -0
  83. package/dist/endpoints/editorSurface.js +1 -1
  84. package/dist/endpoints/events.js +103 -39
  85. package/dist/endpoints/index.js +22 -8
  86. package/dist/endpoints/pages.js +245 -66
  87. package/dist/endpoints/placementStatus.js +8 -4
  88. package/dist/endpoints/results.d.ts +1 -1
  89. package/dist/endpoints/results.js +9 -2
  90. package/dist/endpoints/routeId.d.ts +2 -2
  91. package/dist/endpoints/routeId.js +11 -5
  92. package/dist/endpoints/summary.js +46 -12
  93. package/dist/endpoints/testVersion.d.ts +2 -0
  94. package/dist/endpoints/testVersion.js +38 -0
  95. package/dist/endpoints/transitions.js +41 -29
  96. package/dist/errors.d.ts +4 -0
  97. package/dist/errors.js +6 -0
  98. package/dist/events/request.d.ts +6 -2
  99. package/dist/events/request.js +35 -8
  100. package/dist/events/rows.d.ts +1 -1
  101. package/dist/events/rows.js +24 -8
  102. package/dist/events/writable.d.ts +9 -0
  103. package/dist/events/writable.js +13 -0
  104. package/dist/exports/index.d.ts +1 -1
  105. package/dist/exports/rsc.d.ts +1 -0
  106. package/dist/exports/rsc.js +1 -0
  107. package/dist/goals/fairness.js +2 -2
  108. package/dist/goals/picker/copy.js +1 -1
  109. package/dist/goals/sourceLabel.d.ts +2 -0
  110. package/dist/goals/sourceLabel.js +4 -0
  111. package/dist/hooks/hostHook.js +6 -2
  112. package/dist/hooks/pageGuard.js +4 -0
  113. package/dist/hooks/trackPageCopies.d.ts +11 -0
  114. package/dist/hooks/trackPageCopies.js +7 -0
  115. package/dist/labels/arms.d.ts +3 -0
  116. package/dist/labels/arms.js +8 -0
  117. package/dist/lib/fetchAllDocs.d.ts +1 -1
  118. package/dist/manifest/compile.js +8 -5
  119. package/dist/onInit.js +14 -0
  120. package/dist/options.d.ts +2 -0
  121. package/dist/options.js +23 -2
  122. package/dist/plugin.js +56 -2
  123. package/dist/proxy/pageNavigation.d.ts +4 -0
  124. package/dist/proxy/pageNavigation.js +28 -0
  125. package/dist/proxy/resolve.js +52 -25
  126. package/dist/puck/editor/ConfigureTestDrawer.d.ts +7 -7
  127. package/dist/puck/editor/ConfigureTestDrawer.js +40 -29
  128. package/dist/puck/editor/ExperimentSlotEditor.d.ts +2 -1
  129. package/dist/puck/editor/ExperimentSlotEditor.js +376 -139
  130. package/dist/puck/editor/LeftoverVersions.js +17 -32
  131. package/dist/puck/editor/QuickTestActions.d.ts +6 -3
  132. package/dist/puck/editor/QuickTestActions.js +55 -33
  133. package/dist/puck/editor/ResultsReadout.d.ts +4 -1
  134. package/dist/puck/editor/ResultsReadout.js +28 -15
  135. package/dist/puck/editor/VersionBuilder.d.ts +17 -4
  136. package/dist/puck/editor/VersionBuilder.js +175 -112
  137. package/dist/puck/editor/armWrites.js +2 -2
  138. package/dist/puck/editor/armsCache.js +1 -3
  139. package/dist/puck/editor/copy.d.ts +14 -7
  140. package/dist/puck/editor/copy.js +26 -13
  141. package/dist/puck/editor/editor.chrome.css +10 -8
  142. package/dist/puck/editor/editor.css +15 -9
  143. package/dist/puck/editor/editor.model.d.ts +1 -0
  144. package/dist/puck/editor/placementsCache.d.ts +4 -0
  145. package/dist/puck/editor/usePageSaveReadiness.d.ts +6 -0
  146. package/dist/puck/editor/usePageSaveReadiness.js +31 -0
  147. package/dist/puck/nestedTestCopy.js +2 -2
  148. package/dist/puck/slotConfig.d.ts +1 -1
  149. package/dist/puck/slotConfig.js +1 -1
  150. package/dist/results/aggregate.d.ts +6 -3
  151. package/dist/results/aggregate.js +9 -9
  152. package/dist/results/analyse.d.ts +2 -0
  153. package/dist/results/analyse.js +2 -2
  154. package/dist/results/health.d.ts +8 -0
  155. package/dist/results/health.js +28 -0
  156. package/dist/results/identityCredit.d.ts +1 -0
  157. package/dist/results/identityCredit.js +4 -1
  158. package/dist/results/verdict.d.ts +4 -4
  159. package/dist/results/verdict.js +15 -11
  160. package/dist/runtime/cookie.d.ts +10 -2
  161. package/dist/runtime/cookie.js +38 -6
  162. package/dist/runtime/cookieOptions.d.ts +6 -0
  163. package/dist/runtime/cookieOptions.js +14 -0
  164. package/dist/runtime/proxyRuntime.d.ts +1 -0
  165. package/dist/runtime/proxyRuntime.js +18 -8
  166. package/dist/runtime/signing.d.ts +1 -0
  167. package/dist/runtime/signing.js +5 -0
  168. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  169. package/dist/sanitizeReadinessDetail.js +20 -2
  170. package/dist/server/getAssignments.js +11 -10
  171. package/dist/server/recordContentChange.d.ts +1 -1
  172. package/dist/server/recordContentChange.js +11 -2
  173. package/dist/server/resolveExperimentBlocks.js +2 -4
  174. package/dist/server/resolveExperimentData.js +2 -5
  175. package/dist/server/runResults.js +54 -15
  176. package/dist/server/startExperiment.d.ts +20 -0
  177. package/dist/server/startExperiment.js +70 -0
  178. package/dist/server/trackConversion.js +10 -13
  179. package/dist/testSurface/PreviewLinks.d.ts +2 -1
  180. package/dist/testSurface/PreviewLinks.js +3 -3
  181. package/dist/testSurface/actions/DecideDialog.d.ts +10 -4
  182. package/dist/testSurface/actions/DecideDialog.js +93 -63
  183. package/dist/testSurface/actions/LifecycleAction.d.ts +17 -0
  184. package/dist/testSurface/actions/LifecycleAction.js +107 -0
  185. package/dist/testSurface/actions/MakeContentResult.d.ts +4 -3
  186. package/dist/testSurface/actions/MakeContentResult.js +10 -2
  187. package/dist/testSurface/actions/actions.model.d.ts +13 -5
  188. package/dist/testSurface/actions/actions.model.js +75 -22
  189. package/dist/testSurface/actions/decide.model.d.ts +1 -0
  190. package/dist/testSurface/actions/decide.model.js +1 -0
  191. package/dist/testSurface/allocation.model.js +6 -3
  192. package/dist/testSurface/api.d.ts +9 -6
  193. package/dist/testSurface/api.js +43 -23
  194. package/dist/testSurface/copy/actions.d.ts +37 -14
  195. package/dist/testSurface/copy/actions.js +40 -17
  196. package/dist/testSurface/copy/advanced.d.ts +10 -0
  197. package/dist/testSurface/copy/advanced.js +10 -0
  198. package/dist/testSurface/copy/arms.d.ts +1 -1
  199. package/dist/testSurface/copy/arms.js +1 -1
  200. package/dist/testSurface/copy/audience.d.ts +4 -3
  201. package/dist/testSurface/copy/audience.js +5 -4
  202. package/dist/testSurface/copy/common.d.ts +8 -6
  203. package/dist/testSurface/copy/common.js +8 -6
  204. package/dist/testSurface/copy/languages.d.ts +1 -0
  205. package/dist/testSurface/copy/languages.js +1 -0
  206. package/dist/testSurface/copy/metrics.d.ts +7 -0
  207. package/dist/testSurface/copy/metrics.js +9 -0
  208. package/dist/testSurface/copy/pages.d.ts +67 -7
  209. package/dist/testSurface/copy/pages.js +74 -7
  210. package/dist/testSurface/copy/readiness.d.ts +20 -7
  211. package/dist/testSurface/copy/readiness.js +36 -10
  212. package/dist/testSurface/copy/recommendation.d.ts +1 -22
  213. package/dist/testSurface/copy/recommendation.js +2 -22
  214. package/dist/testSurface/copy/results.d.ts +21 -12
  215. package/dist/testSurface/copy/results.js +24 -13
  216. package/dist/testSurface/copy/review.d.ts +13 -10
  217. package/dist/testSurface/copy/review.js +14 -10
  218. package/dist/testSurface/copy/setting.d.ts +1 -2
  219. package/dist/testSurface/copy/setting.js +1 -2
  220. package/dist/testSurface/copy/surface.d.ts +11 -2
  221. package/dist/testSurface/copy/surface.js +14 -11
  222. package/dist/testSurface/copy/testPage.d.ts +36 -12
  223. package/dist/testSurface/copy/testPage.js +53 -16
  224. package/dist/testSurface/format/date.d.ts +5 -2
  225. package/dist/testSurface/format/date.js +24 -8
  226. package/dist/testSurface/format/roundProgress.d.ts +6 -0
  227. package/dist/testSurface/format/roundProgress.js +15 -0
  228. package/dist/testSurface/format/useDateFormatter.d.ts +3 -0
  229. package/dist/testSurface/format/useDateFormatter.js +8 -0
  230. package/dist/testSurface/labels.d.ts +1 -2
  231. package/dist/testSurface/labels.js +2 -3
  232. package/dist/testSurface/lockedNotice.model.d.ts +2 -0
  233. package/dist/testSurface/lockedNotice.model.js +31 -0
  234. package/dist/testSurface/readPreflight.d.ts +4 -0
  235. package/dist/testSurface/readPreflight.js +6 -0
  236. package/dist/testSurface/readinessRead.d.ts +3 -0
  237. package/dist/testSurface/readinessRead.js +4 -0
  238. package/dist/testSurface/results/CiChart.js +2 -1
  239. package/dist/testSurface/results/DataTable.d.ts +1 -1
  240. package/dist/testSurface/results/DataTable.js +4 -3
  241. package/dist/testSurface/results/VerdictHero.d.ts +3 -2
  242. package/dist/testSurface/results/VerdictHero.js +5 -1
  243. package/dist/testSurface/results/legacy.d.ts +0 -5
  244. package/dist/testSurface/results/legacy.js +0 -14
  245. package/dist/testSurface/results/results.css +2 -2
  246. package/dist/testSurface/results/results.model.d.ts +9 -4
  247. package/dist/testSurface/results/results.model.js +31 -23
  248. package/dist/testSurface/results/snapshot.d.ts +2 -0
  249. package/dist/testSurface/results/snapshot.js +3 -0
  250. package/dist/testSurface/surface/contracts.d.ts +13 -1
  251. package/dist/testSurface/surface/editorPlacement.d.ts +3 -3
  252. package/dist/testSurface/surface/editorPlacement.js +2 -2
  253. package/dist/testSurface/surface/pageBlock/pageBlock.model.js +3 -3
  254. package/dist/testSurface/surface/pageBlock/parts.js +25 -12
  255. package/dist/testSurface/surface/pagePicker/CopyRoute.d.ts +8 -1
  256. package/dist/testSurface/surface/pagePicker/CopyRoute.js +243 -22
  257. package/dist/testSurface/surface/pagePicker/PageCombobox.d.ts +15 -4
  258. package/dist/testSurface/surface/pagePicker/PageCombobox.js +300 -197
  259. package/dist/testSurface/surface/pagePicker/pagePicker.css +73 -10
  260. package/dist/testSurface/surface/pagePicker/pagePicker.model.d.ts +5 -3
  261. package/dist/testSurface/surface/pagePicker/pagePicker.model.js +17 -2
  262. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +9 -5
  263. package/dist/testSurface/surface/readiness/ActionDialogs.js +241 -230
  264. package/dist/testSurface/surface/readiness/Banner.d.ts +5 -1
  265. package/dist/testSurface/surface/readiness/Banner.js +113 -141
  266. package/dist/testSurface/surface/readiness/SaveStatus.d.ts +8 -4
  267. package/dist/testSurface/surface/readiness/SaveStatus.js +23 -22
  268. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -6
  269. package/dist/testSurface/surface/readiness/readiness.model.js +168 -21
  270. package/dist/testSurface/surface/readiness/useTransition.d.ts +6 -4
  271. package/dist/testSurface/surface/readiness/useTransition.js +57 -14
  272. package/dist/testSurface/surface/results/ReleasePages.d.ts +6 -3
  273. package/dist/testSurface/surface/results/ReleasePages.js +42 -41
  274. package/dist/testSurface/surface/results/ResultsBody.d.ts +11 -4
  275. package/dist/testSurface/surface/results/ResultsBody.js +221 -118
  276. package/dist/testSurface/surface/results/recommendation.model.d.ts +6 -9
  277. package/dist/testSurface/surface/results/recommendation.model.js +15 -59
  278. package/dist/testSurface/surface/results/useResults.d.ts +13 -8
  279. package/dist/testSurface/surface/results/useResults.js +3 -2
  280. package/dist/testSurface/surface/setting/parts.js +89 -46
  281. package/dist/testSurface/surface/setting/setting.css +2 -1
  282. package/dist/testSurface/surface/test/AdvancedSection.js +11 -4
  283. package/dist/testSurface/surface/test/DeleteTest.d.ts +10 -2
  284. package/dist/testSurface/surface/test/DeleteTest.js +173 -74
  285. package/dist/testSurface/surface/test/GoalSection.js +18 -14
  286. package/dist/testSurface/surface/test/LengthSection.js +24 -13
  287. package/dist/testSurface/surface/test/PageHoldout.d.ts +1 -1
  288. package/dist/testSurface/surface/test/PageHoldout.js +11 -8
  289. package/dist/testSurface/surface/test/ReadinessBar.d.ts +2 -1
  290. package/dist/testSurface/surface/test/ReadinessBar.js +4 -10
  291. package/dist/testSurface/surface/test/Section.js +8 -0
  292. package/dist/testSurface/surface/test/TargetingSection.js +82 -12
  293. package/dist/testSurface/surface/test/TestSurface.js +73 -37
  294. package/dist/testSurface/surface/test/VersionsSection.js +141 -91
  295. package/dist/testSurface/surface/test/fields.d.ts +32 -6
  296. package/dist/testSurface/surface/test/fields.js +166 -52
  297. package/dist/testSurface/surface/test/pageParts.js +27 -12
  298. package/dist/testSurface/surface/test/testPage.css +9 -2
  299. package/dist/testSurface/surface/test/testPage.model.d.ts +1 -0
  300. package/dist/testSurface/surface/test/testPage.model.js +6 -0
  301. package/dist/testSurface/surface/testDocument.model.d.ts +3 -0
  302. package/dist/testSurface/surface/testDocument.model.js +4 -1
  303. package/dist/testSurface/surface/useTestDocument.d.ts +21 -5
  304. package/dist/testSurface/surface/useTestDocument.js +472 -167
  305. package/dist/testSurface/surface/watchTestDocument.d.ts +15 -0
  306. package/dist/testSurface/surface/watchTestDocument.js +181 -0
  307. package/dist/testSurface/surfaceUrls.d.ts +1 -0
  308. package/dist/testSurface/surfaceUrls.js +4 -0
  309. package/dist/testSurface/useApi.d.ts +8 -5
  310. package/dist/testSurface/useOnTestReturn.d.ts +2 -0
  311. package/dist/testSurface/useOnTestReturn.js +27 -0
  312. package/dist/testSurface/useReadinessPolling.js +3 -1
  313. package/dist/transitions/addMetric.d.ts +2 -5
  314. package/dist/transitions/addMetric.js +5 -1
  315. package/dist/transitions/allocate.d.ts +2 -2
  316. package/dist/transitions/allocate.js +3 -1
  317. package/dist/transitions/archive.d.ts +1 -1
  318. package/dist/transitions/archive.js +3 -2
  319. package/dist/transitions/checkStart.d.ts +1 -0
  320. package/dist/transitions/checkStart.js +17 -6
  321. package/dist/transitions/decide.d.ts +1 -1
  322. package/dist/transitions/decide.js +5 -3
  323. package/dist/transitions/deleteExperiment.d.ts +2 -2
  324. package/dist/transitions/deleteExperiment.js +17 -7
  325. package/dist/transitions/kernel.d.ts +4 -0
  326. package/dist/transitions/kernel.js +9 -4
  327. package/dist/transitions/makeContent.d.ts +2 -1
  328. package/dist/transitions/makeContent.js +12 -8
  329. package/dist/transitions/nestedPlacementNames.d.ts +2 -2
  330. package/dist/transitions/nestedPlacementNames.js +4 -5
  331. package/dist/transitions/pageAddress.d.ts +6 -0
  332. package/dist/transitions/pageAddress.js +71 -0
  333. package/dist/transitions/pageVersions.d.ts +1 -1
  334. package/dist/transitions/phaseRecord.d.ts +2 -0
  335. package/dist/transitions/phaseRecord.js +5 -0
  336. package/dist/transitions/placementInteractions.d.ts +3 -3
  337. package/dist/transitions/placementInteractions.js +8 -7
  338. package/dist/transitions/placements.d.ts +2 -0
  339. package/dist/transitions/placements.js +5 -5
  340. package/dist/transitions/preflightData.d.ts +3 -2
  341. package/dist/transitions/preflightData.js +77 -43
  342. package/dist/transitions/releaseHoldout.d.ts +2 -1
  343. package/dist/transitions/releaseHoldout.js +3 -1
  344. package/dist/transitions/releasePages.d.ts +2 -1
  345. package/dist/transitions/releasePages.js +3 -1
  346. package/dist/transitions/resolveCaps.d.ts +2 -4
  347. package/dist/transitions/start.d.ts +7 -9
  348. package/dist/transitions/start.js +75 -39
  349. package/dist/transitions/startReads.d.ts +7 -0
  350. package/dist/transitions/startReads.js +28 -0
  351. package/dist/transitions/stop.d.ts +2 -1
  352. package/dist/transitions/stop.js +3 -2
  353. package/dist/types/armKey.d.ts +2 -0
  354. package/dist/types/armKey.js +1 -0
  355. package/dist/types/contracts.d.ts +17 -4
  356. package/dist/types/endpoints.d.ts +89 -17
  357. package/dist/types/endpoints.js +1 -1
  358. package/dist/types/runtime.d.ts +15 -9
  359. package/dist/types/snapshot.d.ts +2 -0
  360. package/dist/types/surface.d.ts +7 -9
  361. package/dist/ui/ChipsInput.d.ts +8 -1
  362. package/dist/ui/ChipsInput.js +17 -4
  363. package/dist/ui/Dialog.d.ts +21 -2
  364. package/dist/ui/Dialog.js +101 -4
  365. package/dist/ui/Inputs.js +0 -1
  366. package/dist/ui/ui.css +5 -1
  367. package/package.json +2 -2
@@ -0,0 +1,38 @@
1
+ import { routeId } from './routeId.js';
2
+ export async function handleTestVersion(req) {
3
+ const id = routeId(req);
4
+ const headers = {
5
+ 'Cache-Control': 'private, no-store'
6
+ };
7
+ const doc = id === undefined ? null : await req.payload.findByID({
8
+ collection: 'xp-experiments',
9
+ id,
10
+ req,
11
+ overrideAccess: false,
12
+ depth: 0,
13
+ disableErrors: true,
14
+ select: {
15
+ updatedAt: true,
16
+ status: true,
17
+ phase: true
18
+ }
19
+ });
20
+ if (!doc) return Response.json({
21
+ errors: [
22
+ {
23
+ code: 'not-found',
24
+ message: 'Experiment not found'
25
+ }
26
+ ]
27
+ }, {
28
+ status: 404,
29
+ headers
30
+ });
31
+ return Response.json({
32
+ updatedAt: doc.updatedAt,
33
+ status: doc.status,
34
+ phase: doc.phase ?? 0
35
+ }, {
36
+ headers
37
+ });
38
+ }
@@ -33,6 +33,7 @@ async function body(req) {
33
33
  }
34
34
  }
35
35
  const only = (value, keys)=>Object.keys(value).every((key)=>keys.includes(key));
36
+ const validPhase = (phase)=>phase === undefined || typeof phase === 'number' && Number.isSafeInteger(phase) && phase >= 0;
36
37
  async function respond(req, action) {
37
38
  const id = routeId(req);
38
39
  if (id === undefined) return Response.json({
@@ -63,15 +64,18 @@ async function respond(req, action) {
63
64
  }
64
65
  ]
65
66
  }, {
66
- status: cause.status === 409 ? 422 : cause.status
67
+ status: cause.status === 409 && cause.code !== 'round-changed' ? 422 : cause.status
67
68
  });
68
69
  throw cause;
69
70
  }
70
71
  }
71
72
  export async function handleStart(req, ctx) {
72
73
  const value = await body(req);
73
- if (!value || !only(value, [])) return invalidBody();
74
+ if (!value || !only(value, [
75
+ 'phase'
76
+ ]) || !validPhase(value.phase)) return invalidBody();
74
77
  return respond(req, (id)=>start(req, {
78
+ ...value,
75
79
  experimentId: id,
76
80
  options: ctx.options
77
81
  }));
@@ -79,32 +83,34 @@ export async function handleStart(req, ctx) {
79
83
  export async function handleAllocate(req, _ctx) {
80
84
  const value = await body(req);
81
85
  if (!value || !only(value, [
82
- 'allocation'
83
- ]) || typeof value.allocation !== 'number' || !Number.isInteger(value.allocation) || value.allocation < 1 || value.allocation > 100) return invalidBody();
84
- const allocation = value.allocation;
86
+ 'allocation',
87
+ 'phase'
88
+ ]) || !validPhase(value.phase) || typeof value.allocation !== 'number' || !Number.isInteger(value.allocation) || value.allocation < 1 || value.allocation > 100) return invalidBody();
85
89
  return respond(req, (id)=>allocate(req, {
86
- experimentId: id,
87
- allocation
90
+ ...value,
91
+ experimentId: id
88
92
  }));
89
93
  }
90
94
  export async function handleAddMetric(req, ctx) {
91
95
  const value = await body(req);
92
96
  if (!value || !only(value, [
93
97
  'metric',
94
- 'role'
95
- ]) || !(typeof value.metric === 'string' && value.metric.trim() || typeof value.metric === 'number' && Number.isSafeInteger(value.metric)) || value.role !== 'secondary' && value.role !== 'guardrail') return invalidBody();
96
- const metric = value.metric, role = value.role;
98
+ 'role',
99
+ 'phase'
100
+ ]) || !validPhase(value.phase) || !(typeof value.metric === 'string' && value.metric.trim() || typeof value.metric === 'number' && Number.isSafeInteger(value.metric)) || value.role !== 'secondary' && value.role !== 'guardrail') return invalidBody();
97
101
  return respond(req, (id)=>addMetric(req, {
102
+ ...value,
98
103
  experimentId: id,
99
- metric,
100
- role,
101
104
  options: ctx.options
102
105
  }));
103
106
  }
104
107
  export async function handleStop(req, _ctx) {
105
108
  const value = await body(req);
106
- if (!value || !only(value, [])) return invalidBody();
109
+ if (!value || !only(value, [
110
+ 'phase'
111
+ ]) || !validPhase(value.phase)) return invalidBody();
107
112
  return respond(req, (id)=>stop(req, {
113
+ ...value,
108
114
  experimentId: id
109
115
  }));
110
116
  }
@@ -113,35 +119,42 @@ export async function handleDecide(req, _ctx) {
113
119
  if (!value || !only(value, [
114
120
  'winnerArm',
115
121
  'note',
116
- 'confirmation'
117
- ]) || typeof value.winnerArm !== 'string' || value.note !== undefined && typeof value.note !== 'string' || value.confirmation !== undefined && typeof value.confirmation !== 'string') return invalidBody();
118
- const { winnerArm, note, confirmation } = value;
122
+ 'confirmation',
123
+ 'phase'
124
+ ]) || !validPhase(value.phase) || typeof value.winnerArm !== 'string' || value.note !== undefined && typeof value.note !== 'string' || value.confirmation !== undefined && typeof value.confirmation !== 'string') return invalidBody();
119
125
  return respond(req, (id)=>decide(req, {
120
- experimentId: id,
121
- winnerArm,
122
- note,
123
- confirmation
126
+ ...value,
127
+ experimentId: id
124
128
  }));
125
129
  }
126
130
  export async function handleReleaseHoldout(req, _ctx) {
127
131
  const value = await body(req);
128
- if (!value || !only(value, [])) return invalidBody();
132
+ if (!value || !only(value, [
133
+ 'phase'
134
+ ]) || !validPhase(value.phase)) return invalidBody();
129
135
  return respond(req, (id)=>releaseHoldout(req, {
136
+ ...value,
130
137
  experimentId: id
131
138
  }));
132
139
  }
133
140
  export async function handleMakeContent(req, ctx) {
134
141
  const value = await body(req);
135
- if (!value || !only(value, [])) return invalidBody();
142
+ if (!value || !only(value, [
143
+ 'phase'
144
+ ]) || !validPhase(value.phase)) return invalidBody();
136
145
  return respond(req, (id)=>makeContent(req, {
146
+ ...value,
137
147
  experimentId: id,
138
148
  options: ctx.options
139
149
  }));
140
150
  }
141
151
  export async function handleReleasePages(req, _ctx) {
142
152
  const value = await body(req);
143
- if (!value || !only(value, [])) return invalidBody();
153
+ if (!value || !only(value, [
154
+ 'phase'
155
+ ]) || !validPhase(value.phase)) return invalidBody();
144
156
  return respond(req, (id)=>releasePages(req, {
157
+ ...value,
145
158
  experimentId: id
146
159
  }));
147
160
  }
@@ -175,17 +188,16 @@ export async function handleArchive(req, _ctx) {
175
188
  const value = await body(req);
176
189
  if (!value || !only(value, [
177
190
  'mode',
178
- 'confirmation'
179
- ]) || ![
191
+ 'confirmation',
192
+ 'phase'
193
+ ]) || !validPhase(value.phase) || ![
180
194
  'stopped',
181
195
  'after-content',
182
196
  'discard',
183
197
  'hard-coded'
184
198
  ].includes(value.mode) || value.confirmation !== undefined && typeof value.confirmation !== 'string') return invalidBody();
185
- const { mode, confirmation } = value;
186
199
  return respond(req, (id)=>archive(req, {
187
- experimentId: id,
188
- mode,
189
- confirmation
200
+ ...value,
201
+ experimentId: id
190
202
  }));
191
203
  }
package/dist/errors.d.ts CHANGED
@@ -17,6 +17,10 @@ export declare class XpNoTransactionError extends Error {
17
17
  name: string;
18
18
  constructor(message?: string);
19
19
  }
20
+ export declare class XpStartTransactionOpen extends Error {
21
+ name: string;
22
+ constructor();
23
+ }
20
24
  export declare class XpRefusal extends Error {
21
25
  readonly code: RefusalCode;
22
26
  readonly detail: unknown | undefined;
package/dist/errors.js CHANGED
@@ -21,6 +21,12 @@ export class XpNoTransactionError extends Error {
21
21
  super(message);
22
22
  }
23
23
  }
24
+ export class XpStartTransactionOpen extends Error {
25
+ name = 'XpStartTransactionOpen';
26
+ constructor(){
27
+ super('Call startExperiment after your transaction commits.');
28
+ }
29
+ }
24
30
  export class XpRefusal extends Error {
25
31
  code;
26
32
  detail;
@@ -1,3 +1,7 @@
1
1
  import { NextRequest } from 'next/server.js';
2
- /** Browser beacons carry their page URL in Referer. It supplies targeting context only. */
3
- export declare function sourceRequest(request: NextRequest): NextRequest | null;
2
+ export declare function publicEventOrigin(value: string | undefined): string | undefined;
3
+ /** Fetch Metadata wins. For older clients, use only the deployment's configured origin. */
4
+ export declare function eventRequestContext(request: NextRequest, publicOrigin: string | undefined): {
5
+ allowed: boolean;
6
+ source: NextRequest | null;
7
+ };
@@ -1,14 +1,41 @@
1
1
  import { NextRequest } from 'next/server.js';
2
- /** Browser beacons carry their page URL in Referer. It supplies targeting context only. */ export function sourceRequest(request) {
3
- const referrer = request.headers.get('referer');
4
- if (!referrer) return null;
2
+ function webUrl(value) {
3
+ if (!value) return null;
5
4
  try {
6
- const url = new URL(referrer);
7
- if (url.origin !== request.nextUrl.origin) return null;
8
- return new NextRequest(url, {
9
- headers: request.headers
10
- });
5
+ const url = new URL(value);
6
+ return (url.protocol === 'http:' || url.protocol === 'https:') && !url.username && !url.password ? url : null;
11
7
  } catch {
12
8
  return null;
13
9
  }
14
10
  }
11
+ export function publicEventOrigin(value) {
12
+ if (typeof value === 'string' && /^https?:\/\/[^/?#\\\s]+\/?$/i.test(value)) return webUrl(value)?.origin;
13
+ }
14
+ function browserRequestOrigin(request) {
15
+ // Next can construct the URL from its listener address behind a reverse proxy.
16
+ // Use the forwarded authority only to recover page context after Fetch Metadata passed.
17
+ const host = request.headers.get('x-forwarded-host') ?? request.headers.get('host');
18
+ const protocol = request.headers.get('x-forwarded-proto') ?? request.nextUrl.protocol.slice(0, -1);
19
+ if (host && /^[^\s,/?#@\\]+$/.test(host) && (protocol === 'http' || protocol === 'https')) {
20
+ const origin = publicEventOrigin(`${protocol}://${host}`);
21
+ if (origin) return origin;
22
+ }
23
+ return request.nextUrl.origin;
24
+ }
25
+ /** Fetch Metadata wins. For older clients, use only the deployment's configured origin. */ export function eventRequestContext(request, publicOrigin) {
26
+ const site = request.headers.get('sec-fetch-site');
27
+ const origin = request.headers.get('origin');
28
+ const referrer = request.headers.get('referer');
29
+ const page = webUrl(referrer);
30
+ // Same-site can include siblings. None describes direct navigation, not a page beacon.
31
+ const allowed = site !== null ? site === 'same-origin' : origin !== null ? origin === publicOrigin : referrer === null || page !== null && page.origin === publicOrigin;
32
+ const pageOrigin = site === 'same-origin' ? browserRequestOrigin(request) : publicOrigin;
33
+ const senderOrigin = publicEventOrigin(origin ?? undefined);
34
+ const source = allowed && page && page.origin === pageOrigin && (!senderOrigin || senderOrigin === pageOrigin) ? new NextRequest(page, {
35
+ headers: request.headers
36
+ }) : null;
37
+ return {
38
+ allowed,
39
+ source
40
+ };
41
+ }
@@ -4,4 +4,4 @@ import type { ResolvedOptions } from '../types/contracts.js';
4
4
  import type { Manifest } from '../types/manifest.js';
5
5
  export declare function eventRows<TUser extends {
6
6
  id: string | number;
7
- }>(events: unknown[], manifest: Manifest, assignments: AssignmentResult, options: ResolvedOptions<TUser>, visitorId: string, userId: string | undefined, ts: string, requestAttributes?: Readonly<Record<string, unknown>>, clickKeys?: ReadonlySet<string>): EventRow[];
7
+ }>(events: unknown[], manifest: Manifest, assignments: AssignmentResult, options: ResolvedOptions<TUser>, visitorId: string | undefined, userId: string | undefined, ts: string, unitAgeMs: number | 'legacy' | null, requestAttributes?: Readonly<Record<string, unknown>>, clickKeys?: ReadonlySet<string>): EventRow[];
@@ -1,5 +1,7 @@
1
- import { validClickSource, isClickSource } from '../goals/key.js';
1
+ import { isClickSource } from '../goals/key.js';
2
2
  import { exposureDimensions } from './dimensions.js';
3
+ import { browserWritableEvent } from './writable.js';
4
+ import { USER_BROWSER_CONVERSION_PREFIX } from '../constants.js';
3
5
  function record(value) {
4
6
  return value !== null && typeof value === 'object' && !Array.isArray(value);
5
7
  }
@@ -10,8 +12,13 @@ function record(value) {
10
12
  return definition && typeof item === definition.type && (typeof item !== 'number' || Number.isFinite(item)) && (!definition.values || typeof item === 'string' && definition.values.includes(item));
11
13
  }));
12
14
  }
13
- export function eventRows(events, manifest, assignments, options, visitorId, userId, ts, requestAttributes = {}, clickKeys) {
15
+ export function eventRows(events, manifest, assignments, options, visitorId, userId, ts, unitAgeMs, requestAttributes = {}, clickKeys) {
14
16
  const rows = new Map();
17
+ const telemetry = {
18
+ _xp: {
19
+ unitAgeMs
20
+ }
21
+ };
15
22
  for (const event of events){
16
23
  if (!record(event)) continue;
17
24
  let row;
@@ -37,26 +44,35 @@ export function eventRows(events, manifest, assignments, options, visitorId, use
37
44
  userId,
38
45
  ts,
39
46
  dimensions: mismatch ? null : exposureDimensions(requestAttributes, options.events?.dimensions),
47
+ attributes: telemetry,
40
48
  // §5.5 / §11: diagnostics are separate rows, never exposure denominators or multi-arm counts.
41
49
  dedupeKey: mismatch ? `mismatch:${experiment.id}:${experiment.phase}:${unitId}:${ts.slice(0, 10)}` : `exposure:${experiment.id}:${experiment.phase}:${event.arm}:${unitId}:${ts.slice(0, 10)}`
42
50
  };
43
51
  } else if (event.type === 'conversion') {
44
52
  if (typeof event.eventName !== 'string' || typeof event.idempotencyKey !== 'string' || !event.idempotencyKey.trim() || event.value !== undefined && (typeof event.value !== 'number' || !Number.isFinite(event.value))) continue;
45
- const source = options.metricSources?.find((source)=>source.id === event.eventName);
46
53
  const click = isClickSource(event.eventName);
47
- if (click ? !validClickSource(event.eventName) || !clickKeys?.has(event.eventName.slice(6)) : source ? source.clientWritable !== true || source.kind === 'revenue' : !options.eventSources?.some((source)=>source.name === event.eventName && source.clientWritable)) continue;
54
+ if (!browserWritableEvent(event.eventName, options) || click && !clickKeys?.has(event.eventName.slice(6))) continue;
55
+ const unitId = visitorId ?? userId;
56
+ if (!unitId) continue;
48
57
  row = {
49
58
  type: 'conversion',
50
59
  eventName: event.eventName,
51
60
  value: 1,
52
- unitId: visitorId,
53
- unitType: 'visitor',
61
+ unitId,
62
+ unitType: visitorId ? 'visitor' : 'user',
54
63
  userId,
55
64
  ts,
56
65
  dimensions: null,
57
- attributes: click ? undefined : attributes(event.attributes, options.attributeKeys),
66
+ attributes: {
67
+ ...click ? undefined : attributes(event.attributes, options.attributeKeys),
68
+ ...telemetry
69
+ },
58
70
  // §5.5: scoped by unit and event so one client can never pre-claim another's key.
59
- dedupeKey: `conversion:c:${visitorId}:${event.eventName}:${event.idempotencyKey}`
71
+ dedupeKey: visitorId ? `conversion:c:${visitorId}:${event.eventName}:${event.idempotencyKey}` : USER_BROWSER_CONVERSION_PREFIX + JSON.stringify([
72
+ unitId,
73
+ event.eventName,
74
+ event.idempotencyKey
75
+ ])
60
76
  };
61
77
  } else continue;
62
78
  rows.set(row.dedupeKey, row);
@@ -0,0 +1,9 @@
1
+ import type { MetricSource, ResolvedOptions } from '../types/contracts.js';
2
+ type Sources = Pick<ResolvedOptions, 'eventSources'> & {
3
+ metricSources?: ReadonlyArray<Pick<MetricSource, 'id' | 'kind' | 'clientWritable'>>;
4
+ };
5
+ /** Checks source configuration. Ingestion separately checks that the click key exists. */
6
+ export declare function browserWritableEvent(eventName: string, options: Sources): boolean;
7
+ /** Built-in event metrics use the event name after the `events:` prefix. */
8
+ export declare function browserWritableMetric(source: string | undefined, options: Sources): boolean;
9
+ export {};
@@ -0,0 +1,13 @@
1
+ import { validClickSource } from '../goals/key.js';
2
+ /** Checks source configuration. Ingestion separately checks that the click key exists. */ export function browserWritableEvent(eventName, options) {
3
+ if (eventName.startsWith('click:')) return validClickSource(eventName);
4
+ const metric = options.metricSources?.find((source)=>source.id === eventName);
5
+ if (metric) return metric.clientWritable === true && metric.kind !== 'revenue';
6
+ return options.eventSources?.some((source)=>source.name === eventName && source.clientWritable) ?? false;
7
+ }
8
+ /** Built-in event metrics use the event name after the `events:` prefix. */ export function browserWritableMetric(source, options) {
9
+ if (!source) return false;
10
+ if (!source.startsWith('events:')) return browserWritableEvent(source, options);
11
+ const eventName = source.slice(7);
12
+ return options.eventSources?.some((event)=>event.name === eventName) === true && browserWritableEvent(eventName, options);
13
+ }
@@ -2,7 +2,7 @@ export { createExperimentsPlugin } from '../plugin.js';
2
2
  export { defineFlagPoint, defineMetricSource } from '../define.js';
3
3
  export { contentDone } from '../contentDone.js';
4
4
  export { createArmSelectField } from '../fields/armSelect.js';
5
- export type { SerializedFlagPoint, SerializedMetricSource, SerializedAttributeKeys, EditableField, Assignment, Assignments, FlagPointResult, ClientAssignments, RenderedExposure, DocId, PreviewPlacement, Attributes, ExposurePolicy, ExperimentKind, Status, UnitType, ArmKey, ArmKind, TargetingRule, Arm, ParamField, MetricSource, FlagPoint, RateLimiter, ExperimentsAccess, ExperimentsPluginOptions, ExperimentsPageCollection, ArmIssueCode, RefusalCode, ReadinessCode, ErrorEnvelope, TransitionSuccess, AllocateBody, AddMetricBody, AddMetricWarning, AddMetricResult, ClickKeysResult, PagesResult, PlacementStatusResult, PageTestStatus, DeleteImpactResult, DecideBody, ArchiveBody, MakeContentResult, DismissContentEntryBody, DismissContentEntryResult, RestoreContentEntryBody, RestoreContentEntryResult, ContentReport, PreflightResult, PreviewTokenResult, PhaseSummary, ResultsResponse, SummaryResponse, EventBody, FlagDefault, Manifest, ManifestExperiment, ArmSlot, ExperimentRef, ExperimentSlotProps, ExperimentsProxyRuntimeOptions, ExperimentsProxyRuntime, ExperimentsServerRuntimeOptions, ExperimentsServerRuntime, VerdictCode, Snapshot, MetricUnavailableReason, ContentReportReason, } from '../types/index.js';
5
+ export type { SerializedFlagPoint, SerializedMetricSource, SerializedAttributeKeys, EditableField, Assignment, Assignments, FlagPointResult, ClientAssignments, RenderedExposure, DocId, PreviewPlacement, Attributes, ExposurePolicy, ExperimentKind, Status, UnitType, ArmKey, ArmKind, TargetingRule, Arm, ParamField, MetricSource, FlagPoint, RateLimiter, ExperimentsAccess, ExperimentsPluginOptions, ExperimentsPageCollection, ArmIssueCode, RefusalCode, ReadinessCode, ErrorEnvelope, TransitionSuccess, StartExperimentFirstStartDetail, StartExperimentResult, StartExperimentWarning, AllocateBody, AddMetricBody, AddMetricWarning, AddMetricResult, ClickKeysResult, PageRow, PagesResult, CopyPagePlan, CopyPageResult, PlacementStatusResult, PageTestStatus, DeleteImpactResult, RoundBody, DecideBody, ArchiveBody, MakeContentResult, DismissContentEntryBody, DismissContentEntryResult, RestoreContentEntryBody, RestoreContentEntryResult, ContentReport, PreflightResult, PreviewTokenResult, PhaseSummary, ResultsResponse, SummaryResponse, EventBody, FlagDefault, Manifest, ManifestExperiment, ArmSlot, ExperimentRef, ExperimentSlotProps, ExperimentsProxyRuntimeOptions, ExperimentsProxyRuntime, ExperimentsServerRuntimeOptions, ExperimentsServerRuntime, VerdictCode, Snapshot, MetricUnavailableReason, ContentReportReason, } from '../types/index.js';
6
6
  export { createExperimentBlock } from '../blocks/createExperimentBlock.js';
7
7
  export { EXPERIMENT_BLOCK_SLUG } from '../blocks/model.js';
8
8
  export type { HostBlock, ExperimentBlock, ExperimentBlockGroup, ResolvedHostBlock, ResolvedExperimentBlocks } from '../blocks/model.js';
@@ -8,6 +8,7 @@ export { eraseUser } from '../server/eraseUser.js';
8
8
  export type { MetricUnavailableReason, ContentReportReason } from '../types/reasons.js';
9
9
  export type { PreviewPlacement } from '../types/contracts.js';
10
10
  export { runResults } from '../server/runResults.js';
11
+ export { startExperiment } from '../server/startExperiment.js';
11
12
  export { recordContentChange } from '../server/recordContentChange.js';
12
13
  export { experimentSitemapFilter } from '../server/sitemap.js';
13
14
  export { experimentMetadata } from '../server/metadata.js';
@@ -6,6 +6,7 @@ export { linkIdentity } from '../server/linkIdentity.js';
6
6
  export { trackConversion } from '../server/trackConversion.js';
7
7
  export { eraseUser } from '../server/eraseUser.js';
8
8
  export { runResults } from '../server/runResults.js';
9
+ export { startExperiment } from '../server/startExperiment.js';
9
10
  export { recordContentChange } from '../server/recordContentChange.js';
10
11
  export { experimentSitemapFilter } from '../server/sitemap.js';
11
12
  export { experimentMetadata } from '../server/metadata.js';
@@ -135,7 +135,7 @@ function blockLabels(req) {
135
135
  if (!registration) continue;
136
136
  for (const block of hostBlocks(doc[registration.field])){
137
137
  if (block.blockType !== (registration.blockSlug ?? EXPERIMENT_BLOCK_SLUG) || block.experiment !== experiment.slug) continue;
138
- for (const arm of experiment.arms.filter((a)=>a.kind !== 'holdout'))collect(slotBlocks(block, arm.slot ?? arm.key), byArm.get(arm.key), '', labels);
138
+ for (const arm of experiment.arms.filter((a)=>a.kind !== 'holdout'))collect(slotBlocks(block, arm.key), byArm.get(arm.key), '', labels);
139
139
  }
140
140
  } else {
141
141
  const registration = puckCollections(options).find((c)=>c.slug === placement.collection);
@@ -149,7 +149,7 @@ function blockLabels(req) {
149
149
  if (!isObject(value) || visibility.get(value)?.hidden) return;
150
150
  const props = isObject(value.props) ? value.props : undefined;
151
151
  if (value.type === 'ExperimentSlot' && props && puckExperimentSlug(props.experiment) === experiment.slug) {
152
- for (const arm of experiment.arms.filter((a)=>a.kind !== 'holdout'))collect(props[arm.slot ?? arm.key], byArm.get(arm.key), '', labels, visibility);
152
+ for (const arm of experiment.arms.filter((a)=>a.kind !== 'holdout'))collect(props[arm.key], byArm.get(arm.key), '', labels, visibility);
153
153
  return;
154
154
  }
155
155
  Object.values(value).forEach(walk);
@@ -19,6 +19,6 @@
19
19
  export function puckGoalRefusal(rawKey, block, malformed, more = 0) {
20
20
  // A malformed key can be any length; keep the dialog readable.
21
21
  const key = rawKey.length > 64 ? `${rawKey.slice(0, 64)}…` : rawKey;
22
- const sentence = malformed ? `Click goal "${key}" on the ${block} block isn't a valid short name. Use lowercase letters, numbers, - and _, then publish.` : `Click goal "${key}" doesn't exist yet. Create it with "+ New click goal" on the ${block} block, then publish.`;
22
+ const sentence = malformed ? `Click goal "${key}" on the ${block} block isn't a valid short name. Use lowercase letters, numbers, - and _.` : `Click goal "${key}" doesn't exist yet. Create it with "+ New click goal" on the ${block} block.`;
23
23
  return sentence + (more > 0 ? ` (and ${more} more)` : '');
24
24
  }
@@ -0,0 +1,2 @@
1
+ /** Present unlabelled source keys in sentence case. */
2
+ export declare function goalSourceLabel(key: string): string;
@@ -0,0 +1,4 @@
1
+ /** Present unlabelled source keys in sentence case. */ export function goalSourceLabel(key) {
2
+ const words = key.replace(/^(?:events|click):/, '').replace(/[-_]+/g, ' ').trim().toLowerCase();
3
+ return words.charAt(0).toUpperCase() + words.slice(1);
4
+ }
@@ -4,7 +4,9 @@ import { safeError } from '../log.js';
4
4
  try {
5
5
  return await hook(args);
6
6
  } catch (error) {
7
- console.error(`[payload-experiments] ${name} failed; the document was saved without it`, safeError(error));
7
+ try {
8
+ console.error(`[payload-experiments] ${name} failed; the document was saved without it`, safeError(error));
9
+ } catch {}
8
10
  return args.doc;
9
11
  }
10
12
  };
@@ -14,7 +16,9 @@ import { safeError } from '../log.js';
14
16
  try {
15
17
  return await hook(args);
16
18
  } catch (error) {
17
- console.error(`[payload-experiments] ${name} failed; the document was saved without it`, safeError(error));
19
+ try {
20
+ console.error(`[payload-experiments] ${name} failed; the document was saved without it`, safeError(error));
21
+ } catch {}
18
22
  return args.data;
19
23
  }
20
24
  };
@@ -1,6 +1,7 @@
1
1
  import { refuseNewNestedTests } from './puckNestedTests.js';
2
2
  import { hasLocalizedFields } from '../transitions/contentFields.js';
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
+ import { assertReadCommitted } from '../db/adapter.js';
4
5
  import { previousPublishedContent, storedContent, placementWriteContent } from '../db/appends.js';
5
6
  import { lockPlacementScope, sortLockKeys } from '../db/locks.js';
6
7
  import { txExecutor, pooledExecutor } from '../db/executor.js';
@@ -242,6 +243,7 @@ export const pageGuardBeforeDelete = async ({ req, id, collection })=>{
242
243
  if (!page) {
243
244
  if (!affected.length) return;
244
245
  if (await req.transactionID != null) {
246
+ await assertReadCommitted(req);
245
247
  await lockPlacementScope(exec, guardExperimentIds([], [], collection.slug, [], req.context.xpHeldExperiments, new Set(), affected.map((test)=>test.id)), []);
246
248
  tests = (await removableBlockTests(exec, affected.map((test)=>test.slug))).map((test)=>({
247
249
  ...test,
@@ -249,6 +251,7 @@ export const pageGuardBeforeDelete = async ({ req, id, collection })=>{
249
251
  }));
250
252
  } else tests = affected;
251
253
  } else if (await req.transactionID != null) {
254
+ await assertReadCommitted(req);
252
255
  await lockPlacementScope(exec, guardExperimentIds(tests, allPlacementSlugs(req, collection.slug, published, 'all-locales'), collection.slug, paths, req.context.xpHeldExperiments, taggedIds(published), affected.map((test)=>test.id)), paths);
253
256
  tests = await placementTests(exec);
254
257
  }
@@ -306,6 +309,7 @@ export const pageGuardBeforeChange = async ({ req, collection, originalDoc, oper
306
309
  if (await req.transactionID == null) noTransaction();
307
310
  else {
308
311
  try {
312
+ await assertReadCommitted(req);
309
313
  await lockPlacementScope(exec, guardExperimentIds(tests, [
310
314
  ...beforeSlugs,
311
315
  ...afterSlugs
@@ -0,0 +1,11 @@
1
+ import type { CollectionAfterChangeHook } from 'payload';
2
+ import type { DocId } from '../types/contracts.js';
3
+ declare module 'payload' {
4
+ interface RequestContext {
5
+ xpDuplicate?: {
6
+ collection: string;
7
+ created: DocId[];
8
+ };
9
+ }
10
+ }
11
+ export declare const trackPageCopies: CollectionAfterChangeHook;
@@ -0,0 +1,7 @@
1
+ export const trackPageCopies = ({ collection, context, operation, doc })=>{
2
+ const tracking = context.xpDuplicate;
3
+ if (operation === 'create' && tracking?.collection === collection.slug) {
4
+ tracking.created.push(doc.id);
5
+ }
6
+ return doc;
7
+ };
@@ -5,3 +5,6 @@ export declare const ARM_LABELS: {
5
5
  readonly variantC: "Variant C";
6
6
  readonly holdout: "Holdout";
7
7
  };
8
+ export declare function controlVersionLabel(label?: string): string;
9
+ /** Use an article with the default name and capitalize the phrase at sentence start. */
10
+ export declare function controlVersionName(label?: string, sentenceStart?: boolean): string;
@@ -5,3 +5,11 @@ export const ARM_LABELS = {
5
5
  variantC: 'Variant C',
6
6
  holdout: 'Holdout'
7
7
  };
8
+ export function controlVersionLabel(label) {
9
+ return typeof label === 'string' && label.trim() || ARM_LABELS.control;
10
+ }
11
+ /** Use an article with the default name and capitalize the phrase at sentence start. */ export function controlVersionName(label, sentenceStart = false) {
12
+ const name = controlVersionLabel(label);
13
+ if (name.toLowerCase() === ARM_LABELS.control.toLowerCase()) return `${sentenceStart ? 'The' : 'the'} ${name}`;
14
+ return sentenceStart ? name.replace(/\p{L}/u, (letter)=>letter.toUpperCase()) : name;
15
+ }
@@ -13,4 +13,4 @@ export declare class DocsResponseError extends Error {
13
13
  /** Read every Payload REST page with the caller's credentials and cancellation. Transport,
14
14
  * invalid successful responses and aborts throw; HTTP refusals retain their status/body. Keeps the first document per id; refuses
15
15
  * incomplete lists after 1000 pages with page-limit-exceeded. */
16
- export declare function fetchAllDocs<T>(url: string, options?: Pick<RequestInit, 'credentials' | 'signal'>): Promise<DocsResult<T>>;
16
+ export declare function fetchAllDocs<T>(url: string, options?: Pick<RequestInit, 'cache' | 'credentials' | 'signal'>): Promise<DocsResult<T>>;
@@ -137,7 +137,7 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
137
137
  const testPhase = experiment.lastTestPhase ?? (phase?.phaseKind === 'test' ? phase : null);
138
138
  if (!testPhase) throw new XpRefusal('invalid-status', `Missing last test phase for experiment ${experiment.slug}`, undefined, 409);
139
139
  const winner = testPhase.arms.find((arm)=>arm.key === decision.winnerArm);
140
- if (experiment.kind === 'block' && winner?.slot) manifest.archivedWinners[experiment.slug] = winner.slot;
140
+ if (experiment.kind === 'block' && winner && winner.kind !== 'holdout' && winner.key !== 'holdout') manifest.archivedWinners[experiment.slug] = winner.key;
141
141
  if (experiment.kind === 'page' && winner?.pageTarget) {
142
142
  for (const arm of testPhase.arms){
143
143
  if (arm.pageTarget && arm.pageTarget !== winner.pageTarget) {
@@ -189,12 +189,14 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
189
189
  phaseKind: rollout ? 'rollout' : 'test',
190
190
  seed: phase.seed,
191
191
  coverage: layer || experiment.status === 'decided' && !rollout ? 1 : phase.allocation / 100,
192
- arms: (phase.phaseKind === 'rollout' ? experiment.lastTestPhase?.arms ?? phase.arms : phase.arms).map(({ key, kind, weight, slot, pageTarget, params })=>({
192
+ arms: (phase.phaseKind === 'rollout' ? experiment.lastTestPhase?.arms ?? phase.arms : phase.arms).map(({ key, kind, weight, slot, pageTarget, params })=>{
193
+ const contentSlot = experiment.kind === 'block' ? kind !== 'holdout' && key !== 'holdout' ? key : undefined : slot;
194
+ return {
193
195
  key,
194
196
  kind,
195
197
  weight,
196
- ...slot != null ? {
197
- slot
198
+ ...contentSlot != null ? {
199
+ slot: contentSlot
198
200
  } : {},
199
201
  ...pageTarget != null ? {
200
202
  pageTarget
@@ -202,7 +204,8 @@ export async function loadManifestInputs(req, { excludeIds = [], pruneFlagDefaul
202
204
  ...params != null ? {
203
205
  params
204
206
  } : {}
205
- })),
207
+ };
208
+ }),
206
209
  targeting,
207
210
  exposurePolicy: experiment.exposurePolicy,
208
211
  deferrable: targeting.some((rule)=>rule.attribute === 'loggedIn' || rule.attribute === 'staff'),
package/dist/onInit.js CHANGED
@@ -6,6 +6,10 @@ import { contentBlocks } from './transitions/contentFields.js';
6
6
  import { validateDimensions } from './events/dimensions.js';
7
7
  import { assertPostgresAdapter, probeTransactions } from './db/adapter.js';
8
8
  import { hasHostAttributesOf } from './server/serverRuntime.js';
9
+ import { assertSigningSecrets } from './runtime/signing.js';
10
+ import { assertUnitRateLimit } from './runtime/proxyRuntime.js';
11
+ import { assertCookieOptions } from './runtime/cookieOptions.js';
12
+ import { publicEventOrigin } from './events/request.js';
9
13
  // Diagnostic only: named containers are never accepted by the top-level readers.
10
14
  function registeredPaths(fields, name, parent = []) {
11
15
  return fields.flatMap((field)=>{
@@ -25,6 +29,13 @@ function registeredPaths(fields, name, parent = []) {
25
29
  }
26
30
  export function createOnInit(options) {
27
31
  return async (payload)=>{
32
+ const rateLimit = options.events?.rateLimit;
33
+ if (rateLimit !== false && typeof rateLimit !== 'function') {
34
+ throw new Error('Experiments requires events.rateLimit to be a client-address rate limiter, or false if you rate-limit the events route upstream.');
35
+ }
36
+ assertSigningSecrets(options.runtime.proxyRuntime.secrets);
37
+ assertUnitRateLimit(options.runtime.proxyRuntime.rateLimitUnit);
38
+ assertCookieOptions(options.runtime.proxyRuntime.cookie);
28
39
  const guarded = new Set([
29
40
  ...options.puck?.enabled ? puckCollections(options).map((c)=>c.slug) : [],
30
41
  ...(options.blocks?.collections ?? []).map((c)=>c.slug),
@@ -60,5 +71,8 @@ export function createOnInit(options) {
60
71
  if (Object.hasOwn(options.attributeKeys ?? {}, 'staff') && !hasHostAttributesOf(options.runtime)) {
61
72
  throw new Error('`staff` is declared in attributeKeys, so pass an `attributesOf` that identifies staff to defineExperimentsServerRuntime');
62
73
  }
74
+ if (!options.events.origin && !publicEventOrigin(payload.config.serverURL)) {
75
+ payload.logger.warn('Experiments: set events.origin or Payload serverURL to your public HTTP(S) origin without a path. Until then, browser events with Origin or Referer and without Fetch Metadata are dropped.');
76
+ }
63
77
  };
64
78
  }
package/dist/options.d.ts CHANGED
@@ -9,3 +9,5 @@ export declare function resolveOptions<TUser extends {
9
9
  }>(input: ExperimentsPluginOptions<TUser>): ResolvedOptions<TUser>;
10
10
  /** One published-row rule shared by scans, bindings, writes and editor links. */
11
11
  export declare function documentEditor(options: Pick<ExperimentsPluginOptions, 'puck' | 'blocks'>, collection: string, doc: Record<string, unknown>): 'puck' | 'blocks' | 'page';
12
+ export declare function hasPuckEditor(options: Pick<ExperimentsPluginOptions, 'puck'>, collection: string): boolean;
13
+ export declare function blockPageSlugs(options: Pick<ExperimentsPluginOptions, 'puck' | 'blocks'>): string[];