@bison-lab/payload-core 4.39.0 → 5.0.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 (75) hide show
  1. package/README.md +63 -33
  2. package/dist/admin.d.mts +19 -7
  3. package/dist/admin.d.mts.map +1 -1
  4. package/dist/admin.mjs +229 -16
  5. package/dist/admin.mjs.map +1 -1
  6. package/dist/block-library.d.mts +1 -1
  7. package/dist/block-library.mjs +1 -1
  8. package/dist/{block-thumbnails-DXOUzGjY.mjs → block-thumbnails-DC34uFtE.mjs} +1 -1
  9. package/dist/{block-thumbnails-DXOUzGjY.mjs.map → block-thumbnails-DC34uFtE.mjs.map} +1 -1
  10. package/dist/block-thumbnails-cli.mjs +1 -1
  11. package/dist/block-thumbnails.mjs +1 -1
  12. package/dist/capability-CqdYCzG1.d.mts +434 -0
  13. package/dist/capability-CqdYCzG1.d.mts.map +1 -0
  14. package/dist/capability-DHPE2kon.mjs +2685 -0
  15. package/dist/capability-DHPE2kon.mjs.map +1 -0
  16. package/dist/{catalogue-FxH10X3v.d.mts → catalogue-DWqHWVE5.d.mts} +1 -1
  17. package/dist/{catalogue-FxH10X3v.d.mts.map → catalogue-DWqHWVE5.d.mts.map} +1 -1
  18. package/dist/{facet-field-DjaZ0C7D.d.mts → facet-field-2K22iuWA.d.mts} +1 -1
  19. package/dist/{facet-field-DjaZ0C7D.d.mts.map → facet-field-2K22iuWA.d.mts.map} +1 -1
  20. package/dist/{facet-field-Uf8S4yL1.mjs → facet-field-DO3VT_Cz.mjs} +1 -1
  21. package/dist/{facet-field-Uf8S4yL1.mjs.map → facet-field-DO3VT_Cz.mjs.map} +1 -1
  22. package/dist/index.d.mts +13 -7
  23. package/dist/index.d.mts.map +1 -1
  24. package/dist/index.mjs +25 -667
  25. package/dist/index.mjs.map +1 -1
  26. package/dist/{locale-CFWfB4wP.mjs → locale-B6rUVwpg.mjs} +1 -1
  27. package/dist/locale-B6rUVwpg.mjs.map +1 -0
  28. package/dist/{locale-CWiIcGuU.d.mts → locale-CTT3nn6T.d.mts} +5 -4
  29. package/dist/locale-CTT3nn6T.d.mts.map +1 -0
  30. package/dist/messages-dZV_aAnR.mjs +93 -0
  31. package/dist/messages-dZV_aAnR.mjs.map +1 -0
  32. package/dist/metadata.d.mts +1 -1
  33. package/dist/navigation.d.mts +2 -2
  34. package/dist/navigation.mjs +1 -1
  35. package/dist/og.d.mts +2 -2
  36. package/dist/og.mjs +1 -1
  37. package/dist/{preview-CNBVfmM7.d.mts → preview-1vwxBgm5.d.mts} +2 -2
  38. package/dist/{preview-CNBVfmM7.d.mts.map → preview-1vwxBgm5.d.mts.map} +1 -1
  39. package/dist/{published-_1rrTj_B.d.mts → published-B3etM6X5.d.mts} +3 -3
  40. package/dist/{published-_1rrTj_B.d.mts.map → published-B3etM6X5.d.mts.map} +1 -1
  41. package/dist/{published-D3yVnbxs.mjs → published-BMt7Z5CF.mjs} +2 -2
  42. package/dist/{published-D3yVnbxs.mjs.map → published-BMt7Z5CF.mjs.map} +1 -1
  43. package/dist/{published-DefZv9na.mjs → published-CkqqY08H.mjs} +2 -2
  44. package/dist/{published-DefZv9na.mjs.map → published-CkqqY08H.mjs.map} +1 -1
  45. package/dist/{published-DXjnElZn.d.mts → published-QDNmDi02.d.mts} +2 -2
  46. package/dist/{published-DXjnElZn.d.mts.map → published-QDNmDi02.d.mts.map} +1 -1
  47. package/dist/{published-QyTcDznE.mjs → published-hqtvmVUD.mjs} +1 -1
  48. package/dist/{published-QyTcDznE.mjs.map → published-hqtvmVUD.mjs.map} +1 -1
  49. package/dist/{root-page-key-B86JwL8Z.mjs → root-page-key-kx3C1eyp.mjs} +1 -1
  50. package/dist/{root-page-key-B86JwL8Z.mjs.map → root-page-key-kx3C1eyp.mjs.map} +1 -1
  51. package/dist/seo.mjs +1 -1
  52. package/dist/{messages-Fl1spIwN.mjs → strings-Fd7kUCT7.mjs} +156 -118
  53. package/dist/strings-Fd7kUCT7.mjs.map +1 -0
  54. package/dist/taxonomy.d.mts +1 -1
  55. package/dist/taxonomy.mjs +1 -1
  56. package/dist/theme.d.mts +4 -4
  57. package/dist/theme.mjs +1 -1
  58. package/dist/{title-D_jixG36.d.mts → title-trhUexxM.d.mts} +1 -1
  59. package/dist/{title-D_jixG36.d.mts.map → title-trhUexxM.d.mts.map} +1 -1
  60. package/dist/translate-messages-cli.mjs +3 -2
  61. package/dist/translate-messages-cli.mjs.map +1 -1
  62. package/dist/translate.d.mts +300 -206
  63. package/dist/translate.d.mts.map +1 -1
  64. package/dist/translate.mjs +225 -1027
  65. package/dist/translate.mjs.map +1 -1
  66. package/dist/{types-Db6Iy3hJ.d.mts → types-DLBlHZUd.d.mts} +1 -1
  67. package/dist/{types-Db6Iy3hJ.d.mts.map → types-DLBlHZUd.d.mts.map} +1 -1
  68. package/dist/{wireframe-xcJNJzBf.mjs → wireframe-CXorKFU_.mjs} +1 -1
  69. package/dist/{wireframe-xcJNJzBf.mjs.map → wireframe-CXorKFU_.mjs.map} +1 -1
  70. package/dist/wireframe-cli.mjs +1 -1
  71. package/dist/wireframe.mjs +1 -1
  72. package/package.json +6 -8
  73. package/dist/locale-CFWfB4wP.mjs.map +0 -1
  74. package/dist/locale-CWiIcGuU.d.mts.map +0 -1
  75. package/dist/messages-Fl1spIwN.mjs.map +0 -1
