@delmaredigital/payload-experiments 0.4.1 → 0.5.1

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 (310) 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/blocks/placementLocale.d.ts +14 -0
  22. package/dist/blocks/placementLocale.js +80 -13
  23. package/dist/blocks/placementPublication.d.ts +14 -0
  24. package/dist/blocks/placementPublication.js +24 -0
  25. package/dist/cohorts/build.d.ts +35 -0
  26. package/dist/cohorts/build.js +134 -0
  27. package/dist/cohorts/key.d.ts +12 -0
  28. package/dist/cohorts/key.js +15 -0
  29. package/dist/cohorts/maintenance.d.ts +10 -0
  30. package/dist/cohorts/maintenance.js +70 -0
  31. package/dist/cohorts/readiness.d.ts +30 -0
  32. package/dist/cohorts/readiness.js +54 -0
  33. package/dist/cohorts/readinessData.d.ts +29 -0
  34. package/dist/cohorts/readinessData.js +123 -0
  35. package/dist/cohorts/rule.d.ts +33 -0
  36. package/dist/cohorts/rule.js +50 -0
  37. package/dist/collections/cohortMembers.d.ts +4 -0
  38. package/dist/collections/cohortMembers.js +95 -0
  39. package/dist/collections/experiments/config.js +157 -7
  40. package/dist/collections/experiments/editability.js +10 -6
  41. package/dist/collections/experiments/lockHook.js +39 -20
  42. package/dist/collections/index.js +4 -1
  43. package/dist/collections/phases.js +4 -1
  44. package/dist/constants.d.ts +2 -0
  45. package/dist/constants.js +2 -0
  46. package/dist/db/adapter.d.ts +2 -1
  47. package/dist/db/adapter.js +17 -4
  48. package/dist/db/appends.d.ts +2 -1
  49. package/dist/db/appends.js +3 -2
  50. package/dist/db/bulkPlacementRemoval.d.ts +5 -0
  51. package/dist/db/bulkPlacementRemoval.js +7 -2
  52. package/dist/db/cohortMembership.d.ts +11 -0
  53. package/dist/db/cohortMembership.js +31 -0
  54. package/dist/db/cohortPool.d.ts +9 -0
  55. package/dist/db/cohortPool.js +53 -0
  56. package/dist/db/cohortTransactions.d.ts +3 -0
  57. package/dist/db/cohortTransactions.js +52 -0
  58. package/dist/db/cohorts.d.ts +72 -0
  59. package/dist/db/cohorts.js +280 -0
  60. package/dist/db/erase.d.ts +2 -0
  61. package/dist/db/erase.js +21 -2
  62. package/dist/db/events.d.ts +2 -0
  63. package/dist/db/events.js +8 -0
  64. package/dist/db/executor.d.ts +2 -0
  65. package/dist/db/executor.js +8 -0
  66. package/dist/db/locks.d.ts +7 -0
  67. package/dist/db/locks.js +13 -1
  68. package/dist/db/names.d.ts +95 -1
  69. package/dist/db/names.js +95 -1
  70. package/dist/db/occupancy.d.ts +21 -0
  71. package/dist/db/occupancy.js +46 -0
  72. package/dist/db/pageBindings.d.ts +2 -2
  73. package/dist/db/pageBindings.js +3 -3
  74. package/dist/db/pageOccupancy.d.ts +4 -4
  75. package/dist/db/pageOccupancy.js +13 -10
  76. package/dist/db/pgExecutor.d.ts +4 -0
  77. package/dist/db/pgExecutor.js +1 -1
  78. package/dist/db/placements.d.ts +6 -1
  79. package/dist/db/placements.js +27 -1
  80. package/dist/db/results.d.ts +5 -2
  81. package/dist/db/results.js +32 -5
  82. package/dist/db/slices.d.ts +9 -2
  83. package/dist/db/slices.js +15 -8
  84. package/dist/db/snapshots.d.ts +16 -1
  85. package/dist/db/snapshots.js +27 -2
  86. package/dist/db/sql.d.ts +2 -2
  87. package/dist/db/sql.js +1 -2
  88. package/dist/endpoints/cohortSources.d.ts +16 -0
  89. package/dist/endpoints/cohortSources.js +335 -0
  90. package/dist/endpoints/contentLocale.d.ts +1 -1
  91. package/dist/endpoints/duplicateOriginal.d.ts +1 -0
  92. package/dist/endpoints/events.js +82 -18
  93. package/dist/endpoints/index.js +45 -1
  94. package/dist/endpoints/pausedBy.d.ts +14 -0
  95. package/dist/endpoints/pausedBy.js +94 -0
  96. package/dist/endpoints/preflight.js +4 -1
  97. package/dist/endpoints/previewToken.js +2 -0
  98. package/dist/endpoints/results.d.ts +2 -2
  99. package/dist/endpoints/results.js +111 -3
  100. package/dist/endpoints/routeId.d.ts +2 -1
  101. package/dist/endpoints/routeId.js +6 -2
  102. package/dist/endpoints/summary.js +24 -1
  103. package/dist/endpoints/transitions.d.ts +7 -0
  104. package/dist/endpoints/transitions.js +50 -1
  105. package/dist/events/rows.d.ts +1 -1
  106. package/dist/events/rows.js +5 -3
  107. package/dist/exports/index.d.ts +2 -0
  108. package/dist/exports/index.js +1 -0
  109. package/dist/exports/runtimeProxy.d.ts +1 -0
  110. package/dist/exports/runtimeProxy.js +1 -0
  111. package/dist/hooks/blockRemovalRule.d.ts +1 -1
  112. package/dist/hooks/blockRemovalRule.js +12 -8
  113. package/dist/hooks/pageGuard.d.ts +7 -1
  114. package/dist/hooks/pageGuard.js +177 -4
  115. package/dist/hooks/puckNestedTests.d.ts +1 -1
  116. package/dist/hooks/puckNestedTests.js +3 -1
  117. package/dist/labels/status.d.ts +15 -0
  118. package/dist/labels/status.js +12 -0
  119. package/dist/manifest/compile.d.ts +15 -4
  120. package/dist/manifest/compile.js +91 -3
  121. package/dist/onInit.js +4 -6
  122. package/dist/options.d.ts +1 -0
  123. package/dist/options.js +10 -0
  124. package/dist/proxy/consentFallback.d.ts +1 -1
  125. package/dist/proxy/consentFallback.js +4 -4
  126. package/dist/proxy/control.d.ts +1 -1
  127. package/dist/proxy/control.js +2 -2
  128. package/dist/proxy/pageRewrite.d.ts +1 -1
  129. package/dist/proxy/pageRewrite.js +3 -2
  130. package/dist/proxy/resolve.js +76 -17
  131. package/dist/puck/ExperimentPicker.js +2 -1
  132. package/dist/puck/copy.d.ts +6 -5
  133. package/dist/puck/copy.js +3 -7
  134. package/dist/puck/editor/ExperimentSlotEditor.js +16 -5
  135. package/dist/puck/editor/QuickTestActions.js +7 -1
  136. package/dist/puck/editor/armWrites.js +6 -1
  137. package/dist/puck/editor/copy.d.ts +3 -0
  138. package/dist/puck/editor/copy.js +3 -0
  139. package/dist/puck/editor/editor.css +2 -1
  140. package/dist/puck/editor/editor.model.d.ts +2 -1
  141. package/dist/puck/editor/editor.model.js +2 -0
  142. package/dist/puck/editor/placementsCache.d.ts +1 -1
  143. package/dist/puck/editor/placementsCache.js +6 -3
  144. package/dist/results/analyse.d.ts +3 -1
  145. package/dist/results/analyse.js +20 -3
  146. package/dist/results/health.d.ts +11 -0
  147. package/dist/results/health.js +38 -0
  148. package/dist/results/power.d.ts +1 -1
  149. package/dist/results/power.js +1 -1
  150. package/dist/results/snapshot.d.ts +8 -2
  151. package/dist/results/snapshot.js +23 -1
  152. package/dist/results/unitValues.d.ts +48 -0
  153. package/dist/results/unitValues.js +166 -0
  154. package/dist/runtime/assign.d.ts +7 -3
  155. package/dist/runtime/assign.js +12 -4
  156. package/dist/runtime/cohortCookie.d.ts +15 -0
  157. package/dist/runtime/cohortCookie.js +72 -0
  158. package/dist/runtime/cohortLookup.d.ts +9 -0
  159. package/dist/runtime/cohortLookup.js +25 -0
  160. package/dist/runtime/eligibility.d.ts +11 -5
  161. package/dist/runtime/eligibility.js +33 -7
  162. package/dist/runtime/header.d.ts +1 -0
  163. package/dist/runtime/header.js +1 -1
  164. package/dist/runtime/proxyRuntime.js +5 -1
  165. package/dist/runtime/targeting.d.ts +3 -2
  166. package/dist/runtime/targeting.js +2 -1
  167. package/dist/sanitizeReadinessDetail.d.ts +2 -2
  168. package/dist/sanitizeReadinessDetail.js +41 -4
  169. package/dist/schedule/activeTime.d.ts +28 -0
  170. package/dist/schedule/activeTime.js +322 -0
  171. package/dist/schedule/ranges.d.ts +13 -0
  172. package/dist/schedule/ranges.js +11 -0
  173. package/dist/schedule/roundTime.d.ts +10 -0
  174. package/dist/schedule/roundTime.js +45 -0
  175. package/dist/schedule/types.d.ts +29 -0
  176. package/dist/schedule/types.js +1 -0
  177. package/dist/server/cohortLookup.d.ts +3 -0
  178. package/dist/server/cohortLookup.js +7 -0
  179. package/dist/server/eraseUser.d.ts +1 -0
  180. package/dist/server/getAssignments.js +63 -40
  181. package/dist/server/previewDraft.d.ts +1 -1
  182. package/dist/server/previewDraft.js +3 -2
  183. package/dist/server/recordContentChange.d.ts +1 -1
  184. package/dist/server/recordContentChange.js +42 -20
  185. package/dist/server/recordExposures.js +4 -2
  186. package/dist/server/runResults.js +97 -150
  187. package/dist/testSurface/actions/LifecycleAction.d.ts +2 -1
  188. package/dist/testSurface/actions/LifecycleAction.js +15 -5
  189. package/dist/testSurface/actions/actions.model.d.ts +13 -2
  190. package/dist/testSurface/actions/actions.model.js +38 -5
  191. package/dist/testSurface/api.d.ts +13 -1
  192. package/dist/testSurface/api.js +19 -0
  193. package/dist/testSurface/copy/actions.d.ts +13 -0
  194. package/dist/testSurface/copy/actions.js +13 -0
  195. package/dist/testSurface/copy/cohorts.d.ts +68 -0
  196. package/dist/testSurface/copy/cohorts.js +81 -0
  197. package/dist/testSurface/copy/common.d.ts +2 -3
  198. package/dist/testSurface/copy/common.js +4 -4
  199. package/dist/testSurface/copy/inputs.d.ts +3 -0
  200. package/dist/testSurface/copy/inputs.js +3 -0
  201. package/dist/testSurface/copy/readiness.d.ts +20 -6
  202. package/dist/testSurface/copy/readiness.js +42 -9
  203. package/dist/testSurface/copy/results.d.ts +1 -0
  204. package/dist/testSurface/copy/results.js +1 -0
  205. package/dist/testSurface/copy/schedule.d.ts +58 -0
  206. package/dist/testSurface/copy/schedule.js +150 -0
  207. package/dist/testSurface/copy/surface.d.ts +2 -0
  208. package/dist/testSurface/copy/surface.js +2 -0
  209. package/dist/testSurface/copy/testPage.d.ts +12 -2
  210. package/dist/testSurface/copy/testPage.js +17 -2
  211. package/dist/testSurface/format/roundProgress.d.ts +13 -1
  212. package/dist/testSurface/format/roundProgress.js +34 -5
  213. package/dist/testSurface/format/scheduleStatus.d.ts +34 -0
  214. package/dist/testSurface/format/scheduleStatus.js +93 -0
  215. package/dist/testSurface/format/useScheduleClock.d.ts +3 -0
  216. package/dist/testSurface/format/useScheduleClock.js +20 -0
  217. package/dist/testSurface/labels.d.ts +4 -9
  218. package/dist/testSurface/labels.js +2 -7
  219. package/dist/testSurface/lockedNotice.model.d.ts +2 -2
  220. package/dist/testSurface/lockedNotice.model.js +16 -3
  221. package/dist/testSurface/readPreflight.d.ts +3 -0
  222. package/dist/testSurface/readPreflight.js +14 -0
  223. package/dist/testSurface/readinessRead.d.ts +2 -2
  224. package/dist/testSurface/results/DataQualityPanel.js +7 -7
  225. package/dist/testSurface/results/results.model.d.ts +1 -1
  226. package/dist/testSurface/results/results.model.js +34 -6
  227. package/dist/testSurface/review/cohortEstimate.d.ts +11 -0
  228. package/dist/testSurface/review/cohortEstimate.js +32 -0
  229. package/dist/testSurface/surface/contracts.d.ts +2 -1
  230. package/dist/testSurface/surface/contracts.js +1 -0
  231. package/dist/testSurface/surface/editorPlacement.d.ts +1 -0
  232. package/dist/testSurface/surface/readiness/ActionDialogs.d.ts +3 -2
  233. package/dist/testSurface/surface/readiness/ActionDialogs.js +121 -32
  234. package/dist/testSurface/surface/readiness/Banner.js +29 -11
  235. package/dist/testSurface/surface/readiness/readiness.model.d.ts +20 -2
  236. package/dist/testSurface/surface/readiness/readiness.model.js +35 -5
  237. package/dist/testSurface/surface/readiness/useTransition.js +17 -5
  238. package/dist/testSurface/surface/results/ResultsBody.js +44 -8
  239. package/dist/testSurface/surface/results/useResults.d.ts +16 -1
  240. package/dist/testSurface/surface/results/useResults.js +17 -6
  241. package/dist/testSurface/surface/test/CohortRuleEditor.d.ts +16 -0
  242. package/dist/testSurface/surface/test/CohortRuleEditor.js +492 -0
  243. package/dist/testSurface/surface/test/LengthSection.js +26 -6
  244. package/dist/testSurface/surface/test/ScheduleDateInput.d.ts +4 -0
  245. package/dist/testSurface/surface/test/ScheduleDateInput.js +15 -0
  246. package/dist/testSurface/surface/test/ScheduleSection.d.ts +2 -0
  247. package/dist/testSurface/surface/test/ScheduleSection.js +322 -0
  248. package/dist/testSurface/surface/test/Section.js +1 -1
  249. package/dist/testSurface/surface/test/TargetingSection.js +306 -182
  250. package/dist/testSurface/surface/test/TestSurface.js +9 -0
  251. package/dist/testSurface/surface/test/fields.d.ts +2 -1
  252. package/dist/testSurface/surface/test/fields.js +3 -3
  253. package/dist/testSurface/surface/test/jumpToSection.d.ts +1 -1
  254. package/dist/testSurface/surface/test/jumpToSection.js +4 -4
  255. package/dist/testSurface/surface/test/testPage.css +26 -0
  256. package/dist/testSurface/surface/testDocument.model.d.ts +12 -1
  257. package/dist/testSurface/surface/testDocument.model.js +2 -1
  258. package/dist/testSurface/surface/useTestDocument.js +11 -4
  259. package/dist/testSurface/targeting/targeting.model.d.ts +2 -1
  260. package/dist/testSurface/targeting/targeting.model.js +1 -1
  261. package/dist/testSurface/useApi.d.ts +12 -0
  262. package/dist/transitions/addMetric.js +5 -2
  263. package/dist/transitions/allocate.js +6 -1
  264. package/dist/transitions/assertNoOverlap.d.ts +9 -0
  265. package/dist/transitions/assertNoOverlap.js +24 -0
  266. package/dist/transitions/buildCohorts.d.ts +10 -0
  267. package/dist/transitions/buildCohorts.js +68 -0
  268. package/dist/transitions/cancelSchedule.d.ts +4 -0
  269. package/dist/transitions/cancelSchedule.js +42 -0
  270. package/dist/transitions/checkStart.d.ts +17 -3
  271. package/dist/transitions/checkStart.js +20 -7
  272. package/dist/transitions/decide.js +40 -13
  273. package/dist/transitions/kernel.d.ts +3 -1
  274. package/dist/transitions/kernel.js +5 -2
  275. package/dist/transitions/pause.d.ts +4 -0
  276. package/dist/transitions/pause.js +35 -0
  277. package/dist/transitions/phaseRecord.d.ts +19 -2
  278. package/dist/transitions/phaseRecord.js +50 -11
  279. package/dist/transitions/placementInteractions.d.ts +7 -2
  280. package/dist/transitions/placementInteractions.js +9 -7
  281. package/dist/transitions/placements.d.ts +4 -3
  282. package/dist/transitions/placements.js +28 -14
  283. package/dist/transitions/preflightData.d.ts +11 -3
  284. package/dist/transitions/preflightData.js +134 -81
  285. package/dist/transitions/reschedule.d.ts +4 -0
  286. package/dist/transitions/reschedule.js +58 -0
  287. package/dist/transitions/resume.d.ts +4 -0
  288. package/dist/transitions/resume.js +32 -0
  289. package/dist/transitions/scheduledRound.d.ts +18 -0
  290. package/dist/transitions/scheduledRound.js +42 -0
  291. package/dist/transitions/start.d.ts +4 -0
  292. package/dist/transitions/start.js +139 -56
  293. package/dist/transitions/startReads.d.ts +14 -0
  294. package/dist/transitions/startReads.js +27 -0
  295. package/dist/transitions/stop.d.ts +10 -0
  296. package/dist/transitions/stop.js +35 -22
  297. package/dist/types/admin.d.ts +1 -1
  298. package/dist/types/contracts.d.ts +7 -1
  299. package/dist/types/endpoints.d.ts +72 -3
  300. package/dist/types/manifest.d.ts +9 -0
  301. package/dist/types/runtime.d.ts +5 -0
  302. package/dist/types/snapshot.d.ts +10 -0
  303. package/dist/types/status.d.ts +1 -0
  304. package/dist/types/status.js +1 -0
  305. package/dist/types/surface.d.ts +1 -0
  306. package/dist/ui/Feedback.d.ts +9 -6
  307. package/dist/ui/Feedback.js +10 -9
  308. package/dist/ui/SelectControl.js +1 -1
  309. package/dist/ui/ui.css +2 -1
  310. package/package.json +2 -2
