@justanarthur/payload-plugin-translator 1.3.21 → 3.0.3

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.
@@ -0,0 +1,855 @@
1
+ // src/jobs/constants.ts
2
+ var TRANSLATE_TASK_SLUG = "translateEntityToLocale";
3
+ var TRANSLATE_WORKFLOW_SLUG = "translateEntityToLocales";
4
+
5
+ // src/jobs/createAutoTranslateCollectionHook.ts
6
+ function createAutoTranslateCollectionHook(options) {
7
+ const {
8
+ collectionSlug,
9
+ defaultLocale: defaultLocaleOption,
10
+ targetLocales: targetLocalesOption,
11
+ onlyOnPublished = true,
12
+ workflowSlug = TRANSLATE_WORKFLOW_SLUG
13
+ } = options;
14
+ const afterChange = async ({ doc, req }) => {
15
+ if (shouldSkipAutoTranslate(req.context))
16
+ return doc;
17
+ const typed = doc;
18
+ const requestLocale = readRequestLocale(req);
19
+ const defaultLocale = defaultLocaleOption ?? readConfigDefaultLocale(req) ?? "";
20
+ if (!requestLocale || !defaultLocale || requestLocale !== defaultLocale)
21
+ return doc;
22
+ if (!req.user)
23
+ return doc;
24
+ if (onlyOnPublished && typed._status && typed._status !== "published")
25
+ return doc;
26
+ const targetLocales = targetLocalesOption ?? readTargetLocales(req, defaultLocale);
27
+ if (targetLocales.length === 0)
28
+ return doc;
29
+ const resolverKey = options.resolverKey ?? readFirstResolverKey(req);
30
+ if (!resolverKey) {
31
+ req.payload.logger.error({
32
+ msg: `auto-translate: no resolver key available for collection ${collectionSlug} — pass \`resolverKey\` to \`createAutoTranslateCollectionHook\` or configure \`translator.resolvers\` in \`translator({...})\``
33
+ });
34
+ return doc;
35
+ }
36
+ const updatedAt = typed.updatedAt ?? new Date().toISOString();
37
+ const toLocales = targetLocales.filter((toLocale) => toLocale !== defaultLocale);
38
+ if (toLocales.length === 0)
39
+ return doc;
40
+ try {
41
+ const job = await req.payload.jobs.queue({
42
+ workflow: workflowSlug,
43
+ input: {
44
+ id: typed.id,
45
+ updatedAt,
46
+ collection: collectionSlug,
47
+ fromLocale: defaultLocale,
48
+ resolver: resolverKey || undefined,
49
+ toLocales
50
+ }
51
+ });
52
+ req.payload.logger.info({
53
+ msg: `auto-translate: queued translation of ${collectionSlug}#${typed.id} → [${toLocales.join(", ")}] (job ${job.id})`
54
+ });
55
+ } catch (error) {
56
+ req.payload.logger.error({
57
+ msg: `auto-translate: failed to queue ${collectionSlug}#${typed.id}: ${String(error)}`
58
+ });
59
+ }
60
+ return doc;
61
+ };
62
+ return { afterChange };
63
+ }
64
+ function shouldSkipAutoTranslate(context) {
65
+ return Boolean(context?.disableAutoTranslate);
66
+ }
67
+ function readRequestLocale(req) {
68
+ if (!req || typeof req !== "object")
69
+ return "";
70
+ const locale = req.locale;
71
+ return typeof locale === "string" && locale.length > 0 ? locale : "";
72
+ }
73
+ function readConfigDefaultLocale(req) {
74
+ if (!req || typeof req !== "object")
75
+ return "";
76
+ const config = req.payload?.config;
77
+ const def = config?.localization?.defaultLocale;
78
+ return typeof def === "string" && def.length > 0 ? def : "";
79
+ }
80
+ function readTargetLocales(req, defaultLocale) {
81
+ if (!req || typeof req !== "object")
82
+ return [];
83
+ const list = req.payload?.config?.localization?.locales;
84
+ if (!Array.isArray(list) || list.length === 0)
85
+ return [];
86
+ const out = [];
87
+ for (const entry of list) {
88
+ const code = typeof entry === "string" ? entry : entry?.code;
89
+ if (typeof code === "string" && code.length > 0 && code !== defaultLocale) {
90
+ out.push(code);
91
+ }
92
+ }
93
+ return out;
94
+ }
95
+ function readFirstResolverKey(req) {
96
+ if (!req || typeof req !== "object")
97
+ return "";
98
+ const custom = req.payload?.config?.custom?.translator?.resolvers;
99
+ if (!Array.isArray(custom) || custom.length === 0)
100
+ return "";
101
+ const first = custom[0];
102
+ return typeof first?.key === "string" ? first.key : "";
103
+ }
104
+
105
+ // src/jobs/createAutoTranslateGlobalHook.ts
106
+ function createAutoTranslateGlobalHook(options) {
107
+ const {
108
+ globalSlug,
109
+ defaultLocale: defaultLocaleOption,
110
+ targetLocales: targetLocalesOption,
111
+ workflowSlug = TRANSLATE_WORKFLOW_SLUG
112
+ } = options;
113
+ return async ({ doc, req }) => {
114
+ if (shouldSkipAutoTranslate2(req.context))
115
+ return doc;
116
+ const typed = doc;
117
+ const requestLocale = readRequestLocale2(req);
118
+ const defaultLocale = defaultLocaleOption ?? readConfigDefaultLocale2(req) ?? "";
119
+ if (!requestLocale || !defaultLocale || requestLocale !== defaultLocale)
120
+ return doc;
121
+ if (!req.user)
122
+ return doc;
123
+ const targetLocales = targetLocalesOption ?? readTargetLocales2(req, defaultLocale);
124
+ if (targetLocales.length === 0)
125
+ return doc;
126
+ const resolverKey = options.resolverKey ?? readFirstResolverKey2(req);
127
+ if (!resolverKey) {
128
+ req.payload.logger.error({
129
+ msg: `auto-translate: no resolver key available for global ${globalSlug} — pass \`resolverKey\` to \`createAutoTranslateGlobalHook\` or configure \`translator.resolvers\` in \`translator({...})\``
130
+ });
131
+ return doc;
132
+ }
133
+ const updatedAt = typed.updatedAt ?? new Date().toISOString();
134
+ const toLocales = targetLocales.filter((toLocale) => toLocale !== defaultLocale);
135
+ if (toLocales.length === 0)
136
+ return doc;
137
+ try {
138
+ const job = await req.payload.jobs.queue({
139
+ workflow: workflowSlug,
140
+ input: {
141
+ updatedAt,
142
+ global: globalSlug,
143
+ fromLocale: defaultLocale,
144
+ resolver: resolverKey || undefined,
145
+ toLocales
146
+ }
147
+ });
148
+ req.payload.logger.info({
149
+ msg: `auto-translate: queued translation of ${globalSlug} → [${toLocales.join(", ")}] (job ${job.id})`
150
+ });
151
+ } catch (error) {
152
+ req.payload.logger.error({
153
+ msg: `auto-translate: failed to queue ${globalSlug}: ${String(error)}`
154
+ });
155
+ }
156
+ return doc;
157
+ };
158
+ }
159
+ function shouldSkipAutoTranslate2(context) {
160
+ return Boolean(context?.disableAutoTranslate);
161
+ }
162
+ function readRequestLocale2(req) {
163
+ if (!req || typeof req !== "object")
164
+ return "";
165
+ const locale = req.locale;
166
+ return typeof locale === "string" && locale.length > 0 ? locale : "";
167
+ }
168
+ function readConfigDefaultLocale2(req) {
169
+ if (!req || typeof req !== "object")
170
+ return "";
171
+ const config = req.payload?.config;
172
+ const def = config?.localization?.defaultLocale;
173
+ return typeof def === "string" && def.length > 0 ? def : "";
174
+ }
175
+ function readTargetLocales2(req, defaultLocale) {
176
+ if (!req || typeof req !== "object")
177
+ return [];
178
+ const list = req.payload?.config?.localization?.locales;
179
+ if (!Array.isArray(list) || list.length === 0)
180
+ return [];
181
+ const out = [];
182
+ for (const entry of list) {
183
+ const code = typeof entry === "string" ? entry : entry?.code;
184
+ if (typeof code === "string" && code.length > 0 && code !== defaultLocale) {
185
+ out.push(code);
186
+ }
187
+ }
188
+ return out;
189
+ }
190
+ function readFirstResolverKey2(req) {
191
+ if (!req || typeof req !== "object")
192
+ return "";
193
+ const custom = req.payload?.config?.custom?.translator?.resolvers;
194
+ if (!Array.isArray(custom) || custom.length === 0)
195
+ return "";
196
+ const first = custom[0];
197
+ return typeof first?.key === "string" ? first.key : "";
198
+ }
199
+
200
+ // src/translate/operation.ts
201
+ import he from "he";
202
+ import { APIError as APIError3 } from "payload";
203
+
204
+ // src/translate/findEntityWithConfig.ts
205
+ import { APIError } from "payload";
206
+ var findConfigBySlug = (slug, enities) => enities.find((entity) => entity.slug === slug);
207
+ var findEntityWithConfig = async (args) => {
208
+ const { collectionSlug, globalSlug, id, locale, overrideAccess, req } = args;
209
+ if (!collectionSlug && !globalSlug)
210
+ throw new APIError("Bad Request", 400);
211
+ const { payload } = req;
212
+ const { config } = payload;
213
+ const isGlobal = !!globalSlug;
214
+ if (!isGlobal && !id)
215
+ throw new APIError("Bad Request", 400);
216
+ const entityConfig = isGlobal ? findConfigBySlug(globalSlug, config.globals) : findConfigBySlug(collectionSlug, config.collections);
217
+ if (!entityConfig)
218
+ throw new APIError("Bad Request", 400);
219
+ const docPromise = isGlobal ? payload.findGlobal({
220
+ depth: 0,
221
+ fallbackLocale: undefined,
222
+ locale,
223
+ overrideAccess,
224
+ req,
225
+ slug: args.globalSlug
226
+ }) : payload.findByID({
227
+ collection: collectionSlug,
228
+ depth: 0,
229
+ fallbackLocale: undefined,
230
+ id,
231
+ locale,
232
+ overrideAccess,
233
+ req
234
+ });
235
+ const doc = await docPromise;
236
+ return {
237
+ config: entityConfig,
238
+ doc
239
+ };
240
+ };
241
+
242
+ // src/translate/traverseFields.ts
243
+ import ObjectID from "bson-objectid";
244
+ import { tabHasName } from "payload/shared";
245
+
246
+ // src/utils/isEmpty.ts
247
+ var isEmpty = (value) => {
248
+ if (Array.isArray(value))
249
+ return value.length === 0;
250
+ if (value === null || typeof value === "undefined")
251
+ return true;
252
+ if (typeof value === "object" && Object.keys(value).length === 0)
253
+ return true;
254
+ return false;
255
+ };
256
+
257
+ // src/utils/sanitizeSlug.ts
258
+ var sanitizeSlug = (text) => text.normalize("NFKD").replace(/[\u0300-\u036f]/g, "").toLowerCase().replace(/[^a-z0-9-_]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "");
259
+
260
+ // src/translate/traverseRichText.ts
261
+ var traverseRichText = ({
262
+ onText,
263
+ root,
264
+ siblingData,
265
+ additionalTraverseRichText
266
+ }) => {
267
+ siblingData = siblingData ?? root;
268
+ if (siblingData.text) {
269
+ onText(siblingData);
270
+ }
271
+ if (Array.isArray(siblingData?.children)) {
272
+ for (const child of siblingData.children) {
273
+ traverseRichText({
274
+ onText,
275
+ root,
276
+ siblingData: child,
277
+ additionalTraverseRichText
278
+ });
279
+ }
280
+ } else {
281
+ additionalTraverseRichText?.({ onText, root, siblingData });
282
+ }
283
+ };
284
+
285
+ // src/translate/traverseFields.ts
286
+ var joinPath = (base, segment) => base ? `${base}.${segment}` : segment;
287
+ var traverseFields = ({
288
+ dataFrom,
289
+ emptyOnly,
290
+ fields,
291
+ localizedParent,
292
+ path,
293
+ siblingDataFrom,
294
+ siblingDataTranslated,
295
+ translatedData,
296
+ valuesToTranslate,
297
+ _options
298
+ }) => {
299
+ const { additionalTraverseRichText } = _options ?? {};
300
+ siblingDataFrom = siblingDataFrom ?? dataFrom;
301
+ siblingDataTranslated = siblingDataTranslated ?? translatedData;
302
+ for (const field of fields) {
303
+ switch (field.type) {
304
+ case "tabs":
305
+ for (const tab of field.tabs) {
306
+ const hasName = tabHasName(tab);
307
+ const tabDataFrom = hasName ? siblingDataFrom[tab.name] : siblingDataFrom;
308
+ if (!tabDataFrom)
309
+ return;
310
+ let tabDataTranslated;
311
+ if (hasName) {
312
+ if (!siblingDataTranslated[tab.name])
313
+ siblingDataTranslated[tab.name] = {};
314
+ tabDataTranslated = siblingDataTranslated[tab.name];
315
+ } else {
316
+ tabDataTranslated = siblingDataTranslated;
317
+ }
318
+ traverseFields({
319
+ dataFrom,
320
+ emptyOnly,
321
+ fields: tab.fields,
322
+ localizedParent: localizedParent ?? tab.localized,
323
+ path: hasName ? joinPath(path, tab.name) : path,
324
+ siblingDataFrom: tabDataFrom,
325
+ siblingDataTranslated: tabDataTranslated,
326
+ translatedData,
327
+ valuesToTranslate,
328
+ _options
329
+ });
330
+ }
331
+ break;
332
+ case "group": {
333
+ if (!("name" in field))
334
+ break;
335
+ const groupDataFrom = siblingDataFrom[field.name];
336
+ if (!groupDataFrom)
337
+ break;
338
+ if (!siblingDataTranslated[field.name])
339
+ siblingDataTranslated[field.name] = {};
340
+ const groupDataTranslated = siblingDataTranslated[field.name];
341
+ traverseFields({
342
+ dataFrom,
343
+ emptyOnly,
344
+ fields: field.fields,
345
+ localizedParent: localizedParent ?? field.localized,
346
+ path: joinPath(path, field.name),
347
+ siblingDataFrom: groupDataFrom,
348
+ siblingDataTranslated: groupDataTranslated,
349
+ translatedData,
350
+ valuesToTranslate,
351
+ _options
352
+ });
353
+ break;
354
+ }
355
+ case "array": {
356
+ const arrayDataFrom = siblingDataFrom[field.name];
357
+ if (isEmpty(arrayDataFrom))
358
+ break;
359
+ if (!siblingDataTranslated[field.name])
360
+ siblingDataTranslated[field.name] = [];
361
+ let arrayDataTranslated = siblingDataTranslated[field.name];
362
+ if (field.localized || localizedParent) {
363
+ if (arrayDataTranslated.length > 0 && emptyOnly)
364
+ break;
365
+ arrayDataTranslated = arrayDataFrom.map(() => ({
366
+ id: ObjectID().toHexString()
367
+ }));
368
+ }
369
+ arrayDataTranslated.forEach((item, index) => {
370
+ traverseFields({
371
+ dataFrom,
372
+ emptyOnly,
373
+ fields: field.fields,
374
+ localizedParent: localizedParent ?? field.localized,
375
+ path: `${joinPath(path, field.name)}[${index}]`,
376
+ siblingDataFrom: arrayDataFrom[index],
377
+ siblingDataTranslated: item,
378
+ translatedData,
379
+ valuesToTranslate,
380
+ _options
381
+ });
382
+ });
383
+ siblingDataTranslated[field.name] = arrayDataTranslated;
384
+ break;
385
+ }
386
+ case "blocks": {
387
+ const blocksDataFrom = siblingDataFrom[field.name];
388
+ if (isEmpty(blocksDataFrom))
389
+ break;
390
+ if (!siblingDataTranslated[field.name])
391
+ siblingDataTranslated[field.name] = [];
392
+ let blocksDataTranslated = siblingDataTranslated[field.name];
393
+ if (field.localized || localizedParent) {
394
+ if (blocksDataTranslated.length > 0 && emptyOnly)
395
+ break;
396
+ blocksDataTranslated = blocksDataFrom.map(({ blockType }) => ({
397
+ blockType,
398
+ id: ObjectID().toHexString()
399
+ }));
400
+ }
401
+ blocksDataTranslated.forEach((item, index) => {
402
+ const block = field.blocks.find((each) => each.slug === item.blockType);
403
+ if (!block)
404
+ return;
405
+ traverseFields({
406
+ dataFrom,
407
+ emptyOnly,
408
+ fields: block.fields,
409
+ localizedParent: localizedParent ?? field.localized,
410
+ path: `${joinPath(path, field.name)}[${index}](${item.blockType})`,
411
+ siblingDataFrom: blocksDataFrom[index],
412
+ siblingDataTranslated: item,
413
+ translatedData,
414
+ valuesToTranslate,
415
+ _options
416
+ });
417
+ });
418
+ siblingDataTranslated[field.name] = blocksDataTranslated;
419
+ break;
420
+ }
421
+ case "collapsible":
422
+ case "row":
423
+ traverseFields({
424
+ dataFrom,
425
+ emptyOnly,
426
+ fields: field.fields,
427
+ localizedParent,
428
+ path,
429
+ siblingDataFrom,
430
+ siblingDataTranslated,
431
+ translatedData,
432
+ valuesToTranslate,
433
+ _options
434
+ });
435
+ break;
436
+ case "date":
437
+ case "checkbox":
438
+ case "code":
439
+ case "email":
440
+ case "number":
441
+ case "point":
442
+ case "radio":
443
+ case "relationship":
444
+ case "select":
445
+ case "upload":
446
+ siblingDataTranslated[field.name] = siblingDataFrom[field.name];
447
+ break;
448
+ case "json":
449
+ let traverseObject = function(obj, objPath) {
450
+ if (!obj || typeof obj !== "object")
451
+ return;
452
+ for (const key in obj) {
453
+ const value = obj[key];
454
+ if (typeof value === "string" && value.trim()) {
455
+ ((parentObj, parentKey, parentValue, parentPath) => {
456
+ valuesToTranslate.push({
457
+ onTranslate: (translated) => {
458
+ parentObj[parentKey] = translated;
459
+ },
460
+ value: parentValue,
461
+ path: parentPath
462
+ });
463
+ })(obj, key, value, joinPath(objPath, key));
464
+ } else if (typeof value === "object" && value !== null) {
465
+ traverseObject(value, joinPath(objPath, key));
466
+ }
467
+ }
468
+ };
469
+ if (!(field.localized || localizedParent))
470
+ break;
471
+ if (isEmpty(siblingDataFrom[field.name]))
472
+ break;
473
+ if (emptyOnly && siblingDataTranslated[field.name])
474
+ break;
475
+ const jsonDataFrom = siblingDataFrom[field.name];
476
+ const jsonDataTranslated = JSON.parse(JSON.stringify(jsonDataFrom));
477
+ siblingDataTranslated[field.name] = jsonDataTranslated;
478
+ traverseObject(jsonDataTranslated, joinPath(path, field.name));
479
+ break;
480
+ case "text":
481
+ case "textarea":
482
+ if (field.custom && typeof field.custom === "object" && field.custom.translatorSkip)
483
+ break;
484
+ if (!(field.localized || localizedParent) || isEmpty(siblingDataFrom[field.name]))
485
+ break;
486
+ if (emptyOnly && siblingDataTranslated[field.name])
487
+ break;
488
+ if (field.name === "blockName" || field.name === "id") {
489
+ break;
490
+ }
491
+ valuesToTranslate.push({
492
+ onTranslate: (translated) => {
493
+ siblingDataTranslated[field.name] = field.name === "slug" ? sanitizeSlug(translated) : translated;
494
+ },
495
+ value: siblingDataFrom[field.name],
496
+ path: joinPath(path, field.name)
497
+ });
498
+ break;
499
+ case "richText": {
500
+ if (!(field.localized || localizedParent) || isEmpty(siblingDataFrom[field.name]))
501
+ break;
502
+ if (emptyOnly && siblingDataTranslated[field.name])
503
+ break;
504
+ const richTextDataFrom = siblingDataFrom[field.name];
505
+ siblingDataTranslated[field.name] = richTextDataFrom;
506
+ if (!richTextDataFrom)
507
+ break;
508
+ const isSlate = Array.isArray(richTextDataFrom);
509
+ const isLexical = "root" in richTextDataFrom;
510
+ if (!isSlate && !isLexical)
511
+ break;
512
+ const richTextPath = joinPath(path, field.name);
513
+ let richTextNodeIndex = 0;
514
+ if (isLexical) {
515
+ const root = siblingDataTranslated[field.name]?.root;
516
+ if (root)
517
+ traverseRichText({
518
+ onText: (siblingData, attribute = "text") => {
519
+ valuesToTranslate.push({
520
+ onTranslate: (translated) => {
521
+ siblingData[attribute] = translated;
522
+ },
523
+ value: siblingData[attribute],
524
+ path: `${richTextPath}#${richTextNodeIndex++}`
525
+ });
526
+ },
527
+ root,
528
+ additionalTraverseRichText
529
+ });
530
+ } else {
531
+ for (const root of siblingDataTranslated[field.name]) {
532
+ traverseRichText({
533
+ onText: (siblingData, attribute = "text") => {
534
+ valuesToTranslate.push({
535
+ onTranslate: (translated) => {
536
+ siblingData[attribute] = translated;
537
+ },
538
+ value: siblingData[attribute],
539
+ path: `${richTextPath}#${richTextNodeIndex++}`
540
+ });
541
+ },
542
+ root,
543
+ additionalTraverseRichText
544
+ });
545
+ }
546
+ }
547
+ break;
548
+ }
549
+ default:
550
+ break;
551
+ }
552
+ }
553
+ };
554
+
555
+ // src/translate/updateEntity.ts
556
+ import { APIError as APIError2 } from "payload";
557
+ var updateEntity = ({
558
+ collectionSlug,
559
+ data,
560
+ depth: incomingDepth,
561
+ globalSlug,
562
+ id,
563
+ locale,
564
+ overrideAccess,
565
+ req
566
+ }) => {
567
+ if (!collectionSlug && !globalSlug)
568
+ throw new APIError2("Bad Request", 400);
569
+ const isGlobal = !!globalSlug;
570
+ if (!isGlobal && !id)
571
+ throw new APIError2("Bad Request", 400);
572
+ const depth = incomingDepth ?? req.payload.config.defaultDepth;
573
+ const promise = isGlobal ? req.payload.updateGlobal({
574
+ data,
575
+ depth,
576
+ locale,
577
+ overrideAccess,
578
+ req,
579
+ slug: globalSlug
580
+ }) : req.payload.update({
581
+ collection: collectionSlug,
582
+ data,
583
+ depth,
584
+ id,
585
+ locale,
586
+ overrideAccess,
587
+ req
588
+ });
589
+ return promise;
590
+ };
591
+
592
+ // src/translate/operation.ts
593
+ var preview = (value) => {
594
+ const flat = (typeof value === "string" ? value : String(value ?? "")).replace(/\s+/g, " ").trim();
595
+ return JSON.stringify(flat.length > 60 ? `${flat.slice(0, 57)}…` : flat);
596
+ };
597
+ var translateOperation = async (args) => {
598
+ const req = "req" in args ? args.req : {
599
+ payload: args.payload
600
+ };
601
+ const { collectionSlug, globalSlug, id, locale, localeFrom, overrideAccess } = args;
602
+ const { config, doc: dataFrom } = await findEntityWithConfig({
603
+ collectionSlug,
604
+ globalSlug,
605
+ id,
606
+ locale: localeFrom,
607
+ req
608
+ });
609
+ const resolver = (req.payload.config.custom?.translator?.resolvers ?? []).find((each) => each.key === args.resolver);
610
+ if (!resolver)
611
+ throw new APIError3(`Resolver with the key ${args.resolver} was not found`);
612
+ const valuesToTranslate = [];
613
+ let translatedData = args.data;
614
+ if (!translatedData) {
615
+ const { doc } = await findEntityWithConfig({
616
+ collectionSlug,
617
+ globalSlug,
618
+ id,
619
+ locale,
620
+ overrideAccess,
621
+ req
622
+ });
623
+ translatedData = doc;
624
+ }
625
+ traverseFields({
626
+ dataFrom,
627
+ emptyOnly: args.emptyOnly,
628
+ fields: config.fields,
629
+ translatedData,
630
+ valuesToTranslate,
631
+ _options: req.payload.config.custom?.translator?._options
632
+ });
633
+ const entityLabel = `${collectionSlug || globalSlug}#${id ?? ""}`;
634
+ const direction = `${args.localeFrom}→${args.locale}`;
635
+ req.payload.logger.info({
636
+ msg: `[translate] ${entityLabel} ${direction}: traversed ${valuesToTranslate.length} translatable value(s)`
637
+ });
638
+ const resolveResult = await resolver.resolve({
639
+ localeFrom: args.localeFrom,
640
+ localeTo: args.locale,
641
+ req,
642
+ texts: valuesToTranslate.map((each) => each.value)
643
+ });
644
+ let result;
645
+ if (!resolveResult.success) {
646
+ req.payload.logger.warn({
647
+ msg: `[translate] ${entityLabel} ${direction}: resolver failed — ${valuesToTranslate.length} value(s) traversed but NOT translated` + (valuesToTranslate.length ? `
648
+ ${valuesToTranslate.map((v) => ` ${v.path ?? "(unknown)"}: ${preview(v.value)}`).join(`
649
+ `)}` : "")
650
+ });
651
+ result = {
652
+ success: false
653
+ };
654
+ } else {
655
+ const summary = [];
656
+ resolveResult.translatedTexts.forEach((translated, index) => {
657
+ const formattedValue = he.decode(translated);
658
+ const entry = valuesToTranslate[index];
659
+ summary.push(` ${entry.path ?? "(unknown)"}: ${preview(entry.value)} → ${preview(formattedValue)}`);
660
+ entry.onTranslate(formattedValue);
661
+ });
662
+ req.payload.logger.info({
663
+ msg: `[translate] ${entityLabel} ${direction}: translated ${resolveResult.translatedTexts.length} value(s)` + (summary.length ? `
664
+ ${summary.join(`
665
+ `)}` : "")
666
+ });
667
+ if (args.update) {
668
+ await updateEntity({
669
+ collectionSlug,
670
+ data: translatedData,
671
+ depth: 0,
672
+ globalSlug,
673
+ id,
674
+ locale,
675
+ overrideAccess,
676
+ req
677
+ });
678
+ }
679
+ result = {
680
+ success: true,
681
+ translatedData,
682
+ dataFrom
683
+ };
684
+ }
685
+ return result;
686
+ };
687
+
688
+ // src/jobs/createTranslateTask.ts
689
+ function createTranslateTask(options = {}) {
690
+ const { slug = "translateEntityToLocale" } = options;
691
+ return {
692
+ slug,
693
+ inputSchema: [
694
+ { name: "id", type: "number", required: false },
695
+ { name: "collection", type: "text", required: false },
696
+ { name: "global", type: "text", required: false },
697
+ { name: "fromLocale", type: "text", required: true },
698
+ { name: "toLocale", type: "text", required: true },
699
+ { name: "resolver", type: "text", required: false }
700
+ ],
701
+ outputSchema: [],
702
+ retries: 3,
703
+ handler: async (args) => {
704
+ const { input, job, req } = args;
705
+ const { id, collection, global, fromLocale, toLocale, resolver: inputResolver } = input;
706
+ if (!collection && !global) {
707
+ throw new Error("translateTask: either `collection` or `global` must be provided");
708
+ }
709
+ const resolverKey = options.resolverKey ?? inputResolver ?? readFirstResolverKey3(req);
710
+ if (!resolverKey) {
711
+ throw new Error(`translateTask: no resolver key available — pass \`resolverKey\` to \`createTranslateTask\` or queue the workflow with a \`resolver\` input. Did you forget to pass \`translator.resolvers\` to \`translator({...})\`?`);
712
+ }
713
+ const entityLabel = collection || global;
714
+ req.payload.logger.info({
715
+ jobId: job.id,
716
+ msg: `translating ${entityLabel} to locale ${toLocale}`
717
+ });
718
+ let result;
719
+ try {
720
+ result = await translateOperation({
721
+ req,
722
+ collectionSlug: collection,
723
+ globalSlug: global,
724
+ emptyOnly: false,
725
+ id,
726
+ locale: toLocale,
727
+ localeFrom: fromLocale,
728
+ overrideAccess: true,
729
+ resolver: resolverKey,
730
+ update: false
731
+ });
732
+ } catch (error) {
733
+ req.payload.logger.error({
734
+ jobId: job.id,
735
+ msg: `translateOperation threw for ${entityLabel} → ${toLocale}: ${String(error)}`
736
+ });
737
+ throw error;
738
+ }
739
+ if (!result.success) {
740
+ req.payload.logger.error({
741
+ jobId: job.id,
742
+ msg: `translation for ${entityLabel} to ${toLocale} failed (resolver returned success=false)`
743
+ });
744
+ throw new Error(`translateTask: resolver returned success=false for ${entityLabel} → ${toLocale}`);
745
+ }
746
+ const translated = result.translatedData ?? {};
747
+ const { _locale: _dropLocale, _parent_id: _dropParent, ...data } = translated;
748
+ req.payload.logger.info({
749
+ jobId: job.id,
750
+ msg: `[translate] persisting ${entityLabel}#${id ?? global} → ${toLocale}`
751
+ });
752
+ try {
753
+ if (collection) {
754
+ await req.payload.update({
755
+ collection,
756
+ data,
757
+ id,
758
+ locale: toLocale,
759
+ overrideAccess: true,
760
+ req
761
+ });
762
+ } else {
763
+ await req.payload.updateGlobal({
764
+ slug: global,
765
+ data,
766
+ locale: toLocale,
767
+ overrideAccess: true,
768
+ req
769
+ });
770
+ }
771
+ } catch (error) {
772
+ req.payload.logger.error({
773
+ jobId: job.id,
774
+ msg: `persist failed for ${entityLabel} (id=${id ?? global}) at locale ${toLocale}: ${String(error)}`
775
+ });
776
+ throw error;
777
+ }
778
+ req.payload.logger.info({
779
+ jobId: job.id,
780
+ msg: `translation complete for ${entityLabel} → ${toLocale}`
781
+ });
782
+ return { output: { success: true } };
783
+ }
784
+ };
785
+ }
786
+ function readFirstResolverKey3(req) {
787
+ if (!req || typeof req !== "object")
788
+ return "";
789
+ const custom = req.payload?.config?.custom?.translator?.resolvers;
790
+ if (!Array.isArray(custom) || custom.length === 0)
791
+ return "";
792
+ const first = custom[0];
793
+ return typeof first?.key === "string" ? first.key : "";
794
+ }
795
+
796
+ // src/jobs/createTranslateWorkflow.ts
797
+ function createTranslateWorkflow(options = {}) {
798
+ const { slug = "translateEntityToLocales", taskSlug = "translateEntityToLocale" } = options;
799
+ return {
800
+ slug,
801
+ inputSchema: [
802
+ { name: "id", type: "number", required: false },
803
+ { name: "updatedAt", type: "date", required: true },
804
+ { name: "collection", type: "text", required: false },
805
+ { name: "global", type: "text", required: false },
806
+ { name: "fromLocale", type: "text", required: true },
807
+ { name: "toLocales", type: "json", required: false },
808
+ { name: "toLocale", type: "text", required: false },
809
+ { name: "resolver", type: "text", required: false }
810
+ ],
811
+ handler: async (args) => {
812
+ const { job, req, tasks } = args;
813
+ const { id, collection, global, fromLocale, toLocales, toLocale, updatedAt, resolver } = job.input;
814
+ if (!collection && !global) {
815
+ throw new Error("translateWorkflow: either `collection` or `global` must be provided");
816
+ }
817
+ if (typeof req.payload.config.localization !== "object") {
818
+ req.payload.logger.error({
819
+ jobId: job.id,
820
+ msg: "localization is not enabled — skipping auto-translation workflow"
821
+ });
822
+ return;
823
+ }
824
+ const entityKey = collection ? `${collection}-${id}` : global;
825
+ const updatedAtIso = updatedAt instanceof Date ? updatedAt.toISOString() : String(updatedAt);
826
+ const requested = Array.isArray(toLocales) && toLocales.length > 0 ? toLocales : toLocale ? [toLocale] : [];
827
+ const targets = requested.filter((locale) => typeof locale === "string" && locale && locale !== fromLocale);
828
+ if (targets.length === 0) {
829
+ req.payload.logger.warn({
830
+ jobId: job.id,
831
+ msg: `translateWorkflow: no target locales for ${entityKey} — nothing to translate`
832
+ });
833
+ return;
834
+ }
835
+ req.payload.logger.info({
836
+ jobId: job.id,
837
+ msg: `scheduling translation of ${entityKey}: ${fromLocale} → [${targets.join(", ")}]`
838
+ });
839
+ for (const target of targets) {
840
+ await tasks[taskSlug](`${entityKey}-${fromLocale}-${target}-${updatedAtIso}`, {
841
+ input: {
842
+ id,
843
+ collection,
844
+ global,
845
+ fromLocale,
846
+ toLocale: target,
847
+ resolver
848
+ }
849
+ });
850
+ }
851
+ }
852
+ };
853
+ }
854
+
855
+ export { TRANSLATE_TASK_SLUG, TRANSLATE_WORKFLOW_SLUG, createAutoTranslateCollectionHook, createAutoTranslateGlobalHook, translateOperation, createTranslateTask, createTranslateWorkflow };