@delmaredigital/payload-experiments 0.5.0 → 0.5.2

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 (39) hide show
  1. package/dist/admin/PlacementStatus.js +5 -3
  2. package/dist/blocks/placementLocale.d.ts +14 -0
  3. package/dist/blocks/placementLocale.js +80 -13
  4. package/dist/blocks/placementPublication.d.ts +18 -0
  5. package/dist/blocks/placementPublication.js +31 -0
  6. package/dist/db/adapter.d.ts +1 -0
  7. package/dist/db/adapter.js +3 -0
  8. package/dist/db/appends.d.ts +2 -1
  9. package/dist/db/appends.js +2 -1
  10. package/dist/db/bulkPlacementRemoval.d.ts +5 -0
  11. package/dist/db/bulkPlacementRemoval.js +7 -2
  12. package/dist/db/pageBindings.d.ts +2 -2
  13. package/dist/db/pageBindings.js +3 -3
  14. package/dist/db/pageContent.d.ts +2 -0
  15. package/dist/db/pageContent.js +35 -17
  16. package/dist/db/placements.d.ts +6 -1
  17. package/dist/db/placements.js +26 -0
  18. package/dist/endpoints/duplicateOriginal.d.ts +1 -0
  19. package/dist/endpoints/pages.js +32 -15
  20. package/dist/endpoints/placementStatus.js +52 -8
  21. package/dist/hooks/blockRemovalRule.d.ts +1 -1
  22. package/dist/hooks/blockRemovalRule.js +5 -4
  23. package/dist/hooks/pageGuard.d.ts +7 -1
  24. package/dist/hooks/pageGuard.js +176 -3
  25. package/dist/hooks/puckNestedTests.d.ts +1 -1
  26. package/dist/hooks/puckNestedTests.js +3 -1
  27. package/dist/onInit.js +0 -5
  28. package/dist/server/recordContentChange.d.ts +1 -1
  29. package/dist/server/recordContentChange.js +42 -20
  30. package/dist/testSurface/api.js +1 -1
  31. package/dist/transitions/decide.js +5 -2
  32. package/dist/transitions/pageAddress.js +42 -4
  33. package/dist/transitions/placementInteractions.d.ts +7 -2
  34. package/dist/transitions/placementInteractions.js +8 -6
  35. package/dist/transitions/placements.d.ts +4 -3
  36. package/dist/transitions/placements.js +28 -14
  37. package/dist/transitions/start.js +3 -1
  38. package/dist/types/endpoints.d.ts +2 -0
  39. package/package.json +2 -2
@@ -1,5 +1,7 @@
1
1
  import { flattenTopLevelFields, formatAdminURL } from 'payload/shared';
2
2
  import { placementReader } from '../blocks/placementLocale.js';
3
+ import { pagePublicationStatus, publicationLocale, usesLocalizedPublication } from '../blocks/placementPublication.js';
4
+ import { hasPublishedPageVersion } from '../db/pageContent.js';
3
5
  import { findDraftPageByPath, PAGE_ADDRESS_FIELDS } from '../transitions/pageAddress.js';
4
6
  import { normalisePath } from '../runtime/normalisePath.js';
5
7
  import { blockPageSlugs, hasPuckEditor } from '../options.js';
