@delmaredigital/payload-experiments 0.3.0-rc.4 → 0.4.0-rc.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 (265) hide show
  1. package/README.md +113 -20
  2. package/dist/admin/MetricSourceSelect.js +3 -3
  3. package/dist/admin/PlacementStatus.d.ts +3 -0
  4. package/dist/admin/PlacementStatus.js +54 -0
  5. package/dist/admin/PreviewLinks.d.ts +2 -1
  6. package/dist/admin/PreviewLinks.js +2 -2
  7. package/dist/admin/actions/ConfirmDialog.d.ts +2 -1
  8. package/dist/admin/actions/ConfirmDialog.js +2 -2
  9. package/dist/admin/actions/DecideDialog.d.ts +2 -1
  10. package/dist/admin/actions/DecideDialog.js +2 -2
  11. package/dist/admin/api.d.ts +11 -2
  12. package/dist/admin/api.js +20 -2
  13. package/dist/admin/blocks/BlockPanel.d.ts +4 -0
  14. package/dist/admin/blocks/BlockPanel.js +153 -0
  15. package/dist/admin/blocks/TestBlockField.d.ts +5 -0
  16. package/dist/admin/blocks/TestBlockField.js +163 -0
  17. package/dist/admin/blocks/formApi.d.ts +43 -0
  18. package/dist/admin/blocks/formApi.js +153 -0
  19. package/dist/admin/blocks/inject.d.ts +7 -0
  20. package/dist/admin/blocks/inject.js +41 -0
  21. package/dist/admin/blocks/model.d.ts +17 -0
  22. package/dist/admin/blocks/model.js +45 -0
  23. package/dist/admin/blocks/statusCache.d.ts +7 -0
  24. package/dist/admin/blocks/statusCache.js +83 -0
  25. package/dist/admin/blocks/useBlockForm.d.ts +17 -0
  26. package/dist/admin/blocks/useBlockForm.js +46 -0
  27. package/dist/admin/copy/actions.d.ts +2 -0
  28. package/dist/admin/copy/actions.js +9 -0
  29. package/dist/admin/copy/blocks.d.ts +27 -0
  30. package/dist/admin/copy/blocks.js +38 -0
  31. package/dist/admin/copy/goals.d.ts +2 -0
  32. package/dist/admin/copy/goals.js +4 -1
  33. package/dist/admin/copy/newTest.d.ts +10 -0
  34. package/dist/admin/copy/newTest.js +10 -0
  35. package/dist/admin/copy/pages.d.ts +26 -0
  36. package/dist/admin/copy/pages.js +26 -0
  37. package/dist/admin/copy/readiness.d.ts +22 -3
  38. package/dist/admin/copy/readiness.js +23 -3
  39. package/dist/admin/copy/results.d.ts +1 -0
  40. package/dist/admin/copy/results.js +1 -0
  41. package/dist/admin/copy/testPage.d.ts +4 -0
  42. package/dist/admin/copy/testPage.js +4 -0
  43. package/dist/admin/goals/XpGoalField.d.ts +2 -0
  44. package/dist/admin/goals/XpGoalField.js +152 -0
  45. package/dist/admin/metricSource.model.d.ts +2 -0
  46. package/dist/admin/metricSource.model.js +4 -0
  47. package/dist/admin/pageCollections.d.ts +10 -0
  48. package/dist/admin/pageCollections.js +20 -0
  49. package/dist/admin/paths.d.ts +6 -0
  50. package/dist/admin/paths.js +6 -0
  51. package/dist/admin/placementStatus.model.d.ts +2 -0
  52. package/dist/admin/placementStatus.model.js +19 -0
  53. package/dist/admin/placements/placementLabels.d.ts +11 -0
  54. package/dist/admin/placements/placementLabels.js +21 -0
  55. package/dist/admin/placements/placementLabels.model.d.ts +13 -0
  56. package/dist/admin/placements/placementLabels.model.js +12 -0
  57. package/dist/admin/placements/usePlacementLabels.d.ts +12 -0
  58. package/dist/admin/placements/usePlacementLabels.js +102 -0
  59. package/dist/admin/results/DataQualityPanel.js +4 -1
  60. package/dist/admin/results/results.model.d.ts +3 -0
  61. package/dist/admin/results/results.model.js +8 -4
  62. package/dist/admin/surface/TestsHome.js +37 -6
  63. package/dist/admin/surface/TestsSurface.js +5 -1
  64. package/dist/admin/surface/contracts.d.ts +6 -5
  65. package/dist/admin/surface/goals/GoalForm.js +67 -34
  66. package/dist/admin/surface/goals/GoalsList.js +3 -3
  67. package/dist/admin/surface/goals/data.js +4 -1
  68. package/dist/admin/surface/goals/goals.model.d.ts +1 -2
  69. package/dist/admin/surface/goals/goals.model.js +1 -3
  70. package/dist/admin/surface/home.model.d.ts +1 -1
  71. package/dist/admin/surface/home.model.js +8 -4
  72. package/dist/admin/surface/newTest/NewTest.js +54 -13
  73. package/dist/admin/surface/newTest/PageWizard.d.ts +7 -0
  74. package/dist/admin/surface/newTest/PageWizard.js +209 -0
  75. package/dist/admin/surface/pagePicker/CopyRoute.d.ts +6 -0
  76. package/dist/admin/surface/pagePicker/CopyRoute.js +53 -0
  77. package/dist/admin/surface/pagePicker/PagePicker.d.ts +10 -0
  78. package/dist/admin/surface/pagePicker/PagePicker.js +172 -0
  79. package/dist/admin/surface/pagePicker/pagePicker.model.d.ts +25 -0
  80. package/dist/admin/surface/pagePicker/pagePicker.model.js +25 -0
  81. package/dist/admin/surface/readiness/ActionDialogs.js +99 -64
  82. package/dist/admin/surface/readiness/Banner.js +30 -6
  83. package/dist/admin/surface/readiness/readiness.model.d.ts +8 -1
  84. package/dist/admin/surface/readiness/readiness.model.js +91 -9
  85. package/dist/admin/surface/results/ReleasePages.d.ts +3 -1
  86. package/dist/admin/surface/results/ReleasePages.js +3 -7
  87. package/dist/admin/surface/results/ResultsBody.js +21 -2
  88. package/dist/admin/surface/results/ResultsHeader.js +2 -5
  89. package/dist/admin/surface/results/useResults.d.ts +10 -1
  90. package/dist/admin/surface/test/AdvancedSection.js +111 -104
  91. package/dist/admin/surface/test/GoalSection.js +90 -7
  92. package/dist/admin/surface/test/LengthSection.js +1 -1
  93. package/dist/admin/surface/test/PageHoldout.d.ts +3 -0
  94. package/dist/admin/surface/test/PageHoldout.js +67 -0
  95. package/dist/admin/surface/test/TestPage.js +2 -1
  96. package/dist/admin/surface/test/VersionsSection.js +12 -5
  97. package/dist/admin/surface/test/fields.d.ts +13 -4
  98. package/dist/admin/surface/test/fields.js +46 -14
  99. package/dist/admin/surface/test/jumpToSection.d.ts +1 -1
  100. package/dist/admin/surface/test/jumpToSection.js +4 -3
  101. package/dist/admin/surface/test/pageParts.d.ts +4 -1
  102. package/dist/admin/surface/test/pageParts.js +79 -2
  103. package/dist/admin/surface/test/testPage.css +8 -1
  104. package/dist/admin/surface/testDocument.model.d.ts +1 -0
  105. package/dist/admin/surface/testDocument.model.js +2 -1
  106. package/dist/admin/surface/useTestDocument.d.ts +11 -2
  107. package/dist/admin/surface/useTestDocument.js +53 -15
  108. package/dist/admin/useApi.d.ts +11 -2
  109. package/dist/admin/useApi.js +3 -5
  110. package/dist/admin/views/ExperimentsRootView.js +58 -16
  111. package/dist/blocks/bindings.d.ts +3 -0
  112. package/dist/blocks/bindings.js +34 -0
  113. package/dist/blocks/createExperimentBlock.d.ts +6 -0
  114. package/dist/blocks/createExperimentBlock.js +77 -0
  115. package/dist/blocks/formState.d.ts +31 -0
  116. package/dist/blocks/formState.js +146 -0
  117. package/dist/blocks/model.d.ts +41 -0
  118. package/dist/blocks/model.js +34 -0
  119. package/dist/client/ExperimentGroup.d.ts +6 -0
  120. package/dist/client/ExperimentGroup.js +9 -0
  121. package/dist/client/ExperimentsProvider.js +20 -4
  122. package/dist/client/clickGoals.d.ts +4 -0
  123. package/dist/client/clickGoals.js +43 -0
  124. package/dist/collections/experiments/config.js +12 -2
  125. package/dist/collections/experiments/deleteGuard.d.ts +2 -1
  126. package/dist/collections/experiments/deleteGuard.js +12 -1
  127. package/dist/collections/experiments/editability.js +4 -2
  128. package/dist/collections/experiments/pickSlug.d.ts +2 -0
  129. package/dist/collections/experiments/pickSlug.js +8 -0
  130. package/dist/collections/labels.d.ts +3 -0
  131. package/dist/collections/labels.js +20 -0
  132. package/dist/collections/metrics.js +12 -2
  133. package/dist/collections/phases.js +1 -0
  134. package/dist/collections/serialize.js +7 -0
  135. package/dist/db/clickGoals.d.ts +9 -0
  136. package/dist/db/clickGoals.js +22 -0
  137. package/dist/db/delete.d.ts +1 -0
  138. package/dist/db/delete.js +1 -0
  139. package/dist/db/locks.d.ts +8 -0
  140. package/dist/db/locks.js +27 -4
  141. package/dist/db/names.d.ts +4 -0
  142. package/dist/db/names.js +4 -0
  143. package/dist/db/pageBindings.d.ts +4 -0
  144. package/dist/db/pageBindings.js +17 -0
  145. package/dist/db/pageBusy.d.ts +2 -0
  146. package/dist/db/pageBusy.js +10 -0
  147. package/dist/db/pageContent.d.ts +10 -0
  148. package/dist/db/pageContent.js +79 -0
  149. package/dist/db/placements.d.ts +33 -0
  150. package/dist/db/placements.js +54 -0
  151. package/dist/db/slugs.d.ts +8 -0
  152. package/dist/db/slugs.js +40 -0
  153. package/dist/db/snapshots.d.ts +6 -0
  154. package/dist/db/snapshots.js +8 -5
  155. package/dist/endpoints/clickKeys.d.ts +5 -0
  156. package/dist/endpoints/clickKeys.js +17 -0
  157. package/dist/endpoints/events.js +4 -1
  158. package/dist/endpoints/index.js +28 -0
  159. package/dist/endpoints/pages.d.ts +5 -0
  160. package/dist/endpoints/pages.js +120 -0
  161. package/dist/endpoints/placementStatus.d.ts +6 -0
  162. package/dist/endpoints/placementStatus.js +238 -0
  163. package/dist/endpoints/readBody.d.ts +2 -0
  164. package/dist/endpoints/readBody.js +24 -0
  165. package/dist/endpoints/results.js +5 -1
  166. package/dist/endpoints/summary.js +11 -4
  167. package/dist/endpoints/wrapBlock.d.ts +6 -0
  168. package/dist/endpoints/wrapBlock.js +76 -0
  169. package/dist/errors.d.ts +3 -3
  170. package/dist/errors.js +4 -4
  171. package/dist/events/rows.d.ts +1 -1
  172. package/dist/events/rows.js +5 -3
  173. package/dist/exports/adminClient.d.ts +5 -0
  174. package/dist/exports/adminClient.js +5 -0
  175. package/dist/exports/blocks.d.ts +2 -0
  176. package/dist/exports/blocks.js +1 -0
  177. package/dist/exports/client.d.ts +1 -0
  178. package/dist/exports/client.js +1 -0
  179. package/dist/exports/index.d.ts +6 -1
  180. package/dist/exports/index.js +3 -0
  181. package/dist/exports/puck.d.ts +3 -1
  182. package/dist/exports/puck.js +2 -0
  183. package/dist/exports/puckEditor.d.ts +3 -0
  184. package/dist/exports/puckEditor.js +2 -0
  185. package/dist/exports/rsc.d.ts +3 -0
  186. package/dist/exports/rsc.js +2 -0
  187. package/dist/fields/xpGoal.d.ts +3 -0
  188. package/dist/fields/xpGoal.js +28 -0
  189. package/dist/globals/state.js +10 -0
  190. package/dist/goals/cache.d.ts +3 -0
  191. package/dist/goals/cache.js +35 -0
  192. package/dist/goals/fairness.d.ts +40 -0
  193. package/dist/goals/fairness.js +200 -0
  194. package/dist/goals/key.d.ts +4 -0
  195. package/dist/goals/key.js +3 -0
  196. package/dist/goals/picker/clickGoalPicker.model.d.ts +29 -0
  197. package/dist/goals/picker/clickGoalPicker.model.js +45 -0
  198. package/dist/goals/picker/copy.d.ts +16 -0
  199. package/dist/goals/picker/copy.js +15 -0
  200. package/dist/goals/picker/useClickGoalPicker.d.ts +30 -0
  201. package/dist/goals/picker/useClickGoalPicker.js +220 -0
  202. package/dist/hooks/pageGuard.d.ts +5 -1
  203. package/dist/hooks/pageGuard.js +157 -95
  204. package/dist/onInit.js +29 -0
  205. package/dist/options.d.ts +2 -0
  206. package/dist/options.js +41 -1
  207. package/dist/plugin.js +41 -28
  208. package/dist/puck/copy.d.ts +1 -0
  209. package/dist/puck/copy.js +1 -0
  210. package/dist/puck/editor/editor.chrome.css +1 -0
  211. package/dist/puck/editor/editor.css +1 -0
  212. package/dist/puck/editor/editor.model.d.ts +4 -2
  213. package/dist/puck/editor/editor.model.js +6 -3
  214. package/dist/puck/editor/integration.d.ts +10 -0
  215. package/dist/puck/editor/integration.js +30 -0
  216. package/dist/puck/editor/xpGoalPuckEditorField.d.ts +7 -0
  217. package/dist/puck/editor/xpGoalPuckEditorField.js +134 -0
  218. package/dist/puck/integration.d.ts +6 -0
  219. package/dist/puck/integration.js +21 -0
  220. package/dist/puck/xpGoalField.d.ts +3 -0
  221. package/dist/puck/xpGoalField.js +6 -0
  222. package/dist/results/health.d.ts +4 -0
  223. package/dist/results/health.js +27 -0
  224. package/dist/results/snapshot.js +15 -2
  225. package/dist/sanitizeReadinessDetail.js +41 -0
  226. package/dist/server/pageKindSeoContract.d.ts +27 -0
  227. package/dist/server/pageKindSeoContract.js +80 -0
  228. package/dist/server/recordContentChange.js +58 -8
  229. package/dist/server/resolveExperimentBlocks.d.ts +5 -0
  230. package/dist/server/resolveExperimentBlocks.js +54 -0
  231. package/dist/server/runResults.js +56 -15
  232. package/dist/server/toClientAssignments.js +2 -1
  233. package/dist/transitions/addMetric.d.ts +2 -1
  234. package/dist/transitions/addMetric.js +28 -1
  235. package/dist/transitions/checkStart.d.ts +13 -1
  236. package/dist/transitions/checkStart.js +89 -7
  237. package/dist/transitions/decide.js +24 -0
  238. package/dist/transitions/deleteExperiment.d.ts +3 -1
  239. package/dist/transitions/deleteExperiment.js +27 -1
  240. package/dist/transitions/kernel.js +4 -0
  241. package/dist/transitions/makeContent.d.ts +5 -0
  242. package/dist/transitions/makeContent.js +39 -11
  243. package/dist/transitions/pageCollection.d.ts +10 -0
  244. package/dist/transitions/pageCollection.js +20 -0
  245. package/dist/transitions/pageVersions.d.ts +10 -0
  246. package/dist/transitions/pageVersions.js +44 -0
  247. package/dist/transitions/phaseRecord.d.ts +1 -0
  248. package/dist/transitions/placementInteractions.d.ts +40 -0
  249. package/dist/transitions/placementInteractions.js +94 -0
  250. package/dist/transitions/placements.d.ts +8 -0
  251. package/dist/transitions/placements.js +148 -1
  252. package/dist/transitions/preflightData.d.ts +2 -2
  253. package/dist/transitions/preflightData.js +137 -5
  254. package/dist/transitions/resolveCaps.d.ts +1 -0
  255. package/dist/transitions/resolveCaps.js +6 -2
  256. package/dist/transitions/start.js +45 -1
  257. package/dist/types/admin.d.ts +1 -1
  258. package/dist/types/assignments.d.ts +1 -0
  259. package/dist/types/contracts.d.ts +15 -0
  260. package/dist/types/endpoints.d.ts +92 -5
  261. package/dist/types/index.d.ts +3 -0
  262. package/dist/types/puck.d.ts +7 -1
  263. package/dist/types/snapshot.d.ts +17 -4
  264. package/dist/types/surface.d.ts +13 -0
  265. package/package.json +8 -1
