@bison-lab/payload-core 4.37.0 → 4.39.0

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 (45) hide show
  1. package/README.md +40 -3
  2. package/dist/admin.d.mts +19 -1
  3. package/dist/admin.d.mts.map +1 -1
  4. package/dist/admin.mjs +92 -17
  5. package/dist/admin.mjs.map +1 -1
  6. package/dist/block-library.d.mts +1 -1
  7. package/dist/{catalogue-PvKGCih7.d.mts → catalogue-FxH10X3v.d.mts} +1 -1
  8. package/dist/{catalogue-PvKGCih7.d.mts.map → catalogue-FxH10X3v.d.mts.map} +1 -1
  9. package/dist/{facet-field-CZbLDAQz.d.mts → facet-field-DjaZ0C7D.d.mts} +1 -1
  10. package/dist/{facet-field-CZbLDAQz.d.mts.map → facet-field-DjaZ0C7D.d.mts.map} +1 -1
  11. package/dist/index.d.mts +6 -6
  12. package/dist/index.mjs +1 -1
  13. package/dist/{locale-CxFNy8ex.d.mts → locale-CWiIcGuU.d.mts} +1 -1
  14. package/dist/locale-CWiIcGuU.d.mts.map +1 -0
  15. package/dist/messages-Fl1spIwN.mjs +229 -0
  16. package/dist/messages-Fl1spIwN.mjs.map +1 -0
  17. package/dist/metadata.d.mts +1 -1
  18. package/dist/navigation.d.mts +2 -2
  19. package/dist/navigation.mjs +1 -1
  20. package/dist/og.d.mts +2 -2
  21. package/dist/{preview-v-GlYuqa.d.mts → preview-CNBVfmM7.d.mts} +2 -2
  22. package/dist/{preview-v-GlYuqa.d.mts.map → preview-CNBVfmM7.d.mts.map} +1 -1
  23. package/dist/{published-DACERo16.mjs → published-D3yVnbxs.mjs} +6 -4
  24. package/dist/published-D3yVnbxs.mjs.map +1 -0
  25. package/dist/{published-B3IYStMQ.d.mts → published-DXjnElZn.d.mts} +4 -4
  26. package/dist/published-DXjnElZn.d.mts.map +1 -0
  27. package/dist/{published-Cow49CSZ.d.mts → published-_1rrTj_B.d.mts} +3 -3
  28. package/dist/{published-Cow49CSZ.d.mts.map → published-_1rrTj_B.d.mts.map} +1 -1
  29. package/dist/taxonomy.d.mts +1 -1
  30. package/dist/theme.d.mts +4 -4
  31. package/dist/{title-DFKu53nG.d.mts → title-D_jixG36.d.mts} +1 -1
  32. package/dist/{title-DFKu53nG.d.mts.map → title-D_jixG36.d.mts.map} +1 -1
  33. package/dist/translate-messages-cli.d.mts +1 -0
  34. package/dist/translate-messages-cli.mjs +151 -0
  35. package/dist/translate-messages-cli.mjs.map +1 -0
  36. package/dist/translate.d.mts +463 -0
  37. package/dist/translate.d.mts.map +1 -0
  38. package/dist/translate.mjs +1071 -0
  39. package/dist/translate.mjs.map +1 -0
  40. package/dist/{types-B7Hy1Ho-.d.mts → types-Db6Iy3hJ.d.mts} +1 -1
  41. package/dist/{types-B7Hy1Ho-.d.mts.map → types-Db6Iy3hJ.d.mts.map} +1 -1
  42. package/package.json +15 -5
  43. package/dist/locale-CxFNy8ex.d.mts.map +0 -1
  44. package/dist/published-B3IYStMQ.d.mts.map +0 -1
  45. package/dist/published-DACERo16.mjs.map +0 -1