@@ -40,6 +42,7 @@ export async function handlePages(req, { options }) {
40
42
  const title = config?.admin.useAsTitle;
41
43
  const titleField = title && title !== 'id' ? title : fields.some((field)=>field.name === 'title') ? 'title' : title ?? 'id';
42
44
  const drafts = Boolean(config?.versions && config.versions.drafts);
45
+ const locale = usesLocalizedPublication(req, slug, config) ? publicationLocale(req) : undefined;
43
46
  if (path !== null && collection) {
44
47
  const found = await collection.findByPath(path, req);
45
48
  const main = found ? await req.payload.findByID({
@@ -55,8 +58,9 @@ export async function handlePages(req, { options }) {
55
58
  docs: [],
56
59
  hasNextPage: false
57
60
  });
58
- const published = !drafts || main._status === 'published';
59
- const row = published ? main : await req.payload.findByID({
61
+ const published = !drafts || pagePublicationStatus(main, locale) === 'published';
62
+ const useMain = published || Boolean(locale && (!found || await hasPublishedPageVersion(req, slug, main.id, locale)));
63
+ const row = useMain ? main : await req.payload.findByID({
60
64
  collection: slug,
61
65
  id: main.id,
62
66
  req,
@@ -204,11 +208,12 @@ export async function handlePages(req, { options }) {
204
208
  // Host callbacks can inspect arbitrary fields. Only picker metadata leaves this endpoint.
205
209
  select: hasDocCallbacks ? undefined : metadata
206
210
  });
207
- const draftIds = readDrafts ? result.docs.filter((doc)=>doc._status === 'draft').map((doc)=>doc.id) : [];
208
- const publishedById = new Map();
211
+ const localizedPaths = Boolean(locale && collection && !blockMode);
212
+ const draftIds = readDrafts ? result.docs.filter((doc)=>localizedPaths || pagePublicationStatus(doc, locale) === 'draft').map((doc)=>doc.id) : [];
213
+ const mainById = new Map();
209
214
  if (draftIds.length) {
210
- // Read only the matching live rows, in one bounded query. Whole-page choices
211
- // use the currently served path even when a newer edit changes that path.
215
+ // Read the matching main rows in one bounded query. Localized drafts can
216
+ // carry a sibling's publication state, so only main confirms what is live.
212
217
  const live = await req.payload.find({
213
218
  collection: slug,
214
219
  req,
@@ -219,27 +224,39 @@ export async function handlePages(req, { options }) {
219
224
  id: {
220
225
  in: draftIds
221
226
  },
222
- _status: {
223
- equals: 'published'
224
- }
227
+ ...!localizedPaths ? {
228
+ _status: {
229
+ equals: 'published'
230
+ }
231
+ } : {}
225
232
  },
226
233
  limit: PAGE_SIZE,
227
234
  select: !blockMode && collection ? undefined : {
228
235
  _status: true
229
236
  }
230
237
  });
231
- for (const doc of live.docs)if (doc._status === 'published') publishedById.set(String(doc.id), doc);
238
+ await Promise.all(live.docs.map(async (doc)=>{
239
+ const published = pagePublicationStatus(doc, locale) === 'published';
240
+ if (!published && !localizedPaths) return;
241
+ const usePath = published || await hasPublishedPageVersion(req, slug, doc.id, locale);
242
+ mainById.set(String(doc.id), {
243
+ doc,
244
+ published,
245
+ usePath
246
+ });
247
+ }));
232
248
  }
233
249
  const docs = result.docs.flatMap((row)=>{
234
250
  const placement = reader.read(row, input);
235
251
  const doc = placement.doc;
236
- const live = publishedById.get(String(row.id));
237
- const published = !drafts || row._status === 'published' || live !== undefined;
238
- const pathDoc = !blockMode && live ? reader.read(live, input).doc : doc;
252
+ const main = mainById.get(String(row.id));
253
+ const versionPublished = pagePublicationStatus(row, locale) === 'published';
254
+ const published = !drafts || (main?.published ?? versionPublished);
255
+ const pathDoc = !blockMode && main?.usePath ? reader.read(main.doc, input).doc : doc;
239
256
  const rawPath = collection?.pathOf(pathDoc) ?? null;
240
257
  const storedAddress = blockMode ? addressFields.reduce((value, field)=>value ?? textValue(pathDoc[field]), undefined) : undefined;
241
258
  const address = rawPath ?? storedAddress;
242
- const draftAddress = !blockMode && live ? collection?.pathOf(doc) : null;
259
+ const draftAddress = !blockMode && main?.usePath ? collection?.pathOf(doc) : null;
243
260
  const updatedAt = textValue(doc.updatedAt);
244
261
  const title = doc[titleField];
245
262
  const item = {
@@ -248,7 +265,7 @@ export async function handlePages(req, { options }) {
248
265
  path: rawPath,
249
266
  pathKey: rawPath === null ? null : normalisePath(rawPath),
250
267
  published,
251
- status: live ? 'changed' : published ? 'published' : 'draft',
268
+ status: main?.published && (!localizedPaths || !versionPublished || draftAddress !== rawPath) ? 'changed' : published ? 'published' : 'draft',
252
269
  ...address ? {
253
270
  address
254
271
  } : {},
@@ -1,4 +1,5 @@
1
- import { placementReader } from '../blocks/placementLocale.js';
1
+ import { localeRequest, placementReader } from '../blocks/placementLocale.js';
2
+ import { isPublicationStatus, publicationLocale, usesLocalizedPublication } from '../blocks/placementPublication.js';
2
3
  import { readBody } from './readBody.js';
3
4
  import { safeError } from '../log.js';
4
5
  import { statusPageContent } from '../db/pageContent.js';
@@ -18,6 +19,7 @@ const error = (status, code, message)=>Response.json({
18
19
  const object = (v)=>!!v && typeof v === 'object' && !Array.isArray(v);
19
20
  const id = (v)=>typeof v === 'string' && !!v.trim() || typeof v === 'number' && Number.isSafeInteger(v);
20
21
  export async function handlePlacementStatus(req, { options }) {
22
+ const fallbackLocale = req.fallbackLocale;
21
23
  let value;
22
24
  try {
23
25
  value = await readBody(req);
@@ -161,22 +163,64 @@ export async function handlePlacementStatus(req, { options }) {
161
163
  collection,
162
164
  id,
163
165
  req,
166
+ fallbackLocale,
164
167
  overrideAccess: false,
165
168
  depth: 0,
166
169
  draft: false
167
170
  });
168
171
  const registration = options.pages?.collections.find((entry)=>entry.slug === collection);
169
- const raw = registration ? await statusPageContent(req, collection, id) : null;
170
- const doc = placementReader(req, collection, options).read(raw, 'all-locales').doc;
171
- const rawPath = doc && registration ? registration.pathOf(doc) : null;
172
- const path = rawPath;
173
- const pathKey = path === null ? null : normalisePath(path);
172
+ const reader = placementReader(req, collection, options);
173
+ const localizedStatus = usesLocalizedPublication(req, collection);
174
+ const readPath = async (viewReq)=>{
175
+ if (!registration) return null;
176
+ const raw = await statusPageContent(viewReq, collection, id);
177
+ const input = localizedStatus && isPublicationStatus(raw?._status) ? 'localized' : 'all-locales';
178
+ const view = {
179
+ locale: viewReq.locale ?? '',
180
+ fallbackLocale: viewReq.fallbackLocale ?? false
181
+ };
182
+ const doc = reader.read(raw, input, view).doc;
183
+ return doc ? registration.pathOf(doc) : null;
184
+ };
185
+ let pathsByLocale;
186
+ if (registration && localizedStatus && req.locale === 'all') {
187
+ const paths = await Promise.all(reader.documentViews.map(async (view)=>{
188
+ const viewReq = localeRequest(req, {
189
+ ...view,
190
+ fallbackLocale: fallbackLocale ?? view.fallbackLocale
191
+ });
192
+ const readable = await req.payload.findByID({
193
+ collection,
194
+ id,
195
+ req: viewReq,
196
+ fallbackLocale: viewReq.fallbackLocale,
197
+ overrideAccess: false,
198
+ depth: 0,
199
+ draft: false,
200
+ disableErrors: true
201
+ });
202
+ return [
203
+ view.locale,
204
+ readable ? await readPath(viewReq) : null
205
+ ];
206
+ }));
207
+ pathsByLocale = Object.fromEntries(paths);
208
+ }
209
+ const path = pathsByLocale ? pathsByLocale[publicationLocale(req) ?? ''] ?? null : await readPath(req);
210
+ const pathKeys = new Set((pathsByLocale ? Object.values(pathsByLocale) : [
211
+ path
212
+ ]).flatMap((path)=>path === null ? [] : [
213
+ normalisePath(path)
214
+ ]));
174
215
  const status = {
175
216
  path,
217
+ ...pathsByLocale ? {
218
+ pathsByLocale
219
+ } : {},
176
220
  tests: []
177
221
  };
178
222
  for (const test of tests){
179
- if (test.kind !== 'page' || path === null || test.decision?.pagesReleasedAt || test.decision?.discardedAt || test.status === 'archived' && !test.decision?.winnerArm) continue;
223
+ if (test.kind !== 'page' || !pathKeys.size || test.decision?.pagesReleasedAt || test.decision?.discardedAt || test.status === 'archived' && !test.decision?.winnerArm) continue;
180
224
  const round = rounds.get(test.slug);
181
225
  if (!collections.has(test.slug)) collections.set(test.slug, await resolvePageCollection(req, options, {
182
226
  ...test,
@@ -184,7 +228,7 @@ export async function handlePlacementStatus(req, { options }) {
184
228
  }));
185
229
  const testCollection = collections.get(test.slug);
186
230
  if (testCollection?.slug !== collection) continue;
187
- const arm = round.arms.find((arm)=>arm.kind !== 'holdout' && arm.pageTarget && normalisePath(arm.pageTarget) === pathKey);
231
+ const arm = round.arms.find((arm)=>arm.kind !== 'holdout' && arm.pageTarget && pathKeys.has(normalisePath(arm.pageTarget)));
188
232
  if (!arm) continue;
189
233
  const winner = round.arms.find((arm)=>arm.key === test.decision?.winnerArm);
190
234
  const original = round.arms.find((arm)=>arm.kind === 'control');
@@ -17,7 +17,7 @@ export declare function releaseRemovalClaim(req: PayloadRequest, collection: str
17
17
  export declare function observeUnpublishedRemoval(req: PayloadRequest, collection: string, id: DocId): void;
18
18
  export declare function releaseRestoredRemovalClaims(req: PayloadRequest, collection: string, doc: Record<string, unknown> & {
19
19
  id: DocId;
20
- }, test: PlacementTest): void;
20
+ }, test: PlacementTest, locales?: ReadonlySet<string>): void;
21
21
  export declare const blockRemovalRule: {
22
22
  prepare(req: PayloadRequest, collection: string, before: Record<string, unknown> | undefined, after: Record<string, unknown>, removingPage: boolean, exec?: Executor, tests?: readonly PlacementTest[], input?: PlacementInput): Promise<{
23
23
  views: RemovedPlacementViews;
@@ -32,15 +32,16 @@ export function releaseRemovalClaim(req, collection, id, ownKeys) {
32
32
  if (slug === collection && docId === String(id)) claims.absent.add(`${test}:${key}`);
33
33
  }
34
34
  }
35
- export function releaseRestoredRemovalClaims(req, collection, doc, test) {
35
+ export function releaseRestoredRemovalClaims(req, collection, doc, test, locales) {
36
36
  const claims = req.context.xpPlacementRemovals;
37
37
  if (!claims) return;
38
38
  claims.absent ??= new Set();
39
+ const reader = placementReader(req, collection);
39
40
  for (const key of claims.tests.get(String(test.id)) ?? []){
40
41
  const [slug, id, view] = JSON.parse(key);
41
- if (slug !== collection || id !== String(doc.id)) continue;
42
+ if (slug !== collection || id !== String(doc.id) || locales && !locales.has(view.locale)) continue;
42
43
  const marker = `${test.id}:${key}`;
43
- if (!placementReader(req, collection).read(doc, 'all-locales', view).slugs.includes(test.slug)) claims.absent.add(marker);
44
+ if (locales && doc.deletedAt != null || !reader.isPublished(doc, view) || !reader.read(doc, 'all-locales', view).slugs.includes(test.slug)) claims.absent.add(marker);
44
45
  else if (claims.absent.has(marker) && (claims.counts?.get(String(test.id))?.get(key) ?? 1) === 1) {
45
46
  claims.tests.get(String(test.id)).delete(`${key}`);
46
47
  claims.counts?.get(String(test.id))?.delete(`${key}`);
@@ -149,7 +150,7 @@ export const blockRemovalRule = {
149
150
  return true;
150
151
  }
151
152
  return false;
152
- })) continue;
153
+ }, bulk)) continue;
153
154
  if (transaction == null) throw new XpNoTransactionError('Save this page with transactions on.');
154
155
  // Bulk selection is immutable through every sibling's decision, including
155
156
  // earlier rule refusals. afterOperation explains unrelated failed writes.
@@ -1,9 +1,10 @@
1
1
  import { AsyncLocalStorage } from 'node:async_hooks';
2
2
  import type { CollectionAfterChangeHook, CollectionAfterOperationHook, CollectionBeforeChangeHook, CollectionBeforeDeleteHook, CollectionBeforeOperationHook, PayloadRequest } from 'payload';
3
3
  import type { DocId } from '../types/contracts.js';
4
+ import { type PublicationFlags } from '../blocks/placementPublication.js';
4
5
  import { type PlacementTest } from '../db/placements.js';
5
6
  import { type BulkPlacementRemoval } from '../db/bulkPlacementRemoval.js';
6
- type OperationFrame = {
7
+ type OperationFrame = PublicationFlags & {
7
8
  collection: string;
8
9
  request?: PayloadRequest;
9
10
  draft: boolean;
@@ -17,8 +18,13 @@ type OperationFrame = {
17
18
  detached?: boolean;
18
19
  parent?: OperationFrame;
19
20
  bulk?: BulkPlacementRemoval;
21
+ duplicateFromID?: DocId;
22
+ selectedLocales?: string[];
23
+ publicationWrites?: Map<string, Set<string>>;
20
24
  };
21
25
  export declare const pageGuardOperationScope: AsyncLocalStorage<OperationFrame | undefined>;
26
+ /** Both Publish All and Restore can return a locale-projected document. */
27
+ export declare function writesAllPublicationLocales(req: PayloadRequest, collection: string): boolean;
22
28
  /** Must be first: buildBeforeOperation invokes its first hook synchronously,
23
29
  * before the operation registers its await continuation. Later host hooks may
24
30
  * await nested operations; those keep separate async contexts. No IO here.
@@ -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>;