@delmaredigital/payload-experiments 0.4.1 → 0.5.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 (290) hide show
  1. package/README.md +9 -5
  2. package/dist/admin/blocks/model.js +2 -0
  3. package/dist/admin/copy/blocks.d.ts +1 -0
  4. package/dist/admin/copy/blocks.js +1 -0
  5. package/dist/admin/copy/status.d.ts +3 -0
  6. package/dist/admin/copy/status.js +3 -0
  7. package/dist/admin/placementStatus.model.js +3 -0
  8. package/dist/admin/status.model.d.ts +3 -2
  9. package/dist/admin/status.model.js +9 -3
  10. package/dist/admin/surface/ResultsRoute.js +2 -1
  11. package/dist/admin/surface/TestsHome.d.ts +2 -1
  12. package/dist/admin/surface/TestsHome.js +31 -11
  13. package/dist/admin/surface/TestsSurface.js +4 -0
  14. package/dist/admin/surface/home.model.d.ts +11 -6
  15. package/dist/admin/surface/home.model.js +19 -8
  16. package/dist/admin/surface/newTest/PageWizard.js +13 -3
  17. package/dist/admin/surface/results/ResultsHeader.js +43 -9
  18. package/dist/admin/surface/test/TestPage.js +11 -1
  19. package/dist/admin/useLayerUsage.d.ts +1 -1
  20. package/dist/admin/views/buildSurfaceProps.js +3 -0
  21. package/dist/cohorts/build.d.ts +35 -0
  22. package/dist/cohorts/build.js +134 -0
  23. package/dist/cohorts/key.d.ts +12 -0
  24. package/dist/cohorts/key.js +15 -0
  25. package/dist/cohorts/maintenance.d.ts +10 -0
  26. package/dist/cohorts/maintenance.js +70 -0
  27. package/dist/cohorts/readiness.d.ts +30 -0
  28. package/dist/cohorts/readiness.js +54 -0
  29. package/dist/cohorts/readinessData.d.ts +29 -0
  30. package/dist/cohorts/readinessData.js +123 -0
  31. package/dist/cohorts/rule.d.ts +33 -0
  32. package/dist/cohorts/rule.js +50 -0
  33. package/dist/collections/cohortMembers.d.ts +4 -0
  34. package/dist/collections/cohortMembers.js +95 -0
  35. package/dist/collections/experiments/config.js +157 -7
  36. package/dist/collections/experiments/editability.js +10 -6
  37. package/dist/collections/experiments/lockHook.js +39 -20
  38. package/dist/collections/index.js +4 -1
  39. package/dist/collections/phases.js +4 -1
  40. package/dist/constants.d.ts +2 -0
  41. package/dist/constants.js +2 -0
  42. package/dist/db/adapter.d.ts +1 -1
  43. package/dist/db/adapter.js +14 -4
  44. package/dist/db/appends.js +1 -1
  45. package/dist/db/cohortMembership.d.ts +11 -0
  46. package/dist/db/cohortMembership.js +31 -0
  47. package/dist/db/cohortPool.d.ts +9 -0
  48. package/dist/db/cohortPool.js +53 -0
  49. package/dist/db/cohortTransactions.d.ts +3 -0
  50. package/dist/db/cohortTransactions.js +52 -0
  51. package/dist/db/cohorts.d.ts +72 -0
  52. package/dist/db/cohorts.js +280 -0
  53. package/dist/db/erase.d.ts +2 -0
  54. package/dist/db/erase.js +21 -2
  55. package/dist/db/events.d.ts +2 -0
  56. package/dist/db/events.js +8 -0
  57. package/dist/db/executor.d.ts +2 -0
  58. package/dist/db/executor.js +8 -0
  59. package/dist/db/locks.d.ts +7 -0
  60. package/dist/db/locks.js +13 -1
  61. package/dist/db/names.d.ts +95 -1
  62. package/dist/db/names.js +95 -1
  63. package/dist/db/occupancy.d.ts +21 -0
  64. package/dist/db/occupancy.js +46 -0
  65. package/dist/db/pageOccupancy.d.ts +4 -4
  66. package/dist/db/pageOccupancy.js +13 -10
  67. package/dist/db/pgExecutor.d.ts +4 -0
  68. package/dist/db/pgExecutor.js +1 -1
  69. package/dist/db/placements.js +1 -1
  70. package/dist/db/results.d.ts +5 -2
  71. package/dist/db/results.js +32 -5
  72. package/dist/db/slices.d.ts +9 -2
  73. package/dist/db/slices.js +15 -8
  74. package/dist/db/snapshots.d.ts +16 -1
  75. package/dist/db/snapshots.js +27 -2
  76. package/dist/db/sql.d.ts +2 -2
  77. package/dist/db/sql.js +1 -2
  78. package/dist/endpoints/cohortSources.d.ts +16 -0
  79. package/dist/endpoints/cohortSources.js +335 -0
  80. package/dist/endpoints/contentLocale.d.ts +1 -1
  81. package/dist/endpoints/events.js +82 -18
  82. package/dist/endpoints/index.js +45 -1
  83. package/dist/endpoints/pausedBy.d.ts +14 -0
  84. package/dist/endpoints/pausedBy.js +94 -0
  85. package/dist/endpoints/preflight.js +4 -1
  86. package/dist/endpoints/previewToken.js +2 -0
  87. package/dist/endpoints/results.d.ts +2 -2
  88. package/dist/endpoints/results.js +111 -3
  89. package/dist/endpoints/routeId.d.ts +2 -1
  90. package/dist/endpoints/routeId.js +6 -2
  91. package/dist/endpoints/summary.js +24 -1
  92. package/dist/endpoints/transitions.d.ts +7 -0
  93. package/dist/endpoints/transitions.js +50 -1
  94. package/dist/events/rows.d.ts +1 -1
  95. package/dist/events/rows.js +5 -3
  96. package/dist/exports/index.d.ts +2 -0
  97. package/dist/exports/index.js +1 -0
  98. package/dist/exports/runtimeProxy.d.ts +1 -0
  99. package/dist/exports/runtimeProxy.js +1 -0
  100. package/dist/hooks/blockRemovalRule.js +7 -4
  101. package/dist/hooks/pageGuard.js +1 -1
  102. package/dist/labels/status.d.ts +15 -0
  103. package/dist/labels/status.js +12 -0
  104. package/dist/manifest/compile.d.ts +15 -4
  105. package/dist/manifest/compile.js +91 -3
  106. package/dist/onInit.js +4 -1
  107. package/dist/options.d.ts +1 -0
  108. package/dist/options.js +10 -0
  109. package/dist/proxy/consentFallback.d.ts +1 -1
  110. package/dist/proxy/consentFallback.js +4 -4
  111. package/dist/proxy/control.d.ts +1 -1
  112. package/dist/proxy/control.js +2 -2
  113. package/dist/proxy/pageRewrite.d.ts +1 -1
  114. package/dist/proxy/pageRewrite.js +3 -2
  115. package/dist/proxy/resolve.js +76 -17
  116. package/dist/puck/ExperimentPicker.js +2 -1
  117. package/dist/puck/copy.d.ts +6 -5
  118. package/dist/puck/copy.js +3 -7
  119. package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
  120. package/dist/puck/editor/QuickTestActions.js +7 -1
  121. package/dist/puck/editor/armWrites.js +6 -1
  122. package/dist/puck/editor/copy.d.ts +3 -0
  123. package/dist/puck/editor/copy.js +3 -0
  124. package/dist/puck/editor/editor.css +2 -1
  125. package/dist/puck/editor/editor.model.d.ts +2 -1
  126. package/dist/puck/editor/editor.model.js +2 -0
  127. package/dist/puck/editor/placementsCache.d.ts +1 -1
  128. package/dist/puck/editor/placementsCache.js +6 -3
  129. package/dist/results/analyse.d.ts +3 -1
  130. package/dist/results/analyse.js +20 -3
  131. package/dist/results/health.d.ts +11 -0
  132. package/dist/results/health.js +38 -0
  133. package/dist/results/power.d.ts +1 -1
  134. package/dist/results/power.js +1 -1
  135. package/dist/results/snapshot.d.ts +8 -2
  136. package/dist/results/snapshot.js +23 -1
  137. package/dist/results/unitValues.d.ts +48 -0
  138. package/dist/results/unitValues.js +166 -0
  139. package/dist/runtime/assign.d.ts +7 -3
  140. package/dist/runtime/assign.js +12 -4
  141. package/dist/runtime/cohortCookie.d.ts +15 -0
  142. package/dist/runtime/cohortCookie.js +72 -0
  143. package/dist/runtime/cohortLookup.d.ts +9 -0
  144. package/dist/runtime/cohortLookup.js +25 -0
  145. package/dist/runtime/eligibility.d.ts +11 -5
  146. package/dist/runtime/eligibility.js +33 -7
  147. package/dist/runtime/header.d.ts +1 -0
  148. package/dist/runtime/header.js +1 -1
  149. package/dist/runtime/proxyRuntime.js +5 -1
  150. package/dist/runtime/targeting.d.ts +3 -2
  151. package/dist/runtime/targeting.js +2 -1
  152. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  153. package/dist/sanitizeReadinessDetail.js +41 -4
  154. package/dist/schedule/activeTime.d.ts +28 -0
  155. package/dist/schedule/activeTime.js +322 -0
  156. package/dist/schedule/ranges.d.ts +13 -0
  157. package/dist/schedule/ranges.js +11 -0
  158. package/dist/schedule/roundTime.d.ts +10 -0
  159. package/dist/schedule/roundTime.js +45 -0
  160. package/dist/schedule/types.d.ts +29 -0
  161. package/dist/schedule/types.js +1 -0
  162. package/dist/server/cohortLookup.d.ts +3 -0
  163. package/dist/server/cohortLookup.js +7 -0
  164. package/dist/server/eraseUser.d.ts +1 -0
  165. package/dist/server/getAssignments.js +63 -40
  166. package/dist/server/previewDraft.d.ts +1 -1
  167. package/dist/server/previewDraft.js +3 -2
  168. package/dist/server/recordExposures.js +4 -2
  169. package/dist/server/runResults.js +97 -150
  170. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  171. package/dist/testSurface/actions/LifecycleAction.js +15 -5
  172. package/dist/testSurface/actions/actions.model.d.ts +13 -2
  173. package/dist/testSurface/actions/actions.model.js +38 -5
  174. package/dist/testSurface/api.d.ts +13 -1
  175. package/dist/testSurface/api.js +19 -0
  176. package/dist/testSurface/copy/actions.d.ts +13 -0
  177. package/dist/testSurface/copy/actions.js +13 -0
  178. package/dist/testSurface/copy/cohorts.d.ts +68 -0
  179. package/dist/testSurface/copy/cohorts.js +81 -0
  180. package/dist/testSurface/copy/common.d.ts +2 -3
  181. package/dist/testSurface/copy/common.js +4 -4
  182. package/dist/testSurface/copy/inputs.d.ts +3 -0
  183. package/dist/testSurface/copy/inputs.js +3 -0
  184. package/dist/testSurface/copy/readiness.d.ts +20 -6
  185. package/dist/testSurface/copy/readiness.js +42 -9
  186. package/dist/testSurface/copy/results.d.ts +1 -0
  187. package/dist/testSurface/copy/results.js +1 -0
  188. package/dist/testSurface/copy/schedule.d.ts +58 -0
  189. package/dist/testSurface/copy/schedule.js +150 -0
  190. package/dist/testSurface/copy/surface.d.ts +2 -0
  191. package/dist/testSurface/copy/surface.js +2 -0
  192. package/dist/testSurface/copy/testPage.d.ts +12 -2
  193. package/dist/testSurface/copy/testPage.js +17 -2
  194. package/dist/testSurface/format/roundProgress.d.ts +13 -1
  195. package/dist/testSurface/format/roundProgress.js +34 -5
  196. package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
  197. package/dist/testSurface/format/scheduleStatus.js +93 -0
  198. package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
  199. package/dist/testSurface/format/useScheduleClock.js +20 -0
  200. package/dist/testSurface/labels.d.ts +4 -9
  201. package/dist/testSurface/labels.js +2 -7
  202. package/dist/testSurface/lockedNotice.model.d.ts +2 -2
  203. package/dist/testSurface/lockedNotice.model.js +16 -3
  204. package/dist/testSurface/readPreflight.d.ts +3 -0
  205. package/dist/testSurface/readPreflight.js +14 -0
  206. package/dist/testSurface/readinessRead.d.ts +2 -2
  207. package/dist/testSurface/results/DataQualityPanel.js +7 -7
  208. package/dist/testSurface/results/results.model.d.ts +1 -1
  209. package/dist/testSurface/results/results.model.js +34 -6
  210. package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
  211. package/dist/testSurface/review/cohortEstimate.js +32 -0
  212. package/dist/testSurface/surface/contracts.d.ts +2 -1
  213. package/dist/testSurface/surface/contracts.js +1 -0
  214. package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
  215. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
  216. package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
  217. package/dist/testSurface/surface/readiness/Banner.js +29 -11
  218. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
  219. package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
  220. package/dist/testSurface/surface/readiness/useTransition.js +17 -5
  221. package/dist/testSurface/surface/results/ResultsBody.js +44 -8
  222. package/dist/testSurface/surface/results/useResults.d.ts +16 -1
  223. package/dist/testSurface/surface/results/useResults.js +17 -6
  224. package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
  225. package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
  226. package/dist/testSurface/surface/test/LengthSection.js +26 -6
  227. package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
  228. package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
  229. package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
  230. package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
  231. package/dist/testSurface/surface/test/Section.js +1 -1
  232. package/dist/testSurface/surface/test/TargetingSection.js +306 -182
  233. package/dist/testSurface/surface/test/TestSurface.js +9 -0
  234. package/dist/testSurface/surface/test/fields.d.ts +2 -1
  235. package/dist/testSurface/surface/test/fields.js +3 -3
  236. package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
  237. package/dist/testSurface/surface/test/jumpToSection.js +4 -4
  238. package/dist/testSurface/surface/test/testPage.css +26 -0
  239. package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
  240. package/dist/testSurface/surface/testDocument.model.js +2 -1
  241. package/dist/testSurface/surface/useTestDocument.js +11 -4
  242. package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
  243. package/dist/testSurface/targeting/targeting.model.js +1 -1
  244. package/dist/testSurface/useApi.d.ts +12 -0
  245. package/dist/transitions/addMetric.js +5 -2
  246. package/dist/transitions/allocate.js +6 -1
  247. package/dist/transitions/assertNoOverlap.d.ts +9 -0
  248. package/dist/transitions/assertNoOverlap.js +24 -0
  249. package/dist/transitions/buildCohorts.d.ts +10 -0
  250. package/dist/transitions/buildCohorts.js +68 -0
  251. package/dist/transitions/cancelSchedule.d.ts +4 -0
  252. package/dist/transitions/cancelSchedule.js +42 -0
  253. package/dist/transitions/checkStart.d.ts +17 -3
  254. package/dist/transitions/checkStart.js +20 -7
  255. package/dist/transitions/decide.js +35 -11
  256. package/dist/transitions/kernel.d.ts +3 -1
  257. package/dist/transitions/kernel.js +5 -2
  258. package/dist/transitions/pause.d.ts +4 -0
  259. package/dist/transitions/pause.js +35 -0
  260. package/dist/transitions/phaseRecord.d.ts +19 -2
  261. package/dist/transitions/phaseRecord.js +50 -11
  262. package/dist/transitions/placementInteractions.js +1 -1
  263. package/dist/transitions/preflightData.d.ts +11 -3
  264. package/dist/transitions/preflightData.js +134 -81
  265. package/dist/transitions/reschedule.d.ts +4 -0
  266. package/dist/transitions/reschedule.js +58 -0
  267. package/dist/transitions/resume.d.ts +4 -0
  268. package/dist/transitions/resume.js +32 -0
  269. package/dist/transitions/scheduledRound.d.ts +18 -0
  270. package/dist/transitions/scheduledRound.js +42 -0
  271. package/dist/transitions/start.d.ts +4 -0
  272. package/dist/transitions/start.js +136 -55
  273. package/dist/transitions/startReads.d.ts +14 -0
  274. package/dist/transitions/startReads.js +27 -0
  275. package/dist/transitions/stop.d.ts +10 -0
  276. package/dist/transitions/stop.js +35 -22
  277. package/dist/types/admin.d.ts +1 -1
  278. package/dist/types/contracts.d.ts +7 -1
  279. package/dist/types/endpoints.d.ts +72 -3
  280. package/dist/types/manifest.d.ts +9 -0
  281. package/dist/types/runtime.d.ts +5 -0
  282. package/dist/types/snapshot.d.ts +10 -0
  283. package/dist/types/status.d.ts +1 -0
  284. package/dist/types/status.js +1 -0
  285. package/dist/types/surface.d.ts +1 -0
  286. package/dist/ui/Feedback.d.ts +9 -6
  287. package/dist/ui/Feedback.js +10 -9
  288. package/dist/ui/SelectControl.js +1 -1
  289. package/dist/ui/ui.css +2 -1
  290. package/package.json +2 -2