@@ -0,0 +1,1071 @@
1
+ import { a as translationSystemPrompt, i as parseJsonArray, n as DEFAULT_TRANSLATE_MODEL, o as isTranslatorConfigured, r as anthropicTranslator, s as translateStrings, t as fillMessages } from "./messages-Fl1spIwN.mjs";
2
+ //#region src/translate/fields.ts
3
+ const isDoc = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
4
+ const asRows = (value) => Array.isArray(value) ? value.filter(isDoc) : void 0;
5
+ /** A string with something in it. Blank and whitespace-only strings are not copy to translate. */
6
+ const filled = (value) => typeof value === "string" && value.trim() !== "";
7
+ function isHidden(field) {
8
+ return field.hidden === true || field.admin?.hidden === true;
9
+ }
10
+ function blocksOf(field, configBlocks) {
11
+ const own = field.blocks ?? [];
12
+ const referenced = (field.blockReferences ?? []).flatMap((ref) => {
13
+ if (typeof ref !== "string") return [ref];
14
+ const found = configBlocks?.find((block) => block.slug === ref);
15
+ return found ? [found] : [];
16
+ });
17
+ return [...own, ...referenced];
18
+ }
19
+ /**
20
+ * The row of `rows` that is the same row as `row`, where the two lists are
21
+ * one Payload array read twice (in two locales, or before and after a
22
+ * save): by id when the row has one, else by position.
23
+ *
24
+ * Payload gives every stored array row an id and keeps it across locales, so
25
+ * a row with an id is matched by it and by nothing else: a row that has an id
26
+ * and no partner has no partner, whatever sits at its position. Position is
27
+ * for rows that have no id yet (a row not saved, a fixture), and for rows of
28
+ * a localized array, whose ids differ per locale.
29
+ */
30
+ function sameRow(rows, row, index, byPosition = false) {
31
+ if (!rows) return void 0;
32
+ if (byPosition) return rows[index];
33
+ const id = row.id;
34
+ return typeof id === "string" || typeof id === "number" ? rows.find((other) => other.id === id) : rows[index];
35
+ }
36
+ /** Every Lexical text node in document order, with its child-index path. */
37
+ function textNodes(state) {
38
+ if (!isDoc(state) || !isDoc(state.root)) return null;
39
+ const out = [];
40
+ const visit = (node, path) => {
41
+ if (node.type === "text" && typeof node.text === "string") out.push({
42
+ path,
43
+ node
44
+ });
45
+ const children = node.children;
46
+ if (Array.isArray(children)) children.forEach((child, index) => {
47
+ if (isDoc(child)) visit(child, `${path}.${index}`);
48
+ });
49
+ };
50
+ visit(state.root, "root");
51
+ return out;
52
+ }
53
+ const sameShape = (a, b) => a !== null && b !== null && a.length === b.length && a.every((ref, i) => ref.path === b[i].path);
54
+ const sameText = (a, b) => sameShape(a, b) && a.every((ref, i) => ref.node.text === b[i].node.text);
55
+ /**
56
+ * Every localized string in `doc`, each prefixed with its path, in config
57
+ * order. Two reads of a document compare equal exactly when no copy
58
+ * changed; the path keeps a string moved from one field to another from
59
+ * reading as unchanged.
60
+ */
61
+ function collectLocalizedStrings(schema, doc) {
62
+ const out = [];
63
+ if (isDoc(doc)) collectFields(schema.fields, doc, "", false, schema.blocks, out);
64
+ return out;
65
+ }
66
+ function collectFields(fields, value, prefix, inLocalized, configBlocks, out) {
67
+ for (const field of fields) {
68
+ if (isHidden(field)) continue;
69
+ const localized = inLocalized || field.localized === true;
70
+ const path = field.name ? `${prefix}${field.name}` : prefix;
71
+ switch (field.type) {
72
+ case "tabs":
73
+ for (const tab of field.tabs ?? []) if (tab.name) {
74
+ const nested = value[tab.name];
75
+ if (isDoc(nested)) collectFields(tab.fields, nested, `${prefix}${tab.name}.`, inLocalized || tab.localized === true, configBlocks, out);
76
+ } else collectFields(tab.fields, value, prefix, inLocalized, configBlocks, out);
77
+ break;
78
+ case "row":
79
+ case "collapsible":
80
+ collectFields(field.fields ?? [], value, prefix, inLocalized, configBlocks, out);
81
+ break;
82
+ case "group":
83
+ if (!field.name) collectFields(field.fields ?? [], value, prefix, inLocalized, configBlocks, out);
84
+ else if (isDoc(value[field.name])) collectFields(field.fields ?? [], value[field.name], `${path}.`, localized, configBlocks, out);
85
+ break;
86
+ case "array":
87
+ if (!field.name) break;
88
+ (asRows(value[field.name]) ?? []).forEach((row, index) => {
89
+ const key = typeof row.id === "string" && !localized ? row.id : String(index);
90
+ collectFields(field.fields ?? [], row, `${path}.${key}.`, localized, configBlocks, out);
91
+ });
92
+ break;
93
+ case "blocks": {
94
+ if (!field.name) break;
95
+ const blocks = blocksOf(field, configBlocks);
96
+ (asRows(value[field.name]) ?? []).forEach((row, index) => {
97
+ const block = blocks.find((candidate) => candidate.slug === row.blockType);
98
+ if (!block) return;
99
+ const key = typeof row.id === "string" && !localized ? row.id : String(index);
100
+ collectFields(block.fields, row, `${path}.${key}.`, localized, configBlocks, out);
101
+ });
102
+ break;
103
+ }
104
+ case "text":
105
+ case "textarea":
106
+ if (localized && field.name && !field.hasMany && filled(value[field.name])) out.push(`${path}=${value[field.name]}`);
107
+ break;
108
+ case "richText":
109
+ if (localized && field.name) {
110
+ for (const ref of textNodes(value[field.name]) ?? []) if (filled(ref.node.text)) out.push(`${path}:${ref.path}=${ref.node.text}`);
111
+ }
112
+ break;
113
+ default: break;
114
+ }
115
+ }
116
+ }
117
+ /**
118
+ * The per-string rule, the one every write follows. A string is translated
119
+ * when its source is filled and its target is blank, or its source changed
120
+ * since `previous`, or the call says `overwrite`. Everything else keeps the
121
+ * target it already has, so a string a person corrected by hand in the
122
+ * target locale survives every later publish that does not touch its
123
+ * source.
124
+ */
125
+ function wants(ctx, source, existing, before) {
126
+ if (!filled(source)) return false;
127
+ if (ctx.overwrite || !filled(existing)) return true;
128
+ return ctx.hasPrevious && source !== before;
129
+ }
130
+ function enqueue(ctx, source, set) {
131
+ ctx.sources.push(source);
132
+ ctx.setters.push(set);
133
+ }
134
+ /**
135
+ * What to translate in one target locale, or `null` when the target is
136
+ * already in step with the source.
137
+ *
138
+ * - `source`: the document in the source locale, read at depth 0 so
139
+ * uploads are ids and array rows carry their real ids.
140
+ * - `target`: the document in the target locale, read with
141
+ * `fallbackLocale: false`. With fallback on, a blank target reads as the
142
+ * source, looks "already translated", and nothing is ever written.
143
+ * - `previous`: the source as it was before this change (the last
144
+ * published version, or the hook's `previousDoc` on a collection without
145
+ * drafts). `null` or omitted: there is none.
146
+ *
147
+ * The write carries only the top-level fields that hold a translated
148
+ * string. Inside them it is built from the source's structure (so
149
+ * non-localized values such as links and images are kept, and each array
150
+ * row keeps the source row's id, which is how Payload lands the target copy
151
+ * on the right row), with every localized string set to its translation or
152
+ * to the target copy it already had.
153
+ */
154
+ function translationJob(input) {
155
+ const ctx = {
156
+ overwrite: input.overwrite === true,
157
+ hasPrevious: input.previous != null,
158
+ configBlocks: input.schema.blocks,
159
+ sources: [],
160
+ setters: []
161
+ };
162
+ const out = {};
163
+ const touched = planFields(input.schema.fields, input.source, input.target ?? void 0, input.previous ?? void 0, out, ctx, false);
164
+ if (ctx.sources.length === 0) return null;
165
+ return {
166
+ sources: ctx.sources,
167
+ patch: (translated) => {
168
+ translated.forEach((value, index) => ctx.setters[index]?.(value));
169
+ const data = {};
170
+ for (const name of touched) data[name] = out[name];
171
+ return data;
172
+ }
173
+ };
174
+ }
175
+ /**
176
+ * Walks `fields` over one level of the source, writing into `out` (which
177
+ * starts as a copy of the source level) and returning the names at this
178
+ * level that hold a string being translated.
179
+ */
180
+ function planFields(fields, source, target, previous, out, ctx, inLocalized) {
181
+ const touched = /* @__PURE__ */ new Set();
182
+ const nested = (name, subFields, localized) => {
183
+ const value = source[name];
184
+ if (!isDoc(value)) return;
185
+ const copy = { ...value };
186
+ const prevValue = previous?.[name];
187
+ const targetValue = target?.[name];
188
+ const inner = planFields(subFields, value, isDoc(targetValue) ? targetValue : void 0, isDoc(prevValue) ? prevValue : void 0, copy, ctx, localized);
189
+ out[name] = copy;
190
+ if (inner.size > 0) touched.add(name);
191
+ };
192
+ for (const field of fields) {
193
+ if (isHidden(field)) continue;
194
+ const localized = inLocalized || field.localized === true;
195
+ switch (field.type) {
196
+ case "tabs":
197
+ for (const tab of field.tabs ?? []) if (tab.name) nested(tab.name, tab.fields, inLocalized || tab.localized === true);
198
+ else for (const name of planFields(tab.fields, source, target, previous, out, ctx, inLocalized)) touched.add(name);
199
+ break;
200
+ case "row":
201
+ case "collapsible":
202
+ for (const name of planFields(field.fields ?? [], source, target, previous, out, ctx, inLocalized)) touched.add(name);
203
+ break;
204
+ case "group":
205
+ if (field.name) nested(field.name, field.fields ?? [], localized);
206
+ else for (const name of planFields(field.fields ?? [], source, target, previous, out, ctx, inLocalized)) touched.add(name);
207
+ break;
208
+ case "array":
209
+ case "blocks": {
210
+ if (!field.name) break;
211
+ const rows = asRows(source[field.name]);
212
+ if (!rows) break;
213
+ const targetRows = asRows(target?.[field.name]);
214
+ const previousRows = asRows(previous?.[field.name]);
215
+ const blocks = field.type === "blocks" ? blocksOf(field, ctx.configBlocks) : [];
216
+ let any = false;
217
+ out[field.name] = rows.map((row, index) => {
218
+ const rowFields = field.type === "blocks" ? blocks.find((block) => block.slug === row.blockType)?.fields : field.fields;
219
+ const copy = { ...row };
220
+ if (localized) delete copy.id;
221
+ if (!rowFields) return copy;
222
+ if (planFields(rowFields, row, sameRow(targetRows, row, index, localized), sameRow(previousRows, row, index), copy, ctx, localized).size > 0) any = true;
223
+ return copy;
224
+ });
225
+ if (any) touched.add(field.name);
226
+ break;
227
+ }
228
+ case "text":
229
+ case "textarea": {
230
+ if (!localized || !field.name || field.hasMany) break;
231
+ const name = field.name;
232
+ const value = source[name];
233
+ const existing = target?.[name];
234
+ if (wants(ctx, value, existing, previous?.[name])) {
235
+ enqueue(ctx, value, (translated) => out[name] = translated);
236
+ out[name] = value;
237
+ touched.add(name);
238
+ } else out[name] = filled(existing) ? existing : value;
239
+ break;
240
+ }
241
+ case "richText": {
242
+ if (!localized || !field.name) break;
243
+ const name = field.name;
244
+ const result = planRichText(ctx, source[name], target?.[name], previous?.[name]);
245
+ out[name] = result.value;
246
+ if (result.touched) touched.add(name);
247
+ break;
248
+ }
249
+ default: break;
250
+ }
251
+ }
252
+ return touched;
253
+ }
254
+ /**
255
+ * Rich text is translated per Lexical text node (sentence context across
256
+ * formatting runs is out of scope). When the target tree has the same
257
+ * shape as the source, each node follows the per-string rule. When a
258
+ * person restructured the target (split a run to bold a word), node paths
259
+ * no longer pair: the field is then kept whole unless its source changed,
260
+ * in which case it is rebuilt from the source and every node translated.
261
+ */
262
+ function planRichText(ctx, source, target, previous) {
263
+ const sourceNodes = textNodes(source);
264
+ if (!sourceNodes || !sourceNodes.some((ref) => filled(ref.node.text))) return {
265
+ value: target ?? source,
266
+ touched: false
267
+ };
268
+ const targetNodes = textNodes(target);
269
+ const previousNodes = textNodes(previous);
270
+ const clone = structuredClone(source);
271
+ const cloneNodes = textNodes(clone);
272
+ let touched = false;
273
+ if (sameShape(sourceNodes, targetNodes)) {
274
+ const previousPairs = sameShape(sourceNodes, previousNodes);
275
+ sourceNodes.forEach((ref, index) => {
276
+ const node = cloneNodes[index].node;
277
+ const existing = targetNodes[index].node.text;
278
+ const before = previousPairs ? previousNodes[index].node.text : void 0;
279
+ if (wants(ctx, ref.node.text, existing, before)) {
280
+ enqueue(ctx, ref.node.text, (translated) => node.text = translated);
281
+ touched = true;
282
+ } else if (filled(existing)) node.text = existing;
283
+ });
284
+ return {
285
+ value: clone,
286
+ touched
287
+ };
288
+ }
289
+ const targetFilled = targetNodes?.some((ref) => filled(ref.node.text)) ?? false;
290
+ if (!(ctx.overwrite || !targetFilled || ctx.hasPrevious && !sameText(sourceNodes, previousNodes))) return {
291
+ value: target,
292
+ touched: false
293
+ };
294
+ sourceNodes.forEach((ref, index) => {
295
+ if (!filled(ref.node.text)) return;
296
+ const node = cloneNodes[index].node;
297
+ enqueue(ctx, ref.node.text, (translated) => node.text = translated);
298
+ touched = true;
299
+ });
300
+ return {
301
+ value: clone,
302
+ touched
303
+ };
304
+ }
305
+ //#endregion
306
+ //#region src/translate/state.ts
307
+ /**
308
+ * Where an enabled plugin leaves its options for `translateDocument` and the
309
+ * endpoint to find. Root `config.custom` is server-only in Payload, so the
310
+ * translator never reaches the admin bundle.
311
+ */
312
+ const AUTO_TRANSLATE_STATE = "bisonAutoTranslate";
313
+ function readState(config) {
314
+ return config.custom?.[AUTO_TRANSLATE_STATE];
315
+ }
316
+ /**
317
+ * The test seam: the plugin's state (translator, site, locales, listed
318
+ * collections and globals) on a config that went through `autoTranslate`,
319
+ * or `undefined` when the plugin is off or was not applied. Read it instead
320
+ * of reaching into `config.custom` by key.
321
+ */
322
+ function readTranslateState(config) {
323
+ return readState(config);
324
+ }
325
+ /**
326
+ * The test seam: a copy of `config` whose plugin uses `translator` (a fake in
327
+ * a test) in place of the one it was registered with. The input is not
328
+ * changed. Throws when the config did not go through an enabled
329
+ * `autoTranslate`, so a test cannot silently translate nothing.
330
+ */
331
+ function withTranslator(config, translator) {
332
+ const state = readState(config);
333
+ if (!state) throw new Error("withTranslator: the config has no autoTranslate state; is the plugin enabled?");
334
+ return {
335
+ ...config,
336
+ custom: {
337
+ ...config.custom,
338
+ [AUTO_TRANSLATE_STATE]: {
339
+ ...state,
340
+ translator
341
+ }
342
+ }
343
+ };
344
+ }
345
+ /** The locale codes of a localization config, in order. */
346
+ function localeCodes(localization) {
347
+ if (!localization) return [];
348
+ return localization.locales.map((locale) => typeof locale === "string" ? locale : locale.code);
349
+ }
350
+ //#endregion
351
+ //#region src/translate/document.ts
352
+ function schemaFor(payload, options) {
353
+ if ("collection" in options) {
354
+ const collection = payload.collections[options.collection];
355
+ if (!collection) throw new Error(`translateDocument: no collection "${options.collection}"`);
356
+ return {
357
+ fields: collection.config.fields,
358
+ blocks: payload.config.blocks,
359
+ useAsTitle: collection.config.admin?.useAsTitle
360
+ };
361
+ }
362
+ const global = payload.config.globals.find((candidate) => candidate.slug === options.global);
363
+ if (!global) throw new Error(`translateDocument: no global "${options.global}"`);
364
+ return {
365
+ fields: global.fields,
366
+ blocks: payload.config.blocks
367
+ };
368
+ }
369
+ /** How many times a write is planned again because the source changed during the model call. */
370
+ const REPLANS = 2;
371
+ function defaultContext(slug, doc, useAsTitle) {
372
+ const meta = doc.meta;
373
+ const title = [
374
+ useAsTitle ? doc[useAsTitle] : void 0,
375
+ meta?.title,
376
+ doc.title,
377
+ doc.name
378
+ ].find((value) => typeof value === "string" && value.trim() !== "");
379
+ return title ? `${slug}: ${title}` : slug;
380
+ }
381
+ /**
382
+ * Brings one document's target locales in step with its source locale (the
383
+ * config's default locale), string by string: blank target strings are
384
+ * filled, source strings that changed since `previous` are re-translated,
385
+ * and with `overwrite` every filled string is. Anything else keeps the
386
+ * target copy a person may have corrected.
387
+ *
388
+ * Reads the source at depth 0 (uploads as ids, array rows with their real
389
+ * ids) and each target with `fallbackLocale: false`, sends one batch per
390
+ * target locale, and writes the target with `context: { autoTranslate:
391
+ * false }` so the write cannot start another round.
392
+ *
393
+ * Returns one result per target locale. A translator failure is a `failed`
394
+ * result and leaves that locale as it was; it only throws on Payload errors
395
+ * or a misconfiguration (no localization, no translator, unknown slug).
396
+ */
397
+ async function translateDocument(payload, options) {
398
+ const localization = payload.config.localization;
399
+ if (!localization) throw new Error("translateDocument: the Payload config has no localization");
400
+ const state = readState(payload.config);
401
+ const translator = options.translator ?? state?.translator;
402
+ if (!translator) throw new Error("translateDocument: no translator; register autoTranslate({ enabled: true }) or pass one");
403
+ const sourceLocale = localization.defaultLocale;
404
+ const codes = localeCodes(localization);
405
+ const targets = options.locale === void 0 ? codes.filter((code) => code !== sourceLocale) : typeof options.locale === "string" ? [options.locale] : [...options.locale];
406
+ for (const locale of targets) if (locale === sourceLocale || !codes.includes(locale)) throw new Error(`translateDocument: "${locale}" is not a target locale`);
407
+ const schema = schemaFor(payload, options);
408
+ const { req, user } = options;
409
+ const writeAs = user ? {
410
+ user,
411
+ overrideAccess: false
412
+ } : { overrideAccess: true };
413
+ const versions = "collection" in options ? payload.collections[options.collection]?.config.versions : payload.config.globals.find((candidate) => candidate.slug === options.global)?.versions;
414
+ const hasDrafts = Boolean(versions && typeof versions === "object" && versions.drafts);
415
+ const drafted = user !== void 0 && user !== null && "collection" in options && hasDrafts;
416
+ let draftMode = false;
417
+ if (drafted && "collection" in options) draftMode = (await payload.findByID({
418
+ collection: options.collection,
419
+ id: options.id,
420
+ locale: sourceLocale,
421
+ draft: true,
422
+ depth: 0,
423
+ overrideAccess: true,
424
+ req
425
+ }))._status === "draft";
426
+ const read = async (locale, opts) => "collection" in options ? await payload.findByID({
427
+ collection: options.collection,
428
+ id: options.id,
429
+ locale,
430
+ ...opts.draft ? { draft: true } : {},
431
+ ...opts.fallbackLocale === false ? { fallbackLocale: false } : {},
432
+ depth: 0,
433
+ overrideAccess: true,
434
+ req
435
+ }) : await payload.findGlobal({
436
+ slug: options.global,
437
+ locale,
438
+ ...opts.draft ? { draft: true } : {},
439
+ ...opts.fallbackLocale === false ? { fallbackLocale: false } : {},
440
+ depth: 0,
441
+ overrideAccess: true,
442
+ req
443
+ });
444
+ const source = await read(sourceLocale, { draft: draftMode });
445
+ const slug = "collection" in options ? options.collection : options.global;
446
+ const label = "collection" in options ? `${slug}/${String(options.id)}` : `globals/${slug}`;
447
+ const configured = "collection" in options ? state?.collections[slug] : state?.globals[slug];
448
+ const context = options.context ?? configured?.context?.(source) ?? defaultContext(slug, source, schema.useAsTitle);
449
+ const site = options.site ?? state?.site;
450
+ const plan = (from, target) => translationJob({
451
+ schema,
452
+ source: from,
453
+ target,
454
+ previous: options.previous,
455
+ overwrite: options.overwrite
456
+ });
457
+ const results = [];
458
+ for (const locale of targets) {
459
+ const first = plan(source, await read(locale, {
460
+ draft: draftMode,
461
+ fallbackLocale: false
462
+ }));
463
+ if (!first) {
464
+ results.push({
465
+ locale,
466
+ status: "nothing",
467
+ count: 0
468
+ });
469
+ continue;
470
+ }
471
+ const known = /* @__PURE__ */ new Map();
472
+ const translate = async (strings) => {
473
+ const translated = await translateStrings(strings, {
474
+ translator,
475
+ from: sourceLocale,
476
+ to: locale,
477
+ context,
478
+ ...site ? { site } : {}
479
+ });
480
+ if (!translated) return false;
481
+ strings.forEach((value, index) => known.set(value, translated[index]));
482
+ return true;
483
+ };
484
+ if (!await translate(first.sources)) {
485
+ results.push({
486
+ locale,
487
+ status: "failed",
488
+ count: 0
489
+ });
490
+ continue;
491
+ }
492
+ results.push(await writeLatest(locale));
493
+ /**
494
+ * Plans the write again from the latest version as it is now, then
495
+ * writes it. The model call takes seconds (up to 90s plus a retry), and
496
+ * the document may have moved on meanwhile, in two ways that matter.
497
+ *
498
+ * 1. Payload's update merges into the latest version row
499
+ * (`getLatestCollectionVersion` / `getLatestGlobalVersion`), draft or
500
+ * not: `beforeValidate` fills every field the write omits from it and
501
+ * `beforeChange` fills every localized field's other locales from it,
502
+ * and a non-draft update writes that to the live row and saves it as
503
+ * a version. So a live write after an autosave would publish the
504
+ * draft's copy with no Publish click. A newer draft is therefore
505
+ * written as a draft (`draft: true` leaves the live row and `_status`
506
+ * alone), and its target reaches the site with the next publish. A
507
+ * caller already on a draft stays on drafts even if the latest was
508
+ * published meanwhile, so the button never escalates to a live write.
509
+ * 2. The write carries whole top-level fields built from the planned
510
+ * source's structure (`translationJob`), and a non-localized array or
511
+ * blocks field (`layout`, `hero`) is one row list for every locale. A
512
+ * patch planned from an older version would replace the newer row
513
+ * list: rows the editor added dropped, removed ones restored, links
514
+ * and images reverted. So the job is planned again from the latest
515
+ * source and target, with the same `previous`, which keeps the
516
+ * per-string rule: strings changed since the last publish translate,
517
+ * filled target copy whose source did not change stays.
518
+ *
519
+ * Strings the re-plan meets for the first time go to the model, and the
520
+ * latest version is read again after that call, up to `REPLANS` times.
521
+ * What is left is the gap between the last read and Payload's own read
522
+ * inside the update: milliseconds, against the seconds to minutes of a
523
+ * model call. Closing it would need a row lock Payload's update does not
524
+ * take, so a save landing in exactly that gap can still be overwritten.
525
+ */
526
+ async function writeLatest(locale) {
527
+ for (let round = 0;; round++) {
528
+ const latest = await read(sourceLocale, { draft: hasDrafts || draftMode });
529
+ const writeDraft = draftMode || hasDrafts && latest._status === "draft";
530
+ const job = plan(latest, await read(locale, {
531
+ draft: writeDraft,
532
+ fallbackLocale: false
533
+ }));
534
+ if (!job) return {
535
+ locale,
536
+ status: "nothing",
537
+ count: 0
538
+ };
539
+ const missing = job.sources.filter((value) => !known.has(value));
540
+ if (missing.length > 0) {
541
+ if (round >= REPLANS) {
542
+ payload.logger.warn(`${label}: ${locale} source kept changing during translation; ${locale} left as-is`);
543
+ return {
544
+ locale,
545
+ status: "failed",
546
+ count: 0
547
+ };
548
+ }
549
+ if (!await translate(missing)) return {
550
+ locale,
551
+ status: "failed",
552
+ count: 0
553
+ };
554
+ continue;
555
+ }
556
+ const data = job.patch(job.sources.map((value) => known.get(value)));
557
+ if (writeDraft && !draftMode) payload.logger.info(`${label}: latest version is a draft; ${locale} translation written into the draft, the live ${locale} copy updates on the next publish`);
558
+ const common = {
559
+ locale,
560
+ data,
561
+ depth: 0,
562
+ ...writeDraft ? { draft: true } : {},
563
+ context: { autoTranslate: false },
564
+ ...writeAs,
565
+ req
566
+ };
567
+ if ("collection" in options) await payload.update({
568
+ collection: options.collection,
569
+ id: options.id,
570
+ ...common
571
+ });
572
+ else await payload.updateGlobal({
573
+ slug: options.global,
574
+ ...common
575
+ });
576
+ return {
577
+ locale,
578
+ status: "translated",
579
+ count: job.sources.length
580
+ };
581
+ }
582
+ }
583
+ }
584
+ return results;
585
+ }
586
+ //#endregion
587
+ //#region src/translate/endpoint.ts
588
+ /** The admin component key for the "Translate now" document menu item. */
589
+ const TRANSLATE_NOW = "@bison-lab/payload-core/admin#TranslateNowMenuItem";
590
+ /**
591
+ * True when the request's user may update this document, by the collection's
592
+ * own `access.update`. A query result (`Where`) counts only when it matches
593
+ * this document. It counts against the main document, as Payload's own update
594
+ * does for a draft save, even when the latest version is a newer draft: the
595
+ * write that follows is judged by Payload again, so this is only the early
596
+ * refusal.
597
+ */
598
+ async function canUpdate(req, slug, id) {
599
+ if (!req.user) return false;
600
+ const access = req.payload.collections[slug]?.config.access?.update;
601
+ if (!access) return true;
602
+ const result = await access({
603
+ req,
604
+ id
605
+ });
606
+ if (typeof result === "boolean") return result;
607
+ if (!result || typeof result !== "object") return false;
608
+ const { totalDocs } = await req.payload.count({
609
+ collection: slug,
610
+ where: { and: [result, { id: { equals: id } }] },
611
+ overrideAccess: true
612
+ });
613
+ return totalDocs > 0;
614
+ }
615
+ /**
616
+ * `POST /api/<slug>/:id/translate?locale=<code>`: the "Translate now"
617
+ * action. Re-translates one document with `overwrite`, replacing the target
618
+ * locale's copy (every target locale when `locale` is omitted). Needs update
619
+ * access to the document. Awaits the model, unlike the publish hook: a
620
+ * person pressed the button and is waiting for the answer.
621
+ */
622
+ function translateNowEndpoint(slug) {
623
+ return {
624
+ path: "/:id/translate",
625
+ method: "post",
626
+ handler: async (req) => {
627
+ if (!req.user) return Response.json({ error: "Unauthorized" }, { status: 401 });
628
+ const state = readState(req.payload.config);
629
+ if (!state || !isTranslatorConfigured(state.translator)) return Response.json({ error: "Translation is not configured on the server." }, { status: 503 });
630
+ const id = req.routeParams?.id;
631
+ if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Missing document id" }, { status: 400 });
632
+ const locale = req.searchParams?.get("locale") || void 0;
633
+ if (locale !== void 0 && !state.targetLocales.includes(locale)) return Response.json({ error: `"${locale}" is not a locale this site translates into.` }, { status: 400 });
634
+ if (!await canUpdate(req, slug, String(id))) return Response.json({ error: "You are not allowed to update this document." }, { status: 403 });
635
+ let results;
636
+ try {
637
+ results = await translateDocument(req.payload, {
638
+ collection: slug,
639
+ id,
640
+ ...locale ? { locale } : {},
641
+ overwrite: true,
642
+ user: req.user
643
+ });
644
+ } catch (error) {
645
+ const status = error.status;
646
+ if (typeof status === "number" && status >= 400 && status < 500) {
647
+ const message = error instanceof Error && error.message ? error.message : "Not allowed.";
648
+ return Response.json({ error: message }, { status });
649
+ }
650
+ throw error;
651
+ }
652
+ const failed = results.filter((result) => result.status === "failed");
653
+ const count = results.reduce((sum, result) => sum + result.count, 0);
654
+ if (failed.length > 0 && failed.length === results.length) {
655
+ req.payload.logger.warn(`${slug}/${id}: "Translate now" returned no result`);
656
+ return Response.json({
657
+ error: "The translation service gave no result. Try again in a minute.",
658
+ results
659
+ }, { status: 502 });
660
+ }
661
+ const message = count === 0 ? "Nothing to translate." : `Translated ${count} string(s) into ${results.filter((result) => result.status === "translated").map((result) => result.locale).join(", ")}.${failed.length ? ` ${failed.map((result) => result.locale).join(", ")} failed.` : ""}`;
662
+ return Response.json({
663
+ count,
664
+ message,
665
+ results
666
+ });
667
+ }
668
+ };
669
+ }
670
+ //#endregion
671
+ //#region src/translate/after-commit.ts
672
+ /** How often to re-check whether the request's transaction has ended. */
673
+ const POLL_INTERVAL_MS = 25;
674
+ /**
675
+ * How long to wait for the transaction to end before abandoning the work. Far
676
+ * above any real publish, so reaching it means the request itself hung rather
677
+ * than that the work was slow.
678
+ */
679
+ const TRANSACTION_TIMEOUT_MS = 3e4;
680
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
681
+ /**
682
+ * Resolves true once the request's transaction has ended, false if it never
683
+ * does. Polling is the mechanism because there is nothing to subscribe to:
684
+ * Payload has no post-commit hook, and `req.transactionID` is the only
685
+ * in-process signal that the transaction is over — both commitTransaction and
686
+ * killTransaction finish with `delete req.transactionID`. The alternative,
687
+ * patching payload.db.commitTransaction, is global and order-dependent, and
688
+ * would affect every operation in the process to serve one hook.
689
+ *
690
+ * An absent transactionID means there is nothing to wait for: a script running
691
+ * with `disableTransaction`, or a unit test.
692
+ */
693
+ async function waitForTransactionEnd(req) {
694
+ const deadline = Date.now() + TRANSACTION_TIMEOUT_MS;
695
+ while (req.transactionID !== void 0) {
696
+ if (Date.now() >= deadline) return false;
697
+ await sleep(POLL_INTERVAL_MS);
698
+ }
699
+ return true;
700
+ }
701
+ /**
702
+ * Run `work` once the request's database transaction has ended, so an expensive
703
+ * or failure-prone tail never holds that transaction open.
704
+ *
705
+ * Payload runs `afterOperation` BEFORE commitTransaction (see updateByID.js), so
706
+ * no hook is late enough to do this on its own. Anything scheduled here must
707
+ * also open its own transaction rather than joining `req`'s: joining is
708
+ * mandatory only while the outer transaction is still live — once it has
709
+ * committed, its row locks are released and a fresh transaction is both safe
710
+ * and required. So `work` must pass no `req` to the Local API.
711
+ *
712
+ * The returned promise is handed to `waitUntil` (the site's, e.g. Vercel's),
713
+ * without which a serverless instance may be frozen the moment the response is
714
+ * flushed and the work would never finish. It is also returned to the caller,
715
+ * so tests and scripts can await the deferred work instead of sleeping.
716
+ *
717
+ * Deliberately not awaited by its callers: not awaiting is what removes the
718
+ * hold, and `waitUntil` is what keeps the work alive afterwards.
719
+ *
720
+ * Never rejects. The final catch is a backstop only — callers own their own
721
+ * error reporting — so that a defect in this helper cannot escape as an
722
+ * unhandled rejection and take the process down.
723
+ */
724
+ function runAfterCommit(req, label, work, waitUntil) {
725
+ const deferred = waitForTransactionEnd(req).then((ended) => {
726
+ if (ended) return work();
727
+ req.payload.logger.warn(`${label}: transaction still open after ${TRANSACTION_TIMEOUT_MS}ms; deferred work skipped`);
728
+ }).catch((error) => {
729
+ req.payload.logger.error({ err: error }, `${label}: deferred post-commit work threw`);
730
+ });
731
+ try {
732
+ waitUntil?.(deferred);
733
+ } catch (error) {
734
+ req.payload.logger.error({ err: error }, `${label}: waitUntil threw; the deferred work still runs`);
735
+ }
736
+ return deferred;
737
+ }
738
+ //#endregion
739
+ //#region src/translate/guards.ts
740
+ const FIELD_SEPARATOR = String.fromCharCode(0);
741
+ /** True when no localized copy differs between the two documents. */
742
+ function localizedCopyUnchanged(previousDoc, doc, schema) {
743
+ const before = collectLocalizedStrings(schema, previousDoc ?? {});
744
+ const after = collectLocalizedStrings(schema, doc ?? {});
745
+ return before.join(FIELD_SEPARATOR) === after.join(FIELD_SEPARATOR);
746
+ }
747
+ /**
748
+ * The no-op decision for a collection or global WITHOUT a draft workflow:
749
+ * every write is live, so the incoming `previousDoc` is the right thing to
750
+ * diff. A create (no previous document) always translates.
751
+ */
752
+ function shouldSkipUndraftedTranslation(opts) {
753
+ const { previousDoc, doc, schema } = opts;
754
+ if (!previousDoc || Object.keys(previousDoc).length === 0) return false;
755
+ return localizedCopyUnchanged(previousDoc, doc, schema);
756
+ }
757
+ /**
758
+ * The no-op decision for a drafts-enabled collection or global, which must
759
+ * NOT use the hook's `previousDoc`.
760
+ *
761
+ * Payload hands `afterChange` the most recently saved version, and with autosave
762
+ * on (375ms) that is the draft the editor was just typing into, carrying copy
763
+ * identical to what is being published. Diffing against it therefore reported
764
+ * "nothing changed" on essentially every admin publish, so auto-translation
765
+ * never ran from the admin at all. Diffing against the LAST PUBLISHED version
766
+ * is the question actually worth asking: did the published copy change?
767
+ *
768
+ * That also keeps the property the naive fix broke, namely that a publish which
769
+ * touches no localized copy (an image swap, a reordering) leaves a hand-edited
770
+ * target locale alone. A document with no earlier published version is a first
771
+ * publish and always translates, even one written entirely as a draft.
772
+ *
773
+ * Returns that previous published version too: it is the "before" the
774
+ * per-string rule compares each source string with.
775
+ */
776
+ async function draftedTranslationDecision(opts) {
777
+ const { req, entity, doc, schema, sourceLocale } = opts;
778
+ if (doc?._status !== "published") return {
779
+ skip: true,
780
+ previous: null
781
+ };
782
+ const docUpdatedAt = doc.updatedAt;
783
+ if (typeof docUpdatedAt !== "string") return {
784
+ skip: false,
785
+ previous: null
786
+ };
787
+ const where = {
788
+ "version._status": { equals: "published" },
789
+ updatedAt: { less_than: docUpdatedAt }
790
+ };
791
+ const common = {
792
+ sort: "-updatedAt",
793
+ limit: 1,
794
+ pagination: false,
795
+ depth: 0,
796
+ locale: sourceLocale,
797
+ overrideAccess: true,
798
+ req
799
+ };
800
+ const { docs } = "collection" in entity ? await req.payload.findVersions({
801
+ ...common,
802
+ collection: entity.collection,
803
+ where: {
804
+ parent: { equals: doc.id },
805
+ ...where
806
+ }
807
+ }) : await req.payload.findGlobalVersions({
808
+ ...common,
809
+ slug: entity.global,
810
+ where
811
+ });
812
+ const previousPublished = docs[0]?.version;
813
+ if (!previousPublished || typeof previousPublished !== "object") return {
814
+ skip: false,
815
+ previous: null
816
+ };
817
+ const current = "collection" in entity ? await req.payload.findByID({
818
+ collection: entity.collection,
819
+ id: doc.id,
820
+ locale: sourceLocale,
821
+ depth: 0,
822
+ overrideAccess: true,
823
+ req
824
+ }) : await req.payload.findGlobal({
825
+ slug: entity.global,
826
+ locale: sourceLocale,
827
+ depth: 0,
828
+ overrideAccess: true,
829
+ req
830
+ });
831
+ const previous = previousPublished;
832
+ return {
833
+ skip: localizedCopyUnchanged(previous, current, schema),
834
+ previous
835
+ };
836
+ }
837
+ /** `draftedTranslationDecision`, answering only whether to skip. */
838
+ async function shouldSkipDraftedTranslation(opts) {
839
+ return (await draftedTranslationDecision(opts)).skip;
840
+ }
841
+ //#endregion
842
+ //#region src/translate/hooks.ts
843
+ /**
844
+ * Fill every other locale whenever source-locale copy is PUBLISHED with actual
845
+ * changes, so staff never have to think about translation. Guards, in order:
846
+ *
847
+ * - `autoTranslate: false` context skips the hook entirely (set by seed
848
+ * scripts, which run their own pass, and by the plugin's own target write
849
+ * so it can never re-fire itself).
850
+ * - Edits in a target locale are ignored: a hand edit there must never be
851
+ * clobbered by a machine pass.
852
+ * - Drafts are ignored; Live Preview autosaves every ~375ms and translating
853
+ * each keystroke would be absurd. Publish is the commit point.
854
+ * - No-op RE-publishes are ignored: if no localized string differs from the
855
+ * previously published version (e.g. an image swap), targets stay
856
+ * untouched. A FIRST publish is never a no-op, even though a doc written
857
+ * entirely as a draft carries identical copy either side of the transition:
858
+ * its targets have never been generated. See draftedTranslationDecision.
859
+ * - No API key: the publish goes through and a warning is logged.
860
+ *
861
+ * Failures log a warning and never block or fail the publish; the source goes
862
+ * live and each target stays as it was until the next publish. That holds
863
+ * structurally: the translation does not even begin until the publish is
864
+ * durable.
865
+ *
866
+ * Only the guards run inside the publish's transaction — two cheap indexed
867
+ * reads that need to see the publish's own state. The model round trip and the
868
+ * target writes are deferred past the commit by runAfterCommit, so a publish
869
+ * never holds its transaction open for the seconds a long document takes. The
870
+ * deferred call passes no `req`: it must open its own transaction, and safely
871
+ * can, because the outer one has released its row locks by then.
872
+ */
873
+ async function afterSourceChange(args) {
874
+ const { entity, drafted, schema, doc, req, context } = args;
875
+ if (context?.autoTranslate === false) return {};
876
+ const state = readState(req.payload.config);
877
+ if (!state) return {};
878
+ if (req.locale && req.locale !== state.sourceLocale) return {};
879
+ const slug = "collection" in entity ? entity.collection : entity.global;
880
+ const label = "collection" in entity ? `${slug}/${String(doc.id)}` : `globals/${slug}`;
881
+ const { payload } = req;
882
+ let previous;
883
+ try {
884
+ if (drafted) {
885
+ const decision = await draftedTranslationDecision({
886
+ req,
887
+ entity,
888
+ doc,
889
+ schema,
890
+ sourceLocale: state.sourceLocale
891
+ });
892
+ if (decision.skip) return {};
893
+ previous = decision.previous;
894
+ } else {
895
+ const previousDoc = args.operation === "create" ? void 0 : args.previousDoc;
896
+ if (shouldSkipUndraftedTranslation({
897
+ previousDoc,
898
+ doc,
899
+ schema
900
+ })) return {};
901
+ previous = previousDoc && Object.keys(previousDoc).length > 0 ? previousDoc : null;
902
+ }
903
+ } catch (error) {
904
+ payload.logger.error({ err: error }, `${label}: auto-translation guard failed; targets left as-is`);
905
+ return {};
906
+ }
907
+ if (!isTranslatorConfigured(state.translator)) {
908
+ payload.logger.warn(`${label}: source copy changed but the translator has no API key; targets not translated`);
909
+ return {};
910
+ }
911
+ return { deferred: runAfterCommit(req, label, async () => {
912
+ try {
913
+ logResults(payload, label, await translateDocument(payload, {
914
+ ..."collection" in entity ? {
915
+ collection: slug,
916
+ id: doc.id
917
+ } : { global: slug },
918
+ previous
919
+ }));
920
+ } catch (error) {
921
+ payload.logger.error({ err: error }, `${label}: auto-translation failed; targets left as-is`);
922
+ }
923
+ }, state.waitUntil) };
924
+ }
925
+ function logResults(payload, label, results) {
926
+ for (const result of results) if (result.status === "translated") payload.logger.info(`${label}: auto-translated ${result.count} string(s) to ${result.locale}`);
927
+ else if (result.status === "failed") payload.logger.warn(`${label}: ${result.locale} auto-translation returned no result; ${result.locale} left as-is`);
928
+ }
929
+ function collectionAutoTranslateHook(slug) {
930
+ return async ({ collection, doc, previousDoc, operation, req, context }) => {
931
+ await afterSourceChange({
932
+ entity: { collection: slug },
933
+ drafted: Boolean(collection.versions && collection.versions.drafts),
934
+ schema: {
935
+ fields: collection.fields,
936
+ blocks: req.payload.config.blocks
937
+ },
938
+ doc,
939
+ previousDoc,
940
+ operation,
941
+ req,
942
+ context
943
+ });
944
+ return doc;
945
+ };
946
+ }
947
+ function globalAutoTranslateHook(slug) {
948
+ return async ({ global, doc, previousDoc, req, context }) => {
949
+ await afterSourceChange({
950
+ entity: { global: slug },
951
+ drafted: Boolean(global.versions && global.versions.drafts),
952
+ schema: {
953
+ fields: global.fields,
954
+ blocks: req.payload.config.blocks
955
+ },
956
+ doc,
957
+ previousDoc,
958
+ operation: "update",
959
+ req,
960
+ context
961
+ });
962
+ return doc;
963
+ };
964
+ }
965
+ //#endregion
966
+ //#region src/translate/plugin.ts
967
+ function entries(list) {
968
+ return (list ?? []).map((entry) => typeof entry === "string" ? { slug: entry } : entry);
969
+ }
970
+ function withCollection(collection, configured, sourceLocale, targetLocales) {
971
+ const edit = collection.admin?.components?.edit;
972
+ return {
973
+ ...collection,
974
+ hooks: {
975
+ ...collection.hooks,
976
+ afterChange: [...collection.hooks?.afterChange ?? [], collectionAutoTranslateHook(collection.slug)]
977
+ },
978
+ endpoints: [...collection.endpoints || [], translateNowEndpoint(collection.slug)],
979
+ admin: {
980
+ ...collection.admin,
981
+ components: {
982
+ ...collection.admin?.components,
983
+ edit: {
984
+ ...edit,
985
+ editMenuItems: [...edit?.editMenuItems ?? [], {
986
+ path: TRANSLATE_NOW,
987
+ clientProps: {
988
+ sourceLocale,
989
+ targetLocales,
990
+ configured
991
+ }
992
+ }]
993
+ }
994
+ }
995
+ }
996
+ };
997
+ }
998
+ function withGlobal(global) {
999
+ return {
1000
+ ...global,
1001
+ hooks: {
1002
+ ...global.hooks,
1003
+ afterChange: [...global.hooks?.afterChange ?? [], globalAutoTranslateHook(global.slug)]
1004
+ }
1005
+ };
1006
+ }
1007
+ /**
1008
+ * Fills every locale but the default from the default whenever copy is
1009
+ * published, without overwriting a translation a person corrected. Each site
1010
+ * switches it on or off in its own `payload.config.ts`:
1011
+ *
1012
+ * ```ts
1013
+ * autoTranslate({
1014
+ * enabled: true,
1015
+ * collections: ["pages", { slug: "plans", context: (doc) => `Internet plan: ${doc.name}` }],
1016
+ * translator: anthropicTranslator({ apiKey: process.env.ANTHROPIC_API_KEY, site: { name: "ZoomFiber" } }),
1017
+ * waitUntil,
1018
+ * })
1019
+ * ```
1020
+ *
1021
+ * `enabled: false` returns the config untouched. Without `localization` (or
1022
+ * with one locale) it logs one warning and registers nothing. Otherwise each
1023
+ * listed collection gets an `afterChange` hook, `POST /api/<slug>/:id/translate`
1024
+ * and a "Translate now" item in the document menu (`TRANSLATE_NOW`, run
1025
+ * `payload generate:importmap`). The item is registered whether or not the
1026
+ * translator has a key, so the import map never depends on the environment;
1027
+ * it renders nothing when there is no key. Each listed
1028
+ * global gets the hook.
1029
+ */
1030
+ function autoTranslate(options) {
1031
+ return (config) => {
1032
+ if (!options.enabled) return config;
1033
+ const localization = config.localization;
1034
+ const codes = localeCodes(localization);
1035
+ if (!localization || codes.length < 2) {
1036
+ console.warn("[@bison-lab/payload-core] autoTranslate is enabled but the config has no localization with two or more locales; it registers nothing.");
1037
+ return config;
1038
+ }
1039
+ const sourceLocale = localization.defaultLocale;
1040
+ const targetLocales = codes.filter((code) => code !== sourceLocale);
1041
+ const collections = entries(options.collections);
1042
+ const globals = entries(options.globals);
1043
+ for (const { slug } of collections) if (!config.collections?.some((collection) => collection.slug === slug)) throw new Error(`autoTranslate: no collection "${slug}" in the config`);
1044
+ for (const { slug } of globals) if (!config.globals?.some((global) => global.slug === slug)) throw new Error(`autoTranslate: no global "${slug}" in the config`);
1045
+ const state = {
1046
+ translator: options.translator,
1047
+ ...options.site ? { site: options.site } : {},
1048
+ ...options.waitUntil ? { waitUntil: options.waitUntil } : {},
1049
+ sourceLocale,
1050
+ targetLocales,
1051
+ collections: Object.fromEntries(collections.map(({ slug, context }) => [slug, context ? { context } : {}])),
1052
+ globals: Object.fromEntries(globals.map(({ slug, context }) => [slug, context ? { context } : {}]))
1053
+ };
1054
+ const configured = isTranslatorConfigured(options.translator);
1055
+ const collectionSlugs = new Set(collections.map(({ slug }) => slug));
1056
+ const globalSlugs = new Set(globals.map(({ slug }) => slug));
1057
+ return {
1058
+ ...config,
1059
+ custom: {
1060
+ ...config.custom,
1061
+ [AUTO_TRANSLATE_STATE]: state
1062
+ },
1063
+ collections: (config.collections ?? []).map((collection) => collectionSlugs.has(collection.slug) ? withCollection(collection, configured, sourceLocale, targetLocales) : collection),
1064
+ globals: (config.globals ?? []).map((global) => globalSlugs.has(global.slug) ? withGlobal(global) : global)
1065
+ };
1066
+ };
1067
+ }
1068
+ //#endregion
1069
+ export { DEFAULT_TRANSLATE_MODEL, TRANSACTION_TIMEOUT_MS, TRANSLATE_NOW, anthropicTranslator, autoTranslate, collectLocalizedStrings, draftedTranslationDecision, fillMessages, isTranslatorConfigured, localizedCopyUnchanged, parseJsonArray, readTranslateState, runAfterCommit, sameRow, shouldSkipDraftedTranslation, shouldSkipUndraftedTranslation, translateDocument, translateStrings, translationJob, translationSystemPrompt, withTranslator };
1070
+
1071
+ //# sourceMappingURL=translate.mjs.map