Files
ipal-kit/src/modules/hooks/fillEmptyLocales.ts
T
Radosław SmolińskiandClaude Opus 5.5 71f7108cb8 Admin link-preview hook never throws without a Payload instance
syncAdminMeta returned to payload.logger in its catch even when payload was
undefined, so the Site settings afterChange hook threw with req: {} (an
unhandled rejection that made vitest, and npm publish for 1.14.5, exit 1).
Return early without payload, log through payload?.logger, skip the call in the
hook without req.payload; the fillEmptyLocales hooks get the same guard. Tests:
sync without payload, and every plugin global afterChange hook with req: {}.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-29 12:21:21 +01:00

138 lines
6.2 KiB
TypeScript

import type { BasePayload, CollectionAfterChangeHook, CollectionConfig, GlobalAfterChangeHook, GlobalConfig, PayloadRequest } from 'payload'
/**
* Localized text the editor wrote in one language goes to every language that
* is still empty — so a cookie added in Polish is not blank on the English page.
* A language that already has its own text is never touched: the editor can
* still change any language on its own.
*
* Fields: `'purpose'` (top-level) or `'cookies.purpose'` (a sub-field of the
* rows of an array; rows are matched by their id, which Payload keeps the same
* in every locale).
*
* Payload's own `localization.fallback` only covers part of this: an empty
* locale *reads* as the default locale's text, but nothing is stored, the admin
* shows the field empty, and the text always comes from the default locale,
* not from the language that was just edited.
*/
export type FillEmptyLocalesTarget = { collection: string; id: number | string } | { global: string }
const empty = (v: unknown) => v === undefined || v === null || (typeof v === 'string' && !v.trim())
/** Writes `source`'s text (read in `sourceLocale`) into every other locale where that text is empty. Returns the locales changed. */
export async function fillEmptyLocales({
fields,
payload,
req,
source,
sourceLocale,
target,
}: {
fields: string[]
payload: BasePayload
req?: PayloadRequest
source: Record<string, unknown>
sourceLocale: string
target: FillEmptyLocalesTarget
}): Promise<string[]> {
const l = payload.config.localization
if (!l) {return []}
const others = l.localeCodes.filter((c) => c !== sourceLocale)
const common = { context: { ipalFillLocales: true }, depth: 0, fallbackLocale: false as never, overrideAccess: true, req }
const changedLocales: string[] = []
for (const locale of others) {
const doc = (
'global' in target
? await payload.findGlobal({ ...common, slug: target.global as never, locale: locale as never })
: await payload.findByID({ ...common, id: target.id as never, collection: target.collection as never, locale: locale as never })
) as Record<string, unknown>
const patch: Record<string, unknown> = {}
for (const field of fields) {
const [head, sub] = field.split('.')
if (!sub) {
if (empty(doc[head]) && !empty(source[head])) {patch[head] = source[head]}
continue
}
const sourceRows = Array.isArray(source[head]) ? (source[head] as Record<string, unknown>[]) : []
const rows = (patch[head] as Record<string, unknown>[] | undefined) ?? (Array.isArray(doc[head]) ? (doc[head] as Record<string, unknown>[]).map((r) => ({ ...r })) : [])
let changed = false
for (const row of rows) {
const from = sourceRows.find((s) => s.id != null && s.id === row.id)
if (from && empty(row[sub]) && !empty(from[sub])) {
row[sub] = from[sub]
changed = true
}
}
if (changed) {patch[head] = rows}
}
if (!Object.keys(patch).length) {continue}
if ('global' in target) {
await payload.updateGlobal({ ...common, slug: target.global as never, data: patch as never, locale: locale as never })
} else {
await payload.update({ ...common, id: target.id as never, collection: target.collection as never, data: patch as never, locale: locale as never })
}
changedLocales.push(locale)
}
return changedLocales
}
/** Runs `fn` with `req`, then puts back req.locale / req.fallbackLocale (Local API calls with `req` change them). */
async function keepingLocale(req: PayloadRequest, fn: () => Promise<unknown>) {
const { fallbackLocale, locale } = req
try {
await fn()
} catch (err) {
req.payload?.logger?.error(`[ipal] filling empty locales failed: ${err instanceof Error ? err.message : String(err)}`)
} finally {
req.locale = locale
req.fallbackLocale = fallbackLocale
}
}
/** Skips its own writes and writes that fill every locale themselves (the cookie scanner). */
const skip = (context: Record<string, unknown> | undefined, locale: unknown) =>
Boolean(context?.ipalFillLocales || context?.ipalCookieScan) || typeof locale !== 'string' || locale === 'all' || locale === '*'
/** No Payload instance on the request (tests, scripts): nothing to read or write. */
const noPayload = (req: PayloadRequest | undefined) => !req?.payload
/**
* afterChange hook for a global: text saved in one language fills that field in
* every language where it is empty.
*
* hooks: { afterChange: [buildFillEmptyLocalesGlobalHook({ global: 'cookie-settings', fields: ['cookies.purpose'] })] }
*/
export function buildFillEmptyLocalesGlobalHook({ fields, global }: { fields: string[]; global: string }): GlobalAfterChangeHook {
return async ({ context, doc, req }) => {
if (noPayload(req) || skip(context, req.locale)) {return doc}
await keepingLocale(req, () =>
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { global } }),
)
return doc
}
}
/** The same for a collection: the saved document's text fills its empty languages. */
export function buildFillEmptyLocalesCollectionHook({ collection, fields }: { collection: string; fields: string[] }): CollectionAfterChangeHook {
return async ({ context, doc, req }) => {
if (noPayload(req) || skip(context, req.locale) || doc?.id == null) {return doc}
await keepingLocale(req, () =>
fillEmptyLocales({ fields, payload: req.payload, req, source: doc as Record<string, unknown>, sourceLocale: req.locale as string, target: { id: doc.id, collection } }),
)
return doc
}
}
/** Adds the fill hook to a global or a collection config (no fields = unchanged). */
export function withFillLocales<T extends CollectionConfig | GlobalConfig>(kind: 'collection' | 'global', entity: T, fields: string[] | undefined): T {
if (!fields?.length) {return entity}
const hook =
kind === 'collection'
? buildFillEmptyLocalesCollectionHook({ collection: entity.slug, fields })
: buildFillEmptyLocalesGlobalHook({ fields, global: entity.slug })
return { ...entity, hooks: { ...entity.hooks, afterChange: [...(entity.hooks?.afterChange ?? []), hook] } } as T
}