@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,414 @@
1
+ import { Forbidden, ValidationError } from 'payload';
2
+ import { flattenTopLevelFields, formatAdminURL } from 'payload/shared';
3
+ import { placementReader } from '../blocks/placementLocale.js';
4
+ import { XP_IF_UPDATED_AT_HEADER } from '../constants.js';
5
+ import { collectionLabel } from '../collections/labels.js';
6
+ import { transactionSession } from '../db/executor.js';
7
+ import { lockPagePaths } from '../db/locks.js';
8
+ import { committedPageCopyIds } from '../db/pageCopies.js';
9
+ import { lockExperimentUpdatedAt } from '../db/staleEdit.js';
10
+ import { currentTxid } from '../db/txid.js';
11
+ import { XpRefusal } from '../errors.js';
12
+ import { safeError } from '../log.js';
13
+ import { normalisePath } from '../runtime/normalisePath.js';
14
+ import { orphanedPages, PAGE_COPY } from '../testSurface/copy/pages.js';
15
+ import { contentBlocks, hasLocalizedFields } from '../transitions/contentFields.js';
16
+ import { withTransition } from '../transitions/kernel.js';
17
+ import { PAGE_ADDRESS_FIELDS as addressFields } from '../transitions/pageAddress.js';
18
+ import { resolvePageCollection } from '../transitions/pageCollection.js';
19
+ import { requireCurrentRound } from '../transitions/phaseRecord.js';
20
+ import { readBody } from './readBody.js';
21
+ import { routeId } from './routeId.js';
22
+ import { relationshipId } from '../transitions/checkStart.js';
23
+ const homeFields = [
24
+ 'isHomepage',
25
+ 'homepage',
26
+ 'isHomePage'
27
+ ];
28
+ const invalid = ()=>new XpRefusal('invalid-body', PAGE_COPY.copyUnavailable, undefined, 422);
29
+ const refused = (message = PAGE_COPY.copyUnavailable)=>new XpRefusal('copy-unavailable', message, undefined, 422);
30
+ const transactionLost = ()=>new XpRefusal('transaction-lost', PAGE_COPY.copyTransactionLost, undefined, 500);
31
+ const stale = (label)=>new XpRefusal('stale-edit', PAGE_COPY.copyChanged(label), undefined, 409);
32
+ const response = (value)=>Response.json(value, {
33
+ headers: {
34
+ 'Cache-Control': 'private, no-store'
35
+ }
36
+ });
37
+ async function readTest(req, id) {
38
+ const doc = await req.payload.findByID({
39
+ collection: 'xp-experiments',
40
+ id,
41
+ req,
42
+ overrideAccess: false,
43
+ depth: 0,
44
+ disableErrors: true
45
+ });
46
+ if (!doc) throw new XpRefusal('not-found', PAGE_COPY.copyChanged(), undefined, 404);
47
+ return doc;
48
+ }
49
+ /** Payload's duplicate hydrates source fields with overrideAccess internally. */ function hasProtectedFields(fields, config, seen = new Set()) {
50
+ return fields.some((field)=>{
51
+ if (seen.has(field) || 'disableDuplicate' in field && field.disableDuplicate) return false;
52
+ seen.add(field);
53
+ return Boolean('access' in field && field.access?.read || 'fields' in field && hasProtectedFields(field.fields, config, seen) || field.type === 'tabs' && field.tabs.some((tab)=>tab.access?.read || hasProtectedFields(tab.fields, config, seen)) || field.type === 'blocks' && contentBlocks(field, config.blocks).some((block)=>hasProtectedFields(block.fields, config, seen)));
54
+ });
55
+ }
56
+ async function readOriginal(req, collection, id, label) {
57
+ const read = (draft)=>req.payload.findByID({
58
+ collection,
59
+ id,
60
+ draft,
61
+ depth: 0,
62
+ req,
63
+ overrideAccess: false,
64
+ disableErrors: true
65
+ });
66
+ const published = await read(false);
67
+ const latest = await read(true);
68
+ if (!published || published._status !== 'published' || !latest || latest._status !== 'published' || typeof published.updatedAt !== 'string' || published.updatedAt !== latest.updatedAt) throw refused(PAGE_COPY.copyOriginal(label));
69
+ return published;
70
+ }
71
+ export async function preparePageCopy(req, options, test, key, confirmed) {
72
+ const arms = test.arms ?? [];
73
+ const control = arms.find((arm)=>arm.kind === 'control');
74
+ if (confirmed) {
75
+ if (confirmed.updatedAt !== test.updatedAt) throw stale(control?.label);
76
+ }
77
+ if (test.kind !== 'page' || ![
78
+ 'draft',
79
+ 'stopped'
80
+ ].includes(test.status)) throw stale(control?.label);
81
+ const arm = arms.find((arm)=>arm.key === key && arm.kind === 'variant');
82
+ if (!arm || arm.pageTarget) throw stale(control?.label);
83
+ const originalPath = control?.pageTarget;
84
+ const entry = await resolvePageCollection(req, options, {
85
+ pageCollection: test.pageCollection,
86
+ arms
87
+ }, true);
88
+ if (!entry?.copy) throw new XpRefusal('copy-not-enabled', PAGE_COPY.copyNotEnabled, undefined, 422);
89
+ if (!originalPath) throw refused(PAGE_COPY.copyChooseOriginal(control?.label));
90
+ const overridesFor = entry.copy === true ? undefined : entry.copy.overrides;
91
+ const config = req.payload.collections[entry.slug]?.config;
92
+ if (!config || config.upload || config.timestamps === false) throw refused();
93
+ if (hasProtectedFields(config.fields, req.payload.config)) throw refused(PAGE_COPY.copyProtected);
94
+ if (config.disableDuplicate) throw refused(PAGE_COPY.copyDisabled);
95
+ if (!config.versions?.drafts) throw refused(PAGE_COPY.copyNoDrafts);
96
+ if (hasLocalizedFields(config.fields, req.payload.config)) throw refused(PAGE_COPY.copyLocalized(control?.label));
97
+ const match = await entry.findByPath(originalPath, req);
98
+ if (!match?.published) throw refused(PAGE_COPY.copyOriginal(control?.label));
99
+ const original = await readOriginal(req, entry.slug, match.id, control?.label);
100
+ const sourcePath = entry.pathOf(original);
101
+ if (!sourcePath || normalisePath(sourcePath) !== normalisePath(originalPath)) throw refused(PAGE_COPY.copyOriginal(control?.label));
102
+ const reader = placementReader(req, entry.slug, options);
103
+ if (reader.read(original, 'localized').slugs.length) throw refused(PAGE_COPY.copyEmbeddedTest(control?.label));
104
+ const fields = flattenTopLevelFields(config.fields);
105
+ const useAsTitle = config.admin.useAsTitle;
106
+ const titleField = typeof useAsTitle === 'string' && !addressFields.includes(useAsTitle) && useAsTitle !== 'id' ? useAsTitle : 'title';
107
+ const homeFlags = fields.flatMap((field)=>field.type === 'checkbox' && typeof field.name === 'string' && homeFields.includes(field.name) ? [
108
+ field.name
109
+ ] : []);
110
+ const requiredUniqueFields = fields.flatMap((field)=>typeof field.name === 'string' && 'unique' in field && field.unique && 'required' in field && field.required ? [
111
+ field.name
112
+ ] : []);
113
+ const hasSlugHistory = fields.some((field)=>field.name === 'slugHistory' && (field.type === 'array' || field.type === 'json'));
114
+ const position = arms.filter((arm)=>arm.kind === 'variant').indexOf(arm);
115
+ const suffix = `-variant-${String.fromCharCode(97 + position)}`;
116
+ const base = normalisePath(originalPath);
117
+ const rootName = addressFields.map((name)=>original[name]).find((value)=>typeof value === 'string' && /^\/?[a-z0-9][a-z0-9_-]*(\/[a-z0-9][a-z0-9_-]*)*\/?$/i.test(value));
118
+ const pathBase = base === '/' ? `/${rootName?.replace(/^\/+|\/+$/g, '') ?? 'home'}` : base;
119
+ const used = new Set(arms.flatMap((item)=>item.pageTarget ? [
120
+ normalisePath(item.pageTarget)
121
+ ] : []));
122
+ for(let attempt = 1; attempt <= 30; attempt++){
123
+ const ending = attempt === 1 ? suffix : `${suffix}-${attempt}`;
124
+ const path = pathBase + ending;
125
+ if (confirmed && path !== confirmed.path || used.has(path)) continue;
126
+ const data = Object.fromEntries(homeFlags.map((name)=>[
127
+ name,
128
+ false
129
+ ]));
130
+ if (hasSlugHistory) data.slugHistory = [];
131
+ if (typeof original[titleField] === 'string') data[titleField] = original[titleField];
132
+ for (const field of fields){
133
+ if (field.type !== 'text' || field.virtual || !addressFields.includes(field.name)) continue;
134
+ const value = original[field.name];
135
+ if (typeof value !== 'string' || !value.trim() || value === '/') {
136
+ data[field.name] = field.name === 'path' ? path : field.name === 'pageSegment' ? path.split('/').at(-1) : path.slice(1);
137
+ } else if (field.name === 'pageSegment' || base === '/' || base.endsWith(normalisePath('/' + value.replace(/^\/+/, '')))) {
138
+ data[field.name] = normalisePath(value) + ending;
139
+ }
140
+ }
141
+ if (overridesFor) {
142
+ const overrides = await overridesFor({
143
+ ...original
144
+ }, {
145
+ req,
146
+ path,
147
+ suffix: ending
148
+ });
149
+ if (overrides === null) throw refused();
150
+ Object.assign(data, overrides);
151
+ }
152
+ const proposed = {
153
+ ...original,
154
+ ...data
155
+ };
156
+ const projectedPath = entry.pathOf(proposed);
157
+ if (projectedPath === null || normalisePath(projectedPath) !== path || !path.startsWith('/') || path.startsWith('//') || /[?#\\\s]/.test(path) || homeFlags.some((name)=>proposed[name] !== false)) throw refused(PAGE_COPY.copyAddress);
158
+ // A checked read cannot see a hidden page. Require the inferred address to
159
+ // depend on a unique field, so the insert also checks hidden and racing rows.
160
+ if (!overridesFor && !fields.some((field)=>field.type === 'text' && field.unique && typeof data[field.name] === 'string' && addressFields.includes(field.name) && entry.pathOf({
161
+ ...proposed,
162
+ [field.name]: original[field.name]
163
+ }) !== projectedPath)) throw refused(PAGE_COPY.copyAddress);
164
+ const rawTitle = proposed[titleField];
165
+ const title = typeof rawTitle === 'string' && rawTitle.trim() ? rawTitle : path;
166
+ const addressQueries = fields.flatMap((field)=>field.type === 'text' && !field.virtual && addressFields.includes(field.name) && (field.name !== 'pageSegment' || field.unique) && typeof data[field.name] === 'string' ? [
167
+ {
168
+ [field.name]: {
169
+ equals: data[field.name]
170
+ }
171
+ }
172
+ ] : []);
173
+ // findByPath can report an occupied published address even when the latest draft changed it.
174
+ if (await entry.findByPath(path, req)) continue;
175
+ if (addressQueries.length) {
176
+ const occupied = (draft)=>req.payload.find({
177
+ collection: entry.slug,
178
+ req,
179
+ overrideAccess: false,
180
+ draft,
181
+ depth: 0,
182
+ limit: 1,
183
+ pagination: false,
184
+ where: {
185
+ or: addressQueries
186
+ }
187
+ });
188
+ if ((await occupied(false)).docs.length || (await occupied(true)).docs.length) continue;
189
+ }
190
+ const plan = {
191
+ title,
192
+ path,
193
+ phase: test.phase,
194
+ updatedAt: test.updatedAt,
195
+ originalId: original.id,
196
+ originalUpdatedAt: original.updatedAt
197
+ };
198
+ if (confirmed && (title !== confirmed.title || String(plan.originalId) !== String(confirmed.originalId) || plan.originalUpdatedAt !== confirmed.originalUpdatedAt)) throw stale(control?.label);
199
+ return {
200
+ plan,
201
+ data,
202
+ entry,
203
+ titleField,
204
+ homeFlags,
205
+ hasSlugHistory,
206
+ requiredUniqueFields,
207
+ original,
208
+ arms,
209
+ reader
210
+ };
211
+ }
212
+ if (confirmed) throw stale(control?.label);
213
+ throw refused(PAGE_COPY.copyAddress);
214
+ }
215
+ async function reportOrphanedCopies(req, entry, ids, titleField) {
216
+ const committed = await committedPageCopyIds(req.payload, entry.slug, ids);
217
+ if (!committed.length) return;
218
+ const pages = await Promise.all(committed.map(async (id)=>{
219
+ try {
220
+ const page = await req.payload.findByID({
221
+ collection: entry.slug,
222
+ id,
223
+ req,
224
+ overrideAccess: false,
225
+ draft: false,
226
+ depth: 0,
227
+ disableErrors: true
228
+ });
229
+ if (page) {
230
+ const title = page[titleField];
231
+ const path = entry.pathOf(page);
232
+ return {
233
+ id,
234
+ ...typeof title === 'string' && title.trim() ? {
235
+ title
236
+ } : {},
237
+ path
238
+ };
239
+ }
240
+ } catch (cause) {
241
+ req.payload.logger.warn({
242
+ err: safeError(cause),
243
+ collection: entry.slug,
244
+ id
245
+ }, 'Could not read a committed test page copy');
246
+ }
247
+ return {
248
+ id,
249
+ path: null
250
+ };
251
+ }));
252
+ const label = collectionLabel(req.payload.collections[entry.slug]?.config.labels.plural, entry.slug, req);
253
+ throw new XpRefusal('copy-orphaned', orphanedPages(pages, label), {
254
+ collection: entry.slug,
255
+ pages
256
+ }, 500);
257
+ }
258
+ async function confirmBody(req) {
259
+ const value = await readBody(req).catch(()=>null);
260
+ if (!value || typeof value.arm !== 'string' || !Number.isSafeInteger(value.phase) || typeof value.path !== 'string' || typeof value.title !== 'string' || typeof value.updatedAt !== 'string' || !Number.isFinite(Date.parse(value.updatedAt)) || typeof value.originalUpdatedAt !== 'string' || !(typeof value.originalId === 'number' || typeof value.originalId === 'string') || req.headers.get(XP_IF_UPDATED_AT_HEADER) !== value.updatedAt) throw invalid();
261
+ return value;
262
+ }
263
+ export async function handleDuplicateOriginal(req, { options }) {
264
+ const id = routeId(req);
265
+ if (id === undefined) throw invalid();
266
+ let controlLabel;
267
+ const readCopyTest = async ()=>{
268
+ const test = await readTest(req, id);
269
+ controlLabel = test.arms?.find((arm)=>arm.kind === 'control')?.label;
270
+ return test;
271
+ };
272
+ try {
273
+ if (req.method === 'GET') {
274
+ const arm = new URL(req.url ?? 'http://xp.invalid').searchParams.get('arm');
275
+ if (!arm) throw invalid();
276
+ const { plan } = await preparePageCopy(req, options, await readCopyTest(), arm);
277
+ return response(plan);
278
+ }
279
+ const confirmed = await confirmBody(req);
280
+ const before = await readCopyTest();
281
+ const { result } = await withTransition(req, {
282
+ experimentId: id,
283
+ layerId: relationshipId(before.layer),
284
+ bump: false,
285
+ edit: true,
286
+ requireOwnedTransaction: true
287
+ }, async ({ exec })=>{
288
+ const transactionId = await req.transactionID;
289
+ const xid = await currentTxid(exec);
290
+ const isLive = async ()=>await req.transactionID === transactionId && await transactionSession(req).then(()=>currentTxid(exec)).catch(()=>undefined) === xid;
291
+ const test = await readCopyTest();
292
+ requireCurrentRound(confirmed.phase, test.phase);
293
+ await lockPagePaths(exec, [
294
+ confirmed.path
295
+ ]);
296
+ const updatedAt = await lockExperimentUpdatedAt(exec, id);
297
+ if (updatedAt === null || new Date(updatedAt).getTime() !== Date.parse(confirmed.updatedAt)) throw stale(controlLabel);
298
+ const { plan, data, entry, titleField, homeFlags, hasSlugHistory, requiredUniqueFields, original, arms, reader } = await preparePageCopy(req, options, test, confirmed.arm, confirmed);
299
+ if (!await isLive()) throw transactionLost();
300
+ const previous = req.context.xpDuplicate;
301
+ const tracking = {
302
+ collection: entry.slug,
303
+ created: []
304
+ };
305
+ req.context.xpDuplicate = tracking;
306
+ let created;
307
+ try {
308
+ created = await req.payload.duplicate({
309
+ collection: entry.slug,
310
+ id: original.id,
311
+ req,
312
+ overrideAccess: false,
313
+ draft: true,
314
+ depth: 0,
315
+ data
316
+ });
317
+ } catch (cause) {
318
+ await reportOrphanedCopies(req, entry, tracking.created, titleField);
319
+ if (cause instanceof Forbidden) throw new XpRefusal('copy-no-access', PAGE_COPY.copyNoAccess, undefined, 422);
320
+ if (cause instanceof ValidationError && cause.data?.errors.some((error)=>error.message === (req.t?.('error:valueMustBeUnique') ?? 'Value must be unique'))) {
321
+ throw new XpRefusal('copy-unique-field', PAGE_COPY.copyUnique, undefined, 422);
322
+ }
323
+ throw cause;
324
+ } finally{
325
+ if (previous === undefined) delete req.context.xpDuplicate;
326
+ else req.context.xpDuplicate = previous;
327
+ }
328
+ if (!await isLive()) {
329
+ await reportOrphanedCopies(req, entry, [
330
+ ...tracking.created,
331
+ created.id
332
+ ], titleField);
333
+ throw transactionLost();
334
+ }
335
+ // Read the main row as the manager. A host hook can replace the title,
336
+ // address or status during Create, so verify before linking the copy.
337
+ const copy = await req.payload.findByID({
338
+ collection: entry.slug,
339
+ id: created.id,
340
+ req,
341
+ overrideAccess: false,
342
+ draft: false,
343
+ depth: 0,
344
+ disableErrors: true
345
+ });
346
+ const copyPath = copy && entry.pathOf(copy);
347
+ const rawTitle = copy?.[titleField];
348
+ const copyTitle = typeof rawTitle === 'string' && rawTitle.trim() ? rawTitle : plan.path;
349
+ if (!copy || copy._status !== 'draft' || !copyPath || normalisePath(copyPath) !== plan.path || copyTitle !== plan.title || homeFlags.some((name)=>copy[name] !== false) || hasSlugHistory && (!Array.isArray(copy.slugHistory) || copy.slugHistory.length > 0) || reader.read(copy, 'localized').slugs.length) throw refused();
350
+ if (requiredUniqueFields.some((name)=>copy[name] == null || copy[name] === '')) throw refused();
351
+ if ((await readOriginal(req, entry.slug, original.id, controlLabel)).updatedAt !== original.updatedAt) throw stale(controlLabel);
352
+ const occupant = await entry.findByPath(plan.path, req);
353
+ if (occupant && (occupant.published || String(occupant.id) !== String(copy.id))) throw refused(PAGE_COPY.copyAddress);
354
+ if (!await isLive()) throw transactionLost();
355
+ const doc = await req.payload.update({
356
+ collection: 'xp-experiments',
357
+ id,
358
+ req,
359
+ overrideAccess: false,
360
+ depth: 0,
361
+ data: {
362
+ arms: arms.map((arm)=>arm.key === confirmed.arm ? {
363
+ ...arm,
364
+ pageTarget: copyPath
365
+ } : arm)
366
+ }
367
+ });
368
+ if (!await isLive()) throw transactionLost();
369
+ return {
370
+ doc,
371
+ copy,
372
+ collection: entry.slug,
373
+ path: copyPath,
374
+ title: plan.title
375
+ };
376
+ });
377
+ const { copy, collection, path, title, doc } = result;
378
+ let editorUrl = formatAdminURL({
379
+ adminRoute: req.payload.config.routes.admin,
380
+ path: `/collections/${collection}/${encodeURIComponent(String(copy.id))}`
381
+ });
382
+ try {
383
+ editorUrl = options.admin?.editorUrl?.({
384
+ collection,
385
+ id: copy.id,
386
+ draft: true,
387
+ editor: 'page',
388
+ doc: copy
389
+ }) || editorUrl;
390
+ } catch (cause) {
391
+ req.payload.logger.warn({
392
+ err: safeError(cause),
393
+ collection
394
+ }, 'Could not open the copied test page in its custom editor');
395
+ }
396
+ return response({
397
+ doc,
398
+ copy: {
399
+ id: copy.id,
400
+ title,
401
+ path,
402
+ editorUrl
403
+ }
404
+ });
405
+ } catch (cause) {
406
+ if (cause instanceof XpRefusal) throw cause;
407
+ if (cause instanceof Forbidden) throw refused(PAGE_COPY.copyOriginal(controlLabel));
408
+ req.payload.logger.warn({
409
+ err: safeError(cause),
410
+ experimentId: id
411
+ }, 'Could not make a test page copy');
412
+ throw refused();
413
+ }
414
+ }
@@ -22,7 +22,7 @@ import { buildSurfaceProps } from '../admin/views/buildSurfaceProps.js';
22
22
  'Cache-Control': 'private, no-store'
23
23
  }
24
24
  });