@@ -0,0 +1,29 @@
1
+ export type Weekday = 'mon' | 'tue' | 'wed' | 'thu' | 'fri' | 'sat' | 'sun';
2
+ export type ScheduleWindow = {
3
+ days: Weekday[];
4
+ from: string;
5
+ to: string;
6
+ };
7
+ export type ActiveSpec = {
8
+ from?: string;
9
+ to?: string;
10
+ tz: string;
11
+ windows: ScheduleWindow[];
12
+ };
13
+ export type PauseInterval = {
14
+ from: string;
15
+ to?: string;
16
+ by: string;
17
+ reason?: string;
18
+ };
19
+ export type ExperimentSchedule = {
20
+ startAt?: string;
21
+ endAt?: string;
22
+ timeZone: string;
23
+ windows: ScheduleWindow[];
24
+ };
25
+ /** The part of the frozen phase record needed to calculate time and progress. */
26
+ export type RoundTiming = {
27
+ schedule?: ExperimentSchedule | null;
28
+ pauses?: Array<Pick<PauseInterval, 'from' | 'to'>> | null;
29
+ };
@@ -0,0 +1 @@
1
+ /** The part of the frozen phase record needed to calculate time and progress. */ export { };
@@ -0,0 +1,3 @@
1
+ import type { Payload } from 'payload';
2
+ import type { CohortLookupArgs } from '../db/cohortMembership.js';
3
+ export declare function resolveServerCohorts(payload: Payload | undefined, args: CohortLookupArgs): Promise<Map<string, boolean> | undefined> | undefined;
@@ -0,0 +1,7 @@
1
+ import { payloadCohortPool } from '../db/cohortPool.js';
2
+ import { createPostgresCohortLookup, resolveCohorts } from '../runtime/cohortLookup.js';
3
+ export function resolveServerCohorts(payload, args) {
4
+ if (!args.keys.length) return undefined;
5
+ const options = payload && payloadCohortPool(payload);
6
+ return options ? resolveCohorts(createPostgresCohortLookup(options), args) : undefined;
7
+ }
@@ -4,4 +4,5 @@ export declare function eraseUser(payload: Payload, opts: {
4
4
  }): Promise<{
5
5
  identities: number;
6
6
  events: number;
7
+ cohortMembers: number;
7
8
  }>;
