@delmaredigital/payload-experiments 0.5.0 → 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.
@@ -1,6 +1,7 @@
1
1
  import { refuseNewNestedTests } from './puckNestedTests.js';
2
2
  import { hasLocalizedFields } from '../transitions/contentFields.js';
3
3
  import { AsyncLocalStorage } from 'node:async_hooks';
4
+ import { isDeepStrictEqual } from 'node:util';
4
5
  import { assertReadCommitted } from '../db/adapter.js';
5
6
  import { previousPublishedContent, storedContent, placementWriteContent } from '../db/appends.js';
6
7
  import { lockPlacementScope, sortLockKeys } from '../db/locks.js';
@@ -8,7 +9,8 @@ import { txExecutor, pooledExecutor } from '../db/executor.js';
8
9
  import { normalisePath } from '../runtime/normalisePath.js';
9
10
  import { XpNoTransactionError, XpRefusal } from '../errors.js';
10
11
  import { placementGuardCopy, pageGuardCopy, READINESS_COPY } from '../testSurface/copy/readiness.js';
11
- import { allPlacementSlugs, mergedPlacementLocales, placementDocumentPaths } from '../blocks/placementLocale.js';
12
+ import { allPlacementSlugs, localizedPlacementAfter, mergedPlacementLocales, placementDocumentPaths, placementReader, selectPlacementLocales } from '../blocks/placementLocale.js';
13
+ import { allLocalesStatus, usesLocalizedPublication } from '../blocks/placementPublication.js';
12
14
  import { isObject } from '../blocks/model.js';
13
15
  import { placementTests, removableBlockTests, appendPlacementDoc } from '../db/placements.js';
14
16
  import { isPageBusy } from '../db/pageBusy.js';
@@ -44,6 +46,10 @@ const operationFrame = (req, slug)=>{
44
46
  }
45
47
  return frame?.scoped && frame.collection === slug && (frame.restore || frame.request === req) ? frame : undefined;
46
48
  };