@@ -0,0 +1,220 @@
1
+ 'use client';
2
+ import { useEffect, useRef, useState } from 'react';
3
+ import { fetchAllDocs } from '../../lib/fetchAllDocs.js';
4
+ import { CLICK_KEY } from '../key.js';
5
+ import { clickGoalBody, clickGoalCreateError, clickGoalSlug, definedClickGoals, undefinedClickKey } from './clickGoalPicker.model.js';
6
+ const goalLists = new Map();
7
+ function publish(list, state) {
8
+ // A read may finish after its last row unmounts and a new list has started.
9
+ if (!list.listeners.length || goalLists.get(state.api) !== list) return;
10
+ list.state = state;
11
+ list.listeners.forEach((listener)=>listener(state));
12
+ }
13
+ /** Mounted rows at the same API base share the in-flight read and its result. */ function loadGoals(api) {
14
+ const cached = goalLists.get(api);
15
+ if (cached && (cached.state.status === 'loading' || cached.state.status === 'ready')) return cached;
16
+ const list = cached ?? {
17
+ state: {
18
+ api,
19
+ status: 'loading',
20
+ goals: []
21
+ },
22
+ listeners: []
23
+ };
24
+ if (cached) publish(list, {
25
+ api,
26
+ status: 'loading',
27
+ goals: []
28
+ });
29
+ goalLists.set(api, list);
30
+ void (async ()=>{
31
+ try {
32
+ const result = await fetchAllDocs(`${api}/xp-metrics?where[source][like]=click:&depth=0`, {
33
+ credentials: 'include'
34
+ });
35
+ if (result.ok) {
36
+ publish(list, {
37
+ api,
38
+ status: 'ready',
39
+ goals: definedClickGoals(result.docs)
40
+ });
41
+ return;
42
+ }
43
+ publish(list, {
44
+ api,
45
+ status: result.status === 403 ? 'not-manager' : 'error',
46
+ goals: []
47
+ });
48
+ } catch {
49
+ publish(list, {
50
+ api,
51
+ status: 'error',
52
+ goals: []
53
+ });
54
+ }
55
+ })();
56
+ return list;
57
+ }
58
+ const emptyPanel = ()=>({
59
+ open: false,
60
+ name: '',
61
+ slug: '',
62
+ slugEdited: false,
63
+ advanced: false,
64
+ pending: false,
65
+ errors: {}
66
+ });
67
+ /** UI-free state shared by the two editor hosts. A refused read silently removes management. */ export function useClickGoalPicker(apiRoute, { enabled = true, onSelect }) {
68
+ const api = apiRoute.replace(/\/$/, '');
69
+ const [loaded, setLoaded] = useState({
70
+ api,
71
+ status: 'loading',
72
+ goals: []
73
+ });
74
+ const [panel, setPanel] = useState(emptyPanel);
75
+ const flight = useRef(false);
76
+ const binding = useRef({
77
+ api,
78
+ enabled,
79
+ live: true,
80
+ onSelect
81
+ });
82
+ binding.current.api = api;
83
+ binding.current.enabled = enabled;
84
+ binding.current.onSelect = onSelect;
85
+ useEffect(()=>{
86
+ binding.current.live = true;
87
+ return ()=>{
88
+ binding.current.live = false;
89
+ };
90
+ }, []);
91
+ useEffect(()=>{
92
+ if (!enabled) return;
93
+ setPanel(emptyPanel());
94
+ const list = loadGoals(api);
95
+ setLoaded(list.state);
96
+ list.listeners.push(setLoaded);
97
+ return ()=>{
98
+ list.listeners = list.listeners.filter((listener)=>listener !== setLoaded);
99
+ if (!list.listeners.length && goalLists.get(api) === list) goalLists.delete(api);
100
+ };
101
+ }, [
102
+ api,
103
+ enabled
104
+ ]);
105
+ const status = !enabled ? 'not-manager' : loaded.api === api ? loaded.status : 'loading';
106
+ const goals = status === 'ready' ? loaded.goals : [];
107
+ const canManage = status === 'ready';
108
+ async function create() {
109
+ if (!canManage || !panel.open || flight.current || !panel.name.trim()) return;
110
+ if (!CLICK_KEY.test(panel.slug)) {
111
+ setPanel((current)=>({
112
+ ...current,
113
+ advanced: true,
114
+ errors: clickGoalCreateError(panel.slug)
115
+ }));
116
+ return;
117
+ }
118
+ flight.current = true;
119
+ setPanel((current)=>({
120
+ ...current,
121
+ pending: true,
122
+ errors: {}
123
+ }));
124
+ const current = ()=>binding.current.live && binding.current.enabled && binding.current.api === api;
125
+ try {
126
+ const response = await fetch(`${api}/xp-metrics`, {
127
+ method: 'POST',
128
+ credentials: 'include',
129
+ headers: {
130
+ 'Content-Type': 'application/json'
131
+ },
132
+ body: JSON.stringify(clickGoalBody(panel.name, panel.slug))
133
+ });
134
+ const body = await response.json().catch(()=>undefined);
135
+ if (!response.ok) {
136
+ if (!current()) return;
137
+ if (response.status === 403) {
138
+ setLoaded({
139
+ api,
140
+ status: 'not-manager',
141
+ goals: []
142
+ });
143
+ setPanel(emptyPanel());
144
+ return;
145
+ }
146
+ const errors = clickGoalCreateError(panel.slug, body);
147
+ setPanel((value)=>({
148
+ ...value,
149
+ pending: false,
150
+ advanced: value.advanced || Boolean(errors.slug),
151
+ errors
152
+ }));
153
+ return;
154
+ }
155
+ const doc = body?.doc;
156
+ if (!doc || typeof doc.slug !== 'string' || typeof doc.name !== 'string' || !isFiniteId(doc.id)) throw new Error('response');
157
+ const list = goalLists.get(api);
158
+ if (list) publish(list, {
159
+ api,
160
+ status: 'ready',
161
+ goals: [
162
+ ...list.state.goals.filter((goal)=>goal.id !== doc.id),
163
+ doc
164
+ ]
165
+ });
166
+ if (!current()) return;
167
+ binding.current.onSelect(doc.slug);
168
+ setPanel(emptyPanel());
169
+ } catch {
170
+ if (current()) setPanel((value)=>({
171
+ ...value,
172
+ pending: false,
173
+ errors: clickGoalCreateError(panel.slug)
174
+ }));
175
+ } finally{
176
+ flight.current = false;
177
+ }
178
+ }
179
+ return {
180
+ status,
181
+ goals,
182
+ canManage,
183
+ undefinedKey: (value)=>undefinedClickKey(status, goals, value),
184
+ panel,
185
+ open: ()=>{
186
+ if (canManage) setPanel({
187
+ ...emptyPanel(),
188
+ open: true
189
+ });
190
+ },
191
+ cancel: ()=>{
192
+ if (!flight.current) setPanel(emptyPanel());
193
+ },
194
+ setName: (name)=>setPanel((value)=>{
195
+ const slug = value.slugEdited ? value.slug : clickGoalSlug(name);
196
+ const invalid = !value.slugEdited && !CLICK_KEY.test(slug);
197
+ return {
198
+ ...value,
199
+ name,
200
+ slug,
201
+ advanced: value.advanced || invalid,
202
+ errors: invalid ? clickGoalCreateError(slug) : {}
203
+ };
204
+ }),
205
+ setSlug: (slug)=>setPanel((value)=>({
206
+ ...value,
207
+ slug,
208
+ slugEdited: true,
209
+ errors: {}
210
+ })),
211
+ setAdvanced: (advanced)=>setPanel((value)=>({
212
+ ...value,
213
+ advanced
214
+ })),
215
+ create
216
+ };
217
+ }
218
+ function isFiniteId(id) {
219
+ return typeof id === 'string' || typeof id === 'number' && Number.isFinite(id);
220
+ }
@@ -1,5 +1,9 @@
1
- import type { CollectionAfterOperationHook, CollectionBeforeChangeHook, CollectionBeforeDeleteHook, CollectionBeforeOperationHook } from 'payload';
1
+ import type { CollectionAfterChangeHook, CollectionAfterOperationHook, CollectionBeforeChangeHook, CollectionBeforeDeleteHook, CollectionBeforeOperationHook } from 'payload';
2
+ import { type PlacementTest } from '../db/placements.js';
2
3
  export declare const pageGuardBeforeOperation: CollectionBeforeOperationHook;