@@ -0,0 +1,95 @@
1
+ import { readOnlyAccess } from './access.js';
2
+ function hiddenCollection(options) {
3
+ return {
4
+ graphQL: false,
5
+ versions: false,
6
+ disableDuplicate: true,
7
+ admin: {
8
+ hidden: true
9
+ },
10
+ access: readOnlyAccess(options.access.readIdentities ?? options.access.admin ?? options.access.manage)
11
+ };
12
+ }
13
+ export function cohortMembersCollection(options) {
14
+ return {
15
+ ...hiddenCollection(options),
16
+ slug: 'xp-cohort-members',
17
+ indexes: [
18
+ {
19
+ fields: [
20
+ 'cohortKey',
21
+ 'unitId'
22
+ ],
23
+ unique: true
24
+ }
25
+ ],
26
+ fields: [
27
+ {
28
+ name: 'cohortKey',
29
+ type: 'text',
30
+ required: true
31
+ },
32
+ {
33
+ name: 'unitId',
34
+ type: 'text',
35
+ required: true
36
+ },
37
+ {
38
+ name: 'builtAt',
39
+ type: 'date',
40
+ required: true
41
+ },
42
+ {
43
+ name: 'enteredAt',
44
+ type: 'date',
45
+ required: true
46
+ },
47
+ {
48
+ name: 'exitedAt',
49
+ type: 'date'
50
+ }
51
+ ]
52
+ };
53
+ }
54
+ export function cohortsCollection(options) {
55
+ return {
56
+ ...hiddenCollection(options),
57
+ slug: 'xp-cohorts',
58
+ fields: [
59
+ {
60
+ name: 'cohortKey',
61
+ type: 'text',
62
+ required: true,
63
+ unique: true
64
+ },
65
+ {
66
+ name: 'rule',
67
+ type: 'json',
68
+ required: true
69
+ },
70
+ {
71
+ name: 'state',
72
+ type: 'select',
73
+ options: [
74
+ 'ready'
75
+ ],
76
+ required: true
77
+ },
78
+ {
79
+ name: 'closed',
80
+ type: 'checkbox',
81
+ defaultValue: false
82
+ },
83
+ {
84
+ name: 'members',
85
+ type: 'number',
86
+ required: true
87
+ },
88
+ {
89
+ name: 'builtAt',
90
+ type: 'date',
91
+ required: true
92
+ }
93
+ ]
94
+ };
95
+ }
@@ -1,4 +1,9 @@
1
+ import { COHORT_ARMS, cohortRelationshipId } from '../../cohorts/rule.js';
2
+ import { COHORT_COPY } from '../../testSurface/copy/cohorts.js';
3
+ import { date, relationship } from 'payload/shared';
1
4
  import { SURFACE_COPY } from '../../testSurface/copy/surface.js';