@@ -0,0 +1,2685 @@
1
+ import { f as verifyAnthropicKey, i as ECONOMY_TRANSLATE_MODEL, n as translateStrings, o as anthropicTranslator, r as DEFAULT_TRANSLATE_MODEL, t as isTranslatorConfigured } from "./strings-Fd7kUCT7.mjs";
2
+ import { APIError } from "payload";
3
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from "node:crypto";
4
+ //#region src/features/types.ts
5
+ const FEATURES_SLUG = "features";
6
+ const FEATURE_GROUPS = [
7
+ "pages",
8
+ "media",
9
+ "theme",
10
+ "users"
11
+ ];
12
+ const FEATURE_GROUP_LABELS = {
13
+ pages: "Pages",
14
+ media: "Media",
15
+ theme: "Theme",
16
+ users: "Users"
17
+ };
18
+ const PACKAGE_FEATURE_SLUGS = [
19
+ "content",
20
+ "publish",
21
+ "media",
22
+ "users",
23
+ "roles"
24
+ ];
25
+ /**
26
+ * Package catalogue. Features itself is not a row — that screen is
27
+ * Developer-only in code. Theme is not a row either: every site has the
28
+ * Theme Global, and who may edit it is the Roles grant `theme`. Empty
29
+ * Global falls back to these defaults.
30
+ */
31
+ const PACKAGE_FEATURES = [
32
+ {
33
+ slug: "content",
34
+ label: "Content",
35
+ group: "pages",
36
+ defaultReleased: true
37
+ },
38
+ {
39
+ slug: "publish",
40
+ label: "Publish",
41
+ group: "pages",
42
+ defaultReleased: true
43
+ },
44
+ {
45
+ slug: "media",
46
+ label: "Media",
47
+ group: "media",
48
+ defaultReleased: true
49
+ },
50
+ {
51
+ slug: "users",
52
+ label: "Users",
53
+ group: "users",
54
+ defaultReleased: true
55
+ },
56
+ {
57
+ slug: "roles",
58
+ label: "Roles",
59
+ group: "users",
60
+ defaultReleased: true
61
+ }
62
+ ];
63
+ function isFeatureGroupId(value) {
64
+ return typeof value === "string" && FEATURE_GROUPS.includes(value);
65
+ }
66
+ function isPackageFeatureSlug(value) {
67
+ return typeof value === "string" && PACKAGE_FEATURE_SLUGS.includes(value);
68
+ }
69
+ function isFeatureSlug(value) {
70
+ return typeof value === "string" && /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(value);
71
+ }
72
+ /** @deprecated Locks are gone; the release switch is the valve. */
73
+ function isLockedFeature(_slug, _locked) {
74
+ return false;
75
+ }
76
+ //#endregion
77
+ //#region src/roles/types.ts
78
+ /**
79
+ * The Roles Global a site's generated types will describe. Optional and
80
+ * nullable, no index signature: a generated Global is assignable to this,
81
+ * never the reverse.
82
+ */
83
+ const ROLES = [
84
+ "developer",
85
+ "admin",
86
+ "designer",
87
+ "author"
88
+ ];
89
+ const ROLE_LABELS = {
90
+ developer: "Developer",
91
+ admin: "Admin",
92
+ designer: "Designer",
93
+ author: "Author"
94
+ };
95
+ /** Capability aliases over feature grants. Brand is the Theme grant. */
96
+ const CAPABILITIES = [
97
+ "content",
98
+ "brand",
99
+ "publish",
100
+ "users"
101
+ ];
102
+ /** One Roles grant. Opens the Theme document and brand-assets. Not a Features row. */
103
+ const THEME_FEATURE_SLUGS = ["theme"];
104
+ /**
105
+ * Grants stored before Theme was one row. Reading any of them is the
106
+ * Theme grant, so a Designer who already had Colors keeps Theme.
107
+ */
108
+ const LEGACY_THEME_FEATURE_SLUGS = [
109
+ "theme-colors",
110
+ "theme-typography",
111
+ "theme-appearance",
112
+ "theme-identity",
113
+ "brand-assets"
114
+ ];
115
+ /**
116
+ * The Roles grant that opens Settings → Translation. Not a Features row:
117
+ * every site has the screen. Developer and Admin always hold it; any other
118
+ * role holds it when ticked.
119
+ */
120
+ const TRANSLATION_GRANT_SLUG = "translation";
121
+ /** Roles that hold the translation grant whatever their ticks say. */
122
+ const ALWAYS_TRANSLATION_ROLES = ["admin"];
123
+ const CAPABILITY_FEATURES = {
124
+ content: ["content"],
125
+ publish: ["publish"],
126
+ users: ["users"],
127
+ brand: THEME_FEATURE_SLUGS
128
+ };
129
+ const DEFAULT_ROLE_GRANTS = {
130
+ developer: [],
131
+ admin: [
132
+ "content",
133
+ "publish",
134
+ "media",
135
+ "users",
136
+ "roles",
137
+ TRANSLATION_GRANT_SLUG
138
+ ],
139
+ designer: [
140
+ "content",
141
+ "media",
142
+ ...THEME_FEATURE_SLUGS,
143
+ "users",
144
+ "roles"
145
+ ],
146
+ author: ["content", "media"]
147
+ };
148
+ function isRole(value) {
149
+ return typeof value === "string" && ROLES.includes(value);
150
+ }
151
+ /** Lowercase slug from a letters-and-spaces name: `designer`, `the-designer`. */
152
+ function isRoleSlug(value) {
153
+ return typeof value === "string" && /^[a-z]+(-[a-z]+)*$/.test(value);
154
+ }
155
+ /** Display name: letters and single spaces only. `The Greatest Designer`. */
156
+ function isRoleName(value) {
157
+ return typeof value === "string" && /^[A-Za-z]+(?: [A-Za-z]+)*$/.test(value.trim());
158
+ }
159
+ /** Strip digits and punctuation as the name is typed. Trailing space stays. */
160
+ function sanitizeRoleNameInput(value) {
161
+ return value.replace(/[^A-Za-z ]/g, "").replace(/ {2,}/g, " ");
162
+ }
163
+ /** Name → stored key. `The Greatest Designer` → `the-greatest-designer`. */
164
+ function slugifyRoleName(value) {
165
+ if (typeof value !== "string") return "";
166
+ return value.trim().toLowerCase().replace(/[^a-z]+/g, "-").replace(/^-|-$/g, "");
167
+ }
168
+ function roleLabel(role, label) {
169
+ const trimmed = typeof label === "string" ? label.trim() : "";
170
+ if (trimmed) return trimmed;
171
+ return isRole(role) ? ROLE_LABELS[role] : role;
172
+ }
173
+ function defaultGrantsForRole(role, extraGrants) {
174
+ if (isRole(role)) return [...DEFAULT_ROLE_GRANTS[role]];
175
+ return extraGrants ? [...extraGrants] : [];
176
+ }
177
+ //#endregion
178
+ //#region src/features/matrix.ts
179
+ const MISSING_PACKAGE_FEATURES_MESSAGE = "Features must include Content, Publish, Media, Users, and Roles.";
180
+ function featureCatalogue(extras = []) {
181
+ return [...PACKAGE_FEATURES.map((feature) => ({ ...feature })), ...extras.map((extra) => ({
182
+ slug: extra.slug,
183
+ label: extra.label,
184
+ group: extra.group ?? "users",
185
+ defaultReleased: extra.defaultReleased ?? false
186
+ }))];
187
+ }
188
+ function defaultFeaturesFieldValue(extras = []) {
189
+ return featureCatalogue(extras).map((feature) => ({
190
+ id: feature.slug,
191
+ slug: feature.slug,
192
+ label: feature.label,
193
+ group: feature.group,
194
+ released: feature.defaultReleased
195
+ }));
196
+ }
197
+ function stampFeatureCatalogue(value, extras = []) {
198
+ const bySlug = new Map(featureCatalogue(extras).map((feature) => [feature.slug, feature]));
199
+ if (!Array.isArray(value)) return defaultFeaturesFieldValue(extras);
200
+ return value.flatMap((item) => {
201
+ if (!item || typeof item !== "object") return [];
202
+ const slug = "slug" in item && typeof item.slug === "string" ? item.slug : "";
203
+ const feature = bySlug.get(slug);
204
+ if (!feature) return [];
205
+ return [{
206
+ id: feature.slug,
207
+ slug: feature.slug,
208
+ label: feature.label,
209
+ group: feature.group,
210
+ released: Boolean("released" in item && item.released)
211
+ }];
212
+ });
213
+ }
214
+ function parseFeaturesMatrix(value) {
215
+ if (!Array.isArray(value) || value.length === 0) return {
216
+ ok: false,
217
+ message: MISSING_PACKAGE_FEATURES_MESSAGE
218
+ };
219
+ const rows = [];
220
+ const seen = /* @__PURE__ */ new Set();
221
+ for (const item of value) {
222
+ if (!item || typeof item !== "object") continue;
223
+ const slug = "slug" in item ? item.slug : void 0;
224
+ if (!isFeatureSlug(slug) || seen.has(slug)) continue;
225
+ seen.add(slug);
226
+ const pack = PACKAGE_FEATURES.find((feature) => feature.slug === slug);
227
+ const label = "label" in item && typeof item.label === "string" ? item.label : pack?.label ?? slug;
228
+ const group = "group" in item && isFeatureGroupId(item.group) ? item.group : pack?.group ?? "users";
229
+ rows.push({
230
+ id: slug,
231
+ slug,
232
+ label,
233
+ group,
234
+ released: Boolean("released" in item && item.released)
235
+ });
236
+ }
237
+ if (PACKAGE_FEATURES.some((feature) => !seen.has(feature.slug))) return {
238
+ ok: false,
239
+ message: MISSING_PACKAGE_FEATURES_MESSAGE
240
+ };
241
+ return {
242
+ ok: true,
243
+ rows
244
+ };
245
+ }
246
+ function validateFeaturesMatrix(value, extras = []) {
247
+ const parsed = parseFeaturesMatrix(value);
248
+ if (!parsed.ok) return parsed.message;
249
+ const allowed = new Set(featureCatalogue(extras).map((feature) => feature.slug));
250
+ const legacy = new Set(LEGACY_THEME_FEATURE_SLUGS);
251
+ if (parsed.rows.some((row) => !allowed.has(row.slug) && !legacy.has(row.slug))) return MISSING_PACKAGE_FEATURES_MESSAGE;
252
+ return true;
253
+ }
254
+ function featureGroupLabel(group) {
255
+ return isFeatureGroupId(group) ? FEATURE_GROUP_LABELS[group] : group;
256
+ }
257
+ function packageFeatureLabel(slug, extras = []) {
258
+ if (slug === "theme") return "Theme";
259
+ if (slug === "translation") return "Translation settings";
260
+ const pack = PACKAGE_FEATURES.find((feature) => feature.slug === slug);
261
+ if (pack) return pack.label;
262
+ return extras.find((feature) => feature.slug === slug)?.label ?? slug;
263
+ }
264
+ function isGroupOnlySlug(slug) {
265
+ return isFeatureGroupId(slug) && !PACKAGE_FEATURES.some((feature) => feature.slug === slug);
266
+ }
267
+ //#endregion
268
+ //#region src/roles/matrix.ts
269
+ const ROLES_SLUG = "roles";
270
+ const ROLES_GLOBAL_DESCRIPTION = "Who may do what. Drag to change rank.";
271
+ const ROLES_FIELD_DESCRIPTION = "Drag to change rank. Ticks are features released on Features, plus Theme. Developer has the whole catalogue.";
272
+ /**
273
+ * Default rank and grants. Developer is implicit (empty grants). The
274
+ * Theme grant defaults to Designer.
275
+ */
276
+ const DEFAULT_ROLE_MATRIX = ROLES.map((role) => ({
277
+ role,
278
+ grants: defaultGrantsForRole(role)
279
+ }));
280
+ const DEVELOPER_DESCRIPTION = "Everything, including features not released for assignment.";
281
+ const LAST_USERS_TICK_MESSAGE = "Keep Users granted on at least one of Admin or Developer.";
282
+ const MISSING_SEED_ROLES_MESSAGE = "Roles must include Developer.";
283
+ const DUPLICATE_ROLE_SLUG_MESSAGE = "Each role needs a unique slug.";
284
+ const DUPLICATE_ROLE_NAME_MESSAGE = "Each role needs a unique name.";
285
+ const INVALID_ROLE_NAME_MESSAGE = "Use letters and spaces only.";
286
+ const LEGACY_THEME_GRANTS = new Set(LEGACY_THEME_FEATURE_SLUGS);
287
+ function uniqueSlugs(values) {
288
+ const slugs = [];
289
+ for (const value of values) if (typeof value === "string" && isFeatureSlug(value) && !slugs.includes(value)) slugs.push(value);
290
+ return slugs;
291
+ }
292
+ /** One Theme grant. A stored Colors or brand-assets tick is that grant. */
293
+ function collapseThemeGrant(slugs) {
294
+ let theme = false;
295
+ const next = [];
296
+ for (const slug of slugs) {
297
+ if (slug === "theme" || LEGACY_THEME_GRANTS.has(slug)) {
298
+ theme = true;
299
+ continue;
300
+ }
301
+ next.push(slug);
302
+ }
303
+ if (theme) next.push("theme");
304
+ return next;
305
+ }
306
+ /** Read stored grants, or rebuild them from the old capability ticks. */
307
+ function grantsFromStoredRole(item) {
308
+ if ("grants" in item && Array.isArray(item.grants)) return collapseThemeGrant(uniqueSlugs(item.grants));
309
+ const grants = [];
310
+ if ("content" in item && item.content) grants.push("content", "media");
311
+ if ("publish" in item && item.publish) grants.push("publish");
312
+ if ("users" in item && item.users) grants.push("users", "roles");
313
+ if ("brand" in item && item.brand) grants.push("theme");
314
+ return collapseThemeGrant(uniqueSlugs(grants));
315
+ }
316
+ function seedRoleRows(extras = []) {
317
+ return [...DEFAULT_ROLE_MATRIX.map((row) => ({
318
+ ...row,
319
+ grants: [...row.grants],
320
+ label: isRole(row.role) ? ROLE_LABELS[row.role] : row.role
321
+ })), ...extras.map((extra) => ({
322
+ role: extra.role,
323
+ label: extra.label,
324
+ grants: extra.grants ? [...extra.grants] : []
325
+ }))];
326
+ }
327
+ function defaultRolesFieldValue(extras = []) {
328
+ return seedRoleRows(extras).map((row) => ({
329
+ id: row.role,
330
+ ...row
331
+ }));
332
+ }
333
+ function readRoleRow(item) {
334
+ const role = "role" in item ? item.role : void 0;
335
+ if (typeof role !== "string" || role.trim() === "") return { error: DUPLICATE_ROLE_SLUG_MESSAGE };
336
+ if (!isRoleSlug(role)) return { error: DUPLICATE_ROLE_SLUG_MESSAGE };
337
+ return {
338
+ id: role,
339
+ role,
340
+ label: roleLabel(role, "label" in item && typeof item.label === "string" ? item.label : void 0),
341
+ grants: grantsFromStoredRole(item)
342
+ };
343
+ }
344
+ function parseRolesMatrix(value) {
345
+ if (!Array.isArray(value)) return {
346
+ ok: false,
347
+ message: MISSING_SEED_ROLES_MESSAGE
348
+ };
349
+ const rows = [];
350
+ const seen = /* @__PURE__ */ new Set();
351
+ for (const item of value) {
352
+ if (!item || typeof item !== "object") continue;
353
+ const role = "role" in item ? item.role : void 0;
354
+ if (typeof role !== "string" || role.trim() === "") continue;
355
+ const parsed = readRoleRow(item);
356
+ if ("error" in parsed) return {
357
+ ok: false,
358
+ message: parsed.error
359
+ };
360
+ if (seen.has(parsed.role)) return {
361
+ ok: false,
362
+ message: DUPLICATE_ROLE_SLUG_MESSAGE
363
+ };
364
+ seen.add(parsed.role);
365
+ rows.push(parsed);
366
+ }
367
+ if (!seen.has("developer")) return {
368
+ ok: false,
369
+ message: MISSING_SEED_ROLES_MESSAGE
370
+ };
371
+ return {
372
+ ok: true,
373
+ rows
374
+ };
375
+ }
376
+ function roleHasGrant(row, slug) {
377
+ if (row.role === "developer") return true;
378
+ return row.grants.includes(slug);
379
+ }
380
+ function roleHasCapability(row, capability) {
381
+ if (row.role === "developer") return true;
382
+ return CAPABILITY_FEATURES[capability].some((slug) => row.grants.includes(slug));
383
+ }
384
+ /**
385
+ * Mint a slug from the name only when the row has none yet. An existing
386
+ * key — seed or custom — stays put so a rename cannot orphan users.
387
+ */
388
+ function applyRoleSlugsFromNames(value) {
389
+ if (!Array.isArray(value)) return value;
390
+ return value.map((item) => {
391
+ if (!item || typeof item !== "object") return item;
392
+ const row = item;
393
+ if (isRoleSlug(row.role)) return item;
394
+ const slug = slugifyRoleName(row.label);
395
+ return isRoleSlug(slug) ? {
396
+ ...row,
397
+ role: slug
398
+ } : item;
399
+ });
400
+ }
401
+ function hasDuplicateRoleNames(value) {
402
+ if (!Array.isArray(value)) return false;
403
+ const seen = /* @__PURE__ */ new Set();
404
+ for (const item of value) {
405
+ if (!item || typeof item !== "object") continue;
406
+ const role = "role" in item && typeof item.role === "string" ? item.role : "";
407
+ const name = ("label" in item && typeof item.label === "string" ? item.label : "").trim() || (isRole(role) ? ROLE_LABELS[role] : "");
408
+ if (!name) continue;
409
+ const key = name.toLowerCase();
410
+ if (seen.has(key)) return true;
411
+ seen.add(key);
412
+ }
413
+ return false;
414
+ }
415
+ function hasInvalidRoleName(value) {
416
+ if (!Array.isArray(value)) return false;
417
+ for (const item of value) {
418
+ if (!item || typeof item !== "object") continue;
419
+ const label = "label" in item && typeof item.label === "string" ? item.label.trim() : "";
420
+ if (!label) continue;
421
+ if (!isRoleName(label)) return true;
422
+ }
423
+ return false;
424
+ }
425
+ function validateRolesMatrix(value) {
426
+ if (hasDuplicateRoleNames(value)) return DUPLICATE_ROLE_NAME_MESSAGE;
427
+ if (hasInvalidRoleName(value)) return INVALID_ROLE_NAME_MESSAGE;
428
+ const parsed = parseRolesMatrix(applyRoleSlugsFromNames(value));
429
+ if (!parsed.ok) return parsed.message;
430
+ return true;
431
+ }
432
+ /**
433
+ * Developer is exclusive. Admin does not swallow Designer: both store.
434
+ * Unknown slugs (dropped catalogue keys such as `approver`) fall away unless
435
+ * they appear on the matrix.
436
+ */
437
+ function normalizeStoredRoles(value, matrix = DEFAULT_ROLE_MATRIX) {
438
+ if (!Array.isArray(value)) return [];
439
+ const allowed = new Set(matrix.map((row) => row.role));
440
+ const roles = [...new Set(value.filter((entry) => typeof entry === "string" && allowed.has(entry)))];
441
+ if (roles.includes("developer")) return ["developer"];
442
+ return roles;
443
+ }
444
+ function roleSelectOptions(matrix = DEFAULT_ROLE_MATRIX) {
445
+ return matrix.map((row) => ({
446
+ label: roleLabel(row.role, row.label),
447
+ value: row.role
448
+ }));
449
+ }
450
+ /** Grant copy only. Developer names the unreleased catalogue; nothing about MCP or seed. */
451
+ function roleDescription(role, matrix = DEFAULT_ROLE_MATRIX) {
452
+ if (role === "developer") return DEVELOPER_DESCRIPTION;
453
+ const row = matrix.find((entry) => entry.role === role);
454
+ if (!row) return "No capabilities";
455
+ return row.grants.map((slug) => packageFeatureLabel(slug)).join(", ") || "No capabilities";
456
+ }
457
+ /**
458
+ * Seed grants and package labels come back; extra rows stay as they are.
459
+ */
460
+ function resetRolesMatrix(current) {
461
+ const extras = [];
462
+ if (Array.isArray(current)) for (const item of current) {
463
+ if (!item || typeof item !== "object") continue;
464
+ const parsed = readRoleRow(item);
465
+ if ("error" in parsed || isRole(parsed.role)) continue;
466
+ extras.push(parsed);
467
+ }
468
+ return [...defaultRolesFieldValue(), ...extras];
469
+ }
470
+ //#endregion
471
+ //#region src/roles/access.ts
472
+ function isAccessArgs$1(value) {
473
+ return typeof value === "object" && value !== null && "req" in value;
474
+ }
475
+ function storedRoles(user) {
476
+ return Array.isArray(user?.roles) ? user.roles : [];
477
+ }
478
+ function hasRole(user, role) {
479
+ return storedRoles(user).includes(role);
480
+ }
481
+ /** Not a tick. True only when `developer` is stored on the row. */
482
+ function isDeveloper(user) {
483
+ return hasRole(user, "developer");
484
+ }
485
+ function hasCapability(user, capability, matrix = DEFAULT_ROLE_MATRIX) {
486
+ if (isDeveloper(user)) return true;
487
+ return storedRoles(user).some((role) => {
488
+ const row = matrix.find((entry) => entry.role === role);
489
+ return row ? roleHasCapability(row, capability) : false;
490
+ });
491
+ }
492
+ function hasGrant(user, slug, matrix = DEFAULT_ROLE_MATRIX) {
493
+ if (isDeveloper(user)) return true;
494
+ return storedRoles(user).some((role) => {
495
+ const row = matrix.find((entry) => entry.role === role);
496
+ return row ? roleHasGrant(row, slug) : false;
497
+ });
498
+ }
499
+ /**
500
+ * Reads the saved Roles Global, falling back to the seed when the row is
501
+ * empty, missing, or unreadable. Always override-access so a Designer
502
+ * evaluating Theme does not have to read Settings → Roles.
503
+ */
504
+ async function getRolesMatrix(req = {}, extras = []) {
505
+ const fallback = seedRoleRows(extras);
506
+ const findGlobal = req.payload?.findGlobal;
507
+ if (typeof findGlobal !== "function") return fallback;
508
+ try {
509
+ const doc = await findGlobal({
510
+ slug: ROLES_SLUG,
511
+ overrideAccess: true,
512
+ req
513
+ });
514
+ const parsed = parseRolesMatrix(doc && typeof doc === "object" && "roles" in doc ? doc.roles : void 0);
515
+ return parsed.ok ? parsed.rows : fallback;
516
+ } catch {
517
+ return fallback;
518
+ }
519
+ }
520
+ function capabilityPredicate(capability) {
521
+ function predicate(userOrArgs, matrix) {
522
+ if (isAccessArgs$1(userOrArgs)) {
523
+ const user = userOrArgs.req.user;
524
+ if (matrix) return hasCapability(user, capability, matrix);
525
+ return getRolesMatrix(userOrArgs.req).then((rows) => hasCapability(user, capability, rows));
526
+ }
527
+ return hasCapability(userOrArgs, capability, matrix ?? DEFAULT_ROLE_MATRIX);
528
+ }
529
+ return predicate;
530
+ }
531
+ const canManageContent = capabilityPredicate("content");
532
+ const canManageBrand = capabilityPredicate("brand");
533
+ const canPublish = capabilityPredicate("publish");
534
+ /** Users grant on any held role (Developer is implicit). */
535
+ const isAdmin = capabilityPredicate("users");
536
+ /** This role id currently has the Users grant, or is Developer. */
537
+ function isPrivilegedRole(role, matrix = DEFAULT_ROLE_MATRIX) {
538
+ if (typeof role !== "string") return false;
539
+ if (role === "developer") return true;
540
+ const row = matrix.find((entry) => entry.role === role);
541
+ return row ? roleHasGrant(row, "users") : false;
542
+ }
543
+ function isAuthenticated(userOrArgs) {
544
+ if (isAccessArgs$1(userOrArgs)) return Boolean(userOrArgs.req.user);
545
+ return Boolean(userOrArgs);
546
+ }
547
+ const isAdminOrSelf = async ({ req }) => {
548
+ if (!req.user) return false;
549
+ if (await isAdmin({ req })) return true;
550
+ return { id: { equals: req.user.id } };
551
+ };
552
+ const authenticatedOrPublished = ({ req: { user } }) => {
553
+ if (isAuthenticated(user)) return true;
554
+ return { _status: { equals: "published" } };
555
+ };
556
+ /**
557
+ * API tab condition. Code-locked to the `developer` slug — not a Features
558
+ * row and not a Role tick a client can grant.
559
+ */
560
+ function isDeveloperTab({ req }) {
561
+ return isDeveloper(req.user);
562
+ }
563
+ /** Access for chrome globals (Features, Better Editor settings). */
564
+ function developerOnlyAccess() {
565
+ return {
566
+ read: ({ req }) => isDeveloper(req.user),
567
+ update: ({ req }) => isDeveloper(req.user)
568
+ };
569
+ }
570
+ /** `admin.hidden`: hide unless the login is Developer. */
571
+ function hideUnlessDeveloper({ user }) {
572
+ return !isDeveloper(user);
573
+ }
574
+ //#endregion
575
+ //#region src/features/access.ts
576
+ function isAccessArgs(value) {
577
+ return typeof value === "object" && value !== null && "req" in value;
578
+ }
579
+ function grantedOnReleased(user, slug, row, matrix) {
580
+ if (!row.released) return false;
581
+ return hasGrant(user, slug, matrix);
582
+ }
583
+ /**
584
+ * True when the feature is released and a held role is granted it.
585
+ * Developer is always allowed. An empty Global falls back to catalogue
586
+ * defaults. A group slug (`pages`) is true when any child is.
587
+ * `theme` is the Roles grant: Features cannot release or withhold it.
588
+ */
589
+ function hasFeature(user, slug, features = null, matrix = DEFAULT_ROLE_MATRIX) {
590
+ if (isDeveloper(user)) return true;
591
+ if (!user) return false;
592
+ if (slug === "theme" || LEGACY_THEME_FEATURE_SLUGS.includes(slug)) return hasGrant(user, "theme", matrix);
593
+ if (slug === "translation") return ALWAYS_TRANSLATION_ROLES.some((role) => hasRole(user, role)) || hasGrant(user, slug, matrix);
594
+ const rows = features && features.length > 0 ? features : defaultFeaturesFieldValue();
595
+ const leaf = rows.find((entry) => entry.slug === slug);
596
+ if (leaf) return grantedOnReleased(user, slug, leaf, matrix);
597
+ if (!isGroupOnlySlug(slug)) return false;
598
+ return rows.some((entry) => entry.group === slug && grantedOnReleased(user, entry.slug, entry, matrix));
599
+ }
600
+ /**
601
+ * Reads the saved Features Global. `null` means empty or unreadable — callers
602
+ * fall back to catalogue defaults. Always override-access.
603
+ */
604
+ async function getFeaturesMatrix(req = {}) {
605
+ const findGlobal = req.payload?.findGlobal;
606
+ if (typeof findGlobal !== "function") return null;
607
+ try {
608
+ const doc = await findGlobal({
609
+ slug: FEATURES_SLUG,
610
+ overrideAccess: true,
611
+ req
612
+ });
613
+ const parsed = parseFeaturesMatrix(doc && typeof doc === "object" && "features" in doc ? doc.features : void 0);
614
+ return parsed.ok ? parsed.rows : null;
615
+ } catch {
616
+ return null;
617
+ }
618
+ }
619
+ /**
620
+ * Access / nav helper for one catalogue slug. Sync against a passed grid;
621
+ * async when given `req` so it can read both Globals.
622
+ */
623
+ function canUseFeature(slug) {
624
+ function predicate(userOrArgs, features, roles) {
625
+ if (isAccessArgs(userOrArgs)) {
626
+ const user = userOrArgs.req.user;
627
+ if (features !== void 0) return hasFeature(user, slug, features, roles ?? DEFAULT_ROLE_MATRIX);
628
+ return Promise.all([getFeaturesMatrix(userOrArgs.req), getRolesMatrix(userOrArgs.req)]).then(([grid, matrix]) => hasFeature(user, slug, grid, matrix));
629
+ }
630
+ return hasFeature(userOrArgs, slug, features ?? null, roles ?? DEFAULT_ROLE_MATRIX);
631
+ }
632
+ return predicate;
633
+ }
634
+ /**
635
+ * Feature slugs (and group slugs) this login may use. Written onto the
636
+ * user at afterRead so `admin.hidden({ user })` can follow the saved
637
+ * Features and Roles Globals without a `req`.
638
+ */
639
+ async function allowedFeaturesForUser(user, req = {}) {
640
+ const [features, roles] = await Promise.all([getFeaturesMatrix(req), getRolesMatrix(req)]);
641
+ return [
642
+ ...(features && features.length > 0 ? features : defaultFeaturesFieldValue()).map((row) => row.slug),
643
+ ...FEATURE_GROUPS,
644
+ TRANSLATION_GRANT_SLUG
645
+ ].filter((slug) => hasFeature(user, slug, features, roles));
646
+ }
647
+ function userHasAllowedFeature(user, slug) {
648
+ if (isDeveloper(user)) return true;
649
+ const allowed = user?.allowedFeatures;
650
+ if (!Array.isArray(allowed)) return false;
651
+ return allowed.includes(slug);
652
+ }
653
+ /** `admin.hidden`: hide when the login cannot use the feature. */
654
+ function hideUnlessFeature(slug) {
655
+ return (args) => {
656
+ const user = args.user ?? null;
657
+ if (isDeveloper(user)) return false;
658
+ if (user && Array.isArray(user.allowedFeatures)) return !userHasAllowedFeature(user, slug);
659
+ if (args.req) {
660
+ const result = canUseFeature(slug)({ req: {
661
+ ...args.req,
662
+ user
663
+ } });
664
+ if (result instanceof Promise) return result.then((ok) => !ok);
665
+ return !result;
666
+ }
667
+ return !canUseFeature(slug)(user);
668
+ };
669
+ }
670
+ //#endregion
671
+ //#region src/translate/fields.ts
672
+ const isDoc = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
673
+ const asRows = (value) => Array.isArray(value) ? value.filter(isDoc) : void 0;
674
+ /** A string with something in it. Blank and whitespace-only strings are not copy to translate. */
675
+ const filled = (value) => typeof value === "string" && value.trim() !== "";
676
+ /**
677
+ * Skipped by every walk: hidden fields (derived values a hook writes) and a
678
+ * field a site opts out with `custom: { translate: false }`, which is then
679
+ * never read as copy, never sent to the model and never written.
680
+ */
681
+ function isHidden(field) {
682
+ return field.hidden === true || field.admin?.hidden === true || field.custom?.translate === false;
683
+ }
684
+ function blocksOf(field, configBlocks) {
685
+ const own = field.blocks ?? [];
686
+ const referenced = (field.blockReferences ?? []).flatMap((ref) => {
687
+ if (typeof ref !== "string") return [ref];
688
+ const found = configBlocks?.find((block) => block.slug === ref);
689
+ return found ? [found] : [];
690
+ });
691
+ return [...own, ...referenced];
692
+ }
693
+ /**
694
+ * The row of `rows` that is the same row as `row`, where the two lists are
695
+ * one Payload array read twice (in two locales, or before and after a
696
+ * save): by id when the row has one, else by position.
697
+ *
698
+ * Payload gives every stored array row an id and keeps it across locales, so
699
+ * a row with an id is matched by it and by nothing else: a row that has an id
700
+ * and no partner has no partner, whatever sits at its position. Position is
701
+ * for rows that have no id yet (a row not saved, a fixture), and for rows of
702
+ * a localized array, whose ids differ per locale.
703
+ */
704
+ function sameRow(rows, row, index, byPosition = false) {
705
+ if (!rows) return void 0;
706
+ if (byPosition) return rows[index];
707
+ const id = row.id;
708
+ return typeof id === "string" || typeof id === "number" ? rows.find((other) => other.id === id) : rows[index];
709
+ }
710
+ /** Every Lexical text node in document order, with its child-index path. */
711
+ function textNodes(state) {
712
+ if (!isDoc(state) || !isDoc(state.root)) return null;
713
+ const out = [];
714
+ const visit = (node, path) => {
715
+ if (node.type === "text" && typeof node.text === "string") out.push({
716
+ path,
717
+ node
718
+ });
719
+ const children = node.children;
720
+ if (Array.isArray(children)) children.forEach((child, index) => {
721
+ if (isDoc(child)) visit(child, `${path}.${index}`);
722
+ });
723
+ };
724
+ visit(state.root, "root");
725
+ return out;
726
+ }
727
+ const sameShape = (a, b) => a !== null && b !== null && a.length === b.length && a.every((ref, i) => ref.path === b[i].path);
728
+ const sameText = (a, b) => sameShape(a, b) && a.every((ref, i) => ref.node.text === b[i].node.text);
729
+ /**
730
+ * Every localized string in `doc`, each prefixed with its path, in config
731
+ * order. Two reads of a document compare equal exactly when no copy
732
+ * changed; the path keeps a string moved from one field to another from
733
+ * reading as unchanged.
734
+ */
735
+ function collectLocalizedStrings(schema, doc) {
736
+ const out = [];
737
+ if (isDoc(doc)) collectFields(schema.fields, doc, "", false, schema.blocks, out);
738
+ return out;
739
+ }
740
+ function collectFields(fields, value, prefix, inLocalized, configBlocks, out) {
741
+ for (const field of fields) {
742
+ if (isHidden(field)) continue;
743
+ const localized = inLocalized || field.localized === true;
744
+ const path = field.name ? `${prefix}${field.name}` : prefix;
745
+ switch (field.type) {
746
+ case "tabs":
747
+ for (const tab of field.tabs ?? []) if (tab.name) {
748
+ const nested = value[tab.name];
749
+ if (isDoc(nested)) collectFields(tab.fields, nested, `${prefix}${tab.name}.`, inLocalized || tab.localized === true, configBlocks, out);
750
+ } else collectFields(tab.fields, value, prefix, inLocalized, configBlocks, out);
751
+ break;
752
+ case "row":
753
+ case "collapsible":
754
+ collectFields(field.fields ?? [], value, prefix, inLocalized, configBlocks, out);
755
+ break;
756
+ case "group":
757
+ if (!field.name) collectFields(field.fields ?? [], value, prefix, inLocalized, configBlocks, out);
758
+ else if (isDoc(value[field.name])) collectFields(field.fields ?? [], value[field.name], `${path}.`, localized, configBlocks, out);
759
+ break;
760
+ case "array":
761
+ if (!field.name) break;
762
+ (asRows(value[field.name]) ?? []).forEach((row, index) => {
763
+ const key = typeof row.id === "string" && !localized ? row.id : String(index);
764
+ collectFields(field.fields ?? [], row, `${path}.${key}.`, localized, configBlocks, out);
765
+ });
766
+ break;
767
+ case "blocks": {
768
+ if (!field.name) break;
769
+ const blocks = blocksOf(field, configBlocks);
770
+ (asRows(value[field.name]) ?? []).forEach((row, index) => {
771
+ const block = blocks.find((candidate) => candidate.slug === row.blockType);
772
+ if (!block) return;
773
+ const key = typeof row.id === "string" && !localized ? row.id : String(index);
774
+ collectFields(block.fields, row, `${path}.${key}.`, localized, configBlocks, out);
775
+ });
776
+ break;
777
+ }
778
+ case "text":
779
+ case "textarea":
780
+ if (localized && field.name && !field.hasMany && filled(value[field.name])) out.push(`${path}=${value[field.name]}`);
781
+ break;
782
+ case "richText":
783
+ if (localized && field.name) {
784
+ for (const ref of textNodes(value[field.name]) ?? []) if (filled(ref.node.text)) out.push(`${path}:${ref.path}=${ref.node.text}`);
785
+ }
786
+ break;
787
+ default: break;
788
+ }
789
+ }
790
+ }
791
+ /**
792
+ * The per-string rule, the one every write follows. A string is translated
793
+ * when its source is filled and its target is blank, or its source changed
794
+ * since `previous`, or the call says `overwrite`. Everything else keeps the
795
+ * target it already has, so a string a person corrected by hand in the
796
+ * target locale survives every later publish that does not touch its
797
+ * source.
798
+ */
799
+ function wants(ctx, source, existing, before) {
800
+ if (!filled(source)) return false;
801
+ if (ctx.overwrite || !filled(existing)) return true;
802
+ return ctx.hasPrevious && source !== before;
803
+ }
804
+ function enqueue(ctx, source, set) {
805
+ ctx.sources.push(source);
806
+ ctx.setters.push(set);
807
+ }
808
+ /**
809
+ * What to translate in one target locale, or `null` when the target is
810
+ * already in step with the source.
811
+ *
812
+ * - `source`: the document in the source locale, read at depth 0 so
813
+ * uploads are ids and array rows carry their real ids.
814
+ * - `target`: the document in the target locale, read with
815
+ * `fallbackLocale: false`. With fallback on, a blank target reads as the
816
+ * source, looks "already translated", and nothing is ever written.
817
+ * - `previous`: the source as it was before this change (the last
818
+ * published version, or the hook's `previousDoc` on a collection without
819
+ * drafts). `null` or omitted: there is none.
820
+ *
821
+ * The write carries only the top-level fields that hold a translated
822
+ * string. Inside them it is built from the source's structure (so
823
+ * non-localized values such as links and images are kept, and each array
824
+ * row keeps the source row's id, which is how Payload lands the target copy
825
+ * on the right row), with every localized string set to its translation or
826
+ * to the target copy it already had.
827
+ */
828
+ function translationJob(input) {
829
+ const ctx = {
830
+ overwrite: input.overwrite === true,
831
+ hasPrevious: input.previous != null,
832
+ configBlocks: input.schema.blocks,
833
+ sources: [],
834
+ setters: []
835
+ };
836
+ const out = {};
837
+ const touched = planFields(input.schema.fields, input.source, input.target ?? void 0, input.previous ?? void 0, out, ctx, false);
838
+ if (ctx.sources.length === 0) return null;
839
+ return {
840
+ sources: ctx.sources,
841
+ patch: (translated) => {
842
+ translated.forEach((value, index) => ctx.setters[index]?.(value));
843
+ const data = {};
844
+ for (const name of touched) data[name] = out[name];
845
+ return data;
846
+ }
847
+ };
848
+ }
849
+ /**
850
+ * Walks `fields` over one level of the source, writing into `out` (which
851
+ * starts as a copy of the source level) and returning the names at this
852
+ * level that hold a string being translated.
853
+ */
854
+ function planFields(fields, source, target, previous, out, ctx, inLocalized) {
855
+ const touched = /* @__PURE__ */ new Set();
856
+ const nested = (name, subFields, localized) => {
857
+ const value = source[name];
858
+ if (!isDoc(value)) return;
859
+ const copy = { ...value };
860
+ const prevValue = previous?.[name];
861
+ const targetValue = target?.[name];
862
+ const inner = planFields(subFields, value, isDoc(targetValue) ? targetValue : void 0, isDoc(prevValue) ? prevValue : void 0, copy, ctx, localized);
863
+ out[name] = copy;
864
+ if (inner.size > 0) touched.add(name);
865
+ };
866
+ for (const field of fields) {
867
+ if (isHidden(field)) continue;
868
+ const localized = inLocalized || field.localized === true;
869
+ switch (field.type) {
870
+ case "tabs":
871
+ for (const tab of field.tabs ?? []) if (tab.name) nested(tab.name, tab.fields, inLocalized || tab.localized === true);
872
+ else for (const name of planFields(tab.fields, source, target, previous, out, ctx, inLocalized)) touched.add(name);
873
+ break;
874
+ case "row":
875
+ case "collapsible":
876
+ for (const name of planFields(field.fields ?? [], source, target, previous, out, ctx, inLocalized)) touched.add(name);
877
+ break;
878
+ case "group":
879
+ if (field.name) nested(field.name, field.fields ?? [], localized);
880
+ else for (const name of planFields(field.fields ?? [], source, target, previous, out, ctx, inLocalized)) touched.add(name);
881
+ break;
882
+ case "array":
883
+ case "blocks": {
884
+ if (!field.name) break;
885
+ const rows = asRows(source[field.name]);
886
+ if (!rows) break;
887
+ const targetRows = asRows(target?.[field.name]);
888
+ const previousRows = asRows(previous?.[field.name]);
889
+ const blocks = field.type === "blocks" ? blocksOf(field, ctx.configBlocks) : [];
890
+ let any = false;
891
+ out[field.name] = rows.map((row, index) => {
892
+ const rowFields = field.type === "blocks" ? blocks.find((block) => block.slug === row.blockType)?.fields : field.fields;
893
+ const copy = { ...row };
894
+ if (localized) delete copy.id;
895
+ if (!rowFields) return copy;
896
+ if (planFields(rowFields, row, sameRow(targetRows, row, index, localized), sameRow(previousRows, row, index), copy, ctx, localized).size > 0) any = true;
897
+ return copy;
898
+ });
899
+ if (any) touched.add(field.name);
900
+ break;
901
+ }
902
+ case "text":
903
+ case "textarea": {
904
+ if (!localized || !field.name || field.hasMany) break;
905
+ const name = field.name;
906
+ const value = source[name];
907
+ const existing = target?.[name];
908
+ if (wants(ctx, value, existing, previous?.[name])) {
909
+ enqueue(ctx, value, (translated) => out[name] = translated);
910
+ out[name] = value;
911
+ touched.add(name);
912
+ } else out[name] = filled(existing) ? existing : value;
913
+ break;
914
+ }
915
+ case "richText": {
916
+ if (!localized || !field.name) break;
917
+ const name = field.name;
918
+ const result = planRichText(ctx, source[name], target?.[name], previous?.[name]);
919
+ out[name] = result.value;
920
+ if (result.touched) touched.add(name);
921
+ break;
922
+ }
923
+ default: break;
924
+ }
925
+ }
926
+ return touched;
927
+ }
928
+ /**
929
+ * Rich text is translated per Lexical text node (sentence context across
930
+ * formatting runs is out of scope). When the target tree has the same
931
+ * shape as the source, each node follows the per-string rule. When a
932
+ * person restructured the target (split a run to bold a word), node paths
933
+ * no longer pair: the field is then kept whole unless its source changed,
934
+ * in which case it is rebuilt from the source and every node translated.
935
+ */
936
+ function planRichText(ctx, source, target, previous) {
937
+ const sourceNodes = textNodes(source);
938
+ if (!sourceNodes || !sourceNodes.some((ref) => filled(ref.node.text))) return {
939
+ value: target ?? source,
940
+ touched: false
941
+ };
942
+ const targetNodes = textNodes(target);
943
+ const previousNodes = textNodes(previous);
944
+ const clone = structuredClone(source);
945
+ const cloneNodes = textNodes(clone);
946
+ let touched = false;
947
+ if (sameShape(sourceNodes, targetNodes)) {
948
+ const previousPairs = sameShape(sourceNodes, previousNodes);
949
+ sourceNodes.forEach((ref, index) => {
950
+ const node = cloneNodes[index].node;
951
+ const existing = targetNodes[index].node.text;
952
+ const before = previousPairs ? previousNodes[index].node.text : void 0;
953
+ if (wants(ctx, ref.node.text, existing, before)) {
954
+ enqueue(ctx, ref.node.text, (translated) => node.text = translated);
955
+ touched = true;
956
+ } else if (filled(existing)) node.text = existing;
957
+ });
958
+ return {
959
+ value: clone,
960
+ touched
961
+ };
962
+ }
963
+ const targetFilled = targetNodes?.some((ref) => filled(ref.node.text)) ?? false;
964
+ if (!(ctx.overwrite || !targetFilled || ctx.hasPrevious && !sameText(sourceNodes, previousNodes))) return {
965
+ value: target,
966
+ touched: false
967
+ };
968
+ sourceNodes.forEach((ref, index) => {
969
+ if (!filled(ref.node.text)) return;
970
+ const node = cloneNodes[index].node;
971
+ enqueue(ctx, ref.node.text, (translated) => node.text = translated);
972
+ touched = true;
973
+ });
974
+ return {
975
+ value: clone,
976
+ touched
977
+ };
978
+ }
979
+ //#endregion
980
+ //#region src/translate/key.ts
981
+ /**
982
+ * The site's own Anthropic key, as an Admin pastes it on Settings →
983
+ * Translation. Stored AES-256-GCM encrypted under a key derived from
984
+ * `PAYLOAD_SECRET`, in the unversioned, unreadable `translation-state`
985
+ * Global, so it is in no version row and no API response. Only its last 4
986
+ * characters are ever shown.
987
+ */
988
+ const VERSION = "v1";
989
+ function cipherKey(secret) {
990
+ return createHash("sha256").update(`bison-translation-key:${secret}`).digest();
991
+ }
992
+ /** `v1:<iv>:<tag>:<ciphertext>`, base64 parts. */
993
+ function encryptApiKey(apiKey, secret) {
994
+ if (!secret) throw new Error("encryptApiKey: PAYLOAD_SECRET is empty");
995
+ const iv = randomBytes(12);
996
+ const cipher = createCipheriv("aes-256-gcm", cipherKey(secret), iv);
997
+ const body = Buffer.concat([cipher.update(apiKey, "utf8"), cipher.final()]);
998
+ return [
999
+ VERSION,
1000
+ iv.toString("base64"),
1001
+ cipher.getAuthTag().toString("base64"),
1002
+ body.toString("base64")
1003
+ ].join(":");
1004
+ }
1005
+ /** The key, or `null` when the value is malformed or `secret` is not the one it was sealed with. */
1006
+ function decryptApiKey(sealed, secret) {
1007
+ const [version, iv, tag, body] = sealed.split(":");
1008
+ if (version !== VERSION || !iv || !tag || !body || !secret) return null;
1009
+ try {
1010
+ const decipher = createDecipheriv("aes-256-gcm", cipherKey(secret), Buffer.from(iv, "base64"));
1011
+ decipher.setAuthTag(Buffer.from(tag, "base64"));
1012
+ return Buffer.concat([decipher.update(Buffer.from(body, "base64")), decipher.final()]).toString("utf8");
1013
+ } catch {
1014
+ return null;
1015
+ }
1016
+ }
1017
+ /** The last 4 characters, the only part of a key the admin ever shows. */
1018
+ function lastFour(apiKey) {
1019
+ return apiKey.trim().slice(-4);
1020
+ }
1021
+ /** True on Vercel's production environment, the only place the stored key is used. */
1022
+ function isProductionEnvironment() {
1023
+ return process.env.VERCEL_ENV === "production";
1024
+ }
1025
+ /**
1026
+ * Which key a translation uses. Only on production (`VERCEL_ENV=production`)
1027
+ * is the stored key considered, and there it wins over the environment's
1028
+ * `ANTHROPIC_API_KEY`. Everywhere else (local, previews, a cloned database)
1029
+ * only the environment key is used, so a copy of production's data never
1030
+ * spends production's money. A stored key that cannot be decrypted reads
1031
+ * as no key, with a note.
1032
+ */
1033
+ function resolveApiKey(input) {
1034
+ const production = input.production ?? isProductionEnvironment();
1035
+ const env = input.env?.trim() || void 0;
1036
+ const fromEnv = (note) => env ? {
1037
+ apiKey: env,
1038
+ source: "environment",
1039
+ last4: lastFour(env),
1040
+ ...note ? { note } : {}
1041
+ } : note ? { note } : {};
1042
+ if (!input.sealed) return fromEnv();
1043
+ if (!production) return fromEnv("The stored key is used only on production. Here only the server's ANTHROPIC_API_KEY is used.");
1044
+ const apiKey = decryptApiKey(input.sealed, input.secret);
1045
+ if (!apiKey) return fromEnv("The stored key could not be decrypted (PAYLOAD_SECRET may have changed), so it reads as no key. Paste it again.");
1046
+ return {
1047
+ apiKey,
1048
+ source: "admin",
1049
+ last4: lastFour(apiKey)
1050
+ };
1051
+ }
1052
+ //#endregion
1053
+ //#region src/translate/languages.ts
1054
+ /**
1055
+ * The languages every Bison site carries. The library owns this list: a new
1056
+ * language is a library release that sites take by updating the package
1057
+ * (and running the migration it brings). The first entry is the default
1058
+ * locale of a site that declares no localization of its own.
1059
+ */
1060
+ const LIBRARY_LOCALES = [{
1061
+ code: "en",
1062
+ label: "English"
1063
+ }, {
1064
+ code: "es",
1065
+ label: "Español"
1066
+ }];
1067
+ const LIBRARY_DEFAULT_LOCALE = "en";
1068
+ /** The codes of `LIBRARY_LOCALES`, in order. */
1069
+ const LIBRARY_LOCALE_CODES = LIBRARY_LOCALES.map((locale) => locale.code);
1070
+ function codeOf(entry) {
1071
+ return typeof entry === "string" ? entry : entry.code;
1072
+ }
1073
+ /**
1074
+ * A config's `localization` with every library language in it. A site with
1075
+ * none gets the library's (English default, `fallback: true`, so an empty
1076
+ * Spanish field reads as English). A site with its own keeps its locales,
1077
+ * labels and default, and gains any library language it lacks.
1078
+ */
1079
+ function withLibraryLocales(localization) {
1080
+ if (!localization) return {
1081
+ locales: LIBRARY_LOCALES.map((locale) => ({ ...locale })),
1082
+ defaultLocale: "en",
1083
+ fallback: true
1084
+ };
1085
+ const own = localization.locales;
1086
+ const have = new Set(own.map(codeOf));
1087
+ const missing = LIBRARY_LOCALES.filter((locale) => !have.has(locale.code));
1088
+ if (missing.length === 0) return localization;
1089
+ const locales = [...own.map((entry) => typeof entry === "string" ? {
1090
+ code: entry,
1091
+ label: entry
1092
+ } : entry), ...missing.map((locale) => ({ ...locale }))];
1093
+ return {
1094
+ ...localization,
1095
+ locales
1096
+ };
1097
+ }
1098
+ /** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */
1099
+ const ACTIVE_LOCALES_CACHE_MS = 6e4;
1100
+ const cache$1 = /* @__PURE__ */ new WeakMap();
1101
+ /** The last answer read from the database, kept for when a later read fails. */
1102
+ const lastGood = /* @__PURE__ */ new WeakMap();
1103
+ /** After a failed read, how soon to try the database again. */
1104
+ const ACTIVE_LOCALES_RETRY_MS = 5e3;
1105
+ /** Drops the cached answer, so the next `activeLocales` reads again. */
1106
+ function invalidateActiveLocales(payload) {
1107
+ cache$1.delete(payload);
1108
+ }
1109
+ /**
1110
+ * The ticked target languages, as the Translation screen stores them.
1111
+ * `null` or absent (never saved) means the defaults: the target locales the
1112
+ * site declared itself before the library's were added.
1113
+ */
1114
+ function resolveActiveTargets(stored, targets, defaults) {
1115
+ const chosen = Array.isArray(stored) ? stored : defaults;
1116
+ return targets.filter((code) => chosen.includes(code));
1117
+ }
1118
+ /**
1119
+ * The site's active languages, for routing and middleware: the default
1120
+ * locale plus each target language ticked on Settings → Translation. Cached
1121
+ * per process for `ttlMs` (60s by default): a request reads memory, and the
1122
+ * database is read only when the cache refreshes, or after a save of the
1123
+ * screen in the same process. Never throws. When a read fails it answers
1124
+ * with the last good read (or, before the first one, the defaults) and
1125
+ * tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout
1126
+ * never stands in for the Admin's ticks for a whole cache period, which
1127
+ * would send a ticked language's visitors permanent redirects.
1128
+ */
1129
+ function activeLocales(payload, options = {}) {
1130
+ const ttl = options.ttlMs ?? 6e4;
1131
+ const hit = cache$1.get(payload);
1132
+ if (hit && Date.now() - hit.at < (hit.ttl ?? ttl)) return hit.value;
1133
+ const entry = {
1134
+ at: Date.now(),
1135
+ value: void 0
1136
+ };
1137
+ entry.value = readActiveLocales(payload).then((read) => {
1138
+ if (read.ok) {
1139
+ lastGood.set(payload, read.value);
1140
+ return read.value;
1141
+ }
1142
+ entry.ttl = ACTIVE_LOCALES_RETRY_MS;
1143
+ return lastGood.get(payload) ?? read.value;
1144
+ });
1145
+ cache$1.set(payload, entry);
1146
+ return entry.value;
1147
+ }
1148
+ /** The slug `activeLocales` reads; the Translation screen's. */
1149
+ const SETTINGS_SLUG = "translation-settings";
1150
+ /** Where `applyTranslation` leaves the default ticks: the site's own target locales. */
1151
+ const DEFAULT_ACTIVE_LOCALES = "bisonDefaultActiveLocales";
1152
+ async function readActiveLocales(payload) {
1153
+ const localization = payload.config.localization;
1154
+ const codes = localization ? localization.locales.map(codeOf) : ["en"];
1155
+ const defaultLocale = localization ? localization.defaultLocale : "en";
1156
+ const targets = codes.filter((code) => code !== defaultLocale);
1157
+ const defaults = payload.config.custom?.["bisonDefaultActiveLocales"] ?? targets;
1158
+ let stored;
1159
+ let ok = true;
1160
+ try {
1161
+ const doc = await payload.findGlobal({
1162
+ slug: SETTINGS_SLUG,
1163
+ depth: 0,
1164
+ overrideAccess: true
1165
+ });
1166
+ stored = doc?.languagesChosen ? doc.languages ?? [] : void 0;
1167
+ } catch {
1168
+ stored = void 0;
1169
+ ok = false;
1170
+ }
1171
+ const ticked = resolveActiveTargets(stored, targets, defaults);
1172
+ return {
1173
+ ok,
1174
+ value: {
1175
+ defaultLocale,
1176
+ active: codes.filter((code) => code === defaultLocale || ticked.includes(code)),
1177
+ inactive: targets.filter((code) => !ticked.includes(code))
1178
+ }
1179
+ };
1180
+ }
1181
+ /**
1182
+ * Where a request for an inactive language goes: the same path without
1183
+ * its locale prefix, for a 308. `null` when the path is not under an
1184
+ * inactive locale. In a site's middleware:
1185
+ *
1186
+ * ```ts
1187
+ * const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));
1188
+ * if (to) {
1189
+ * const response = NextResponse.redirect(new URL(to + url.search, url), 308);
1190
+ * response.headers.set("Cache-Control", "no-store"); // so ticking the language again works for these visitors
1191
+ * return response;
1192
+ * }
1193
+ * ```
1194
+ */
1195
+ function inactiveLocaleRedirect(pathname, locales) {
1196
+ const [, first, ...rest] = pathname.split("/");
1197
+ if (!first || !locales.inactive.includes(first)) return null;
1198
+ return `/${rest.join("/").replace(/^[\\/]+/, "")}`;
1199
+ }
1200
+ /**
1201
+ * A page's language alternates (for hreflang and a language switcher),
1202
+ * keeping only active languages. `paths` maps each locale to that
1203
+ * language's URL for the page.
1204
+ */
1205
+ function activeAlternates(paths, locales) {
1206
+ return Object.fromEntries(Object.entries(paths).filter(([code]) => locales.active.includes(code)));
1207
+ }
1208
+ //#endregion
1209
+ //#region src/translate/settings.ts
1210
+ /** Settings → Translation: the switch, model, instructions and the key's public record. Versioned. */
1211
+ const TRANSLATION_SETTINGS_SLUG = "translation-settings";
1212
+ /**
1213
+ * Server-only state beside it: the encrypted key and what the last check
1214
+ * found. Unversioned and unreadable through the API, so the key is in no
1215
+ * version row and no response.
1216
+ */
1217
+ const TRANSLATION_STATE_SLUG = "translation-state";
1218
+ /** The Roles grant that opens Settings → Translation. Developer and Admin always hold it. */
1219
+ const TRANSLATION_GRANT = "translation";
1220
+ /** The admin component for the key panel on Settings → Translation. */
1221
+ const TRANSLATION_KEY_PANEL = "@bison-lab/payload-core/admin#TranslationKeyPanel";
1222
+ /** "Español" for `es`: the library's label, else the code. */
1223
+ function localeLabel(code) {
1224
+ return LIBRARY_LOCALES.find((locale) => locale.code === code)?.label ?? code;
1225
+ }
1226
+ const MODEL_IDS = {
1227
+ quality: DEFAULT_TRANSLATE_MODEL,
1228
+ economy: ECONOMY_TRANSLATE_MODEL
1229
+ };
1230
+ /**
1231
+ * The model id for a choice. `ANTHROPIC_TRANSLATE_MODEL` overrides the
1232
+ * screen off production, so a developer can try a model locally without
1233
+ * touching the setting.
1234
+ */
1235
+ function resolveModel(choice, production) {
1236
+ const override = process.env.ANTHROPIC_TRANSLATE_MODEL?.trim();
1237
+ if (override && !production) return override;
1238
+ return MODEL_IDS[choice ?? "quality"] ?? "claude-sonnet-5-5";
1239
+ }
1240
+ const trimmed = (value) => typeof value === "string" && value.trim() !== "" ? value.trim() : void 0;
1241
+ /**
1242
+ * The saved instructions as a `TranslateSite`, or `undefined` when every
1243
+ * field is blank. A blank business name drops only the name: frozen words,
1244
+ * voice and dialects still reach the model.
1245
+ */
1246
+ function siteFromInstructions(instructions) {
1247
+ const name = trimmed(instructions?.businessName);
1248
+ const about = trimmed(instructions?.about);
1249
+ const voice = trimmed(instructions?.voice);
1250
+ const keepVerbatim = (instructions?.frozenWords ?? []).map((row) => trimmed(row?.word)).filter((word) => Boolean(word));
1251
+ const languages = Object.fromEntries((instructions?.dialects ?? []).map((row) => [trimmed(row?.locale), trimmed(row?.name)]).filter((pair) => Boolean(pair[0] && pair[1])));
1252
+ const site = {
1253
+ ...name ? { name } : {},
1254
+ ...about ? { about } : {},
1255
+ ...voice ? { voice } : {},
1256
+ ...keepVerbatim.length ? { keepVerbatim } : {},
1257
+ ...Object.keys(languages).length ? { languages } : {}
1258
+ };
1259
+ return Object.keys(site).length > 0 ? site : void 0;
1260
+ }
1261
+ const cache = /* @__PURE__ */ new WeakMap();
1262
+ /** Drops the cached read, so the next one sees a save at once. */
1263
+ function invalidateTranslationSettings(payload) {
1264
+ cache.delete(payload);
1265
+ }
1266
+ async function readGlobal(payload, slug) {
1267
+ try {
1268
+ return await payload.findGlobal({
1269
+ slug,
1270
+ depth: 0,
1271
+ overrideAccess: true
1272
+ }) ?? {};
1273
+ } catch {
1274
+ return {};
1275
+ }
1276
+ }
1277
+ /**
1278
+ * Settings → Translation and its server state, read once per
1279
+ * `SETTINGS_CACHE_MS` per process. A missing Global (a site that has not
1280
+ * migrated yet) reads as "off".
1281
+ */
1282
+ function readTranslationSettings(payload, codeSite) {
1283
+ const hit = cache.get(payload);
1284
+ if (hit && Date.now() - hit.at < 5e3) return hit.value;
1285
+ const value = (async () => {
1286
+ const [doc, state] = await Promise.all([readGlobal(payload, TRANSLATION_SETTINGS_SLUG), readGlobal(payload, TRANSLATION_STATE_SLUG)]);
1287
+ const saved = typeof doc.updatedAt === "string" && doc.updatedAt !== "";
1288
+ const site = saved ? siteFromInstructions(doc.instructions) : codeSite;
1289
+ const localization = payload.config?.localization;
1290
+ const targets = localization ? localization.locales.map((locale) => typeof locale === "string" ? locale : locale.code).filter((code) => code !== localization.defaultLocale) : [];
1291
+ const defaults = (payload.config?.custom)?.["bisonDefaultActiveLocales"] ?? targets;
1292
+ return {
1293
+ enabled: doc.enabled === true,
1294
+ languages: resolveActiveTargets(doc.languagesChosen ? doc.languages ?? [] : void 0, targets, defaults),
1295
+ model: doc.model === "economy" ? "economy" : "quality",
1296
+ ...site ? { site } : {},
1297
+ saved,
1298
+ doc,
1299
+ state
1300
+ };
1301
+ })();
1302
+ cache.set(payload, {
1303
+ at: Date.now(),
1304
+ value
1305
+ });
1306
+ value.catch(() => cache.delete(payload));
1307
+ return value;
1308
+ }
1309
+ /** The key a translation would use right now, from the stored key and the environment. */
1310
+ function keyFor(payload, settings) {
1311
+ return resolveApiKey({
1312
+ sealed: settings.state.keyCipher,
1313
+ secret: payload.secret,
1314
+ env: process.env.ANTHROPIC_API_KEY
1315
+ });
1316
+ }
1317
+ /**
1318
+ * Records what a call found about the stored key: a key saved while
1319
+ * Anthropic was unreachable is checked on its first use.
1320
+ */
1321
+ async function recordKeyOutcome(payload, settings, event) {
1322
+ const status = settings.state.keyStatus;
1323
+ let next;
1324
+ if (event.ok) next = status === "valid" ? void 0 : "valid";
1325
+ else if (event.failure === "key-rejected") next = "rejected";
1326
+ else if (event.failure === "out-of-credit") next = "out-of-credit";
1327
+ if (!next) return;
1328
+ await payload.updateGlobal({
1329
+ slug: TRANSLATION_STATE_SLUG,
1330
+ data: {
1331
+ keyStatus: next,
1332
+ keyCheckedAt: (/* @__PURE__ */ new Date()).toISOString()
1333
+ },
1334
+ overrideAccess: true,
1335
+ context: { autoTranslate: false }
1336
+ });
1337
+ invalidateTranslationSettings(payload);
1338
+ }
1339
+ /**
1340
+ * The translator Settings → Translation describes: its key (see
1341
+ * `resolveApiKey`), its model and its instructions. `configured: false`
1342
+ * when there is no key to use here.
1343
+ */
1344
+ function settingsTranslator(payload, settings, seam = {}) {
1345
+ const key = keyFor(payload, settings);
1346
+ const production = key.source === "admin" || process.env.VERCEL_ENV === "production";
1347
+ return anthropicTranslator({
1348
+ apiKey: key.apiKey ?? null,
1349
+ ...seam.client && key.apiKey ? { client: seam.client } : {},
1350
+ model: resolveModel(settings.model, production),
1351
+ ...settings.site ? { site: settings.site } : {},
1352
+ onCall: (event) => key.source === "admin" ? recordKeyOutcome(payload, settings, event) : void 0
1353
+ });
1354
+ }
1355
+ const FROZEN_WORDS_DESCRIPTION = "Kept exactly as written in every language. Matching is whole-word and case-sensitive: \"ProtectIQ\" does not match \"protectiq\".";
1356
+ const OUT_OF_CREDIT_MESSAGE = "The Anthropic account behind this key is out of credit, so translation cannot be switched on. Add credit, press Check again, then switch it on.";
1357
+ /**
1358
+ * Switching on is refused while the stored key's account is out of credit,
1359
+ * where that key is the one in use (production). Off stays possible.
1360
+ */
1361
+ const refuseOutOfCredit = async ({ data, originalDoc, req }) => {
1362
+ if (data?.enabled !== true || originalDoc?.enabled === true) return data;
1363
+ if (!isProductionEnvironment()) return data;
1364
+ const state = await readGlobal(req.payload, TRANSLATION_STATE_SLUG);
1365
+ if (state.keyCipher && state.keyStatus === "out-of-credit") throw new APIError(OUT_OF_CREDIT_MESSAGE, 400);
1366
+ return data;
1367
+ };
1368
+ /**
1369
+ * Who made each save, so every version in the history names them, and
1370
+ * whether the language ticks have been chosen. Set by the server, never by
1371
+ * the form.
1372
+ */
1373
+ const stampChangedBy = ({ data, req }) => {
1374
+ if (!data) return data;
1375
+ return {
1376
+ ...data,
1377
+ changedBy: who(req.user),
1378
+ ...Array.isArray(data.languages) ? { languagesChosen: true } : {}
1379
+ };
1380
+ };
1381
+ /** A name for the user on a request: their name, else email, else id. */
1382
+ function who(user) {
1383
+ const record = user ?? {};
1384
+ if (typeof record.name === "string" && record.name.trim()) return record.name.trim();
1385
+ if (typeof record.email === "string" && record.email) return record.email;
1386
+ return record.id !== void 0 && record.id !== null ? `user ${String(record.id)}` : "the server";
1387
+ }
1388
+ /** Fields only the server writes: the form and the REST API cannot change them. */
1389
+ const serverOnly = { update: () => false };
1390
+ const clearCache = ({ doc, req }) => {
1391
+ invalidateTranslationSettings(req.payload);
1392
+ invalidateActiveLocales(req.payload);
1393
+ return doc;
1394
+ };
1395
+ function instructionFields(options) {
1396
+ const site = options.site;
1397
+ return [
1398
+ {
1399
+ name: "businessName",
1400
+ type: "text",
1401
+ label: "Business name",
1402
+ defaultValue: site?.name,
1403
+ admin: { description: "Kept exactly as written in every language." }
1404
+ },
1405
+ {
1406
+ name: "about",
1407
+ type: "text",
1408
+ label: "What the business is, in one line",
1409
+ defaultValue: site?.about,
1410
+ admin: { description: "For word choice, e.g. \"a gigabit fiber provider in Kansas\"." }
1411
+ },
1412
+ {
1413
+ name: "voice",
1414
+ type: "text",
1415
+ label: "Voice",
1416
+ defaultValue: site?.voice,
1417
+ admin: { description: "E.g. \"confident, friendly, speed-first\"." }
1418
+ },
1419
+ {
1420
+ name: "dialects",
1421
+ type: "array",
1422
+ dbName: "tr_dialects",
1423
+ label: "Dialect per language",
1424
+ labels: {
1425
+ singular: "Dialect",
1426
+ plural: "Dialects"
1427
+ },
1428
+ defaultValue: Object.entries(site?.languages ?? {}).map(([locale, name]) => ({
1429
+ locale,
1430
+ name
1431
+ })),
1432
+ fields: [{
1433
+ name: "locale",
1434
+ type: "select",
1435
+ label: "Language",
1436
+ required: true,
1437
+ enumName: "enum_translation_dialect_locale",
1438
+ options: options.targetLocales.map((code) => ({
1439
+ label: localeLabel(code),
1440
+ value: code
1441
+ }))
1442
+ }, {
1443
+ name: "name",
1444
+ type: "text",
1445
+ label: "Dialect",
1446
+ required: true,
1447
+ admin: { description: "E.g. \"Latin American Spanish\"." }
1448
+ }]
1449
+ },
1450
+ {
1451
+ name: "frozenWords",
1452
+ type: "array",
1453
+ dbName: "tr_frozen_words",
1454
+ label: "Frozen words",
1455
+ labels: {
1456
+ singular: "Frozen word",
1457
+ plural: "Frozen words"
1458
+ },
1459
+ defaultValue: (site?.keepVerbatim ?? []).map((word) => ({ word })),
1460
+ admin: { description: FROZEN_WORDS_DESCRIPTION },
1461
+ fields: [{
1462
+ name: "word",
1463
+ type: "text",
1464
+ label: "Word",
1465
+ required: true
1466
+ }]
1467
+ }
1468
+ ];
1469
+ }
1470
+ /**
1471
+ * Settings → Translation. Opened by the `translation` grant (Developer and
1472
+ * Admin always). Versioned with no drafts: its history shows who changed
1473
+ * the switch, model and instructions, and every key change as a line of
1474
+ * text ("key replaced (ends …a1b2) by …"), never the key.
1475
+ */
1476
+ function translationSettingsGlobal(options) {
1477
+ const canUse = canUseFeature(TRANSLATION_GRANT);
1478
+ return {
1479
+ slug: TRANSLATION_SETTINGS_SLUG,
1480
+ label: "Translation",
1481
+ admin: {
1482
+ group: "Settings",
1483
+ hidden: hideUnlessFeature(TRANSLATION_GRANT),
1484
+ description: "Translates published copy into the site's other languages with your own Anthropic key. Hand corrections are never overwritten."
1485
+ },
1486
+ access: {
1487
+ read: (args) => canUse(args),
1488
+ update: (args) => canUse(args)
1489
+ },
1490
+ versions: { max: 100 },
1491
+ hooks: {
1492
+ beforeChange: [refuseOutOfCredit, stampChangedBy],
1493
+ afterChange: [clearCache]
1494
+ },
1495
+ fields: [
1496
+ {
1497
+ name: "keyPanel",
1498
+ type: "ui",
1499
+ admin: { components: { Field: TRANSLATION_KEY_PANEL } }
1500
+ },
1501
+ {
1502
+ name: "enabled",
1503
+ type: "checkbox",
1504
+ label: "Translate content",
1505
+ defaultValue: false,
1506
+ admin: { description: "On: blank translations fill when copy is saved or published, and changed copy is re-translated on publish. Off: nothing translates; the key and existing translations are kept." }
1507
+ },
1508
+ {
1509
+ name: "languages",
1510
+ type: "select",
1511
+ label: "Translate into",
1512
+ hasMany: true,
1513
+ defaultValue: [...options.defaultActive ?? []],
1514
+ options: options.targetLocales.map((code) => ({
1515
+ label: localeLabel(code),
1516
+ value: code
1517
+ })),
1518
+ hooks: { afterRead: [({ value, siblingData }) => siblingData?.languagesChosen ? value : [...options.defaultActive ?? []]] },
1519
+ admin: { description: "Only ticked languages are translated and served. An unticked language costs nothing and has no pages: its URLs redirect to English." }
1520
+ },
1521
+ {
1522
+ name: "model",
1523
+ type: "radio",
1524
+ label: "Model",
1525
+ defaultValue: "quality",
1526
+ options: [{
1527
+ label: "Quality (Sonnet)",
1528
+ value: "quality"
1529
+ }, {
1530
+ label: "Economy (Haiku)",
1531
+ value: "economy"
1532
+ }]
1533
+ },
1534
+ {
1535
+ name: "keyChange",
1536
+ type: "text",
1537
+ label: "Last key change",
1538
+ access: serverOnly,
1539
+ admin: { readOnly: true }
1540
+ },
1541
+ {
1542
+ name: "changedBy",
1543
+ type: "text",
1544
+ label: "Saved by",
1545
+ access: serverOnly,
1546
+ admin: {
1547
+ readOnly: true,
1548
+ description: "Who made this save. Each version in the history keeps it."
1549
+ }
1550
+ },
1551
+ {
1552
+ name: "languagesChosen",
1553
+ type: "checkbox",
1554
+ access: serverOnly,
1555
+ admin: { hidden: true }
1556
+ },
1557
+ {
1558
+ name: "keyLast4",
1559
+ type: "text",
1560
+ access: serverOnly,
1561
+ admin: { hidden: true }
1562
+ },
1563
+ {
1564
+ name: "keySetAt",
1565
+ type: "date",
1566
+ access: serverOnly,
1567
+ admin: { hidden: true }
1568
+ },
1569
+ {
1570
+ name: "keySetBy",
1571
+ type: "text",
1572
+ access: serverOnly,
1573
+ admin: { hidden: true }
1574
+ },
1575
+ {
1576
+ name: "instructions",
1577
+ type: "group",
1578
+ label: "Instructions",
1579
+ admin: { description: "What the translator is told about the business. Changes apply to translations from now on; existing translations are not touched." },
1580
+ fields: instructionFields(options)
1581
+ }
1582
+ ]
1583
+ };
1584
+ }
1585
+ /** The encrypted key and its last check. Hidden, unreadable through the API, unversioned. */
1586
+ function translationStateGlobal() {
1587
+ return {
1588
+ slug: TRANSLATION_STATE_SLUG,
1589
+ label: "Translation state",
1590
+ admin: { hidden: true },
1591
+ access: {
1592
+ read: () => false,
1593
+ update: () => false
1594
+ },
1595
+ hooks: { afterChange: [clearCache] },
1596
+ fields: [
1597
+ {
1598
+ name: "keyCipher",
1599
+ type: "text"
1600
+ },
1601
+ {
1602
+ name: "keyStatus",
1603
+ type: "select",
1604
+ options: [
1605
+ "valid",
1606
+ "out-of-credit",
1607
+ "rejected",
1608
+ "unchecked"
1609
+ ]
1610
+ },
1611
+ {
1612
+ name: "keyCheckedAt",
1613
+ type: "date"
1614
+ }
1615
+ ]
1616
+ };
1617
+ }
1618
+ //#endregion
1619
+ //#region src/translate/state.ts
1620
+ /**
1621
+ * Where an enabled plugin leaves its options for `translateDocument` and the
1622
+ * endpoint to find. Root `config.custom` is server-only in Payload, so the
1623
+ * translator never reaches the admin bundle.
1624
+ */
1625
+ const AUTO_TRANSLATE_STATE = "bisonAutoTranslate";
1626
+ function readState(config) {
1627
+ return config.custom?.[AUTO_TRANSLATE_STATE];
1628
+ }
1629
+ /**
1630
+ * The test seam: the plugin's state (translator, site, locales, listed
1631
+ * collections and globals) on a config that went through `autoTranslate`,
1632
+ * or `undefined` when the plugin is off or was not applied. Read it instead
1633
+ * of reaching into `config.custom` by key.
1634
+ */
1635
+ function readTranslateState(config) {
1636
+ return readState(config);
1637
+ }
1638
+ /**
1639
+ * The test seam: a copy of `config` whose plugin uses `translator` (a fake in
1640
+ * a test) in place of the one it was registered with. The input is not
1641
+ * changed. Throws when the config did not go through an enabled
1642
+ * `autoTranslate`, so a test cannot silently translate nothing.
1643
+ */
1644
+ function withTranslator(config, translator) {
1645
+ const state = readState(config);
1646
+ if (!state) throw new Error("withTranslator: the config has no autoTranslate state; is the plugin enabled?");
1647
+ return {
1648
+ ...config,
1649
+ custom: {
1650
+ ...config.custom,
1651
+ [AUTO_TRANSLATE_STATE]: {
1652
+ ...state,
1653
+ translator
1654
+ }
1655
+ }
1656
+ };
1657
+ }
1658
+ /** The locale codes of a localization config, in order. */
1659
+ function localeCodes(localization) {
1660
+ if (!localization) return [];
1661
+ return localization.locales.map((locale) => typeof locale === "string" ? locale : locale.code);
1662
+ }
1663
+ //#endregion
1664
+ //#region src/translate/types.ts
1665
+ /** The `context` key that carries a `BisonTranslationMarker`. */
1666
+ const BISON_TRANSLATION_CONTEXT = "bisonTranslation";
1667
+ //#endregion
1668
+ //#region src/translate/document.ts
1669
+ function schemaFor(payload, options) {
1670
+ if ("collection" in options) {
1671
+ const collection = payload.collections[options.collection];
1672
+ if (!collection) throw new Error(`translateDocument: no collection "${options.collection}"`);
1673
+ return {
1674
+ fields: collection.config.fields,
1675
+ blocks: payload.config.blocks,
1676
+ useAsTitle: collection.config.admin?.useAsTitle
1677
+ };
1678
+ }
1679
+ const global = payload.config.globals.find((candidate) => candidate.slug === options.global);
1680
+ if (!global) throw new Error(`translateDocument: no global "${options.global}"`);
1681
+ return {
1682
+ fields: global.fields,
1683
+ blocks: payload.config.blocks
1684
+ };
1685
+ }
1686
+ /** How many times a write is planned again because the source changed during the model call. */
1687
+ const REPLANS = 2;
1688
+ function defaultContext(slug, doc, useAsTitle) {
1689
+ const meta = doc.meta;
1690
+ const title = [
1691
+ useAsTitle ? doc[useAsTitle] : void 0,
1692
+ meta?.title,
1693
+ doc.title,
1694
+ doc.name
1695
+ ].find((value) => typeof value === "string" && value.trim() !== "");
1696
+ return title ? `${slug}: ${title}` : slug;
1697
+ }
1698
+ /**
1699
+ * Brings one document's target locales in step with its source locale (the
1700
+ * config's default locale), string by string: blank target strings are
1701
+ * filled, source strings that changed since `previous` are re-translated,
1702
+ * and with `overwrite` every filled string is. Anything else keeps the
1703
+ * target copy a person may have corrected.
1704
+ *
1705
+ * Reads the source at depth 0 (uploads as ids, array rows with their real
1706
+ * ids) and each target with `fallbackLocale: false`, sends one batch per
1707
+ * target locale, and writes the target with `context: { autoTranslate:
1708
+ * false }` so the write cannot start another round.
1709
+ *
1710
+ * Returns one result per target locale. A translator failure is a `failed`
1711
+ * result and leaves that locale as it was; it only throws on Payload errors
1712
+ * or a misconfiguration (no localization, no translator, unknown slug).
1713
+ */
1714
+ async function translateDocument(payload, options) {
1715
+ const localization = payload.config.localization;
1716
+ if (!localization) throw new Error("translateDocument: the Payload config has no localization");
1717
+ const state = readState(payload.config);
1718
+ const given = options.translator ?? state?.translator;
1719
+ const settings = given && options.site && options.locale !== void 0 ? void 0 : await readTranslationSettings(payload, state?.site);
1720
+ const translator = given ?? settingsTranslator(payload, settings);
1721
+ const kind = options.kind ?? "manual";
1722
+ const sourceLocale = localization.defaultLocale;
1723
+ const codes = localeCodes(localization);
1724
+ const targets = options.locale === void 0 ? settings?.languages ?? codes.filter((code) => code !== sourceLocale) : typeof options.locale === "string" ? [options.locale] : [...options.locale];
1725
+ for (const locale of targets) if (locale === sourceLocale || !codes.includes(locale)) throw new Error(`translateDocument: "${locale}" is not a target locale`);
1726
+ const schema = schemaFor(payload, options);
1727
+ const { req, user } = options;
1728
+ const writeAs = user ? {
1729
+ user,
1730
+ overrideAccess: false
1731
+ } : { overrideAccess: true };
1732
+ const versions = "collection" in options ? payload.collections[options.collection]?.config.versions : payload.config.globals.find((candidate) => candidate.slug === options.global)?.versions;
1733
+ const hasDrafts = Boolean(versions && typeof versions === "object" && versions.drafts);
1734
+ const drafted = user !== void 0 && user !== null && "collection" in options && hasDrafts;
1735
+ let draftMode = false;
1736
+ if (drafted && "collection" in options) draftMode = (await payload.findByID({
1737
+ collection: options.collection,
1738
+ id: options.id,
1739
+ locale: sourceLocale,
1740
+ draft: true,
1741
+ depth: 0,
1742
+ overrideAccess: true,
1743
+ req
1744
+ }))._status === "draft";
1745
+ const read = async (locale, opts) => "collection" in options ? await payload.findByID({
1746
+ collection: options.collection,
1747
+ id: options.id,
1748
+ locale,
1749
+ ...opts.draft ? { draft: true } : {},
1750
+ ...opts.fallbackLocale === false ? { fallbackLocale: false } : {},
1751
+ depth: 0,
1752
+ overrideAccess: true,
1753
+ req
1754
+ }) : await payload.findGlobal({
1755
+ slug: options.global,
1756
+ locale,
1757
+ ...opts.draft ? { draft: true } : {},
1758
+ ...opts.fallbackLocale === false ? { fallbackLocale: false } : {},
1759
+ depth: 0,
1760
+ overrideAccess: true,
1761
+ req
1762
+ });
1763
+ const source = await read(sourceLocale, { draft: draftMode });
1764
+ const slug = "collection" in options ? options.collection : options.global;
1765
+ const label = "collection" in options ? `${slug}/${String(options.id)}` : `globals/${slug}`;
1766
+ const configured = "collection" in options ? state?.collections[slug] : state?.globals[slug];
1767
+ const context = options.context ?? configured?.context?.(source) ?? defaultContext(slug, source, schema.useAsTitle);
1768
+ const site = options.site ?? (settings ? settings.site : state?.site);
1769
+ const plan = (from, target) => translationJob({
1770
+ schema,
1771
+ source: from,
1772
+ target,
1773
+ previous: options.previous,
1774
+ overwrite: options.overwrite
1775
+ });
1776
+ const results = [];
1777
+ for (const locale of targets) {
1778
+ const first = plan(source, await read(locale, {
1779
+ draft: draftMode,
1780
+ fallbackLocale: false
1781
+ }));
1782
+ if (!first) {
1783
+ results.push({
1784
+ locale,
1785
+ status: "nothing",
1786
+ count: 0
1787
+ });
1788
+ continue;
1789
+ }
1790
+ const known = /* @__PURE__ */ new Map();
1791
+ const translate = async (strings) => {
1792
+ const translated = await translateStrings(strings, {
1793
+ translator,
1794
+ from: sourceLocale,
1795
+ to: locale,
1796
+ context,
1797
+ ...site ? { site } : {}
1798
+ });
1799
+ if (!translated) return false;
1800
+ strings.forEach((value, index) => known.set(value, translated[index]));
1801
+ return true;
1802
+ };
1803
+ if (!await translate(first.sources)) {
1804
+ results.push({
1805
+ locale,
1806
+ status: "failed",
1807
+ count: 0
1808
+ });
1809
+ continue;
1810
+ }
1811
+ results.push(await writeLatest(locale));
1812
+ /**
1813
+ * Plans the write again from the latest version as it is now, then
1814
+ * writes it. The model call takes seconds (up to 90s plus a retry), and
1815
+ * the document may have moved on meanwhile, in two ways that matter.
1816
+ *
1817
+ * 1. Payload's update merges into the latest version row
1818
+ * (`getLatestCollectionVersion` / `getLatestGlobalVersion`), draft or
1819
+ * not: `beforeValidate` fills every field the write omits from it and
1820
+ * `beforeChange` fills every localized field's other locales from it,
1821
+ * and a non-draft update writes that to the live row and saves it as
1822
+ * a version. So a live write after an autosave would publish the
1823
+ * draft's copy with no Publish click. A newer draft is therefore
1824
+ * written as a draft (`draft: true` leaves the live row and `_status`
1825
+ * alone), and its target reaches the site with the next publish. A
1826
+ * caller already on a draft stays on drafts even if the latest was
1827
+ * published meanwhile, so the button never escalates to a live write.
1828
+ * 2. The write carries whole top-level fields built from the planned
1829
+ * source's structure (`translationJob`), and a non-localized array or
1830
+ * blocks field (`layout`, `hero`) is one row list for every locale. A
1831
+ * patch planned from an older version would replace the newer row
1832
+ * list: rows the editor added dropped, removed ones restored, links
1833
+ * and images reverted. So the job is planned again from the latest
1834
+ * source and target, with the same `previous`, which keeps the
1835
+ * per-string rule: strings changed since the last publish translate,
1836
+ * filled target copy whose source did not change stays.
1837
+ *
1838
+ * Strings the re-plan meets for the first time go to the model, and the
1839
+ * latest version is read again after that call, up to `REPLANS` times.
1840
+ * What is left is the gap between the last read and Payload's own read
1841
+ * inside the update: milliseconds, against the seconds to minutes of a
1842
+ * model call. Closing it would need a row lock Payload's update does not
1843
+ * take, so a save landing in exactly that gap can still be overwritten.
1844
+ */
1845
+ async function writeLatest(locale) {
1846
+ for (let round = 0;; round++) {
1847
+ const latest = await read(sourceLocale, { draft: hasDrafts || draftMode });
1848
+ const writeDraft = draftMode || hasDrafts && latest._status === "draft";
1849
+ const job = plan(latest, await read(locale, {
1850
+ draft: writeDraft,
1851
+ fallbackLocale: false
1852
+ }));
1853
+ if (!job) return {
1854
+ locale,
1855
+ status: "nothing",
1856
+ count: 0
1857
+ };
1858
+ const missing = job.sources.filter((value) => !known.has(value));
1859
+ if (missing.length > 0) {
1860
+ if (round >= REPLANS) {
1861
+ payload.logger.warn(`${label}: ${locale} source kept changing during translation; ${locale} left as-is`);
1862
+ return {
1863
+ locale,
1864
+ status: "failed",
1865
+ count: 0
1866
+ };
1867
+ }
1868
+ if (!await translate(missing)) return {
1869
+ locale,
1870
+ status: "failed",
1871
+ count: 0
1872
+ };
1873
+ continue;
1874
+ }
1875
+ const data = job.patch(job.sources.map((value) => known.get(value)));
1876
+ 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`);
1877
+ const marker = {
1878
+ locale,
1879
+ kind
1880
+ };
1881
+ const plain = req !== void 0 && Object.getPrototypeOf(req) === Object.prototype;
1882
+ const writeReq = req && plain ? {
1883
+ ...req,
1884
+ context: { ...req.context ?? {} }
1885
+ } : req;
1886
+ const restore = req && !plain ? {
1887
+ context: req.context,
1888
+ locale: req.locale,
1889
+ fallbackLocale: req.fallbackLocale
1890
+ } : void 0;
1891
+ const common = {
1892
+ locale,
1893
+ data,
1894
+ depth: 0,
1895
+ ...writeDraft ? { draft: true } : {},
1896
+ context: {
1897
+ autoTranslate: false,
1898
+ [BISON_TRANSLATION_CONTEXT]: marker
1899
+ },
1900
+ ...writeAs,
1901
+ ...writeReq ? { req: writeReq } : {}
1902
+ };
1903
+ try {
1904
+ if ("collection" in options) await payload.update({
1905
+ collection: options.collection,
1906
+ id: options.id,
1907
+ ...common
1908
+ });
1909
+ else await payload.updateGlobal({
1910
+ slug: options.global,
1911
+ ...common
1912
+ });
1913
+ } finally {
1914
+ if (req && restore) {
1915
+ req.context = restore.context;
1916
+ req.locale = restore.locale;
1917
+ req.fallbackLocale = restore.fallbackLocale;
1918
+ }
1919
+ }
1920
+ return {
1921
+ locale,
1922
+ status: "translated",
1923
+ count: job.sources.length
1924
+ };
1925
+ }
1926
+ }
1927
+ }
1928
+ return results;
1929
+ }
1930
+ //#endregion
1931
+ //#region src/translate/endpoint.ts
1932
+ /** The admin component key for the "Translate now" document menu item. */
1933
+ const TRANSLATE_NOW = "@bison-lab/payload-core/admin#TranslateNowMenuItem";
1934
+ /**
1935
+ * True when the request's user may update this document, by the collection's
1936
+ * own `access.update`. A query result (`Where`) counts only when it matches
1937
+ * this document. It counts against the main document, as Payload's own update
1938
+ * does for a draft save, even when the latest version is a newer draft: the
1939
+ * write that follows is judged by Payload again, so this is only the early
1940
+ * refusal.
1941
+ */
1942
+ async function canUpdate(req, slug, id) {
1943
+ if (!req.user) return false;
1944
+ const access = req.payload.collections[slug]?.config.access?.update;
1945
+ if (!access) return true;
1946
+ const result = await access({
1947
+ req,
1948
+ id
1949
+ });
1950
+ if (typeof result === "boolean") return result;
1951
+ if (!result || typeof result !== "object") return false;
1952
+ const { totalDocs } = await req.payload.count({
1953
+ collection: slug,
1954
+ where: { and: [result, { id: { equals: id } }] },
1955
+ overrideAccess: true
1956
+ });
1957
+ return totalDocs > 0;
1958
+ }
1959
+ /**
1960
+ * `POST /api/<slug>/:id/translate?locale=<code>`: the "Translate now"
1961
+ * action. Re-translates one document with `overwrite`, replacing the target
1962
+ * locale's copy (every target locale when `locale` is omitted). Needs update
1963
+ * access to the document. Awaits the model, unlike the publish hook: a
1964
+ * person pressed the button and is waiting for the answer.
1965
+ */
1966
+ function translateNowEndpoint(slug) {
1967
+ return {
1968
+ path: "/:id/translate",
1969
+ method: "post",
1970
+ handler: async (req) => {
1971
+ if (!req.user) return Response.json({ error: "Unauthorized" }, { status: 401 });
1972
+ const state = readState(req.payload.config);
1973
+ if (!state) return Response.json({ error: "Translation is not set up on this site." }, { status: 503 });
1974
+ const settings = await readTranslationSettings(req.payload, state.site);
1975
+ if (!settings.enabled) return Response.json({ error: "Translation is switched off in Settings → Translation." }, { status: 409 });
1976
+ if (settings.languages.length === 0) return Response.json({ error: "No language is ticked in Settings → Translation." }, { status: 409 });
1977
+ const translator = state.translator ?? settingsTranslator(req.payload, settings);
1978
+ if (!isTranslatorConfigured(translator)) return Response.json({ error: "Translation has no API key here." }, { status: 503 });
1979
+ const id = req.routeParams?.id;
1980
+ if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Missing document id" }, { status: 400 });
1981
+ const locale = req.searchParams?.get("locale") || void 0;
1982
+ if (locale !== void 0 && !settings.languages.includes(locale)) return Response.json({ error: `"${locale}" is not a locale this site translates into.` }, { status: 400 });
1983
+ if (!await canUpdate(req, slug, String(id))) return Response.json({ error: "You are not allowed to update this document." }, { status: 403 });
1984
+ let results;
1985
+ try {
1986
+ results = await translateDocument(req.payload, {
1987
+ collection: slug,
1988
+ id,
1989
+ ...locale ? { locale } : {},
1990
+ overwrite: true,
1991
+ user: req.user,
1992
+ translator,
1993
+ kind: "manual"
1994
+ });
1995
+ } catch (error) {
1996
+ const status = error.status;
1997
+ if (typeof status === "number" && status >= 400 && status < 500) {
1998
+ const message = error instanceof Error && error.message ? error.message : "Not allowed.";
1999
+ return Response.json({ error: message }, { status });
2000
+ }
2001
+ throw error;
2002
+ }
2003
+ const failed = results.filter((result) => result.status === "failed");
2004
+ const count = results.reduce((sum, result) => sum + result.count, 0);
2005
+ if (failed.length > 0 && failed.length === results.length) {
2006
+ req.payload.logger.warn(`${slug}/${id}: "Translate now" returned no result`);
2007
+ return Response.json({
2008
+ error: "The translation service gave no result. Try again in a minute.",
2009
+ results
2010
+ }, { status: 502 });
2011
+ }
2012
+ 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.` : ""}`;
2013
+ return Response.json({
2014
+ count,
2015
+ message,
2016
+ results
2017
+ });
2018
+ }
2019
+ };
2020
+ }
2021
+ /**
2022
+ * `GET /api/translation/available`: whether "Translate now" can run, for
2023
+ * any signed-in editor. Says only yes or no; the screen's details are
2024
+ * behind the `translation` grant.
2025
+ */
2026
+ function translationAvailableEndpoint() {
2027
+ return {
2028
+ path: "/translation/available",
2029
+ method: "get",
2030
+ handler: async (req) => {
2031
+ if (!req.user) return Response.json({ available: false }, { status: 401 });
2032
+ const state = readState(req.payload.config);
2033
+ if (!state) return Response.json({ available: false });
2034
+ const settings = await readTranslationSettings(req.payload, state.site);
2035
+ const translator = state.translator ?? settingsTranslator(req.payload, settings);
2036
+ return Response.json({
2037
+ available: settings.enabled && settings.languages.length > 0 && isTranslatorConfigured(translator),
2038
+ languages: settings.languages
2039
+ });
2040
+ }
2041
+ };
2042
+ }
2043
+ //#endregion
2044
+ //#region src/translate/after-commit.ts
2045
+ /** How often to re-check whether the request's transaction has ended. */
2046
+ const POLL_INTERVAL_MS = 25;
2047
+ /**
2048
+ * How long to wait for the transaction to end before abandoning the work. Far
2049
+ * above any real publish, so reaching it means the request itself hung rather
2050
+ * than that the work was slow.
2051
+ */
2052
+ const TRANSACTION_TIMEOUT_MS = 3e4;
2053
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
2054
+ /**
2055
+ * Resolves true once the request's transaction has ended, false if it never
2056
+ * does. Polling is the mechanism because there is nothing to subscribe to:
2057
+ * Payload has no post-commit hook, and `req.transactionID` is the only
2058
+ * in-process signal that the transaction is over — both commitTransaction and
2059
+ * killTransaction finish with `delete req.transactionID`. The alternative,
2060
+ * patching payload.db.commitTransaction, is global and order-dependent, and
2061
+ * would affect every operation in the process to serve one hook.
2062
+ *
2063
+ * An absent transactionID means there is nothing to wait for: a script running
2064
+ * with `disableTransaction`, or a unit test.
2065
+ */
2066
+ async function waitForTransactionEnd(req) {
2067
+ const deadline = Date.now() + TRANSACTION_TIMEOUT_MS;
2068
+ while (req.transactionID !== void 0) {
2069
+ if (Date.now() >= deadline) return false;
2070
+ await sleep(POLL_INTERVAL_MS);
2071
+ }
2072
+ return true;
2073
+ }
2074
+ /**
2075
+ * Run `work` once the request's database transaction has ended, so an expensive
2076
+ * or failure-prone tail never holds that transaction open.
2077
+ *
2078
+ * Payload runs `afterOperation` BEFORE commitTransaction (see updateByID.js), so
2079
+ * no hook is late enough to do this on its own. Anything scheduled here must
2080
+ * also open its own transaction rather than joining `req`'s: joining is
2081
+ * mandatory only while the outer transaction is still live — once it has
2082
+ * committed, its row locks are released and a fresh transaction is both safe
2083
+ * and required. So `work` must pass no `req` to the Local API.
2084
+ *
2085
+ * The returned promise is handed to `waitUntil` (the site's, e.g. Vercel's),
2086
+ * without which a serverless instance may be frozen the moment the response is
2087
+ * flushed and the work would never finish. It is also returned to the caller,
2088
+ * so tests and scripts can await the deferred work instead of sleeping.
2089
+ *
2090
+ * Deliberately not awaited by its callers: not awaiting is what removes the
2091
+ * hold, and `waitUntil` is what keeps the work alive afterwards.
2092
+ *
2093
+ * Never rejects. The final catch is a backstop only — callers own their own
2094
+ * error reporting — so that a defect in this helper cannot escape as an
2095
+ * unhandled rejection and take the process down.
2096
+ */
2097
+ function runAfterCommit(req, label, work, waitUntil) {
2098
+ const deferred = waitForTransactionEnd(req).then((ended) => {
2099
+ if (ended) return work();
2100
+ req.payload.logger.warn(`${label}: transaction still open after ${TRANSACTION_TIMEOUT_MS}ms; deferred work skipped`);
2101
+ }).catch((error) => {
2102
+ req.payload.logger.error({ err: error }, `${label}: deferred post-commit work threw`);
2103
+ });
2104
+ try {
2105
+ waitUntil?.(deferred);
2106
+ } catch (error) {
2107
+ req.payload.logger.error({ err: error }, `${label}: waitUntil threw; the deferred work still runs`);
2108
+ }
2109
+ return deferred;
2110
+ }
2111
+ //#endregion
2112
+ //#region src/translate/guards.ts
2113
+ const FIELD_SEPARATOR = String.fromCharCode(0);
2114
+ /** True when no localized copy differs between the two documents. */
2115
+ function localizedCopyUnchanged(previousDoc, doc, schema) {
2116
+ const before = collectLocalizedStrings(schema, previousDoc ?? {});
2117
+ const after = collectLocalizedStrings(schema, doc ?? {});
2118
+ return before.join(FIELD_SEPARATOR) === after.join(FIELD_SEPARATOR);
2119
+ }
2120
+ /**
2121
+ * The no-op decision for a collection or global WITHOUT a draft workflow:
2122
+ * every write is live, so the incoming `previousDoc` is the right thing to
2123
+ * diff. A create (no previous document) always translates.
2124
+ */
2125
+ function shouldSkipUndraftedTranslation(opts) {
2126
+ const { previousDoc, doc, schema } = opts;
2127
+ if (!previousDoc || Object.keys(previousDoc).length === 0) return false;
2128
+ return localizedCopyUnchanged(previousDoc, doc, schema);
2129
+ }
2130
+ /**
2131
+ * The no-op decision for a drafts-enabled collection or global, which must
2132
+ * NOT use the hook's `previousDoc`.
2133
+ *
2134
+ * Payload hands `afterChange` the most recently saved version, and with autosave
2135
+ * on (375ms) that is the draft the editor was just typing into, carrying copy
2136
+ * identical to what is being published. Diffing against it therefore reported
2137
+ * "nothing changed" on essentially every admin publish, so auto-translation
2138
+ * never ran from the admin at all. Diffing against the LAST PUBLISHED version
2139
+ * is the question actually worth asking: did the published copy change?
2140
+ *
2141
+ * That also keeps the property the naive fix broke, namely that a publish which
2142
+ * touches no localized copy (an image swap, a reordering) leaves a hand-edited
2143
+ * target locale alone. A document with no earlier published version is a first
2144
+ * publish and always translates, even one written entirely as a draft.
2145
+ *
2146
+ * Returns that previous published version too: it is the "before" the
2147
+ * per-string rule compares each source string with.
2148
+ */
2149
+ async function draftedTranslationDecision(opts) {
2150
+ const { req, entity, doc, schema, sourceLocale } = opts;
2151
+ if (doc?._status !== "published") return {
2152
+ skip: true,
2153
+ previous: null
2154
+ };
2155
+ const docUpdatedAt = doc.updatedAt;
2156
+ if (typeof docUpdatedAt !== "string") return {
2157
+ skip: false,
2158
+ previous: null
2159
+ };
2160
+ const where = {
2161
+ "version._status": { equals: "published" },
2162
+ updatedAt: { less_than: docUpdatedAt }
2163
+ };
2164
+ const common = {
2165
+ sort: "-updatedAt",
2166
+ limit: 1,
2167
+ pagination: false,
2168
+ depth: 0,
2169
+ locale: sourceLocale,
2170
+ overrideAccess: true,
2171
+ req
2172
+ };
2173
+ const { docs } = "collection" in entity ? await req.payload.findVersions({
2174
+ ...common,
2175
+ collection: entity.collection,
2176
+ where: {
2177
+ parent: { equals: doc.id },
2178
+ ...where
2179
+ }
2180
+ }) : await req.payload.findGlobalVersions({
2181
+ ...common,
2182
+ slug: entity.global,
2183
+ where
2184
+ });
2185
+ const previousPublished = docs[0]?.version;
2186
+ if (!previousPublished || typeof previousPublished !== "object") return {
2187
+ skip: false,
2188
+ previous: null
2189
+ };
2190
+ const current = "collection" in entity ? await req.payload.findByID({
2191
+ collection: entity.collection,
2192
+ id: doc.id,
2193
+ locale: sourceLocale,
2194
+ depth: 0,
2195
+ overrideAccess: true,
2196
+ req
2197
+ }) : await req.payload.findGlobal({
2198
+ slug: entity.global,
2199
+ locale: sourceLocale,
2200
+ depth: 0,
2201
+ overrideAccess: true,
2202
+ req
2203
+ });
2204
+ const previous = previousPublished;
2205
+ return {
2206
+ skip: localizedCopyUnchanged(previous, current, schema),
2207
+ previous
2208
+ };
2209
+ }
2210
+ /** `draftedTranslationDecision`, answering only whether to skip. */
2211
+ async function shouldSkipDraftedTranslation(opts) {
2212
+ return (await draftedTranslationDecision(opts)).skip;
2213
+ }
2214
+ //#endregion
2215
+ //#region src/translate/hooks.ts
2216
+ /** True for the admin's autosave (`?autosave=true`), which never translates. */
2217
+ function isAutosave(req) {
2218
+ const query = req.query;
2219
+ return req.searchParams?.get?.("autosave") === "true" || query?.autosave === "true" || query?.autosave === true;
2220
+ }
2221
+ /**
2222
+ * Vercel's `waitUntil` for the current request, when there is one. It is
2223
+ * what `@vercel/functions` reads; using it directly keeps that package off
2224
+ * every site. Without it the deferred work still runs in the same process.
2225
+ */
2226
+ function vercelWaitUntil() {
2227
+ const waitUntil = globalThis[Symbol.for("@vercel/request-context")]?.get?.()?.waitUntil;
2228
+ return typeof waitUntil === "function" ? waitUntil : void 0;
2229
+ }
2230
+ /**
2231
+ * Fills the other locales from the source locale when copy is saved, while
2232
+ * Settings → Translation is switched on. Every collection and global with
2233
+ * localized fields has this hook; there is no exclude list. Rules, in order:
2234
+ *
2235
+ * - `autoTranslate: false` context skips it (seeds and scripts, and the
2236
+ * translation's own write, so it never re-fires itself).
2237
+ * - Edits in a target locale are ignored: a hand edit there is never
2238
+ * clobbered by a machine pass.
2239
+ * - Autosave never translates (Live Preview autosaves every ~375ms).
2240
+ * - Switch off: nothing translates.
2241
+ * - Save draft: blank target strings fill, written into the draft.
2242
+ * - Publish (or any save on a collection without drafts): blank target
2243
+ * strings fill, and source strings changed since the last published
2244
+ * version (the previous document, without drafts) are re-translated.
2245
+ * Target copy whose source did not change is kept, so a hand correction
2246
+ * survives every publish that does not change its English.
2247
+ * - No key: the save goes through and a warning is logged.
2248
+ *
2249
+ * The write is made as the user who saved (`overrideAccess: false`), with
2250
+ * `context.bisonTranslation = { locale, kind: "auto" }`. Failures log and
2251
+ * never fail the save, and the work starts only once the save has committed
2252
+ * (runAfterCommit), so a save never waits on the model.
2253
+ */
2254
+ async function afterSourceChange(args) {
2255
+ const { entity, drafted, schema, doc, req, context } = args;
2256
+ if (context?.autoTranslate === false) return {};
2257
+ const state = readState(req.payload.config);
2258
+ if (!state) return {};
2259
+ if (req.locale && req.locale !== state.sourceLocale) return {};
2260
+ if (isAutosave(req)) return {};
2261
+ const status = drafted ? doc._status : void 0;
2262
+ if (drafted && status !== "published" && status !== "draft") return {};
2263
+ const slug = "collection" in entity ? entity.collection : entity.global;
2264
+ const label = "collection" in entity ? `${slug}/${String(doc.id)}` : `globals/${slug}`;
2265
+ const { payload } = req;
2266
+ let previous;
2267
+ let translator;
2268
+ let targets;
2269
+ try {
2270
+ const settings = await readTranslationSettings(payload, state.site);
2271
+ if (!settings.enabled || settings.languages.length === 0) return {};
2272
+ targets = settings.languages;
2273
+ if (drafted && status === "draft") previous = null;
2274
+ else if (drafted) previous = (await draftedTranslationDecision({
2275
+ req,
2276
+ entity,
2277
+ doc,
2278
+ schema,
2279
+ sourceLocale: state.sourceLocale
2280
+ })).previous;
2281
+ else {
2282
+ const previousDoc = args.operation === "create" ? void 0 : args.previousDoc;
2283
+ previous = previousDoc && Object.keys(previousDoc).length > 0 ? previousDoc : null;
2284
+ }
2285
+ translator = state.translator ?? settingsTranslator(payload, settings);
2286
+ } catch (error) {
2287
+ payload.logger.error({ err: error }, `${label}: auto-translation check failed; targets left as-is`);
2288
+ return {};
2289
+ }
2290
+ if (!isTranslatorConfigured(translator)) {
2291
+ payload.logger.warn(`${label}: copy saved but translation has no API key here; targets not translated`);
2292
+ return {};
2293
+ }
2294
+ const user = req.user ?? void 0;
2295
+ return { deferred: runAfterCommit(req, label, async () => {
2296
+ try {
2297
+ logResults(payload, label, await translateDocument(payload, {
2298
+ ..."collection" in entity ? {
2299
+ collection: slug,
2300
+ id: doc.id
2301
+ } : { global: slug },
2302
+ previous,
2303
+ translator,
2304
+ locale: targets,
2305
+ kind: "auto",
2306
+ ...user ? { user } : {}
2307
+ }));
2308
+ } catch (error) {
2309
+ payload.logger.error({ err: error }, `${label}: auto-translation failed; targets left as-is`);
2310
+ }
2311
+ }, state.waitUntil ?? vercelWaitUntil()) };
2312
+ }
2313
+ function logResults(payload, label, results) {
2314
+ for (const result of results) if (result.status === "translated") payload.logger.info(`${label}: auto-translated ${result.count} string(s) to ${result.locale}`);
2315
+ else if (result.status === "failed") payload.logger.warn(`${label}: ${result.locale} auto-translation returned no result; ${result.locale} left as-is`);
2316
+ }
2317
+ function collectionAutoTranslateHook(slug) {
2318
+ return async ({ collection, doc, previousDoc, operation, req, context }) => {
2319
+ await afterSourceChange({
2320
+ entity: { collection: slug },
2321
+ drafted: Boolean(collection.versions && collection.versions.drafts),
2322
+ schema: {
2323
+ fields: collection.fields,
2324
+ blocks: req.payload.config.blocks
2325
+ },
2326
+ doc,
2327
+ previousDoc,
2328
+ operation,
2329
+ req,
2330
+ context
2331
+ });
2332
+ return doc;
2333
+ };
2334
+ }
2335
+ function globalAutoTranslateHook(slug) {
2336
+ return async ({ global, doc, previousDoc, req, context }) => {
2337
+ await afterSourceChange({
2338
+ entity: { global: slug },
2339
+ drafted: Boolean(global.versions && global.versions.drafts),
2340
+ schema: {
2341
+ fields: global.fields,
2342
+ blocks: req.payload.config.blocks
2343
+ },
2344
+ doc,
2345
+ previousDoc,
2346
+ operation: "update",
2347
+ req,
2348
+ context
2349
+ });
2350
+ return doc;
2351
+ };
2352
+ }
2353
+ //#endregion
2354
+ //#region src/translate/settings-endpoints.ts
2355
+ async function allowed(req) {
2356
+ if (!req.user) return false;
2357
+ return Boolean(await canUseFeature(TRANSLATION_GRANT)({ req }));
2358
+ }
2359
+ function forbidden(req) {
2360
+ return Response.json({ error: "You cannot manage translation." }, { status: req.user ? 403 : 401 });
2361
+ }
2362
+ async function status(req) {
2363
+ invalidateTranslationSettings(req.payload);
2364
+ const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
2365
+ const key = keyFor(req.payload, settings);
2366
+ const doc = settings.doc;
2367
+ return {
2368
+ enabled: settings.enabled,
2369
+ production: isProductionEnvironment(),
2370
+ stored: settings.state.keyCipher && doc.keyLast4 ? {
2371
+ last4: doc.keyLast4,
2372
+ setAt: doc.keySetAt,
2373
+ setBy: doc.keySetBy,
2374
+ status: settings.state.keyStatus
2375
+ } : null,
2376
+ inUse: key.apiKey && key.source && key.last4 ? {
2377
+ source: key.source,
2378
+ last4: key.last4
2379
+ } : null,
2380
+ ...key.note ? { note: key.note } : {}
2381
+ };
2382
+ }
2383
+ const STATUS_BY_CHECK = {
2384
+ valid: "valid",
2385
+ "out-of-credit": "out-of-credit",
2386
+ unreachable: "unchecked"
2387
+ };
2388
+ async function writeState(req, data) {
2389
+ await req.payload.updateGlobal({
2390
+ slug: TRANSLATION_STATE_SLUG,
2391
+ data,
2392
+ overrideAccess: true,
2393
+ req,
2394
+ context: { autoTranslate: false }
2395
+ });
2396
+ }
2397
+ /** Writes the key's public record as a version of Settings → Translation, so its history shows the change. */
2398
+ async function writeKeyRecord(req, data) {
2399
+ await req.payload.updateGlobal({
2400
+ slug: TRANSLATION_SETTINGS_SLUG,
2401
+ data,
2402
+ overrideAccess: true,
2403
+ req,
2404
+ context: { autoTranslate: false }
2405
+ });
2406
+ }
2407
+ const today = () => (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
2408
+ /**
2409
+ * The key endpoints of Settings → Translation, all behind the `translation`
2410
+ * grant:
2411
+ *
2412
+ * - `GET /api/translation/status`: what the key panel shows.
2413
+ * - `POST /api/translation/key` `{ key }`: checks the key with one tiny call.
2414
+ * A 401 refuses it and keeps the previous key. Out of credit saves it
2415
+ * (switching on is then refused). No answer saves it as unchecked.
2416
+ * - `POST /api/translation/key/check`: checks the stored key again.
2417
+ * - `DELETE /api/translation/key`: removes the stored key.
2418
+ */
2419
+ function translationSettingsEndpoints(options = {}) {
2420
+ const verify = (key) => verifyAnthropicKey(key, options.verifyClient ? { client: options.verifyClient } : {});
2421
+ return [
2422
+ {
2423
+ path: "/translation/status",
2424
+ method: "get",
2425
+ handler: async (req) => {
2426
+ if (!await allowed(req)) return forbidden(req);
2427
+ return Response.json(await status(req));
2428
+ }
2429
+ },
2430
+ {
2431
+ path: "/translation/key",
2432
+ method: "post",
2433
+ handler: async (req) => {
2434
+ if (!await allowed(req)) return forbidden(req);
2435
+ let body;
2436
+ try {
2437
+ body = await req.json?.();
2438
+ } catch {
2439
+ body = void 0;
2440
+ }
2441
+ const key = typeof body?.key === "string" ? body.key.trim() : "";
2442
+ if (!key) return Response.json({ error: "Paste a key first." }, { status: 400 });
2443
+ const check = await verify(key);
2444
+ if (check === "rejected") return Response.json({
2445
+ error: "Anthropic rejected this key (401). The previous key is kept.",
2446
+ status: await status(req)
2447
+ }, { status: 400 });
2448
+ const before = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
2449
+ const now = (/* @__PURE__ */ new Date()).toISOString();
2450
+ const by = who(req.user);
2451
+ const replaced = before.state.keyCipher ? "key replaced" : "key set";
2452
+ await writeState(req, {
2453
+ keyCipher: encryptApiKey(key, req.payload.secret),
2454
+ keyStatus: STATUS_BY_CHECK[check],
2455
+ keyCheckedAt: check === "unreachable" ? null : now
2456
+ });
2457
+ await writeKeyRecord(req, {
2458
+ keyLast4: lastFour(key),
2459
+ keySetAt: now,
2460
+ keySetBy: by,
2461
+ keyChange: `${replaced} (ends …${lastFour(key)}) by ${by}, ${today()}`
2462
+ });
2463
+ invalidateTranslationSettings(req.payload);
2464
+ const message = check === "out-of-credit" ? "Key saved, but its Anthropic account is out of credit. Translation cannot be switched on until credit is added." : check === "unreachable" ? "Key saved. Anthropic did not answer, so it will be checked on first use." : "Key saved and checked.";
2465
+ return Response.json({
2466
+ message,
2467
+ check,
2468
+ status: await status(req)
2469
+ });
2470
+ }
2471
+ },
2472
+ {
2473
+ path: "/translation/key/check",
2474
+ method: "post",
2475
+ handler: async (req) => {
2476
+ if (!await allowed(req)) return forbidden(req);
2477
+ const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
2478
+ const sealed = settings.state.keyCipher;
2479
+ const key = sealed ? decryptApiKey(sealed, req.payload.secret) : null;
2480
+ if (!key) return Response.json({ error: "There is no stored key to check." }, { status: 400 });
2481
+ const check = await verify(key);
2482
+ await writeState(req, {
2483
+ keyStatus: check === "rejected" ? "rejected" : STATUS_BY_CHECK[check],
2484
+ keyCheckedAt: check === "unreachable" ? settings.state.keyCheckedAt ?? null : (/* @__PURE__ */ new Date()).toISOString()
2485
+ });
2486
+ invalidateTranslationSettings(req.payload);
2487
+ return Response.json({
2488
+ check,
2489
+ status: await status(req)
2490
+ });
2491
+ }
2492
+ },
2493
+ {
2494
+ path: "/translation/key",
2495
+ method: "delete",
2496
+ handler: async (req) => {
2497
+ if (!await allowed(req)) return forbidden(req);
2498
+ const before = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
2499
+ if (!before.state.keyCipher) return Response.json({ status: await status(req) });
2500
+ const last4 = before.doc.keyLast4 ?? "";
2501
+ await writeState(req, {
2502
+ keyCipher: null,
2503
+ keyStatus: null,
2504
+ keyCheckedAt: null
2505
+ });
2506
+ await writeKeyRecord(req, {
2507
+ keyLast4: null,
2508
+ keySetAt: null,
2509
+ keySetBy: null,
2510
+ keyChange: `key removed (ended …${last4}) by ${who(req.user)}, ${today()}`
2511
+ });
2512
+ invalidateTranslationSettings(req.payload);
2513
+ return Response.json({ status: await status(req) });
2514
+ }
2515
+ }
2516
+ ];
2517
+ }
2518
+ //#endregion
2519
+ //#region src/translate/capability.ts
2520
+ /** True when any field, at any depth, is localized: the entity has copy to translate. */
2521
+ function hasLocalizedFields(fields, blocks = []) {
2522
+ const seen = /* @__PURE__ */ new Set();
2523
+ const walk = (list) => list.some((field) => {
2524
+ if (field.localized === true) return true;
2525
+ if (field.fields && walk(field.fields)) return true;
2526
+ if (field.tabs?.some((tab) => tab.localized === true || walk(tab.fields))) return true;
2527
+ const own = field.blocks ?? [];
2528
+ const referenced = (field.blockReferences ?? []).map((ref) => typeof ref === "string" ? blocks.find((b) => b.slug === ref) : ref);
2529
+ return [...own, ...referenced].some((block) => {
2530
+ if (!block || seen.has(block)) return false;
2531
+ seen.add(block);
2532
+ return walk(block.fields);
2533
+ });
2534
+ });
2535
+ return walk(fields);
2536
+ }
2537
+ function entityHint(entity, hints) {
2538
+ const own = entity.custom?.bisonTranslation ?? void 0;
2539
+ const context = hints?.[entity.slug]?.context ?? own?.context;
2540
+ return context ? { context } : {};
2541
+ }
2542
+ function withCollection(collection, sourceLocale, targetLocales) {
2543
+ const edit = collection.admin?.components?.edit;
2544
+ return {
2545
+ ...collection,
2546
+ hooks: {
2547
+ ...collection.hooks,
2548
+ afterChange: [...collection.hooks?.afterChange ?? [], collectionAutoTranslateHook(collection.slug)]
2549
+ },
2550
+ endpoints: [...collection.endpoints || [], translateNowEndpoint(collection.slug)],
2551
+ admin: {
2552
+ ...collection.admin,
2553
+ components: {
2554
+ ...collection.admin?.components,
2555
+ edit: {
2556
+ ...edit,
2557
+ editMenuItems: [...edit?.editMenuItems ?? [], {
2558
+ path: TRANSLATE_NOW,
2559
+ clientProps: {
2560
+ sourceLocale,
2561
+ targetLocales
2562
+ }
2563
+ }]
2564
+ }
2565
+ }
2566
+ }
2567
+ };
2568
+ }
2569
+ function withGlobal(global) {
2570
+ return {
2571
+ ...global,
2572
+ hooks: {
2573
+ ...global.hooks,
2574
+ afterChange: [...global.hooks?.afterChange ?? [], globalAutoTranslateHook(global.slug)]
2575
+ }
2576
+ };
2577
+ }
2578
+ /**
2579
+ * Gives a config the translation capability: Settings → Translation (and
2580
+ * its hidden state Global), the key endpoints, and on every collection and
2581
+ * global with localized fields the save hook, plus "Translate now" on each
2582
+ * collection. `adminNav()` applies it, so a site gets it with no line of
2583
+ * its own; `translation()` is the same for a site without `adminNav()`.
2584
+ *
2585
+ * Safe to apply more than once: options merge (later wins), the Globals
2586
+ * and endpoints are added once, and each entity is hooked once, so a second
2587
+ * pass only picks up entities a later plugin registered.
2588
+ *
2589
+ * It also puts every library language (`LIBRARY_LOCALES`) into the
2590
+ * config's `localization`, adding it when the site has none, so every site
2591
+ * carries every language in its schema. A target language is translated
2592
+ * and served only once it is ticked on the screen (`activeLocales`).
2593
+ */
2594
+ function applyTranslation(config, options = {}) {
2595
+ const prior = readState(config);
2596
+ const custom = config.custom ?? {};
2597
+ const siteDefault = config.localization ? config.localization.defaultLocale : void 0;
2598
+ const defaultActive = custom["bisonDefaultActiveLocales"] ?? localeCodes(config.localization).filter((code) => code !== siteDefault);
2599
+ const localization = withLibraryLocales(config.localization);
2600
+ const codes = localeCodes(localization);
2601
+ const sourceLocale = localization ? localization.defaultLocale : "en";
2602
+ const targetLocales = codes.filter((code) => code !== sourceLocale);
2603
+ const translator = options.translator ?? prior?.translator;
2604
+ const site = options.site ?? prior?.site;
2605
+ const waitUntil = options.waitUntil ?? prior?.waitUntil;
2606
+ const state = {
2607
+ ...translator ? { translator } : {},
2608
+ ...site ? { site } : {},
2609
+ ...waitUntil ? { waitUntil } : {},
2610
+ sourceLocale,
2611
+ targetLocales,
2612
+ collections: { ...prior?.collections ?? {} },
2613
+ globals: { ...prior?.globals ?? {} }
2614
+ };
2615
+ const translatable = codes.length >= 2;
2616
+ const blocks = config.blocks ?? [];
2617
+ const collections = (config.collections ?? []).map((collection) => {
2618
+ const hint = entityHint(collection, options.hints);
2619
+ if (collection.slug in state.collections) {
2620
+ if (hint.context) state.collections[collection.slug] = hint;
2621
+ return collection;
2622
+ }
2623
+ if (!translatable || !hasLocalizedFields(collection.fields, blocks)) return collection;
2624
+ state.collections[collection.slug] = hint;
2625
+ return withCollection(collection, sourceLocale, targetLocales);
2626
+ });
2627
+ const hasGlobal = (slug) => (config.globals ?? []).some((global) => global.slug === slug);
2628
+ const globals = [
2629
+ ...config.globals ?? [],
2630
+ ...hasGlobal("translation-settings") ? [] : [translationSettingsGlobal({
2631
+ site,
2632
+ targetLocales,
2633
+ defaultActive
2634
+ })],
2635
+ ...hasGlobal("translation-state") ? [] : [translationStateGlobal()]
2636
+ ].map((global) => {
2637
+ const hint = entityHint(global, options.hints);
2638
+ if (global.slug in state.globals) {
2639
+ if (hint.context) state.globals[global.slug] = hint;
2640
+ return global;
2641
+ }
2642
+ if (!translatable || !hasLocalizedFields(global.fields, blocks)) return global;
2643
+ state.globals[global.slug] = hint;
2644
+ return withGlobal(global);
2645
+ });
2646
+ const endpoints = config.endpoints ?? [];
2647
+ const hasEndpoints = endpoints.some((endpoint) => endpoint.path === "/translation/status");
2648
+ return {
2649
+ ...config,
2650
+ localization,
2651
+ custom: {
2652
+ ...custom,
2653
+ [AUTO_TRANSLATE_STATE]: state,
2654
+ [DEFAULT_ACTIVE_LOCALES]: defaultActive
2655
+ },
2656
+ collections,
2657
+ globals,
2658
+ endpoints: hasEndpoints ? endpoints : [
2659
+ ...endpoints,
2660
+ ...translationSettingsEndpoints(options.endpoints),
2661
+ translationAvailableEndpoint(),
2662
+ activeLocalesEndpoint()
2663
+ ]
2664
+ };
2665
+ }
2666
+ /** `applyTranslation` as a plugin, for a site that does not use `adminNav()`. */
2667
+ function translation(options = {}) {
2668
+ return (config) => applyTranslation(config, options);
2669
+ }
2670
+ /**
2671
+ * `GET /api/translation/locales`: the site's active languages, public and
2672
+ * cacheable for a minute, for middleware that cannot load Payload (an edge
2673
+ * runtime). Node middleware calls `activeLocales(payload)` directly.
2674
+ */
2675
+ function activeLocalesEndpoint() {
2676
+ return {
2677
+ path: "/translation/locales",
2678
+ method: "get",
2679
+ handler: async (req) => Response.json(await activeLocales(req.payload), { headers: { "Cache-Control": "public, max-age=60, s-maxage=60" } })
2680
+ };
2681
+ }
2682
+ //#endregion
2683
+ export { hasRole as $, isFeatureSlug as $t, activeLocales as A, featureCatalogue as At, allowedFeaturesForUser as B, THEME_FEATURE_SLUGS as Bt, resolveModel as C, resetRolesMatrix as Ct, LIBRARY_LOCALES as D, validateRolesMatrix as Dt, LIBRARY_DEFAULT_LOCALE as E, seedRoleRows as Et, encryptApiKey as F, CAPABILITIES as Ft, authenticatedOrPublished as G, sanitizeRoleNameInput as Gt, getFeaturesMatrix as H, isRoleName as Ht, resolveApiKey as I, CAPABILITY_FEATURES as It, canPublish as J, FEATURE_GROUPS as Jt, canManageBrand as K, slugifyRoleName as Kt, collectLocalizedStrings as L, DEFAULT_ROLE_GRANTS as Lt, invalidateActiveLocales as M, parseFeaturesMatrix as Mt, withLibraryLocales as N, stampFeatureCatalogue as Nt, LIBRARY_LOCALE_CODES as O, MISSING_PACKAGE_FEATURES_MESSAGE as Ot, decryptApiKey as P, validateFeaturesMatrix as Pt, hasGrant as Q, isFeatureGroupId as Qt, sameRow as R, ROLES as Rt, readTranslationSettings as S, parseRolesMatrix as St, ACTIVE_LOCALES_CACHE_MS as T, roleSelectOptions as Tt, hasFeature as U, isRoleSlug as Ut, canUseFeature as V, isRole as Vt, hideUnlessFeature as W, roleLabel as Wt, getRolesMatrix as X, PACKAGE_FEATURES as Xt, developerOnlyAccess as Y, FEATURE_GROUP_LABELS as Yt, hasCapability as Z, PACKAGE_FEATURE_SLUGS as Zt, TRANSLATION_GRANT as _, ROLES_SLUG as _t, isAutosave as a, isDeveloperTab as at, TRANSLATION_STATE_SLUG as b, grantsFromStoredRole as bt, shouldSkipDraftedTranslation as c, DEFAULT_ROLE_MATRIX as ct, runAfterCommit as d, DUPLICATE_ROLE_SLUG_MESSAGE as dt, isLockedFeature as en, hideUnlessDeveloper as et, TRANSLATE_NOW as f, INVALID_ROLE_NAME_MESSAGE as ft, withTranslator as g, ROLES_GLOBAL_DESCRIPTION as gt, readTranslateState as h, ROLES_FIELD_DESCRIPTION as ht, translationSettingsEndpoints as i, isDeveloper as it, inactiveLocaleRedirect as j, featureGroupLabel as jt, activeAlternates as k, defaultFeaturesFieldValue as kt, shouldSkipUndraftedTranslation as l, DEVELOPER_DESCRIPTION as lt, BISON_TRANSLATION_CONTEXT as m, MISSING_SEED_ROLES_MESSAGE as mt, hasLocalizedFields as n, isAdminOrSelf as nt, draftedTranslationDecision as o, isPrivilegedRole as ot, translateDocument as p, LAST_USERS_TICK_MESSAGE as pt, canManageContent as q, FEATURES_SLUG as qt, translation as r, isAuthenticated as rt, localizedCopyUnchanged as s, storedRoles as st, applyTranslation as t, isPackageFeatureSlug as tn, isAdmin as tt, TRANSACTION_TIMEOUT_MS as u, DUPLICATE_ROLE_NAME_MESSAGE as ut, TRANSLATION_KEY_PANEL as v, applyRoleSlugsFromNames as vt, siteFromInstructions as w, roleDescription as wt, invalidateTranslationSettings as x, normalizeStoredRoles as xt, TRANSLATION_SETTINGS_SLUG as y, defaultRolesFieldValue as yt, translationJob as z, ROLE_LABELS as zt };
2684
+
2685
+ //# sourceMappingURL=capability-DHPE2kon.mjs.map