3
4
  export declare const pageGuardAfterOperation: CollectionAfterOperationHook;
5
+ export declare function guardExperimentIds(tests: readonly PlacementTest[], slugs: readonly string[], collection: string, paths: readonly string[], held: unknown, tags?: Set<string>): string[];
4
6
  export declare const pageGuardBeforeDelete: CollectionBeforeDeleteHook;
5
7
  export declare const pageGuardBeforeChange: CollectionBeforeChangeHook;
8
+ /** Unwrapped: these writes must fail the publish closed, unlike the best-effort audit. */
9
+ export declare const pageGuardAfterChange: CollectionAfterChangeHook;
@@ -1,14 +1,18 @@
1
- import { previousPublishedContent } from '../db/appends.js';
2
- import { lockPagePaths } from '../db/locks.js';
3
- import { txExecutor } from '../db/executor.js';
1
+ import { previousPublishedContent, storedContent } from '../db/appends.js';
2
+ import { lockPlacementScope, sortLockKeys } from '../db/locks.js';
3
+ import { txExecutor, pooledExecutor } from '../db/executor.js';
4
4
  import { normalisePath } from '../runtime/normalisePath.js';
5
5
  import { XpNoTransactionError, XpRefusal } from '../errors.js';
6
- import { pageGuardCopy, READINESS_COPY } from '../admin/copy/readiness.js';
6
+ import { placementGuardCopy, pageGuardCopy, READINESS_COPY } from '../admin/copy/readiness.js';
7
+ import { placementSlugs } from '../blocks/bindings.js';
8
+ import { isObject } from '../blocks/model.js';
9
+ import { placementTests, appendPlacementDoc } from '../db/placements.js';
10
+ import { isPageBusy } from '../db/pageBusy.js';
7
11
  // createLocalReq replaces context with a shallow copy on nested calls. Keep