5
+ import { SCHEDULE_VALIDATION } from '../../testSurface/copy/testPage.js';
6
+ import { isValidTimeZone } from '../../schedule/activeTime.js';
2
7
  import * as paths from '../../admin/paths.js';
3
8
  import { managedAccess } from '../access.js';
4
9
  import { serializeAttributeKeys, serializeFlagPoints } from '../serialize.js';
@@ -13,6 +18,16 @@ import { checkArms } from './armInvariants.js';
13
18
  import { XpNotImplemented, XpRefusal } from '../../errors.js';
14
19
  const targetingValue = (rule)=>rule.op === 'in' || rule.op === 'nin' ? readListValue(rule.value) : rule.value;
15
20
  const positiveInteger = (value)=>value != null && Number.isInteger(value) && value > 0 || 'Enter a positive whole number.';
21
+ const weekdays = [
22
+ 'mon',
23
+ 'tue',
24
+ 'wed',
25
+ 'thu',
26
+ 'fri',
27
+ 'sat',
28
+ 'sun'
29
+ ];
30
+ const validClockTime = (value)=>typeof value === 'string' && value.length === 5 && /^(?:[01]\d|2[0-3]):[0-5]\d$/.test(value) || SCHEDULE_VALIDATION.clockTime;
16
31
  export function experimentsCollection(options) {
17
32
  const flagPoints = serializeFlagPoints(options);
18
33
  const attributeKeys = serializeAttributeKeys(options);
@@ -136,6 +151,7 @@ export function experimentsCollection(options) {
136
151
  options: [
137
152
  'draft',
138
153
  'running',
154
+ 'paused',
139
155
  'stopped',
140
156
  'decided',
141
157
  'archived'
@@ -251,7 +267,7 @@ export function experimentsCollection(options) {
251
267
  const status = data?.status ?? 'draft';
252
268
  if (data?.kind === 'block' && (status === 'draft' || status === 'stopped')) {
253
269
  for (const rule of value ?? []){
254
- if (rule.attribute !== 'path') continue;
270
+ if (rule.kind === 'cohort' || rule.attribute !== 'path') continue;
255
271
  const previous = rule.id == null ? undefined : previousValue?.find((stored)=>stored.id != null && String(stored.id) === String(rule.id));
256
272
  if (!previous || previous.attribute !== rule.attribute || previous.op !== rule.op || JSON.stringify(targetingValue(previous)) !== JSON.stringify(targetingValue(rule))) {
257
273
  return 'Page block tests run on their page; remove the page-path rule.';
@@ -261,26 +277,34 @@ export function experimentsCollection(options) {
261
277
  return true;
262
278
  },
263
279
  fields: [
280
+ {
281
+ name: 'kind',
282
+ type: 'select',
283
+ required: true,
284
+ defaultValue: 'attribute',
285
+ options: [
286
+ 'attribute',
287
+ 'cohort'
288
+ ]
289
+ },
264
290
  {
265
291
  name: 'attribute',
266
292
  type: 'text',
267
- required: true,
268
- validate: (value)=>typeof value === 'string' && Object.hasOwn(attributeKeys, value) || 'Choose a registered attribute.'
293
+ validate: (value, { siblingData })=>siblingData?.kind === 'cohort' || typeof value === 'string' && Object.hasOwn(attributeKeys, value) || 'Choose a registered attribute.'
269
294
  },
270
295
  {
271
296
  name: 'op',
272
297
  type: 'select',
273
- required: true,
274
298
  options: [
275
299
  ...new Set(Object.values(TARGETING_OPS).flat())
276
300
  ],
277
- validate: (value, { siblingData })=>isOpValid(attributeKeys[siblingData?.attribute ?? '']?.type ?? '', value) || 'Choose an operator supported by this attribute.'
301
+ validate: (value, { siblingData })=>siblingData?.kind === 'cohort' || isOpValid(attributeKeys[siblingData?.attribute ?? '']?.type ?? '', value) || 'Choose an operator supported by this attribute.'
278
302
  },
279
303
  {
280
304
  name: 'value',
281
305
  type: 'json',
282
- required: true,
283
306
  validate: (value, { siblingData })=>{
307
+ if (siblingData?.kind === 'cohort') return true;
284
308
  const type = attributeKeys[siblingData?.attribute ?? '']?.type;
285
309
  const op = siblingData?.op ?? '';
286
310
  if (!type || !isOpValid(type, op)) return 'Choose a registered attribute and supported operator.';
@@ -288,6 +312,48 @@ export function experimentsCollection(options) {
288
312
  if (!valid && type === 'string' && (op === 'in' || op === 'nin') && Array.isArray(value) && value.length === 0) return 'Add at least one value; an empty list matches nobody.';
289
313
  return valid || 'Enter a value of the type required by this attribute and operator.';
290
314
  }
315
+ },
316
+ {
317
+ name: 'sourceExperiment',
318
+ type: 'relationship',
319
+ relationTo: 'xp-experiments',
320
+ validate: (value, context)=>{
321
+ const { id, data, siblingData } = context;
322
+ if (siblingData?.kind !== 'cohort') return true;
323
+ const source = cohortRelationshipId(value);
324
+ if (source === undefined) return COHORT_COPY.source;
325
+ if (String(source) === String(id ?? data?.id)) return COHORT_COPY.self;
326
+ return relationship(value, context);
327
+ }
328
+ },
329
+ {
330
+ name: 'sourcePhase',
331
+ type: 'number',
332
+ validate: (value, { siblingData })=>siblingData?.kind !== 'cohort' || value == null || positiveInteger(value) === true || COHORT_COPY.round
333
+ },
334
+ {
335
+ name: 'arms',
336
+ type: 'select',
337
+ hasMany: true,
338
+ options: [
339
+ ...COHORT_ARMS
340
+ ],
341
+ validate: (value, { siblingData })=>siblingData?.kind !== 'cohort' || Array.isArray(value) && value.length > 0 && value.every((arm)=>COHORT_ARMS.includes(arm)) || COHORT_COPY.arms
342
+ },
343
+ metric('goalMetric'),
344
+ {
345
+ name: 'goalCompleted',
346
+ type: 'select',
347
+ options: [
348
+ 'completed',
349
+ 'notCompleted'
350
+ ],
351
+ validate: (value, { siblingData })=>siblingData?.kind !== 'cohort' || siblingData.goalMetric == null || value === 'completed' || value === 'notCompleted' || COHORT_COPY.goal
352
+ },
353
+ {
354
+ name: 'include',
355
+ type: 'checkbox',
356
+ defaultValue: true
291
357
  }
292
358
  ]
293
359
  }
@@ -440,6 +506,72 @@ export function experimentsCollection(options) {
440
506
  }
441
507
  ]
442
508
  },
509
+ {
510
+ name: 'schedule',
511
+ type: 'group',
512
+ hooks: {
513
+ beforeValidate: [
514
+ ({ value })=>{
515
+ // Give Payload a group object to traverse when a PATCH clears the schedule.
516
+ return value === null ? {
517
+ startAt: null,
518
+ endAt: null,
519
+ timeZone: null,
520
+ windows: []
521
+ } : value;
522
+ }
523
+ ]
524
+ },
525
+ fields: [
526
+ {
527
+ name: 'startAt',
528
+ type: 'date'
529
+ },
530
+ {
531
+ name: 'endAt',
532
+ type: 'date',
533
+ validate: async (value, context)=>{
534
+ const valid = await date(value, context);
535
+ const start = context.siblingData?.startAt;
536
+ return valid === true && value && start && new Date(value).getTime() <= new Date(start).getTime() ? SCHEDULE_VALIDATION.endAt : valid;
537
+ }
538
+ },
539
+ {
540
+ name: 'timeZone',
541
+ type: 'text',
542
+ hooks: {
543
+ beforeValidate: [
544
+ ({ operation, value })=>operation === 'create' && value === undefined ? options.timeZone : value
545
+ ]
546
+ },
547
+ validate: (value)=>value == null || value === '' || isValidTimeZone(value) || SCHEDULE_VALIDATION.timeZone
548
+ },
549
+ {
550
+ name: 'windows',
551
+ type: 'array',
552
+ fields: [
553
+ {
554
+ name: 'days',
555
+ type: 'json',
556
+ required: true,
557
+ validate: (value)=>Array.isArray(value) && value.length > 0 && value.every((day)=>weekdays.includes(day)) || SCHEDULE_VALIDATION.days
558
+ },
559
+ {
560
+ name: 'from',
561
+ type: 'text',
562
+ required: true,
563
+ validate: validClockTime
564
+ },
565
+ {
566
+ name: 'to',
567
+ type: 'text',
568
+ required: true,
569
+ validate: validClockTime
570
+ }
571
+ ]
572
+ }
573
+ ]
574
+ },
443
575
  {
444
576
  name: 'layerSlices',
445
577
  type: 'json',
@@ -465,8 +597,11 @@ export function experimentsCollection(options) {
465
597
  ...[
466
598
  'startedAt',
467
599
  'stoppedAt',
600
+ 'pausedAt',
468
601
  'decidedAt',
469
- 'archivedAt'
602
+ 'archivedAt',
603
+ 'claimFrom',
604
+ 'claimTo'
470
605
  ].map((name)=>({
471
606
  name,
472
607
  type: 'date',
@@ -474,6 +609,21 @@ export function experimentsCollection(options) {
474
609
  hidden: true
475
610
  }
476
611
  })),
612
+ {
613
+ name: 'pausedBy',
614
+ type: 'text',
615
+ admin: {
616
+ hidden: true
617
+ }
618
+ },
619
+ {
620
+ name: 'pauseReason',
621
+ type: 'textarea',
622
+ maxLength: 500,
623
+ admin: {
624
+ hidden: true
625
+ }
626
+ },
477
627
  {
478
628
  name: 'decision',
479
629
  type: 'group',
@@ -1,3 +1,7 @@
1
+ const runningFields = [
2
+ 'name',
3
+ 'hypothesis'
4
+ ];
1
5
  export const EDITABLE_BY_STATUS = {
2
6
  draft: [
3
7
  'name',
@@ -9,7 +13,8 @@ export const EDITABLE_BY_STATUS = {
9
13
  'metrics',
10
14
  'analysis',
11
15
  'exposurePolicy',
12
- 'pageCollection'
16
+ 'pageCollection',
17
+ 'schedule'
13
18
  ],
14
19
  stopped: [
15
20
  'name',
@@ -20,12 +25,11 @@ export const EDITABLE_BY_STATUS = {
20
25
  'metrics',
21
26
  'analysis',
22
27
  'exposurePolicy',
23
- 'pageCollection'
24
- ],
25
- running: [
26
- 'name',
27
- 'hypothesis'
28
+ 'pageCollection',
29
+ 'schedule'
28
30
  ],
31
+ running: runningFields,
32
+ paused: runningFields,
29
33
  decided: [
30
34
  'name',
31
35
  'hypothesis'
@@ -12,15 +12,21 @@ const relationships = new Set([
12
12
  'metrics.primary',
13
13
  'metrics.secondary',
14
14
  'metrics.guardrails',
15
+ 'pausedBy',
15
16
  'decision.decidedBy',
16
17
  'decision.pagesReleasedBy',
17
18
  'decision.snapshotId'
18
19
  ]);
19
20
  const dates = new Set([
21
+ 'claimFrom',
22
+ 'claimTo',
20
23
  'startedAt',
21
24
  'stoppedAt',
25
+ 'pausedAt',
22
26
  'decidedAt',
23
27
  'archivedAt',
28
+ 'schedule.startAt',
29
+ 'schedule.endAt',
24
30
  'decision.discardedAt',
25
31
  'decision.holdoutReleasedAt',
26
32
  'decision.pagesReleasedAt'
@@ -42,25 +48,32 @@ const dates = new Set([
42
48
  const date = new Date(value);
43
49
  if (!Number.isNaN(date.valueOf())) return date.toISOString();
44
50
  }
45
- if (Array.isArray(value)) return value.map((item)=>{
46
- if (!json && [
47
- 'arms',
48
- 'targeting'
49
- ].includes(path) && isObject(item)) {
50
- const { id: _rowId, ...row } = item;
51
- return normalize(row, path);
52
- }
53
- return normalize(item, path, json);
54
- });
55
- if (isObject(value)) return Object.fromEntries(Object.keys(value).sort().flatMap((key)=>{
56
- const nested = normalize(value[key], `${path}.${key}`, json);
57
- return nested === undefined ? [] : [
58
- [
59
- key,
60
- nested
61
- ]
62
- ];
63
- }));
51
+ if (Array.isArray(value)) {
52
+ if (path === 'schedule.windows' && !value.length) return undefined;
53
+ return value.map((item)=>{
54
+ if (!json && [
55
+ 'arms',
56
+ 'targeting',
57
+ 'schedule.windows'
58
+ ].includes(path) && isObject(item)) {
59
+ const { id: _rowId, ...row } = item;
60
+ return normalize(row, path);
61
+ }
62
+ return normalize(item, path, json);
63
+ });
64
+ }
65
+ if (isObject(value)) {
66
+ const entries = Object.keys(value).sort().flatMap((key)=>{
67
+ const nested = normalize(value[key], `${path}.${key}`, json);
68
+ return nested === undefined ? [] : [
69
+ [
70
+ key,
71
+ nested
72
+ ]
73
+ ];
74
+ });
75
+ return path === 'schedule' && !entries.length ? undefined : Object.fromEntries(entries);
76
+ }
64
77
  return value;
65
78
  }
66
79
  const same = (a, b, path)=>JSON.stringify(normalize(a, path)) === JSON.stringify(normalize(b, path));
@@ -111,8 +124,13 @@ export const lockHook = async ({ data, originalDoc, operation, req })=>{
111
124
  for (const field of [
112
125
  'seed',
113
126
  'layerSlices',
127
+ 'claimFrom',
128
+ 'claimTo',
114
129
  'startedAt',
115
130
  'stoppedAt',
131
+ 'pausedAt',
132
+ 'pausedBy',
133
+ 'pauseReason',
116
134
  'decidedAt',
117
135
  'archivedAt',
118
136
  'decision'
@@ -154,7 +172,8 @@ export const lockHook = async ({ data, originalDoc, operation, req })=>{
154
172
  if ([
155
173
  'analysis',
156
174
  'metrics',
157
- 'decision'
175
+ 'decision',
176
+ 'schedule'
158
177
  ].includes(field) && isObject(value)) {
159
178
  for (const [key, nested] of Object.entries(value))await check(`${field}.${key}`, nested, originalDoc[field]?.[key]);
160
179
  } else {
@@ -1,3 +1,4 @@
1
+ import { cohortMembersCollection, cohortsCollection } from './cohortMembers.js';
1
2
  import { experimentsCollection } from './experiments/config.js';
2
3
  import { phasesCollection } from './phases.js';
3
4
  import { layersCollection } from './layers.js';
@@ -15,7 +16,9 @@ export function buildCollections(options) {
15
16
  metricsCollection(options),
16
17
  eventsCollection(options),
17
18
  identitiesCollection(options),
18
- snapshotsCollection(options)
19
+ snapshotsCollection(options),
20
+ cohortMembersCollection(options),
21
+ cohortsCollection(options)
19
22
  ],
20
23
  globals: [
21
24
  stateGlobal(options)
@@ -51,7 +51,10 @@ export function phasesCollection(options) {
51
51
  'metricDefinitions',
52
52
  'analysis',
53
53
  'placementDocs',
54
- 'contentChanges'
54
+ 'contentChanges',
55
+ 'pauses',
56
+ 'schedule',
57
+ 'scheduleChanges'
55
58
  ].map((name)=>({
56
59
  name,
57
60
  type: 'json'
@@ -2,9 +2,11 @@ export declare const DEFAULT_SEQUENTIAL_TUNING_PARAMETER = 5000;
2
2
  export declare const MAX_EVENTS_PER_BODY = 20;
3
3
  export declare const DEFAULT_MAX_BODY_BYTES = 8192;
4
4
  export declare const XP_COOKIE = "xp_id";
5
+ export declare const XP_COHORT_COOKIE = "xp_c";
5
6
  export declare const XP_HEADER = "x-xp-assignments";
6
7
  export declare const XP_PREVIEW_PARAM = "xp_preview";
7
8
  export declare const XP_MANIFEST_KEY_HEADER = "x-xp-manifest-key";
8
9
  export declare const XP_REQUEST_HEADER = "x-xp-request";
9
10
  export declare const XP_IF_UPDATED_AT_HEADER = "x-xp-if-updated-at";
10
11
  export declare const USER_BROWSER_CONVERSION_PREFIX = "conversion:cu:";
12
+ export declare const COHORT_START_BUDGET_MS = 20000;
package/dist/constants.js CHANGED
@@ -2,9 +2,11 @@ export const DEFAULT_SEQUENTIAL_TUNING_PARAMETER = 5000;
2
2
  export const MAX_EVENTS_PER_BODY = 20;
3
3
  export const DEFAULT_MAX_BODY_BYTES = 8192;
4
4
  export const XP_COOKIE = 'xp_id';
5
+ export const XP_COHORT_COOKIE = 'xp_c';
5
6
  export const XP_HEADER = 'x-xp-assignments';
6
7
  export const XP_PREVIEW_PARAM = 'xp_preview';
7
8
  export const XP_MANIFEST_KEY_HEADER = 'x-xp-manifest-key';
8
9
  export const XP_REQUEST_HEADER = 'x-xp-request';
9
10
  export const XP_IF_UPDATED_AT_HEADER = 'x-xp-if-updated-at';
10
11
  export const USER_BROWSER_CONVERSION_PREFIX = 'conversion:cu:';
12
+ export const COHORT_START_BUDGET_MS = 20_000;
@@ -5,7 +5,7 @@ export declare class XpTransactionIsolationError extends APIError {
5
5
  /** Payload's initTransaction cannot pass options to the adapter. Like that
6
6
  * helper, publish the pending transaction on the request before awaiting it.
7
7
  */
8
- export declare function initTransitionTransaction(req: PayloadRequest): Promise<boolean>;
8
+ export declare function initTransitionTransaction(req: PayloadRequest, deadline?: number): Promise<boolean>;
9
9
  export declare function assertReadCommitted(req: PayloadRequest): Promise<void>;
10
10
  export declare function assertPostgresAdapter(payload: Payload): void;
11
11
  export declare function probeTransactions(payload: Payload): Promise<void>;
@@ -1,7 +1,7 @@
1
1
  import { APIError } from 'payload';
2
2
  import { XpNoTransactionError } from '../errors.js';
3
3
  import { API_MESSAGES } from '../testSurface/copy/common.js';
4
- import { transactionSession, txExecutor } from './executor.js';
4
+ import { raceDeadline, ResultsBudgetError, transactionSession, txExecutor } from './executor.js';
5
5
  const transitionIsolation = 'read committed';
6
6
  const isolationMessage = 'Experiments requires PostgreSQL READ COMMITTED so it can see changes committed while waiting for locks. Set the Postgres adapter\'s transactionOptions.isolationLevel to "read committed" or remove the override.';
7
7
  const checkedSessions = new WeakMap();
@@ -12,17 +12,24 @@ export class XpTransactionIsolationError extends APIError {
12
12
  }
13
13
  /** Payload's initTransaction cannot pass options to the adapter. Like that
14
14
  * helper, publish the pending transaction on the request before awaiting it.
15
- */ export async function initTransitionTransaction(req) {
15
+ */ export async function initTransitionTransaction(req, deadline) {
16
16
  if (req.transactionID != null) {
17
17
  await req.transactionID;
18
18
  return false;
19
19
  }
20
+ if (deadline !== undefined && Date.now() >= deadline) throw new ResultsBudgetError();
20
21
  const db = req.payload.db;
21
22
  const pending = db.beginTransaction({
22
23
  ...db.transactionOptions || {},
23
24
  isolationLevel: transitionIsolation
24
- }).then((id)=>{
25
+ }).then(async (id)=>{
25
26
  if (id == null) throw new XpNoTransactionError();
27
+ // Acquisition can finish after the results deadline. Return the connection
28
+ // without exposing the transaction or letting any transition writes start.
29
+ if (deadline !== undefined && Date.now() >= deadline) {
30
+ await db.rollbackTransaction(id);
31
+ throw new ResultsBudgetError();
32
+ }
26
33
  const session = db.sessions?.[id];
27
34
  if (session) checkedSessions.set(session, Promise.resolve());
28
35
  req.transactionID = id;
@@ -30,10 +37,13 @@ export class XpTransactionIsolationError extends APIError {
30
37
  });
31
38
  req.transactionID = pending;
32
39
  try {
33
- await pending;
40
+ await (deadline === undefined ? pending : raceDeadline(deadline, ()=>pending));
34
41
  return true;
35
42
  } catch (error) {
36
43
  if (req.transactionID === pending) delete req.transactionID;
44
+ // If the timer won before attaching to the already-started acquisition,
45
+ // the late acquisition still rolls back independently.
46
+ if (deadline !== undefined) void pending.catch(()=>{});
37
47
  throw error;
38
48
  }
39
49
  }
@@ -111,7 +111,7 @@ export async function placementWriteContent(req, collection, id, main, path = {}
111
111
  */ export async function runningContentExperiment(exec, binding) {
112
112
  const table = qualifiedTable(exec, TABLES.experiments);
113
113
  const c = COLUMNS.experiments;
114
- const { rows } = await exec.query(`SELECT ${quote(c.id)} AS id, ${quote(c.phase)} AS phase FROM ${table} WHERE ${quote(c[binding.field])} = $1 AND ${quote(c.status)} = 'running' LIMIT 1`, [
114
+ const { rows } = await exec.query(`SELECT ${quote(c.id)} AS id, ${quote(c.phase)} AS phase FROM ${table} WHERE ${quote(c[binding.field])} = $1 AND ${quote(c.status)} IN ('running', 'paused') LIMIT 1`, [
115
115
  binding.value
116
116
  ]);
117
117
  return rows[0];
@@ -0,0 +1,11 @@
1
+ import type { Executor } from './pgExecutor.js';
2
+ export type CohortLookupArgs = {
3
+ keys: string[];
4
+ visitorId?: string;
5
+ userId?: string;
6
+ };
7
+ /** CTEs usable in a query or a correlated LATERAL subquery. The two inputs are
8
+ * trusted SQL expressions, normally bind parameters or typed input columns. */
9
+ export declare function cohortIdentitySet(exec: Partial<Executor>, visitor: string, user: string): string;
10
+ export declare function cohortMembershipQuery(exec: Partial<Executor>, keys?: string, visitor?: string, user?: string): string;
11
+ export declare function lookupCohortMembership(exec: Executor, { keys, visitorId, userId }: CohortLookupArgs): Promise<Set<string>>;
@@ -0,0 +1,31 @@
1
+ import { COLUMNS, TABLES } from './names.js';
2
+ import { qualifiedTable, quoteIdentifier as q } from './sql.js';
3
+ /** CTEs usable in a query or a correlated LATERAL subquery. The two inputs are
4
+ * trusted SQL expressions, normally bind parameters or typed input columns. */ export function cohortIdentitySet(exec, visitor, user) {
5
+ const identities = qualifiedTable(exec, TABLES.identities);
6
+ const i = COLUMNS.identities;
7
+ return `me AS (
8
+ SELECT (${visitor})::text AS id WHERE (${visitor})::text IS NOT NULL
9
+ UNION SELECT (${user})::text WHERE (${user})::text IS NOT NULL
10
+ UNION SELECT ${q(i.userId)} FROM ${identities} WHERE ${q(i.anonymousId)} = (${visitor})::text
11
+ ), ids AS (
12
+ SELECT id FROM me
13
+ UNION SELECT ${q(i.anonymousId)} FROM ${identities} WHERE ${q(i.userId)} IN (SELECT id FROM me)
14
+ )`;
15
+ }
16
+ export function cohortMembershipQuery(exec, keys = '$1', visitor = '$2', user = '$3') {
17
+ const members = qualifiedTable(exec, TABLES.cohortMembers);
18
+ const { cohortKey, unitId, exitedAt } = COLUMNS.cohortMembers;
19
+ // Any current member among the person's linked IDs counts, even if other IDs saw a different arm.
20
+ return `WITH ${cohortIdentitySet(exec, visitor, user)}
21
+ SELECT DISTINCT ${q(cohortKey)} FROM ${members}
22
+ WHERE ${q(cohortKey)} = ANY(${keys}::text[]) AND ${q(unitId)} IN (SELECT id FROM ids) AND ${q(exitedAt)} IS NULL`;
23
+ }
24
+ export async function lookupCohortMembership(exec, { keys, visitorId, userId }) {
25
+ const { rows } = await exec.query(cohortMembershipQuery(exec), [
26
+ keys,
27
+ visitorId ?? null,
28
+ userId ?? null
29
+ ]);
30
+ return new Set(rows.map((row)=>row.cohort_key));
31
+ }
@@ -0,0 +1,9 @@
1
+ import type { Pool } from 'pg';
2
+ import type { Payload } from 'payload';
3
+ import { type CohortLookupArgs } from './cohortMembership.js';
4
+ export declare const COHORT_LOOKUP_TIMEOUT_MS = 200;
5
+ export declare function lookupPooledCohorts(pool: Pool, schemaName: string | undefined, { keys, visitorId, userId }: CohortLookupArgs): Promise<Set<string>>;
6
+ export declare function payloadCohortPool(payload: Payload): {
7
+ pool: Pool;
8
+ schemaName?: string;
9
+ } | undefined;