@@ -2,7 +2,8 @@ import { cache } from 'react';
2
2
  import { headers } from 'next/headers.js';
3
3
  import { XP_HEADER } from '../constants.js';
4
4
  import { assign, fillFlagPoints } from '../runtime/assign.js';
5
- import { readUnitCookie } from '../runtime/cookie.js';
5
+ import { cohortKeysToResolve, isEntryActive } from '../runtime/eligibility.js';
6
+ import { readSignedUnit } from '../runtime/cookie.js';
6
7
  import { decodeAssignmentsHeader } from '../runtime/header.js';
7
8
  import { verifyPreviewToken } from '../runtime/previewToken.js';
8
9
  import { isBot } from '../runtime/bot.js';
@@ -13,6 +14,7 @@ import { emptyManifest, rememberManifest, serverManifest, suppressExposure } fro
13
14
  import { serverRequest } from './request.js';
14
15
  import { previewDraft } from './previewDraft.js';
15
16
  import { verifiedHeaderRevision } from './headerRevision.js';
17
+ import { resolveServerCohorts } from './cohortLookup.js';
16
18
  // The mutable cell lives in React's request cache, never a process-wide user cache.
17
19
  const requestCell = cache((_runtime, _userId)=>({
18
20
  value: undefined
@@ -25,8 +27,10 @@ export async function getAssignments(serverRuntime, opts) {
25
27
  async function readAssignments(runtime, suppliedUser) {
26
28
  const requestHeaders = new Headers(await headers());
27
29
  const proxy = runtime.proxyRuntime;
30
+ const clock = proxy.now ?? (()=>new Date());
31
+ let now = clock();
28
32
  const { request, hasContext, consent } = serverRequest(requestHeaders, proxy.secrets);
29
- const visitorId = consent === false ? undefined : readUnitCookie(requestHeaders, proxy) ?? undefined;
33
+ const visitorId = consent === false ? undefined : readSignedUnit(requestHeaders, proxy, now.getTime())?.unitId;
30
34
  let payload;
31
35
  let payloadFailed = false;
32
36
  try {
@@ -92,7 +96,8 @@ async function readAssignments(runtime, suppliedUser) {
92
96
  secrets: proxy.secrets,
93
97
  visitorId,
94
98
  userId: headerUserId,
95
- manifest
99
+ manifest,
100
+ now
96
101
  }) : null;
97
102
  const mustResolveStaff = Boolean(options?.attributeKeys?.staff && (decoded?.sessionUnknown || unit.sessionUnknown));
98
103
  const needsUser = !decoded || decoded.deferred.length > 0 || mustResolveStaff || suppliedUser !== undefined;
@@ -110,7 +115,7 @@ async function readAssignments(runtime, suppliedUser) {
110
115
  }
111
116
  }
112
117
  const userId = canAssignUser ? user === undefined ? unit.userId : user ? runtime.userIdOf(user) : undefined : undefined;
113
- const token = hasContext ? verifyPreviewToken(request.nextUrl.searchParams.get('xp_preview') ?? '', proxy.secrets) : null;
118
+ const token = hasContext ? verifyPreviewToken(request.nextUrl.searchParams.get('xp_preview') ?? '', proxy.secrets, Math.floor(now.getTime() / 1000)) : null;
114
119
  const context = {
115
120
  visitorId,
116
121
  userId,
@@ -134,20 +139,44 @@ async function readAssignments(runtime, suppliedUser) {
134
139
  return result;
135
140
  };
136
141
  const lastResort = ()=>rememberManifest(fillHostDefaults(emptyAssignments(context)), emptyManifest());
142
+ const recompute = async (subset)=>{
143
+ const unit = {
144
+ visitorId,
145
+ userId,
146
+ sessionUnknown: context.sessionUnknown
147
+ };
148
+ const opts = {
149
+ ...context,
150
+ now
151
+ };
152
+ const keys = cohortKeysToResolve(subset, unit, attributes, opts);
153
+ const pending = resolveServerCohorts(payload, {
154
+ keys,
155
+ visitorId,
156
+ userId
157
+ });
158
+ const cohorts = pending && await pending;
159
+ if (pending) now = clock();
160
+ return assign(subset, unit, attributes, {
161
+ ...opts,
162
+ now,
163
+ cohorts
164
+ });
165
+ };
137
166
  let result;
138
167
  if (payloadFailed) {
139
168
  try {
140
- result = controlAssignments(manifest, context);
169
+ result = controlAssignments(manifest, context, now);
141
170
  } catch {
142
171
  return lastResort();
143
172
  }
144
173
  } else if (consent === false && !decoded) {
145
174
  try {
146
- result = consentFallback(manifest, attributes, context);
175
+ result = consentFallback(manifest, attributes, context, now);
147
176
  } catch {
148
177
  console.error('[payload-experiments] consent fallback failed; serving non-exposable control');
149
178
  try {
150
- result = controlAssignments(manifest, context);
179
+ result = controlAssignments(manifest, context, now);
151
180
  } catch {
152
181
  return lastResort();
153
182
  }
@@ -162,62 +191,56 @@ async function readAssignments(runtime, suppliedUser) {
162
191
  };
163
192
  const slugs = new Set(hasContext ? decoded.deferred : []);
164
193
  if (canAssignUser && user !== undefined && userId !== headerUserId) {
165
- for (const e of manifest.experiments)if (e.unitType === 'user') slugs.add(e.slug);
194
+ // Visitor cohort membership can also depend on the user resolved by the server.
195
+ // A signed page assignment already selected the path served by the proxy.
196
+ for (const e of manifest.experiments)if (e.unitType === 'user' || e.kind !== 'page' && e.cohorts?.length) slugs.add(e.slug);
166
197
  }
167
198
  if (slugs.size && canResolveUser && !userFailed) {
168
199
  try {
169
- const resolved = assign(manifest, {
170
- visitorId,
171
- userId,
172
- sessionUnknown: context.sessionUnknown
173
- }, attributes, {
174
- ...context,
175
- now: Math.floor(Date.now() / 1000)
200
+ const resolved = await recompute({
201
+ ...manifest,
202
+ experiments: manifest.experiments.filter((e)=>slugs.has(e.slug))
176
203
  });
177
204
  for (const slug of slugs){
178
- result.bySlug[slug] = resolved.bySlug[slug] ?? controlAssignments(manifest, context).bySlug[slug];
205
+ result.bySlug[slug] = resolved.bySlug[slug] ?? controlAssignments(manifest, context, now).bySlug[slug];
179
206
  }
180
207
  } catch {
181
208
  userFailed = true;
182
209
  }
183
210
  }
184
- } else if (!visitorId && !userId || !hasContext) result = controlAssignments(manifest, context);
211
+ } else if (!visitorId && !userId || !hasContext) result = controlAssignments(manifest, context, now);
185
212
  else {
186
213
  try {
187
- result = assign(manifest, {
188
- visitorId,
189
- userId,
190
- sessionUnknown: context.sessionUnknown
191
- }, attributes, {
192
- ...context,
193
- now: Math.floor(Date.now() / 1000)
194
- });
214
+ result = await recompute(manifest);
195
215
  } catch {
196
216
  console.error('[payload-experiments] assign failed; serving non-exposable control');
197
- result = controlAssignments(manifest, context);
217
+ result = controlAssignments(manifest, context, now);
198
218
  }
199
219
  }
200
- // Missing users left deferred by assign must still render explicit, safe control.
201
- const controls = controlAssignments(manifest, context);
220
+ // A signed assignment can cross a schedule boundary before the server renders.
221
+ // Missing users left deferred by assign also need an explicit control.
222
+ const controls = controlAssignments(manifest, context, now);
202
223
  for (const experiment of manifest.experiments){
203
- if (!result.bySlug[experiment.slug]) result.bySlug[experiment.slug] = controls.bySlug[experiment.slug];
224
+ if (!result.bySlug[experiment.slug] || !isEntryActive(experiment, now)) result.bySlug[experiment.slug] = controls.bySlug[experiment.slug];
204
225
  }
205
- fillFlagPoints(result, manifest);
226
+ fillFlagPoints(result, manifest, now);
206
227
  fillHostDefaults(result);
207
228
  if (token && visitorId && payload) {
208
229
  const live = manifest.experiments.find((e)=>e.id === token.e && e.phase === token.p && e.arms.some((a)=>a.key === token.a));
209
230
  if (live) {
210
231
  result.preview = true;
211
- result.bySlug[live.slug] = {
212
- slug: live.slug,
213
- experimentId: live.id,
214
- arm: token.a,
215
- phase: token.p,
216
- policy: live.exposurePolicy,
217
- exposable: false,
218
- source: 'preview'
219
- };
220
- fillFlagPoints(result, manifest);
232
+ if (isEntryActive(live, now)) {
233
+ result.bySlug[live.slug] = {
234
+ slug: live.slug,
235
+ experimentId: live.id,
236
+ arm: token.a,
237
+ phase: token.p,
238
+ policy: live.exposurePolicy,
239
+ exposable: false,
240
+ source: 'preview'
241
+ };
242
+ fillFlagPoints(result, manifest, now);
243
+ }
221
244
  } else await previewDraft(payload, await resolveUser(), token, result, requestHeaders);
222
245
  }
223
246
  if (suppressExposure(result) || !hasContext || payloadFailed || userFailed || mustResolveStaff && !runtime.getUser && suppliedUser === undefined) {
@@ -1,7 +1,7 @@
1
1
  import type { Payload } from 'payload';
2
2
  import type { PreviewToken } from '../runtime/previewToken.js';
3
3
  import type { Assignments } from '../types/assignments.js';
4
- /** Draft previews use the authenticated manager's normal collection access. */
4
+ /** Previews outside the manifest use the authenticated manager's normal collection access. */
5
5
  export declare function previewDraft(payload: Payload, user: {
6
6
  id: string | number;
7
7
  } | null, token: PreviewToken, assignments: Assignments, headers: Headers): Promise<void>;
@@ -1,4 +1,4 @@
1
- /** Draft previews use the authenticated manager's normal collection access. */ export async function previewDraft(payload, user, token, assignments, headers) {
1
+ /** Previews outside the manifest use the authenticated manager's normal collection access. */ export async function previewDraft(payload, user, token, assignments, headers) {
2
2
  if (!user) return;
3
3
  try {
4
4
  const doc = await payload.findByID({
@@ -12,7 +12,7 @@
12
12
  headers
13
13
  }
14
14
  });
15
- if (doc.status !== 'draft' && doc.status !== 'stopped' || doc.phase !== token.p || typeof doc.slug !== 'string' || !Array.isArray(doc.arms)) return;
15
+ if (doc.status !== 'draft' && doc.status !== 'stopped' && doc.status !== 'paused' || doc.phase !== token.p || typeof doc.slug !== 'string' || !Array.isArray(doc.arms)) return;
16
16
  const arm = doc.arms.find((a)=>a.key === token.a);
17
17
  if (!arm || ![
18
18
  'render',
@@ -21,6 +21,7 @@
21
21
  'manual'
22
22
  ].includes(doc.exposurePolicy)) return;
23
23
  assignments.preview = true;
24
+ if (doc.status === 'paused') return;
24
25
  assignments.bySlug[doc.slug] = {
25
26
  slug: doc.slug,
26
27
  experimentId: doc.id,
@@ -1,6 +1,6 @@
1
1
  import type { CollectionAfterChangeHook, CollectionBeforeChangeHook } from 'payload';
2
2
  /** Paired raw beforeChange capture: previousDoc may be an autosaved draft. */
3
- export declare function capturePublishedContent({ req, collection, originalDoc, operation }: Parameters<CollectionBeforeChangeHook>[0]): Promise<void>;
3
+ export declare function capturePublishedContent({ req, collection, originalDoc, operation, data }: Parameters<CollectionBeforeChangeHook>[0]): Promise<void>;
4
4
  type ContentChangeArgs = Pick<Parameters<CollectionAfterChangeHook>[0], 'doc' | 'previousDoc' | 'req' | 'collection'>;
5
5
  /** Publish-only host helper. Audit failures are logged after savepoint recovery. */
6
6
  export declare function recordContentChange(args: ContentChangeArgs): Promise<void>;
@@ -1,4 +1,5 @@
1
1
  import { placementReader } from '../blocks/placementLocale.js';
2
+ import { publishedInLocale, usesLocalizedPublication } from '../blocks/placementPublication.js';
2
3
  import { puckExperimentSlug } from '../puck/experimentSlug.js';
3
4
  import { puckVisibility } from '../puck/visibility.js';
4
5
  import { EXPERIMENT_BLOCK_SLUG, hostBlocks } from '../blocks/model.js';
@@ -9,6 +10,7 @@ import { appendContentChange, contentChangeSavepoint, previousPublishedContent,
9
10
  import { txExecutor } from '../db/executor.js';
10
11
  import { pageContentBindings } from '../db/pageBindings.js';
11
12
  import { sortLockKeys } from '../db/locks.js';
13
+ import { writesAllPublicationLocales } from '../hooks/pageGuard.js';
12
14
  import { normalisePath } from '../runtime/normalisePath.js';
13
15
  import { comparableContent } from '../transitions/pageVersions.js';
14
16
  import { puckCollections } from '../options.js';
@@ -65,7 +67,7 @@ function bindings(data, puck) {
65
67
  return found;
66
68
  }
67
69
  const baselineKey = (collection, id)=>`${collection}:${id}`;
68
- /** Paired raw beforeChange capture: previousDoc may be an autosaved draft. */ export async function capturePublishedContent({ req, collection, originalDoc, operation }) {
70
+ /** Paired raw beforeChange capture: previousDoc may be an autosaved draft. */ export async function capturePublishedContent({ req, collection, originalDoc, operation, data }) {
69
71
  if (await req.transactionID == null) {
70
72
  req.payload.logger?.debug('[payload-experiments] contentChanges baseline skipped without a transaction');
71
73
  return;
@@ -76,10 +78,14 @@ const baselineKey = (collection, id)=>`${collection}:${id}`;
76
78
  delete baselines[key];
77
79
  const audit = await contentChangeSavepoint(txExecutor(req), async ()=>operation === 'create' ? undefined : collection.versions && collection.versions.drafts ? previousPublishedContent(req, collection.slug, id) : storedContent(req, collection.slug, id));
78
80
  if (!audit.ok) throw audit.error;
81
+ // Payload 3 passes the original status map to beforeChange on Publish All,
82
+ // including on host collections that install the audit without the guard.
83
+ const publishAllLocales = data?._status === 'published' && object(originalDoc?._status);
79
84
  baselines[key] = {
80
85
  collection: collection.slug,
81
86
  id,
82
- doc: audit.result
87
+ doc: audit.result,
88
+ publishAllLocales
83
89
  };
84
90
  }
85
91
  /** Publish-only host helper. Audit failures are logged after savepoint recovery. */ export async function recordContentChange(args) {
@@ -97,14 +103,19 @@ const baselineKey = (collection, id)=>`${collection}:${id}`;
97
103
  }
98
104
  async function auditContentChange({ doc, previousDoc, req, collection }) {
99
105
  const drafts = Boolean(collection.versions && collection.versions.drafts);
100
- if (drafts && doc._status !== 'published') return;
106
+ const localizedStatus = usesLocalizedPublication(req, collection.slug, collection);
107
+ const statusMap = localizedStatus && object(doc._status);
108
+ const baselines = req.context.xpPublishedContent;
109
+ const creating = previousDoc?.id == null;
110
+ const key = baselineKey(collection.slug, creating ? '__create__' : doc.id);
111
+ const baseline = baselines?.[key];
112
+ // Restore can supply the raw previous version alongside a projected result.
113
+ const allLocales = localizedStatus && (statusMap || req.locale === 'all' || baseline?.publishAllLocales || object(previousDoc?._status) || creating && doc._status === 'published' || writesAllPublicationLocales(req, collection.slug));
114
+ if (drafts && !allLocales && doc._status !== 'published') return;
101
115
  if (await req.transactionID == null) {
102
116
  req.payload.logger?.debug('[payload-experiments] contentChanges skipped without a transaction');
103
117
  return;
104
118
  }
105
- const baselines = req.context.xpPublishedContent;
106
- const key = baselineKey(collection.slug, previousDoc?.id == null ? '__create__' : doc.id);
107
- const baseline = baselines?.[key];
108
119
  if (baselines) delete baselines[key];
109
120
  // Missing capture must never turn an unchanged publish into a false marker.
110
121
  if (drafts && !baseline) {
@@ -148,9 +159,6 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
148
159
  ])
149
160
  ].filter((key)=>!isDeepStrictEqual(before.get(key)?.contents, after.get(key)?.contents)).map((key)=>after.get(key) ?? before.get(key));
150
161
  };
151
- const changes = (previous, current, input)=>(input === 'all-locales' ? reader.documentViews : [
152
- undefined
153
- ]).flatMap((view)=>changesOne(reader.read(object(previous) ? previous : undefined, input, view).doc, reader.read(object(current) ? current : undefined, input, view).doc));
154
162
  // Include discovery reads in the savepoint: a SQL read error also aborts Postgres.
155
163
  // An explicit host call must supply its afterChange request's transaction.
156
164
  const executor = txExecutor(req);
@@ -158,23 +166,41 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
158
166
  // Compare like with like. A captured baseline is adapter-raw, so it meets the stored row after the
159
167
  // write. Without one, previousDoc and doc are both afterRead documents (same locale projection,
160
168
  // hidden fields and field hooks) that differ only in depth, so only relationships are normalised.
161
- const locales = req.payload.config.localization ? req.payload.config.localization.localeCodes : [];
169
+ const localization = req.payload.config.localization;
170
+ const locales = localization ? localization.localeCodes : [];
162
171
  const normalise = (value)=>normaliseContentRelationships(value, collection.fields, req.payload.config.blocks, locales);
163
- let changed;
164
172
  let beforeRow, afterRow;
165
173
  if (baseline) {
166
174
  const current = await storedContent(req, collection.slug, doc.id);
167
175
  if (!current) throw new Error('The saved content row was not found.');
168
176
  beforeRow = baseline.doc;
169
177
  afterRow = current;
170
- changed = changes(beforeRow, afterRow, 'all-locales');
171
178
  } else {
172
179
  beforeRow = normalise(previousDoc);
173
180
  afterRow = normalise(doc);
174
- changed = changes(beforeRow, afterRow, 'localized');
175
181
  }
182
+ const previous = object(beforeRow) ? beforeRow : undefined;
183
+ const current = object(afterRow) ? afterRow : undefined;
184
+ const locale = req.locale || (localization ? localization.defaultLocale : '');
185
+ const contentViews = (input)=>{
186
+ const views = input === 'all-locales' ? reader.documentViews : [
187
+ undefined
188
+ ];
189
+ return views.flatMap((view)=>{
190
+ // Draft versions can carry published statuses for untouched locales.
191
+ // Compare the main row and only the views this save can publish.
192
+ if (localizedStatus && view && (!allLocales && view.locale !== locale || statusMap && !publishedInLocale(doc, view.locale) || !publishedInLocale(current, view.locale))) return [];
193
+ const before = localizedStatus && view && !publishedInLocale(previous, view.locale) ? undefined : previous;
194
+ return [
195
+ [
196
+ reader.read(before, input, view).doc,
197
+ reader.read(current, input, view).doc
198
+ ]
199
+ ];
200
+ });
201
+ };
176
202
  const experiments = new Map();
177
- for (const binding of changed){
203
+ for (const binding of contentViews(baseline ? 'all-locales' : 'localized').flatMap(([before, after])=>changesOne(before, after))){
178
204
  const experiment = await runningContentExperiment(executor, binding);
179
205
  if (experiment) experiments.set(String(experiment.id), experiment.id);
180
206
  }
@@ -182,11 +208,7 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
182
208
  if (page?.contentOf) {
183
209
  const input = baseline || req.locale === 'all' ? 'all-locales' : 'localized';
184
210
  const paths = new Set();
185
- for (const view of input === 'all-locales' ? reader.documentViews : [
186
- undefined
187
- ]){
188
- const before = reader.read(object(beforeRow) ? beforeRow : undefined, input, view).doc;
189
- const after = reader.read(object(afterRow) ? afterRow : undefined, input, view).doc;
211
+ for (const [before, after] of contentViews(input)){
190
212
  if (isDeepStrictEqual(comparableContent(before ? page.contentOf(before) : undefined), comparableContent(after ? page.contentOf(after) : undefined))) continue;
191
213
  for (const doc of [
192
214
  before,
@@ -198,7 +220,7 @@ async function auditContentChange({ doc, previousDoc, req, collection }) {
198
220
  }
199
221
  if (paths.size) for (const id of (await pageContentBindings(executor, collection.slug, sortLockKeys([
200
222
  ...paths
201
- ]))))experiments.set(String(id), id);
223
+ ]), localizedStatus)))experiments.set(String(id), id);
202
224
  }
203
225
  // Successful audit locks persist until commit; acquire multiple E locks in order.
204
226
  for (const key of sortLockKeys([
@@ -4,6 +4,7 @@ import { insertEvents } from '../db/events.js';
4
4
  import { exposureDimensions } from '../events/dimensions.js';
5
5
  import { requestAttributesOf } from './context.js';
6
6
  import { readManifestRow } from '../db/manifest.js';
7
+ import { isEntryActive } from '../runtime/eligibility.js';
7
8
  export async function recordExposures(serverRuntime, rendered, ctx) {
8
9
  let payload;
9
10
  try {
@@ -18,7 +19,8 @@ export async function recordExposures(serverRuntime, rendered, ctx) {
18
19
  });
19
20
  if (!candidates.length) return;
20
21
  const { visitorId, userId } = ctx;
21
- const ts = new Date().toISOString();
22
+ const now = serverRuntime.proxyRuntime?.now?.() ?? new Date();
23
+ const ts = now.toISOString();
22
24
  payload = await serverRuntime.getPayload();
23
25
  const options = payload.config?.custom?.xp;
24
26
  const dimensions = exposureDimensions(requestAttributesOf(ctx), options?.events?.dimensions);
@@ -27,7 +29,7 @@ export async function recordExposures(serverRuntime, rendered, ctx) {
27
29
  const manifest = await readManifestRow(exec);
28
30
  const rows = candidates.flatMap((assignment)=>{
29
31
  const experiment = manifest?.manifest.experiments.find((exp)=>exp.id === assignment.experimentId && exp.slug === assignment.slug);
30
- if (!experiment) return [];
32
+ if (!experiment || !isEntryActive(experiment, now)) return [];
31
33
  const unitId = experiment.unitType === 'visitor' ? visitorId : userId;
32
34
  if (!unitId) return [];
33
35
  return [