8
12
  // the shared stack in that context so both the outer req and its proxies see it.
9
13
  const operations = (req)=>req.context.xpPageGuardOperations;
10
14
  export const pageGuardBeforeOperation = ({ args, operation })=>{
11
- if (operation !== 'update' && operation !== 'restoreVersion') return;
15
+ if (operation !== 'create' && operation !== 'update' && operation !== 'restoreVersion') return;
12
16
  const call = args;
13
17
  let collections = operations(call.req);
14
18
  if (!collections) call.req.context.xpPageGuardOperations = collections = new Map();
@@ -22,7 +26,7 @@ export const pageGuardBeforeOperation = ({ args, operation })=>{
22
26
  };
23
27
  export const pageGuardAfterOperation = ({ req, collection, operation, result })=>{
24
28
  // beforeOperation reports by-id updates as 'update'; afterOperation reports 'updateByID'.
25
- if (operation === 'update' || operation === 'updateByID' || operation === 'restoreVersion') {
29
+ if (operation === 'create' || operation === 'update' || operation === 'updateByID' || operation === 'restoreVersion') {
26
30
  const collections = operations(req);
27
31
  const stack = collections?.get(collection.slug);
28
32
  stack?.pop();
@@ -30,110 +34,168 @@ export const pageGuardAfterOperation = ({ req, collection, operation, result })=
30
34
  }
31
35
  return result;
32
36
  };
33
- async function protect(req, path) {
34
- // Serialise with Start (CORE-52 path locks, taken there after the experiment lock): a concurrent Start
35
- // either commits first, so this check sees it, or waits and then sees this change. Raw SQL on the
36
- // host's transaction; without one there is nothing to hold the lock for.
37
- if (await req.transactionID != null) {
38
- try {
39
- await lockPagePaths(txExecutor(req), [
40
- normalisePath(path)
41
- ]);
42
- } catch (error) {
43
- // A request id without a database session (e.g. a transaction already killed) has no lock to take.
44
- if (!(error instanceof XpNoTransactionError)) throw error;
45
- }
37
+ function optionsOf(req) {
38
+ return req.payload.config.custom?.xp;
39
+ }
40
+ function registration(req, slug) {
41
+ return optionsOf(req).pages?.collections.find((entry)=>entry.slug === slug);
42
+ }
43
+ const active = (test)=>test.status === 'running' || test.status === 'decided';
44
+ const pathsOf = (req, collection, rows)=>{
45
+ const page = registration(req, collection);
46
+ return page ? sortLockKeys(rows.flatMap((row)=>{
47
+ const path = row ? page.pathOf(row) : null;
48
+ return path === null ? [] : [
49
+ normalisePath(path)
50
+ ];
51
+ })) : [];
52
+ };
53
+ /** The later audit also recognises arm-select tags; include those ids in its lock superset. */ function taggedIds(value, ids = new Set()) {
54
+ if (Array.isArray(value)) value.forEach((v)=>taggedIds(v, ids));
55
+ else if (isObject(value)) {
56
+ if (typeof value.experiment === 'string' && typeof value.arm === 'string') ids.add(value.experiment);
57
+ Object.values(value).forEach((v)=>taggedIds(v, ids));
46
58
  }
47
- // page guard: the hook must see test placements regardless of the editor's access
48
- const tests = await req.payload.find({
49
- collection: 'xp-experiments',
50
- req,
51
- overrideAccess: true,
52
- depth: 0,
53
- limit: 0,
54
- where: {
55
- and: [
56
- {
57
- kind: {
58
- equals: 'page'
59
- }
60
- },
61
- {
62
- status: {
63
- in: [
64
- 'running',
65
- 'decided',
66
- 'archived'
67
- ]
68
- }
69
- }
70
- ]
71
- }
72
- });
73
- for (const test of tests.docs){
74
- const decision = test.decision;
59
+ return ids;
60
+ }
61
+ export function guardExperimentIds(tests, slugs, collection, paths, held, tags = new Set()) {
62
+ const excluded = new Set(Array.isArray(held) ? held.map(String) : []);
63
+ return sortLockKeys(tests.filter((test)=>slugs.includes(test.slug) || tags.has(String(test.id)) || test.kind === 'page' && (!test.pageCollection || test.pageCollection === collection) && test.arms.some((a)=>typeof a.pageTarget === 'string' && paths.includes(normalisePath(a.pageTarget)))).map((test)=>String(test.id)).filter((id)=>!excluded.has(id)));
64
+ }
65
+ function protect(tests, path) {
66
+ for (const test of tests){
67
+ if (test.kind !== 'page' || !active(test) && test.status !== 'archived') continue;
75
68
  const archived = test.status === 'archived';
76
- if (archived && (!decision?.winnerArm || decision.discardedAt || decision.pagesReleasedAt)) continue;
77
- // page guard: the hook must see test placements regardless of the editor's access
78
- const phases = await req.payload.find({
79
- collection: 'xp-phases',
80
- req,
81
- overrideAccess: true,
82
- depth: 0,
83
- limit: 1,
84
- sort: '-phase',
85
- where: {
86
- experiment: {
87
- equals: test.id
88
- },
89
- phaseKind: {
90
- equals: 'test'
91
- }
92
- }
93
- });
94
- const phase = phases.docs[0];
95
- if (!phase) throw new XpRefusal('invalid-phase', READINESS_COPY.missingVersions, {
69
+ if (archived && (!test.winnerArm || test.discardedAt || test.pagesReleasedAt)) continue;
70
+ if (!test.arms.length) throw new XpRefusal('invalid-phase', READINESS_COPY.missingVersions, {
71
+ experimentId: test.id
72
+ }, 409);
73
+ const arms = archived ? test.arms.filter((a)=>a.kind === 'control' || a.key === test.winnerArm) : test.arms;
74
+ const matched = arms.find((a)=>typeof a.pageTarget === 'string' && normalisePath(a.pageTarget) === path);
75
+ if (matched) throw new XpRefusal('locked-placement', pageGuardCopy(test.name, test.status, archived && matched.key !== test.winnerArm ? 'original' : 'winner'), {
96
76
  experimentId: test.id
97
77
  }, 409);
98
- const arms = phase.arms;
99
- const protectedArms = archived ? arms.filter((arm)=>arm.kind === 'control' || arm.key === decision.winnerArm) : arms;
100
- const matched = protectedArms.find((arm)=>arm.pageTarget !== undefined && normalisePath(arm.pageTarget) === normalisePath(path));
101
- if (matched) {
102
- const role = archived && matched.key !== decision.winnerArm ? 'original' : 'winner';
103
- throw new XpRefusal('locked-placement', pageGuardCopy(String(test.name), test.status, role), {
104
- experimentId: test.id
105
- }, 409);
106
- }
107
78
  }
108
79
  }
109
- function registration(req, slug) {
110
- return (req.payload.config.custom?.xp).pages?.collections.find((entry)=>entry.slug === slug);
80
+ function refuseInteraction(tests, beforeSlugs, afterSlugs, beforePaths, afterPaths, collection) {
81
+ const blocks = tests.filter((test)=>test.kind === 'block' && active(test) && afterSlugs.includes(test.slug));
82
+ const pages = tests.filter((test)=>test.kind === 'page' && active(test) && (!test.pageCollection || test.pageCollection === collection));
83
+ for (const page of pages){
84
+ if (!page.arms.some((a)=>typeof a.pageTarget === 'string' && afterPaths.includes(normalisePath(a.pageTarget)))) continue;
85
+ const block = blocks[0];
86
+ if (!block) continue;
87
+ const preExisting = beforeSlugs.includes(block.slug) && page.arms.some((a)=>typeof a.pageTarget === 'string' && beforePaths.includes(normalisePath(a.pageTarget)));
88
+ throw new XpRefusal('interacting-tests', placementGuardCopy(page, block, preExisting), {
89
+ experimentId: page.id,
90
+ blockId: block.id
91
+ }, 409);
92
+ }
93
+ }
94
+ function mapBusy(error) {
95
+ if (isPageBusy(error)) throw new XpRefusal('page-busy', 'This page is being updated by a test right now. Try again in a moment.', undefined, 409, {
96
+ cause: error
97
+ });
98
+ throw error;
111
99
  }
112
100
  export const pageGuardBeforeDelete = async ({ req, id, collection })=>{
113
101
  const page = registration(req, collection.slug);
114
102
  if (!page) return;
115
- const published = await previousPublishedContent(req, collection.slug, id);
116
- if (!published || published._status === 'draft') return;
117
- const path = page.pathOf(published);
118
- if (path !== null) await protect(req, path);
103
+ try {
104
+ const published = await previousPublishedContent(req, collection.slug, id);
105
+ if (!published || published._status === 'draft') return;
106
+ const paths = pathsOf(req, collection.slug, [
107
+ published
108
+ ]);
109
+ const exec = await req.transactionID != null ? txExecutor(req) : pooledExecutor(req.payload);
110
+ let tests = await placementTests(exec);
111
+ if (await req.transactionID != null) {
112
+ await lockPlacementScope(exec, guardExperimentIds(tests, placementSlugs(optionsOf(req), collection.slug, published), collection.slug, paths, req.context.xpHeldExperiments, taggedIds(published)), paths);
113
+ tests = await placementTests(exec);
114
+ }
115
+ for (const path of paths)protect(tests.filter((t)=>!t.pageCollection || t.pageCollection === collection.slug), path);
116
+ } catch (error) {
117
+ mapBusy(error);
118
+ }
119
119
  };
120
120
  export const pageGuardBeforeChange = async ({ req, collection, originalDoc, operation, data })=>{
121
- if (operation !== 'update') return data;
122
- const page = registration(req, collection.slug);
123
- if (!page) return data;
124
121
  const drafts = Boolean(collection.versions && collection.versions.drafts);
125
- // updateDocument computes isSavingDraft from draftArg and _status before
126
- // beforeChange, and writes the main row only when !isSavingDraft.
127
122
  const call = operations(req)?.get(collection.slug)?.at(-1);
128
123
  if (drafts && call?.draft && (call.restore || data._status !== 'published')) return data;
129
- const published = await previousPublishedContent(req, collection.slug, originalDoc.id);
130
- if (!published || published._status === 'draft') return data;
131
- const path = page.pathOf(published);
132
- const unpublishing = drafts && data._status === 'draft';
133
- const trashing = collection.trash && data.deletedAt != null && !originalDoc.deletedAt;
134
- if (path !== null && (trashing || unpublishing || page.pathOf({
124
+ const after = operation === 'create' ? data : {
135
125
  ...originalDoc,
136
126
  ...data
137
- }) !== path)) await protect(req, path);
138
- return data;
127
+ };
128
+ const options = optionsOf(req);
129
+ try {
130
+ const published = operation === 'create' ? undefined : await previousPublishedContent(req, collection.slug, originalDoc.id);
131
+ const before = published?._status === 'draft' ? undefined : published;
132
+ const beforeSlugs = placementSlugs(options, collection.slug, before);
133
+ const afterSlugs = placementSlugs(options, collection.slug, after);
134
+ const beforePaths = pathsOf(req, collection.slug, [
135
+ before
136
+ ]), afterPaths = pathsOf(req, collection.slug, [
137
+ after
138
+ ]);
139
+ const paths = sortLockKeys([
140
+ ...beforePaths,
141
+ ...afterPaths
142
+ ]);
143
+ const exec = await req.transactionID != null ? txExecutor(req) : pooledExecutor(req.payload);
144
+ let tests = await placementTests(exec);
145
+ const publishes = !drafts || after._status === 'published';
146
+ const noTransaction = ()=>{
147
+ if (publishes && tests.some((t)=>t.kind === 'block' && active(t) && afterSlugs.includes(t.slug))) throw new XpNoTransactionError('Save this page with transactions on.');
148
+ };
149
+ if (await req.transactionID == null) noTransaction();
150
+ else {
151
+ try {
152
+ await lockPlacementScope(exec, guardExperimentIds(tests, [
153
+ ...beforeSlugs,
154
+ ...afterSlugs
155
+ ], collection.slug, paths, req.context.xpHeldExperiments, taggedIds([
156
+ before,
157
+ after
158
+ ])), paths);
159
+ tests = await placementTests(exec);
160
+ } catch (error) {
161
+ if (!(error instanceof XpNoTransactionError)) throw error;
162
+ // Only a session lost after discovery reaches this fallback. The first discovery
163
+ // read and delete have no fallback: a dead session fails those operations closed.
164
+ tests = await placementTests(pooledExecutor(req.payload));
165
+ noTransaction();
166
+ }
167
+ }
168
+ if (operation === 'update' && before) {
169
+ const page = registration(req, collection.slug);
170
+ const old = page?.pathOf(before);
171
+ const unpublishing = drafts && data._status === 'draft';
172
+ const trashing = collection.trash && data.deletedAt != null && !originalDoc.deletedAt;
173
+ if (old != null && (unpublishing || trashing || page.pathOf(after) !== old)) protect(tests.filter((t)=>!t.pageCollection || t.pageCollection === collection.slug), normalisePath(old));
174
+ }
175
+ if (publishes) refuseInteraction(tests, beforeSlugs, afterSlugs, beforePaths, afterPaths, collection.slug);
176
+ return data;
177
+ } catch (error) {
178
+ mapBusy(error);
179
+ }
180
+ };
181
+ /** Unwrapped: these writes must fail the publish closed, unlike the best-effort audit. */ export const pageGuardAfterChange = async ({ req, collection, doc })=>{
182
+ const call = operations(req)?.get(collection.slug)?.at(-1);
183
+ const drafts = Boolean(collection.versions && collection.versions.drafts);
184
+ if (drafts && (doc._status !== 'published' || call?.draft && call.restore)) return doc;
185
+ if (await req.transactionID == null) return doc;
186
+ try {
187
+ const stored = await storedContent(req, collection.slug, doc.id);
188
+ if (!stored) throw new Error('The saved placement row was not found.');
189
+ const slugs = placementSlugs(optionsOf(req), collection.slug, stored);
190
+ const exec = txExecutor(req);
191
+ for (const test of (await placementTests(exec))){
192
+ if (test.kind === 'block' && active(test) && slugs.includes(test.slug)) await appendPlacementDoc(exec, test.id, test.phase, {
193
+ collection: collection.slug,
194
+ id: doc.id
195
+ });
196
+ }
197
+ return doc;
198
+ } catch (error) {
199
+ mapBusy(error);
200
+ }
139
201
  };
package/dist/onInit.js CHANGED
@@ -1,8 +1,37 @@
1
+ import { findRegisteredBlocksField } from './blocks/formState.js';
2
+ import { EXPERIMENT_BLOCK_SLUG } from './blocks/model.js';
3
+ import { contentBlocks } from './transitions/contentFields.js';
1
4
  import { validateDimensions } from './events/dimensions.js';
2
5
  import { assertPostgresAdapter, probeTransactions } from './db/adapter.js';
3
6
  import { hasHostAttributesOf } from './server/serverRuntime.js';
7
+ // Diagnostic only: named containers are never accepted by the top-level readers.
8
+ function registeredPaths(fields, name, parent = []) {
9
+ return fields.flatMap((field)=>{
10
+ const path = 'name' in field && field.name ? [
11
+ ...parent,
12
+ field.name
13
+ ] : parent;
14
+ if (field.type === 'blocks' && field.name === name) return [
15
+ path.join('.')
16
+ ];
17
+ if (field.type === 'tabs') return field.tabs.flatMap((tab)=>registeredPaths(tab.fields, name, 'name' in tab && tab.name ? [
18
+ ...path,
19
+ tab.name
20
+ ] : path));
21
+ return 'fields' in field ? registeredPaths(field.fields, name, path) : [];
22
+ });
23
+ }
4
24
  export function createOnInit(options) {
5
25
  return async (payload)=>{
26
+ for (const registration of options.blocks?.collections ?? []){
27
+ const config = payload.config.collections.find((c)=>c.slug === registration.slug);
28
+ const found = findRegisteredBlocksField(config?.fields ?? [], registration.field);
29
+ if (!found) throw new Error(`Experiments blocks field ${registration.slug}.${registeredPaths(config?.fields ?? [], registration.field)[0] ?? registration.field} must be a top-level blocks field and must contain ${registration.blockSlug ?? EXPERIMENT_BLOCK_SLUG}`);
30
+ if (!contentBlocks(found.field, payload.config.blocks).some((b)=>b.slug === (registration.blockSlug ?? EXPERIMENT_BLOCK_SLUG))) {
31
+ throw new Error(`Experiments blocks field ${registration.slug}.${registration.field} must contain ${registration.blockSlug ?? EXPERIMENT_BLOCK_SLUG}`);
32
+ }
33
+ }
34
+ if (options.metricSources?.some((source)=>source.id.startsWith('click:'))) throw new Error('metricSources ids starting with click: are reserved for click goals');
6
35
  validateDimensions(options.events?.dimensions);
7
36
  assertPostgresAdapter(payload);
8
37
  await probeTransactions(payload);
package/dist/options.d.ts CHANGED
@@ -7,3 +7,5 @@ export declare function puckCollections(options: Pick<ExperimentsPluginOptions,
7
7
  export declare function resolveOptions<TUser extends {
8
8
  id: string | number;
9
9
  }>(input: ExperimentsPluginOptions<TUser>): ResolvedOptions<TUser>;
10
+ /** One published-row rule shared by scans, bindings, writes and editor links. */
11
+ export declare function documentEditor(options: Pick<ExperimentsPluginOptions, 'puck' | 'blocks'>, collection: string, doc: Record<string, unknown>): 'puck' | 'blocks' | 'page';
package/dist/options.js CHANGED
@@ -49,7 +49,8 @@ export function resolveOptions(input) {
49
49
  if (![
50
50
  'block',
51
51
  'document',
52
- 'setting'
52
+ 'setting',
53
+ 'page'
53
54
  ].includes(key)) throw new Error(`Unknown experiments admin.descriptions option: ${key}`);
54
55
  if (value !== undefined && typeof value !== 'string') throw new Error(`Experiments admin.descriptions.${key} must be a string`);
55
56
  }
@@ -62,6 +63,31 @@ export function resolveOptions(input) {
62
63
  if (!entry || typeof entry.slug !== 'string' || !entry.slug.trim() || slugs.has(entry.slug) || typeof entry.pathOf !== 'function' || typeof entry.findByPath !== 'function') {
63
64
  throw new Error('Experiments pages.collections requires unique slugs, pathOf and findByPath functions');
64
65
  }
66
+ if (entry.contentOf !== undefined && typeof entry.contentOf !== 'function') throw new Error('Experiments contentOf must be a function');
67
+ for (const [key, max] of [
68
+ [
69
+ 'copyHint',
70
+ 200
71
+ ],
72
+ [
73
+ 'copyLabel',
74
+ 40
75
+ ]
76
+ ]){
77
+ const value = entry[key];
78
+ if (value !== undefined && (typeof value !== 'string' || !value.trim() || value.length > max)) throw new Error(`Experiments ${key} must be a non-empty string of at most ${max} characters`);
79
+ }
80
+ if (entry.copyUrl !== undefined && !validCopyUrl(entry.copyUrl)) throw new Error('Experiments copyUrl must be a root-relative path');
81
+ if (entry.copyLabel !== undefined && entry.copyUrl === undefined) throw new Error('Experiments copyLabel requires copyUrl');
82
+ slugs.add(entry.slug);
83
+ }
84
+ }
85
+ if (input.blocks !== undefined) {
86
+ if (!input.blocks || !Array.isArray(input.blocks.collections) || !input.blocks.collections.length) throw new Error('Experiments blocks.collections must be a non-empty array');
87
+ const slugs = new Set();
88
+ for (const entry of input.blocks.collections){
89
+ if (!entry || typeof entry.slug !== 'string' || !entry.slug.trim() || slugs.has(entry.slug) || typeof entry.field !== 'string' || !entry.field.trim() || entry.blockSlug !== undefined && (typeof entry.blockSlug !== 'string' || !entry.blockSlug.trim()) || entry.appliesTo !== undefined && typeof entry.appliesTo !== 'function') throw new Error('Invalid experiments blocks collection');
90
+ if (puckCollections(input).some((puck)=>puck.slug === entry.slug) && !entry.appliesTo) throw new Error('A collection registered in puck and blocks requires appliesTo');
65
91
  slugs.add(entry.slug);
66
92
  }
67
93
  }
@@ -150,3 +176,17 @@ export function resolveOptions(input) {
150
176
  }
151
177
  };
152
178
  }
179
+ function validCopyUrl(value) {
180
+ if (typeof value !== 'string' || !/^\/(?![/\\])/.test(value) || /[\s\x00-\x1f\x7f]/.test(value)) return false;
181
+ try {
182
+ return new URL(value, 'http://x').origin === 'http://x';
183
+ } catch {
184
+ return false;
185
+ }
186
+ }
187
+ /** One published-row rule shared by scans, bindings, writes and editor links. */ export function documentEditor(options, collection, doc) {
188
+ const block = options.blocks?.collections.find((entry)=>entry.slug === collection);
189
+ const puck = options.puck?.enabled !== false && puckCollections(options).some((entry)=>entry.slug === collection);
190
+ if (block && (block.appliesTo ? block.appliesTo(doc) : true)) return 'blocks';
191
+ return puck ? 'puck' : 'page';
192
+ }