25
- const { route: _route, id: _id, pages: _pages, returnToTest: _return, ...surface } = props;
25
+ const { route: _route, id: _id, returnToTest: _return, ...surface } = props;
26
26
  return Response.json(surface, {
27
27
  headers: {
28
28
  'Cache-Control': 'private, no-store'
@@ -7,90 +7,154 @@ import { pooledExecutor } from '../db/executor.js';
7
7
  import { insertEvents } from '../db/events.js';
8
8
  import { EventsBodyError, readEvents } from '../events/body.js';
9
9
  import { isPreview } from '../events/preview.js';
10
- import { sourceRequest } from '../events/request.js';
10
+ import { eventRequestContext, publicEventOrigin } from '../events/request.js';
11
11
  import { eventRows } from '../events/rows.js';
12
12
  import { assign } from '../runtime/assign.js';
13
13
  import { isBot } from '../runtime/bot.js';
14
- import { readUnitCookie } from '../runtime/cookie.js';
14
+ import { readSignedUnit } from '../runtime/cookie.js';
15
15
  import { requestAttributes } from '../runtime/normalisePath.js';
16
16
  import { serverManifest } from '../server/context.js';
17
17
  const accepted = ()=>Response.json({}, {
18
18
  status: 202
19
19
  });
20
+ const originDrops = new WeakMap();
21
+ function logSessionLookupError(payload, error) {
22
+ try {
23
+ payload.logger.error({
24
+ err: safeError(error)
25
+ }, 'Experiments: events session lookup failed');
26
+ } catch {}
27
+ }
28
+ function countOriginDrop(payload, now) {
29
+ const drops = originDrops.get(payload) ?? {
30
+ count: 0,
31
+ nextLogAt: 0
32
+ };
33
+ originDrops.set(payload, drops);
34
+ drops.count++;
35
+ if (now < drops.nextLogAt) return;
36
+ drops.nextLogAt = now + 60_000;
37
+ try {
38
+ payload.logger.warn({
39
+ droppedRequests: drops.count
40
+ }, 'Experiments: browser event requests dropped by origin check');
41
+ drops.count = 0;
42
+ } catch {}
43
+ }
20
44
  export async function handleEvents(req, { options }) {
45
+ const receivedAt = Date.now();
21
46
  const runtime = options.runtime, proxy = runtime.proxyRuntime;
22
- const visitorId = readUnitCookie(req.headers, proxy);
23
- if (!visitorId) return Response.json({
24
- errors: [
25
- {
26
- code: 'unauthenticated',
27
- message: 'Invalid unit cookie'
28
- }
29
- ]
30
- }, {
31
- status: 401
32
- });
33
- let events;
34
- try {
35
- events = await readEvents(req.body, options.events?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
36
- } catch (error) {
37
- if (error instanceof EventsBodyError) return Response.json({
38
- errors: [
39
- {
40
- code: error.code,
41
- message: error.message
42
- }
43
- ]
44
- }, {
45
- status: error.status
46
- });
47
- throw error;
48
- }
47
+ const unitCookie = readSignedUnit(req.headers, proxy, receivedAt);
48
+ const visitorId = unitCookie?.unitId;
49
+ const issuedAtMs = unitCookie?.issuedAtMs;
50
+ const unitAgeMs = typeof issuedAtMs === 'number' ? receivedAt >= issuedAtMs ? receivedAt - issuedAtMs : null : issuedAtMs ?? null;
49
51
  try {
50
52
  const request = new NextRequest(req.url ?? 'https://xp.invalid/', {
51
53
  headers: req.headers,
52
54
  method: req.method
53
55
  });
56
+ const { allowed, source } = eventRequestContext(request, options.events?.origin ?? publicEventOrigin(req.payload.config?.serverURL));
57
+ if (!allowed) {
58
+ countOriginDrop(req.payload, receivedAt);
59
+ return accepted();
60
+ }
54
61
  // API paths bypass the proxy: re-check consent even when a stale signed cookie exists.
55
62
  try {
56
63
  if (proxy.cookie.consent?.(request) === false) return accepted();
57
64
  } catch {
58
65
  return accepted();
59
66
  }
60
- if (options.events?.rateLimit && await options.events.rateLimit({
67
+ const limit = options.events?.rateLimit;
68
+ if (visitorId && limit !== false && await limit?.({
61
69
  req,
62
- unitId: visitorId
70
+ unitId: visitorId,
71
+ unitType: 'visitor'
63
72
  }) !== true) return accepted();
73
+ // Payload and the host runtime verify sessions server-side. The page URL below
74
+ // supplies targeting attributes only, so it can never select a user identity.
75
+ let user = req.user ?? null;
76
+ let sessionUnresolved = false;
77
+ if (!user && runtime.getUser) {
78
+ try {
79
+ user = await runtime.getUser();
80
+ } catch (error) {
81
+ if (!visitorId) throw error;
82
+ sessionUnresolved = true;
83
+ logSessionLookupError(req.payload, error);
84
+ }
85
+ }
86
+ const useProxySession = !user && !runtime.getUser;
87
+ let requestUnit;
88
+ if (useProxySession) {
89
+ try {
90
+ requestUnit = await proxy.getUnit?.(request);
91
+ } catch (error) {
92
+ if (!visitorId) throw error;
93
+ sessionUnresolved = true;
94
+ logSessionLookupError(req.payload, error);
95
+ }
96
+ }
97
+ const userId = user ? runtime.userIdOf(user) : requestUnit?.sessionUnknown ? undefined : requestUnit?.userId;
98
+ if (!visitorId) {
99
+ if (!userId) return Response.json({
100
+ errors: [
101
+ {
102
+ code: 'unauthenticated',
103
+ message: 'A valid visitor cookie or signed-in session is required'
104
+ }
105
+ ]
106
+ }, {
107
+ status: 401
108
+ });
109
+ if (limit !== false && await limit?.({
110
+ req,
111
+ unitId: userId,
112
+ unitType: 'user'
113
+ }) !== true) return accepted();
114
+ }
115
+ const events = await readEvents(req.body, options.events?.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES);
64
116
  const manifest = await serverManifest(proxy);
65
117
  if (!manifest) return accepted();
66
- const source = sourceRequest(request);
67
- const unit = await proxy.getUnit?.(source ?? request);
68
- const user = req.user ?? null;
69
- const userId = user ? runtime.userIdOf(user) : undefined;
118
+ const unit = source || !useProxySession ? await proxy.getUnit?.(source ?? request) : requestUnit;
70
119
  // The beacon URL is an API route, not the page whose content was rendered.
71
120
  // A referrer supplies page context only, never an identity or an assigned arm.
121
+ const serverAttributes = userId && !user ? {
122
+ loggedIn: true
123
+ } : runtime.attributesOf(user);
72
124
  const attributes = requestAttributes({
73
125
  ...unit?.attributes,
74
- ...runtime.attributesOf(user)
126
+ ...serverAttributes
75
127
  }, source?.nextUrl.pathname);
76
- const unresolvedStaff = Boolean(options.attributeKeys?.staff && unit?.sessionUnknown && !user);
128
+ const unresolvedStaff = Boolean(options.attributeKeys?.staff && !user && (sessionUnresolved || unit?.sessionUnknown || requestUnit?.sessionUnknown));
77
129
  const assignments = assign(manifest, {
78
130
  visitorId,
79
131
  userId
80
132
  }, attributes, {
81
133
  now: Math.floor(Date.now() / 1000),
82
134
  method: req.method,
83
- staff: unit?.attributes.staff === true || attributes.staff === true,
135
+ sessionUnknown: sessionUnresolved,
136
+ staff: requestUnit?.attributes.staff === true || unit?.attributes.staff === true || attributes.staff === true,
84
137
  bot: isBot(req.headers.get('user-agent')),
85
138
  preview: isPreview(request)
86
139
  });
87
140
  if (unresolvedStaff) for (const assignment of Object.values(assignments.bySlug))assignment.exposable = false;
88
141
  const keys = events.some((event)=>event && typeof event === 'object' && 'eventName' in event && validClickSource(event.eventName)) ? await clickKeys(req.payload) : undefined;
89
- const rows = eventRows(events, manifest, assignments, options, visitorId, userId, new Date().toISOString(), attributes, keys);
142
+ // Age measures arrival. Keep attribution at the time the round was validated.
143
+ const rows = eventRows(events, manifest, assignments, options, visitorId, userId, new Date().toISOString(), unitAgeMs, attributes, keys);
90
144
  // §7.8 events insert / assignment lookup exception: pooled SQL and cached manifest,
91
145
  // no Local API calls (and hence no implicit overrideAccess defaults).
92
146
  if (rows.length) await insertEvents(pooledExecutor(req.payload), rows, (message)=>req.payload.logger.error(message));
93
147
  } catch (error) {
148
+ if (error instanceof EventsBodyError) return Response.json({
149
+ errors: [
150
+ {
151
+ code: error.code,
152
+ message: error.message
153
+ }
154
+ ]
155
+ }, {
156
+ status: error.status
157
+ });
94
158
  try {
95
159
  req.payload.logger.error({
96
160
  err: safeError(error)