49
+ /** Both Publish All and Restore can return a locale-projected document. */ export function writesAllPublicationLocales(req, collection) {
50
+ const call = operationFrame(req, collection);
51
+ return Boolean(call && !call.draft && (call.publishAllLocales || call.restore));
52
+ }
47
53
  /** Must be first: buildBeforeOperation invokes its first hook synchronously,
48
54
  * before the operation registers its await continuation. Later host hooks may
49
55
  * await nested operations; those keep separate async contexts. No IO here.
@@ -92,6 +98,10 @@ export const pageGuardBeforeOperation = ({ args, operation })=>{
92
98
  versionId: operation === 'restoreVersion' ? call.id : undefined,
93
99
  isBulk,
94
100
  publishSpecificLocale: call.publishSpecificLocale,
101
+ publishAllLocales: call.publishAllLocales,
102
+ unpublishAllLocales: call.unpublishAllLocales,
103
+ duplicateFromID: call.duplicateFromID,
104
+ selectedLocales: call.selectedLocales,
95
105
  bulk,
96
106
  pending: false
97
107
  });
@@ -232,8 +242,10 @@ export const pageGuardBeforeDelete = async ({ req, id, collection })=>{
232
242
  try {
233
243
  const page = registration(req, collection.slug);
234
244
  // Keep the earlier page guard's baseline read and every refusal intact.
235
- const published = page ? await previousPublishedContent(req, collection.slug, id) : await storedContent(req, collection.slug, id);
245
+ const localized = usesLocalizedPublication(req, collection.slug, collection);
246
+ const published = page && !localized ? await previousPublishedContent(req, collection.slug, id) : await storedContent(req, collection.slug, id);
236
247
  if (!published || published._status === 'draft') return;
248
+ if (localized && (!isObject(published._status) || !Object.values(published._status).includes('published'))) return;
237
249
  const paths = sortLockKeys(documentPathsOf(req, collection.slug, [
238
250
  published
239
251
  ]).map(normalisePath));
@@ -262,8 +274,12 @@ export const pageGuardBeforeDelete = async ({ req, id, collection })=>{
262
274
  }
263
275
  };
264
276
  export const pageGuardBeforeChange = async ({ req, collection, originalDoc, operation, data })=>{
277
+ if (operation !== 'create' && operation !== 'update') return data;
265
278
  const drafts = Boolean(collection.versions && collection.versions.drafts);
266
279
  const call = operationFrame(req, collection.slug);
280
+ if (usesLocalizedPublication(req, collection.slug, collection)) {
281
+ return guardLocalizedSave(req, collection, originalDoc, operation, data, call);
282
+ }
267
283
  if (drafts && call?.draft && (call.restore || data._status !== 'published')) {
268
284
  await blockRemovalRule.prepare(req, collection.slug, undefined, data, false);
269
285
  return data;
@@ -339,8 +355,165 @@ export const pageGuardBeforeChange = async ({ req, collection, originalDoc, oper
339
355
  mapBusy(error);
340
356
  }
341
357
  };
342
- /** Unwrapped: these writes must fail the publish closed, unlike the best-effort audit. */ export const pageGuardAfterChange = async ({ req, collection, doc })=>{
358
+ function changedPublicationLocales(req, collection, before, after, locales) {
359
+ const reader = placementReader(req, collection);
360
+ const result = new Set(locales);
361
+ for (const view of reader.documentViews){
362
+ if (result.has(view.locale) || !reader.isPublished(before, view) && !reader.isPublished(after, view)) continue;
363
+ const previous = reader.read(before, 'all-locales', view).doc;
364
+ const next = reader.read(after, 'all-locales', view).doc;
365
+ if (!isDeepStrictEqual({
366
+ ...previous,
367
+ updatedAt: undefined
368
+ }, {
369
+ ...next,
370
+ updatedAt: undefined
371
+ })) result.add(view.locale);
372
+ }
373
+ return result;
374
+ }
375
+ async function guardLocalizedSave(req, collection, originalDoc, operation, data, call) {
376
+ if (call?.draft && (call.restore || operation === 'create' && call.duplicateFromID == null || operation === 'update' && data._status !== 'published')) return data;
377
+ const slug = collection.slug;
378
+ const id = operation === 'update' ? originalDoc.id : undefined;
379
+ const key = id == null ? '' : String(id);
380
+ const localization = req.payload.config.localization;
381
+ if (!localization) return data;
382
+ try {
383
+ const status = allLocalesStatus(req, call, data._status, operation);
384
+ const locales = status && localization.filterAvailableLocales ? (await localization.filterAvailableLocales({
385
+ locales: localization.locales,
386
+ req
387
+ })).map((entry)=>typeof entry === 'string' ? entry : entry.code) : localization.localeCodes;
388
+ const all = status ? {
389
+ status,
390
+ locales
391
+ } : undefined;
392
+ if (call?.bulk?.change) call.bulk.change.all = all;
393
+ const main = id == null ? undefined : await storedContent(req, slug, id);
394
+ const sourceID = id ?? call?.duplicateFromID;
395
+ let base = sourceID == null ? undefined : await placementWriteContent(req, slug, sourceID, id == null ? await storedContent(req, slug, sourceID) : main, {
396
+ versionId: call?.versionId,
397
+ bulk: call?.isBulk,
398
+ draft: call?.draft,
399
+ trashing: Boolean(collection.trash && data.deletedAt != null)
400
+ });
401
+ if (operation === 'create' && call?.selectedLocales?.length && base) {
402
+ base = selectPlacementLocales(req, slug, base, new Set(call.selectedLocales));
403
+ }
404
+ // Restore hooks receive the default locale for validation, but Payload
405
+ // starts with the selected version's entire locale map.
406
+ const after = localizedPlacementAfter(req, slug, main, base, call?.restore ? data : {
407
+ ...originalDoc,
408
+ ...data
409
+ }, {
410
+ status: call?.restore ? data._status : data._status ?? originalDoc?._status,
411
+ all,
412
+ restore: call?.restore
413
+ });
414
+ const requested = new Set(all?.locales ?? (call?.restore || req.locale === 'all' ? locales : [
415
+ req.locale || localization.defaultLocale
416
+ ]));
417
+ const changed = changedPublicationLocales(req, slug, main, after, requested);
418
+ const reader = placementReader(req, slug);
419
+ const page = registration(req, slug);
420
+ const trashing = Boolean(collection.trash && after.deletedAt != null);
421
+ const before = collection.trash && main?.deletedAt != null ? undefined : main;
422
+ const views = reader.documentViews.filter((view)=>changed.has(view.locale)).map((view)=>{
423
+ const old = reader.isPublished(before, view) ? reader.read(before, 'all-locales', view) : undefined;
424
+ const next = !trashing && reader.isPublished(after, view) ? reader.read(after, 'all-locales', view) : undefined;
425
+ const oldPath = old?.doc ? page?.pathOf(old.doc) : undefined;
426
+ const nextPath = next?.doc ? page?.pathOf(next.doc) : undefined;
427
+ return {
428
+ beforeSlugs: old?.slugs ?? [],
429
+ afterSlugs: next?.slugs ?? [],
430
+ oldPath,
431
+ nextPath
432
+ };
433
+ });
434
+ const beforeSlugs = views.flatMap((view)=>view.beforeSlugs);
435
+ const afterSlugs = views.flatMap((view)=>view.afterSlugs);
436
+ const paths = sortLockKeys(views.flatMap(({ oldPath, nextPath })=>[
437
+ oldPath,
438
+ nextPath
439
+ ].flatMap((path)=>path == null ? [] : [
440
+ normalisePath(path)
441
+ ])));
442
+ const exec = await req.transactionID == null ? pooledExecutor(req.payload) : txExecutor(req);
443
+ let tests = await placementTests(exec);
444
+ const removal = await blockRemovalRule.prepare(req, slug, before, after, trashing, exec, tests, 'all-locales');
445
+ const noTransaction = ()=>{
446
+ if (tests.some((test)=>test.kind === 'block' && active(test) && afterSlugs.includes(test.slug))) throw new XpNoTransactionError('Save this page with transactions on.');
447
+ };
448
+ if (await req.transactionID == null) noTransaction();
449
+ else {
450
+ try {
451
+ await assertReadCommitted(req);
452
+ await lockPlacementScope(exec, guardExperimentIds(tests, [
453
+ ...beforeSlugs,
454
+ ...afterSlugs
455
+ ], slug, paths, req.context.xpHeldExperiments, taggedIds([
456
+ before,
457
+ after
458
+ ]), removal.affected.map((test)=>test.id)), paths);
459
+ tests = await placementTests(exec);
460
+ } catch (error) {
461
+ if (!(error instanceof XpNoTransactionError)) throw error;
462
+ tests = await placementTests(pooledExecutor(req.payload));
463
+ noTransaction();
464
+ }
465
+ }
466
+ const pageTests = tests.filter((test)=>!test.pageCollection || test.pageCollection === slug);
467
+ for (const { oldPath, nextPath, beforeSlugs, afterSlugs } of views){
468
+ if (oldPath != null && oldPath !== nextPath) protect(pageTests, normalisePath(oldPath));
469
+ if (nextPath != null) refuseInteraction(tests, beforeSlugs, afterSlugs, oldPath == null ? [] : [
470
+ normalisePath(oldPath)
471
+ ], [
472
+ normalisePath(nextPath)
473
+ ], slug);
474
+ }
475
+ if (!trashing) refuseNewNestedTests(req, slug, before, after, tests, changed);
476
+ if (id != null && removal.affected.length) {
477
+ const removingPage = trashing || [
478
+ ...removal.views.values()
479
+ ].flat().every((view)=>!reader.isPublished(after, view));
480
+ await blockRemovalRule.check(req, tests, removal.affected, slug, id, removingPage, removal.views, call?.bulk, removal.hidden);
481
+ }
482
+ if (call) (call.publicationWrites ??= new Map()).set(key, changed);
483
+ return data;
484
+ } catch (error) {
485
+ mapBusy(error);
486
+ }
487
+ }
488
+ /** Unwrapped: these writes must fail the publish closed, unlike the best-effort audit. */ export const pageGuardAfterChange = async ({ req, collection, doc, operation })=>{
343
489
  const call = operationFrame(req, collection.slug);
490
+ if (usesLocalizedPublication(req, collection.slug, collection)) {
491
+ const write = call?.publicationWrites?.get(operation === 'create' ? '' : String(doc.id));
492
+ if (call?.draft && !write || await req.transactionID == null) return doc;
493
+ try {
494
+ const stored = await storedContent(req, collection.slug, doc.id);
495
+ if (!stored) throw new Error('The saved placement row was not found.');
496
+ const reader = placementReader(req, collection.slug);
497
+ const locales = write ?? new Set(reader.views.map((view)=>view.locale));
498
+ const slugs = new Set(reader.views.flatMap((view)=>locales.has(view.locale) && reader.isPublished(stored, view) && (!collection.trash || stored.deletedAt == null) ? reader.read(stored, 'all-locales', view).slugs : []));
499
+ const claims = req.context.xpPlacementRemovals;
500
+ const exec = txExecutor(req);
501
+ for (const test of (await placementTests(exec))){
502
+ if (test.kind !== 'block') continue;
503
+ if (active(test) && slugs.has(test.slug)) await appendPlacementDoc(exec, test.id, test.phase, {
504
+ collection: collection.slug,
505
+ id: doc.id
506
+ });
507
+ if (claims && claims.transaction === await req.transactionID) releaseRestoredRemovalClaims(req, collection.slug, {
508
+ ...stored,
509
+ id: doc.id
510
+ }, test, locales);
511
+ }
512
+ return doc;
513
+ } catch (error) {
514
+ mapBusy(error);
515
+ }
516
+ }
344
517
  const drafts = Boolean(collection.versions && collection.versions.drafts);
345
518
  if (!call?.draft && (drafts && doc._status !== 'published' || collection.trash && doc.deletedAt != null)) observeUnpublishedRemoval(req, collection.slug, doc.id);
346
519
  if (drafts && (doc._status !== 'published' || call?.draft && call.restore)) return doc;
@@ -5,4 +5,4 @@ import { type PayloadRequest } from 'payload';
5
5
  export declare function refuseNewNestedTests(req: PayloadRequest, collection: string, before: Record<string, unknown> | undefined, after: Record<string, unknown>, tests: readonly {
6
6
  slug: string;
7
7
  name: string;
8
- }[]): void;
8
+ }[], locales?: ReadonlySet<string>): void;
@@ -5,13 +5,15 @@ import { nestedTests, nestedTestKey, nestedTestLabel, nestedTestSlug, nearestOut
5
5
  import { nestedTestCopy } from '../puck/nestedTestCopy.js';
6
6
  /** Called by the page guard with its published baseline and merged write, only on publish.
7
7
  * Puck's public reducer bypasses slot disallow; this server check covers that path.
8
- */ export function refuseNewNestedTests(req, collection, before, after, tests) {
8
+ */ export function refuseNewNestedTests(req, collection, before, after, tests, locales) {
9
9
  const options = req.payload.config.custom?.xp;
10
10
  const registration = puckCollections(options).find((entry)=>entry.slug === collection);
11
11
  if (!registration) return;
12
12
  const reader = placementReader(req, collection, options);
13
13
  for (const view of reader.views){
14
+ if (locales && !locales.has(view.locale) || !reader.isPublished(after, view)) continue;
14
15
  const read = (doc)=>{
16
+ if (!reader.isPublished(doc, view)) return [];
15
17
  const content = reader.read(doc, 'all-locales', view);
16
18
  return content.editor === 'puck' ? nestedTests(content.doc?.[registration.field]) : [];
17
19
  };
package/dist/onInit.js CHANGED
@@ -46,11 +46,6 @@ export function createOnInit(options) {
46
46
  ]);
47
47
  for (const collection of payload.config.collections ?? []){
48
48
  if (!guarded.has(collection.slug)) continue;
49
- // Page-only guards also read the raw main row's scalar _status when
50
- // protecting unpublishes and restores; localized status breaks those too.
51
- if (payload.config.localization && payload.config.experimental?.localizeStatus && collection.versions && collection.versions.drafts && collection.versions.drafts.localizeStatus) {
52
- throw new Error(`Experiments collection ${collection.slug} does not support versions.drafts.localizeStatus. Use a shared publication status.`);
53
- }
54
49
  if (collection.hooks) {
55
50
  const hooks = collection.hooks.beforeOperation ?? [];
56
51
  collection.hooks.beforeOperation = [
@@ -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([
@@ -18,7 +18,10 @@ import { requireStarted } from './scheduledRound.js';
18
18
  export async function decide(req, { experimentId, winnerArm, note, confirmation, phase: expectedPhase }) {
19
19
  const before = await readExperiment(req, experimentId);
20
20
  const options = req.payload.config.custom?.xp;
21
- const placements = before.status === 'stopped' && before.kind === 'block' ? await detached(req, ()=>scanPlacements(req, options, before.slug)) : [];
21
+ const placementScan = {
22
+ publishedOnly: 'localized'
23
+ };
24
+ const placements = before.status === 'stopped' && before.kind === 'block' ? await detached(req, ()=>scanPlacements(req, options, before.slug, placementScan)) : [];
22
25
  const { result: doc, revision } = await withTransition(req, {
23
26
  experimentId,
24
27
  layerId: relationshipId(before.layer),
@@ -64,7 +67,7 @@ export async function decide(req, { experimentId, winnerArm, note, confirmation,
64
67
  const rescan = await lockAndRescanPlacements(req, exec, options, {
65
68
  ...current,
66
69
  arms: test.arms
67
- }, placements);
70
+ }, placements, placementScan);
68
71
  if (rescan.placements.length === 0) refuse('placement-removed');
69
72
  await refreshPlacementDocs(exec, experimentId, test.phase, rescan.docs);
70
73
  }
@@ -5,9 +5,13 @@ import { type PlacementDoc } from '../db/placements.js';
5
5
  import { type BlockPlacement } from './placements.js';
6
6
  export declare function detached<T>(req: PayloadRequest, fn: () => Promise<T>): Promise<T>;
7
7
  export declare function uniquePlacementDocs(placements: readonly Pick<BlockPlacement, 'collection' | 'id'>[]): PlacementDoc[];
8
+ type PlacementScanOptions = {
9
+ system?: boolean;
10
+ publishedOnly?: 'localized';
11
+ };
8
12
  export declare function scanPlacements<TUser extends {
9
13
  id: DocId;
10
- }>(req: PayloadRequest, options: ResolvedOptions<TUser>, slug: string, system?: boolean): Promise<BlockPlacement[]>;
14
+ }>(req: PayloadRequest, options: ResolvedOptions<TUser>, slug: string, scan?: PlacementScanOptions): Promise<BlockPlacement[]>;
11
15
  export declare function placementPaths<TUser extends {
12
16
  id: DocId;
13
17
  }>(req: PayloadRequest, options: ResolvedOptions<TUser>, docs: readonly PlacementDoc[]): Promise<string[]>;
@@ -34,7 +38,8 @@ export declare function lockAndRescanPlacements<TUser extends {
34
38
  slug: string;
35
39
  kind: string;
36
40
  arms: Arm[];
37
- }, before: readonly BlockPlacement[], system?: boolean): Promise<{
41
+ }, before: readonly BlockPlacement[], scan?: PlacementScanOptions): Promise<{
38
42
  placements: BlockPlacement[];
39
43
  docs: PlacementDoc[];
40
44
  }>;
45
+ export {};
@@ -30,12 +30,12 @@ export function uniquePlacementDocs(placements) {
30
30
  ])).values()
31
31
  ];
32
32
  }
33
- export function scanPlacements(req, options, slug, system = false) {
33
+ export function scanPlacements(req, options, slug, scan) {
34
34
  return scanBlockPlacements(req, {
35
35
  slug,
36
36
  puckCollections: options.puck?.collections ?? [],
37
37
  blocksCollections: options.blocks?.collections ?? [],
38
- system
38
+ ...scan
39
39
  });
40
40
  }
41
41
  export async function placementPaths(req, options, docs) {
@@ -68,7 +68,9 @@ export async function placementInteractions(req, exec, options, experiment, path
68
68
  version: test.arms.some((a)=>a.kind === 'variant' && a.pageTarget && normalisePath(a.pageTarget) === path)
69
69
  });
70
70
  } else if (experiment.kind === 'page' && test.kind === 'block') {
71
- const docs = test.placementDocs ?? uniquePlacementDocs(await detached(req, ()=>scanPlacements(req, options, test.slug, system)));
71
+ const docs = test.placementDocs ?? uniquePlacementDocs(await detached(req, ()=>scanPlacements(req, options, test.slug, {
72
+ system
73
+ })));
72
74
  const relevant = docs.filter((doc)=>!experiment.pageCollection || doc.collection === experiment.pageCollection);
73
75
  for (const path of (await placementPaths(req, options, relevant)).filter((path)=>paths.includes(path)))result.push({
74
76
  experimentId: test.id,
@@ -82,14 +84,14 @@ export async function placementInteractions(req, exec, options, experiment, path
82
84
  }
83
85
  return result;
84
86
  }
85
- export async function lockAndRescanPlacements(req, exec, options, experiment, before, system = false) {
87
+ export async function lockAndRescanPlacements(req, exec, options, experiment, before, scan) {
86
88
  const paths = await placementPaths(req, options, uniquePlacementDocs(before));
87
89
  await lockPagePaths(exec, paths);
88
- const placements = await detached(req, ()=>scanPlacements(req, options, experiment.slug, system));
90
+ const placements = await detached(req, ()=>scanPlacements(req, options, experiment.slug, scan));
89
91
  const docs = uniquePlacementDocs(placements);
90
92
  const afterPaths = await placementPaths(req, options, docs);
91
93
  if (afterPaths.some((path)=>!paths.includes(path))) throw new XpRefusal('placements-changed', "This test's pages changed while it was starting. Try again.", undefined, 409);
92
- const conflicts = await placementInteractions(req, exec, options, experiment, paths, system);
94
+ const conflicts = await placementInteractions(req, exec, options, experiment, paths, scan?.system);
93
95
  if (conflicts.length) throw new XpRefusal('interacting-tests', interactingTestsCopy(conflicts[0].path, conflicts[0].status, conflicts[0].name, conflicts[0].version), conflicts, 409);
94
96
  return {
95
97
  placements,
@@ -2,6 +2,7 @@ import type { PayloadRequest } from 'payload';
2
2
  import type { Arm, DocId, FlagPoint, PreviewPlacement, ResolvedOptions } from '../types/contracts.js';
3
3
  import type { ArmSlot } from '../types/puck.js';
4
4
  import { type PlacementLocaleView } from '../blocks/placementLocale.js';
5
+ import type { BulkPlacementRemoval } from '../db/bulkPlacementRemoval.js';
5
6
  export interface BlockPlacement extends PreviewPlacement {
6
7
  nestedTests?: Array<{
7
8
  outer: string;
@@ -35,8 +36,8 @@ interface ScanOptions {
35
36
  puckCollections: NonNullable<ResolvedOptions['puck']>['collections'];
36
37
  blocksCollections: NonNullable<ResolvedOptions['blocks']>['collections'];
37
38
  compareVersions?: boolean;
38
- /** Read the current visitor surface without fetching newer unpublished drafts. */
39
- publishedOnly?: boolean;
39
+ /** Read the visitor surface, optionally keeping legacy draft discovery for scalar collections. */
40
+ publishedOnly?: boolean | 'localized';
40
41
  /** Hooks and manager-authorized visitor-impact reads must see every placement (CORE-21). */
41
42
  pageGuard?: true;
42
43
  /** Trusted server-side Start checks placements without a manager actor. */
@@ -48,7 +49,7 @@ interface ScanOptions {
48
49
  */
49
50
  export declare function hasOtherPublishedBlockPlacement(req: PayloadRequest, options: ResolvedOptions, slug: string, excluded: (collection: string, id: DocId, view: PlacementLocaleView, doc: Record<string, unknown> & {
50
51
  id: DocId;
51
- }) => boolean): Promise<boolean>;
52
+ }) => boolean, bulk?: BulkPlacementRemoval): Promise<boolean>;
52
53
  interface PublishedBlockPlacement {
53
54
  id: DocId;
54
55
  editor: 'puck' | 'blocks';