@bison-lab/payload-core 5.0.0 → 5.2.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.
@@ -1,6 +1,6 @@
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";
1
+ import { c as estimateCost, f as verifyAnthropicKey, i as ECONOMY_TRANSLATE_MODEL, n as translateStrings, o as anthropicTranslator, r as DEFAULT_TRANSLATE_MODEL, s as containsWord, t as isTranslatorConfigured } from "./strings-Fd7kUCT7.mjs";
2
+ import { APIError, Forbidden } from "payload";
3
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
4
4
  //#region src/features/types.ts
5
5
  const FEATURES_SLUG = "features";
6
6
  const FEATURE_GROUPS = [
@@ -798,6 +798,7 @@ function collectFields(fields, value, prefix, inLocalized, configBlocks, out) {
798
798
  */
799
799
  function wants(ctx, source, existing, before) {
800
800
  if (!filled(source)) return false;
801
+ if (ctx.force) return ctx.force(source, existing);
801
802
  if (ctx.overwrite || !filled(existing)) return true;
802
803
  return ctx.hasPrevious && source !== before;
803
804
  }
@@ -830,6 +831,7 @@ function translationJob(input) {
830
831
  overwrite: input.overwrite === true,
831
832
  hasPrevious: input.previous != null,
832
833
  configBlocks: input.schema.blocks,
834
+ ...input.force ? { force: input.force } : {},
833
835
  sources: [],
834
836
  setters: []
835
837
  };
@@ -961,7 +963,8 @@ function planRichText(ctx, source, target, previous) {
961
963
  };
962
964
  }
963
965
  const targetFilled = targetNodes?.some((ref) => filled(ref.node.text)) ?? false;
964
- if (!(ctx.overwrite || !targetFilled || ctx.hasPrevious && !sameText(sourceNodes, previousNodes))) return {
966
+ const targetText = (targetNodes ?? []).map((ref) => String(ref.node.text ?? "")).join(" ");
967
+ if (!(ctx.force ? sourceNodes.some((ref) => filled(ref.node.text) && ctx.force(ref.node.text, targetText)) : ctx.overwrite || !targetFilled || ctx.hasPrevious && !sameText(sourceNodes, previousNodes))) return {
965
968
  value: target,
966
969
  touched: false
967
970
  };
@@ -1097,14 +1100,14 @@ function withLibraryLocales(localization) {
1097
1100
  }
1098
1101
  /** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */
1099
1102
  const ACTIVE_LOCALES_CACHE_MS = 6e4;
1100
- const cache$1 = /* @__PURE__ */ new WeakMap();
1103
+ const cache$2 = /* @__PURE__ */ new WeakMap();
1101
1104
  /** The last answer read from the database, kept for when a later read fails. */
1102
1105
  const lastGood = /* @__PURE__ */ new WeakMap();
1103
1106
  /** After a failed read, how soon to try the database again. */
1104
1107
  const ACTIVE_LOCALES_RETRY_MS = 5e3;
1105
1108
  /** Drops the cached answer, so the next `activeLocales` reads again. */
1106
1109
  function invalidateActiveLocales(payload) {
1107
- cache$1.delete(payload);
1110
+ cache$2.delete(payload);
1108
1111
  }
1109
1112
  /**
1110
1113
  * The ticked target languages, as the Translation screen stores them.
@@ -1128,7 +1131,7 @@ function resolveActiveTargets(stored, targets, defaults) {
1128
1131
  */
1129
1132
  function activeLocales(payload, options = {}) {
1130
1133
  const ttl = options.ttlMs ?? 6e4;
1131
- const hit = cache$1.get(payload);
1134
+ const hit = cache$2.get(payload);
1132
1135
  if (hit && Date.now() - hit.at < (hit.ttl ?? ttl)) return hit.value;
1133
1136
  const entry = {
1134
1137
  at: Date.now(),
@@ -1142,7 +1145,7 @@ function activeLocales(payload, options = {}) {
1142
1145
  entry.ttl = ACTIVE_LOCALES_RETRY_MS;
1143
1146
  return lastGood.get(payload) ?? read.value;
1144
1147
  });
1145
- cache$1.set(payload, entry);
1148
+ cache$2.set(payload, entry);
1146
1149
  return entry.value;
1147
1150
  }
1148
1151
  /** The slug `activeLocales` reads; the Translation screen's. */
@@ -1206,6 +1209,242 @@ function activeAlternates(paths, locales) {
1206
1209
  return Object.fromEntries(Object.entries(paths).filter(([code]) => locales.active.includes(code)));
1207
1210
  }
1208
1211
  //#endregion
1212
+ //#region src/translate/cas.ts
1213
+ /**
1214
+ * An atomic compare-and-set on one row: write `set` only where the row's
1215
+ * `guard` columns still hold the values given, and say whether it did.
1216
+ *
1217
+ * Payload's update-by-`where` is not this: it finds the matching rows, then
1218
+ * updates each, so two writers that both read the old value both "win".
1219
+ * The job lease and the usage counter need exactly one winner, so on
1220
+ * Postgres this is one parameterized `UPDATE … WHERE … RETURNING` through
1221
+ * the adapter's own pool (raw SQL because the Local API cannot express an
1222
+ * atomic conditional write; every value is a bound parameter, and table
1223
+ * and column names come only from this package's fixed `dbName`s and
1224
+ * field names). On another adapter it falls back to the Local API, which
1225
+ * is right for one writer at a time but not atomic.
1226
+ */
1227
+ async function compareAndSet(payload, input) {
1228
+ const pool = payload.db?.pool;
1229
+ if (pool && typeof pool.query === "function") {
1230
+ const values = [];
1231
+ const param = (value) => {
1232
+ values.push(value);
1233
+ return `$${values.length}`;
1234
+ };
1235
+ const assignments = Object.entries(input.set).map(([field, value]) => `${column(field)} = ${param(value)}`);
1236
+ const conditions = [`"id" = ${param(input.id)}`, ...Object.entries(input.guard).map(([field, value]) => value === null || value === void 0 ? `${column(field)} IS NULL` : `${column(field)} = ${param(value)}`)];
1237
+ return ((await pool.query(`UPDATE ${quote(input.table)} SET ${assignments.join(", ")}, "updated_at" = now() WHERE ${conditions.join(" AND ")}`, values)).rowCount ?? 0) === 1;
1238
+ }
1239
+ return ((await payload.update({
1240
+ collection: input.collection,
1241
+ where: { and: [{ id: { equals: input.id } }, ...Object.entries(input.guard).map(([field, value]) => ({ [field]: { equals: value ?? null } }))] },
1242
+ data: input.set,
1243
+ depth: 0,
1244
+ overrideAccess: true,
1245
+ context: { autoTranslate: false }
1246
+ })).docs?.length ?? 0) === 1;
1247
+ }
1248
+ /** `leaseRev` → `"lease_rev"`: Payload's Postgres column for a top-level field. */
1249
+ function column(field) {
1250
+ return quote(field.replace(/([a-z0-9])([A-Z])/g, "$1_$2").toLowerCase());
1251
+ }
1252
+ function quote(name) {
1253
+ if (!/^[a-z_][a-z0-9_]*$/.test(name)) throw new Error(`compareAndSet: unexpected identifier ${name}`);
1254
+ return `"${name}"`;
1255
+ }
1256
+ //#endregion
1257
+ //#region src/translate/usage.ts
1258
+ /**
1259
+ * What translation cost and why it last failed. Usage is one row per month
1260
+ * in a hidden collection (kept, so previous months stay viewable); the
1261
+ * failure lives on the unversioned `translation-state` Global and clears on
1262
+ * the next success.
1263
+ */
1264
+ const TRANSLATION_USAGE_SLUG = "translation-usage";
1265
+ /** How many 429s in a row make "rate limited" worth a banner. A single one is routine. */
1266
+ const RATE_LIMIT_STREAK = 3;
1267
+ /** `2026-11`, in UTC. */
1268
+ function monthKey(date = /* @__PURE__ */ new Date()) {
1269
+ return date.toISOString().slice(0, 7);
1270
+ }
1271
+ /** One row per month. Hidden; read by the screen's endpoints, written only by the server. */
1272
+ function translationUsageCollection() {
1273
+ return {
1274
+ slug: TRANSLATION_USAGE_SLUG,
1275
+ dbName: "translation_usage",
1276
+ labels: {
1277
+ singular: "Translation usage",
1278
+ plural: "Translation usage"
1279
+ },
1280
+ admin: { hidden: true },
1281
+ access: {
1282
+ read: () => false,
1283
+ create: () => false,
1284
+ update: () => false,
1285
+ delete: () => false
1286
+ },
1287
+ fields: [
1288
+ {
1289
+ name: "month",
1290
+ type: "text",
1291
+ required: true,
1292
+ unique: true,
1293
+ index: true
1294
+ },
1295
+ {
1296
+ name: "strings",
1297
+ type: "number",
1298
+ defaultValue: 0
1299
+ },
1300
+ {
1301
+ name: "inputTokens",
1302
+ type: "number",
1303
+ defaultValue: 0
1304
+ },
1305
+ {
1306
+ name: "outputTokens",
1307
+ type: "number",
1308
+ defaultValue: 0
1309
+ },
1310
+ {
1311
+ name: "cost",
1312
+ type: "number",
1313
+ defaultValue: 0
1314
+ },
1315
+ {
1316
+ name: "rev",
1317
+ type: "number",
1318
+ defaultValue: 0
1319
+ }
1320
+ ]
1321
+ };
1322
+ }
1323
+ /** Attempts at a compare-and-set increment before giving up on one call's usage. */
1324
+ const USAGE_ATTEMPTS = 8;
1325
+ async function monthRow(payload, month) {
1326
+ const { docs } = await payload.find({
1327
+ collection: TRANSLATION_USAGE_SLUG,
1328
+ where: { month: { equals: month } },
1329
+ limit: 1,
1330
+ depth: 0,
1331
+ overrideAccess: true
1332
+ });
1333
+ return docs[0];
1334
+ }
1335
+ /** This month's usage, zeros when nothing ran. */
1336
+ async function usageThisMonth(payload, now = /* @__PURE__ */ new Date()) {
1337
+ const month = monthKey(now);
1338
+ const row = await monthRow(payload, month).catch(() => void 0);
1339
+ return {
1340
+ month,
1341
+ strings: row?.strings ?? 0,
1342
+ inputTokens: row?.inputTokens ?? 0,
1343
+ outputTokens: row?.outputTokens ?? 0,
1344
+ cost: row?.cost ?? 0
1345
+ };
1346
+ }
1347
+ /** The last `months` months that have usage, newest first. */
1348
+ async function usageHistory(payload, months = 12) {
1349
+ try {
1350
+ const { docs } = await payload.find({
1351
+ collection: TRANSLATION_USAGE_SLUG,
1352
+ sort: "-month",
1353
+ limit: months,
1354
+ depth: 0,
1355
+ overrideAccess: true
1356
+ });
1357
+ return docs.map(({ month, strings, inputTokens, outputTokens, cost }) => ({
1358
+ month,
1359
+ strings: strings ?? 0,
1360
+ inputTokens: inputTokens ?? 0,
1361
+ outputTokens: outputTokens ?? 0,
1362
+ cost: cost ?? 0
1363
+ }));
1364
+ } catch {
1365
+ return [];
1366
+ }
1367
+ }
1368
+ /**
1369
+ * Adds one successful call to its month. Calls finish concurrently (editor
1370
+ * saves beside a running job), so the add is a compare-and-set on the
1371
+ * row's `rev`: a write that lost the race reads again and retries, and no
1372
+ * call's tokens or cost are lost to the cap.
1373
+ */
1374
+ async function recordUsage(payload, event, now = /* @__PURE__ */ new Date()) {
1375
+ const month = monthKey(now);
1376
+ const cost = estimateCost(event.model, event.inputTokens, event.outputTokens);
1377
+ for (let attempt = 0; attempt < USAGE_ATTEMPTS; attempt++) {
1378
+ const row = await monthRow(payload, month);
1379
+ if (!row) try {
1380
+ await payload.create({
1381
+ collection: TRANSLATION_USAGE_SLUG,
1382
+ data: {
1383
+ month,
1384
+ strings: event.strings,
1385
+ inputTokens: event.inputTokens,
1386
+ outputTokens: event.outputTokens,
1387
+ cost,
1388
+ rev: 0
1389
+ },
1390
+ overrideAccess: true,
1391
+ context: { autoTranslate: false }
1392
+ });
1393
+ return;
1394
+ } catch {
1395
+ continue;
1396
+ }
1397
+ const rev = row.rev ?? 0;
1398
+ if (await compareAndSet(payload, {
1399
+ collection: "translation-usage",
1400
+ table: "translation_usage",
1401
+ id: row.id,
1402
+ guard: { rev },
1403
+ set: {
1404
+ strings: (row.strings ?? 0) + event.strings,
1405
+ inputTokens: (row.inputTokens ?? 0) + event.inputTokens,
1406
+ outputTokens: (row.outputTokens ?? 0) + event.outputTokens,
1407
+ cost: (row.cost ?? 0) + cost,
1408
+ rev: rev + 1
1409
+ }
1410
+ })) return;
1411
+ }
1412
+ }
1413
+ /** What an Admin should do about each failure, in the banner's words. */
1414
+ const FAILURE_ADVICE = {
1415
+ "out-of-credit": "The Anthropic account is out of credit, so nothing is being translated. Add credit in the Anthropic Console, then press Check again in Settings → Translation.",
1416
+ "key-rejected": "Anthropic rejected the API key, so nothing is being translated. Paste a working key in Settings → Translation.",
1417
+ "rate-limited": "Anthropic keeps refusing requests for going too fast (rate limit). Translation retries on the next save; if it persists, raise the account's limits.",
1418
+ "cap-reached": "This month's translation spending cap is reached, so translation is paused until next month. Raise or clear the cap in Settings → Translation to resume."
1419
+ };
1420
+ /**
1421
+ * The failure (if any) a call's outcome records on the state Global:
1422
+ * out of credit and a rejected key at once, a rate limit only after
1423
+ * `RATE_LIMIT_STREAK` in a row. A success clears it. `unreachable` and
1424
+ * `other` change nothing: the next save tries again.
1425
+ */
1426
+ function nextFailure(event, streak) {
1427
+ if (event.ok) return {
1428
+ failure: null,
1429
+ streak: 0
1430
+ };
1431
+ if (event.failure === "rate-limited") {
1432
+ const next = streak + 1;
1433
+ return {
1434
+ failure: next >= 3 ? "rate-limited" : void 0,
1435
+ streak: next
1436
+ };
1437
+ }
1438
+ if (event.failure === "out-of-credit" || event.failure === "key-rejected") return {
1439
+ failure: event.failure,
1440
+ streak: 0
1441
+ };
1442
+ return {
1443
+ failure: void 0,
1444
+ streak
1445
+ };
1446
+ }
1447
+ //#endregion
1209
1448
  //#region src/translate/settings.ts
1210
1449
  /** Settings → Translation: the switch, model, instructions and the key's public record. Versioned. */
1211
1450
  const TRANSLATION_SETTINGS_SLUG = "translation-settings";
@@ -1217,6 +1456,10 @@ const TRANSLATION_SETTINGS_SLUG = "translation-settings";
1217
1456
  const TRANSLATION_STATE_SLUG = "translation-state";
1218
1457
  /** The Roles grant that opens Settings → Translation. Developer and Admin always hold it. */
1219
1458
  const TRANSLATION_GRANT = "translation";
1459
+ /** The admin-wide month-to-date line and failure banner, for `translation` holders only. */
1460
+ const TRANSLATION_STATUS_BAR = "@bison-lab/payload-core/admin#TranslationStatusBar";
1461
+ /** Usage, jobs and the bulk buttons on Settings → Translation. */
1462
+ const TRANSLATION_ACTIVITY_PANEL = "@bison-lab/payload-core/admin#TranslationActivityPanel";
1220
1463
  /** The admin component for the key panel on Settings → Translation. */
1221
1464
  const TRANSLATION_KEY_PANEL = "@bison-lab/payload-core/admin#TranslationKeyPanel";
1222
1465
  /** "Español" for `es`: the library's label, else the code. */
@@ -1258,10 +1501,10 @@ function siteFromInstructions(instructions) {
1258
1501
  };
1259
1502
  return Object.keys(site).length > 0 ? site : void 0;
1260
1503
  }
1261
- const cache = /* @__PURE__ */ new WeakMap();
1504
+ const cache$1 = /* @__PURE__ */ new WeakMap();
1262
1505
  /** Drops the cached read, so the next one sees a save at once. */
1263
1506
  function invalidateTranslationSettings(payload) {
1264
- cache.delete(payload);
1507
+ cache$1.delete(payload);
1265
1508
  }
1266
1509
  async function readGlobal(payload, slug) {
1267
1510
  try {
@@ -1280,7 +1523,7 @@ async function readGlobal(payload, slug) {
1280
1523
  * migrated yet) reads as "off".
1281
1524
  */
1282
1525
  function readTranslationSettings(payload, codeSite) {
1283
- const hit = cache.get(payload);
1526
+ const hit = cache$1.get(payload);
1284
1527
  if (hit && Date.now() - hit.at < 5e3) return hit.value;
1285
1528
  const value = (async () => {
1286
1529
  const [doc, state] = await Promise.all([readGlobal(payload, TRANSLATION_SETTINGS_SLUG), readGlobal(payload, TRANSLATION_STATE_SLUG)]);
@@ -1291,6 +1534,7 @@ function readTranslationSettings(payload, codeSite) {
1291
1534
  const defaults = (payload.config?.custom)?.["bisonDefaultActiveLocales"] ?? targets;
1292
1535
  return {
1293
1536
  enabled: doc.enabled === true,
1537
+ monthlyCap: typeof doc.monthlyCap === "number" && doc.monthlyCap >= 0 ? doc.monthlyCap : null,
1294
1538
  languages: resolveActiveTargets(doc.languagesChosen ? doc.languages ?? [] : void 0, targets, defaults),
1295
1539
  model: doc.model === "economy" ? "economy" : "quality",
1296
1540
  ...site ? { site } : {},
@@ -1299,11 +1543,11 @@ function readTranslationSettings(payload, codeSite) {
1299
1543
  state
1300
1544
  };
1301
1545
  })();
1302
- cache.set(payload, {
1546
+ cache$1.set(payload, {
1303
1547
  at: Date.now(),
1304
1548
  value
1305
1549
  });
1306
- value.catch(() => cache.delete(payload));
1550
+ value.catch(() => cache$1.delete(payload));
1307
1551
  return value;
1308
1552
  }
1309
1553
  /** The key a translation would use right now, from the stored key and the environment. */
@@ -1336,21 +1580,69 @@ async function recordKeyOutcome(payload, settings, event) {
1336
1580
  });
1337
1581
  invalidateTranslationSettings(payload);
1338
1582
  }
1583
+ /** Writes a failure (or its clearing) and the rate-limit streak to the state Global, only when they change. */
1584
+ async function recordFailure(payload, state, outcome) {
1585
+ const failureChanged = outcome.failure !== void 0 && outcome.failure !== (state.failure ?? null);
1586
+ const streakChanged = outcome.streak !== (state.rateLimitStreak ?? 0);
1587
+ if (!failureChanged && !streakChanged) return;
1588
+ await payload.updateGlobal({
1589
+ slug: TRANSLATION_STATE_SLUG,
1590
+ data: {
1591
+ rateLimitStreak: outcome.streak,
1592
+ ...failureChanged ? {
1593
+ failure: outcome.failure,
1594
+ failureAt: outcome.failure ? (/* @__PURE__ */ new Date()).toISOString() : null
1595
+ } : {}
1596
+ },
1597
+ overrideAccess: true,
1598
+ context: { autoTranslate: false }
1599
+ });
1600
+ state.failure = outcome.failure === void 0 ? state.failure : outcome.failure;
1601
+ state.rateLimitStreak = outcome.streak;
1602
+ invalidateTranslationSettings(payload);
1603
+ }
1604
+ /** The advice the banner shows for the recorded failure, or `null`. */
1605
+ function failureAdvice(state) {
1606
+ return state.failure ? FAILURE_ADVICE[state.failure] : null;
1607
+ }
1339
1608
  /**
1340
1609
  * The translator Settings → Translation describes: its key (see
1341
1610
  * `resolveApiKey`), its model and its instructions. `configured: false`
1342
1611
  * when there is no key to use here.
1612
+ *
1613
+ * Every call is counted toward this month's usage, and its failure (out
1614
+ * of credit, a rejected key, persistent rate limits) is recorded for the
1615
+ * banner; a success clears it. With a monthly cap, a call that would start
1616
+ * once the month's estimated cost has reached it is not made: it records
1617
+ * `cap-reached` and returns no result, so the save goes on untranslated.
1343
1618
  */
1344
1619
  function settingsTranslator(payload, settings, seam = {}) {
1345
1620
  const key = keyFor(payload, settings);
1346
1621
  const production = key.source === "admin" || process.env.VERCEL_ENV === "production";
1347
- return anthropicTranslator({
1622
+ const inner = anthropicTranslator({
1348
1623
  apiKey: key.apiKey ?? null,
1349
1624
  ...seam.client && key.apiKey ? { client: seam.client } : {},
1350
1625
  model: resolveModel(settings.model, production),
1351
1626
  ...settings.site ? { site: settings.site } : {},
1352
- onCall: (event) => key.source === "admin" ? recordKeyOutcome(payload, settings, event) : void 0
1627
+ onCall: async (event) => {
1628
+ if (key.source === "admin") await recordKeyOutcome(payload, settings, event);
1629
+ if (event.ok) await recordUsage(payload, event);
1630
+ await recordFailure(payload, settings.state, nextFailure(event, settings.state.rateLimitStreak ?? 0));
1631
+ }
1353
1632
  });
1633
+ const capped = async (strings, request) => {
1634
+ if (settings.monthlyCap !== null && strings.length > 0) {
1635
+ if ((await usageThisMonth(payload)).cost >= settings.monthlyCap) {
1636
+ await recordFailure(payload, settings.state, {
1637
+ failure: "cap-reached",
1638
+ streak: settings.state.rateLimitStreak ?? 0
1639
+ });
1640
+ return null;
1641
+ }
1642
+ }
1643
+ return inner(strings, request);
1644
+ };
1645
+ return Object.assign(capped, { configured: inner.configured });
1354
1646
  }
1355
1647
  const FROZEN_WORDS_DESCRIPTION = "Kept exactly as written in every language. Matching is whole-word and case-sensitive: \"ProtectIQ\" does not match \"protectiq\".";
1356
1648
  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.";
@@ -1387,6 +1679,22 @@ function who(user) {
1387
1679
  }
1388
1680
  /** Fields only the server writes: the form and the REST API cannot change them. */
1389
1681
  const serverOnly = { update: () => false };
1682
+ /**
1683
+ * A raised or cleared cap clears a recorded `cap-reached`, so the banner
1684
+ * goes and paused jobs can resume, without waiting for a call to succeed.
1685
+ */
1686
+ const clearCapFailure = async ({ doc, req }) => {
1687
+ const state = await readGlobal(req.payload, TRANSLATION_STATE_SLUG);
1688
+ if (state.failure !== "cap-reached") return doc;
1689
+ const cap = doc.monthlyCap;
1690
+ const spent = (await usageThisMonth(req.payload)).cost;
1691
+ if (typeof cap === "number" && cap >= 0 && spent >= cap) return doc;
1692
+ await recordFailure(req.payload, state, {
1693
+ failure: null,
1694
+ streak: state.rateLimitStreak ?? 0
1695
+ });
1696
+ return doc;
1697
+ };
1390
1698
  const clearCache = ({ doc, req }) => {
1391
1699
  invalidateTranslationSettings(req.payload);
1392
1700
  invalidateActiveLocales(req.payload);
@@ -1420,6 +1728,7 @@ function instructionFields(options) {
1420
1728
  name: "dialects",
1421
1729
  type: "array",
1422
1730
  dbName: "tr_dialects",
1731
+ admin: { initCollapsed: false },
1423
1732
  label: "Dialect per language",
1424
1733
  labels: {
1425
1734
  singular: "Dialect",
@@ -1457,7 +1766,10 @@ function instructionFields(options) {
1457
1766
  plural: "Frozen words"
1458
1767
  },
1459
1768
  defaultValue: (site?.keepVerbatim ?? []).map((word) => ({ word })),
1460
- admin: { description: FROZEN_WORDS_DESCRIPTION },
1769
+ admin: {
1770
+ description: FROZEN_WORDS_DESCRIPTION,
1771
+ initCollapsed: false
1772
+ },
1461
1773
  fields: [{
1462
1774
  name: "word",
1463
1775
  type: "text",
@@ -1490,7 +1802,7 @@ function translationSettingsGlobal(options) {
1490
1802
  versions: { max: 100 },
1491
1803
  hooks: {
1492
1804
  beforeChange: [refuseOutOfCredit, stampChangedBy],
1493
- afterChange: [clearCache]
1805
+ afterChange: [clearCache, clearCapFailure]
1494
1806
  },
1495
1807
  fields: [
1496
1808
  {
@@ -1498,6 +1810,11 @@ function translationSettingsGlobal(options) {
1498
1810
  type: "ui",
1499
1811
  admin: { components: { Field: TRANSLATION_KEY_PANEL } }
1500
1812
  },
1813
+ {
1814
+ name: "activityPanel",
1815
+ type: "ui",
1816
+ admin: { components: { Field: TRANSLATION_ACTIVITY_PANEL } }
1817
+ },
1501
1818
  {
1502
1819
  name: "enabled",
1503
1820
  type: "checkbox",
@@ -1518,6 +1835,13 @@ function translationSettingsGlobal(options) {
1518
1835
  hooks: { afterRead: [({ value, siblingData }) => siblingData?.languagesChosen ? value : [...options.defaultActive ?? []]] },
1519
1836
  admin: { description: "Only ticked languages are translated and served. An unticked language costs nothing and has no pages: its URLs redirect to English." }
1520
1837
  },
1838
+ {
1839
+ name: "monthlyCap",
1840
+ type: "number",
1841
+ label: "Monthly spending cap (USD)",
1842
+ min: 0,
1843
+ admin: { description: "Blank: no cap. When this month's estimated cost reaches it, translation pauses until next month and translation managers see a banner." }
1844
+ },
1521
1845
  {
1522
1846
  name: "model",
1523
1847
  type: "radio",
@@ -1611,6 +1935,25 @@ function translationStateGlobal() {
1611
1935
  {
1612
1936
  name: "keyCheckedAt",
1613
1937
  type: "date"
1938
+ },
1939
+ {
1940
+ name: "failure",
1941
+ type: "select",
1942
+ options: [
1943
+ "out-of-credit",
1944
+ "key-rejected",
1945
+ "rate-limited",
1946
+ "cap-reached"
1947
+ ]
1948
+ },
1949
+ {
1950
+ name: "failureAt",
1951
+ type: "date"
1952
+ },
1953
+ {
1954
+ name: "rateLimitStreak",
1955
+ type: "number",
1956
+ defaultValue: 0
1614
1957
  }
1615
1958
  ]
1616
1959
  };
@@ -1771,7 +2114,8 @@ async function translateDocument(payload, options) {
1771
2114
  source: from,
1772
2115
  target,
1773
2116
  previous: options.previous,
1774
- overwrite: options.overwrite
2117
+ overwrite: options.overwrite,
2118
+ ...options.force ? { force: options.force } : {}
1775
2119
  });
1776
2120
  const results = [];
1777
2121
  for (const locale of targets) {
@@ -2351,7 +2695,714 @@ function globalAutoTranslateHook(slug) {
2351
2695
  };
2352
2696
  }
2353
2697
  //#endregion
2698
+ //#region src/translate/jobs.ts
2699
+ /**
2700
+ * Background translation jobs: the backfill that starts when translation
2701
+ * is switched on (or a key is saved while it is on), "Fill all blank", and
2702
+ * "Apply frozen words to existing Spanish". A job is a row in a hidden
2703
+ * collection holding its queue of documents and a cursor, saved after every
2704
+ * document, so a job interrupted by a failure or a redeploy resumes where it
2705
+ * stopped and never redoes a finished document.
2706
+ *
2707
+ * A run processes documents for `RUN_BUDGET_MS`, then hands on to the next
2708
+ * run with a signed request to its own endpoint, so no single function
2709
+ * invocation runs long. A job whose last heartbeat is older than
2710
+ * `STALE_AFTER_MS` (its chain broke on a redeploy) is resumed on the next
2711
+ * cold start (`onInit`) or the next time the screen polls.
2712
+ */
2713
+ const TRANSLATION_JOBS_SLUG = "translation-jobs";
2714
+ const TRANSLATION_JOBS_TABLE = "translation_jobs";
2715
+ const RUN_BUDGET_MS = 25e3;
2716
+ /**
2717
+ * How long a claim lasts without renewal. Renewed before every document, so
2718
+ * it covers one document's model calls (90s, one retry) with room to spare;
2719
+ * a runner silent this long is gone, and the job may be claimed again.
2720
+ */
2721
+ const LEASE_MS = 3e5;
2722
+ function translationJobsCollection() {
2723
+ return {
2724
+ slug: TRANSLATION_JOBS_SLUG,
2725
+ dbName: TRANSLATION_JOBS_TABLE,
2726
+ labels: {
2727
+ singular: "Translation job",
2728
+ plural: "Translation jobs"
2729
+ },
2730
+ admin: { hidden: true },
2731
+ access: {
2732
+ read: () => false,
2733
+ create: () => false,
2734
+ update: () => false,
2735
+ delete: () => false
2736
+ },
2737
+ fields: [
2738
+ {
2739
+ name: "kind",
2740
+ type: "select",
2741
+ required: true,
2742
+ options: [
2743
+ "backfill",
2744
+ "fill-blank",
2745
+ "frozen-fix"
2746
+ ]
2747
+ },
2748
+ {
2749
+ name: "status",
2750
+ type: "select",
2751
+ required: true,
2752
+ index: true,
2753
+ options: [
2754
+ "running",
2755
+ "paused",
2756
+ "done",
2757
+ "failed"
2758
+ ]
2759
+ },
2760
+ {
2761
+ name: "queue",
2762
+ type: "json"
2763
+ },
2764
+ {
2765
+ name: "cursor",
2766
+ type: "number",
2767
+ defaultValue: 0
2768
+ },
2769
+ {
2770
+ name: "strings",
2771
+ type: "number",
2772
+ defaultValue: 0
2773
+ },
2774
+ {
2775
+ name: "translated",
2776
+ type: "number",
2777
+ defaultValue: 0
2778
+ },
2779
+ {
2780
+ name: "words",
2781
+ type: "json"
2782
+ },
2783
+ {
2784
+ name: "startedBy",
2785
+ type: "text"
2786
+ },
2787
+ {
2788
+ name: "origin",
2789
+ type: "text"
2790
+ },
2791
+ {
2792
+ name: "heartbeatAt",
2793
+ type: "date"
2794
+ },
2795
+ {
2796
+ name: "message",
2797
+ type: "text"
2798
+ },
2799
+ {
2800
+ name: "reason",
2801
+ type: "text"
2802
+ },
2803
+ {
2804
+ name: "skipped",
2805
+ type: "number",
2806
+ defaultValue: 0
2807
+ },
2808
+ {
2809
+ name: "lease",
2810
+ type: "text"
2811
+ },
2812
+ {
2813
+ name: "leaseUntil",
2814
+ type: "date"
2815
+ },
2816
+ {
2817
+ name: "leaseRev",
2818
+ type: "number",
2819
+ defaultValue: 0
2820
+ }
2821
+ ]
2822
+ };
2823
+ }
2824
+ /** Rough tokens per string, and per call, for an estimate before a bulk job. */
2825
+ const TOKENS_IN_PER_STRING = 40;
2826
+ const TOKENS_OUT_PER_STRING = 40;
2827
+ const TOKENS_PER_CALL = 600;
2828
+ function schemaOf(payload, target) {
2829
+ if ("collection" in target) {
2830
+ const config = payload.collections[target.collection].config;
2831
+ const versions = config.versions;
2832
+ return {
2833
+ fields: config.fields,
2834
+ blocks: payload.config.blocks,
2835
+ drafts: Boolean(versions && typeof versions === "object" && versions.drafts)
2836
+ };
2837
+ }
2838
+ const global = payload.config.globals.find((entry) => entry.slug === target.global);
2839
+ const versions = global.versions;
2840
+ return {
2841
+ fields: global.fields,
2842
+ blocks: payload.config.blocks,
2843
+ drafts: Boolean(versions && typeof versions === "object" && versions.drafts)
2844
+ };
2845
+ }
2846
+ async function readLatest(payload, target, locale, drafts, target2 = false) {
2847
+ const common = {
2848
+ locale,
2849
+ depth: 0,
2850
+ overrideAccess: true,
2851
+ ...drafts ? { draft: true } : {},
2852
+ ...target2 ? { fallbackLocale: false } : {}
2853
+ };
2854
+ return "collection" in target ? await payload.findByID({
2855
+ collection: target.collection,
2856
+ id: target.id,
2857
+ ...common
2858
+ }) : await payload.findGlobal({
2859
+ slug: target.global,
2860
+ ...common
2861
+ });
2862
+ }
2863
+ /** Strings in the frozen-word fix: English keeps a frozen word (whole word, case-sensitive) and the translation lost it. */
2864
+ function frozenWordForce(words) {
2865
+ return (source, existing) => words.some((word) => containsWord(source, word) && !(typeof existing === "string" && containsWord(existing, word)));
2866
+ }
2867
+ async function allTargets(payload) {
2868
+ const state = readState(payload.config);
2869
+ if (!state) return [];
2870
+ const out = [];
2871
+ for (const slug of Object.keys(state.collections)) {
2872
+ let page = 1;
2873
+ for (;;) {
2874
+ const result = await payload.find({
2875
+ collection: slug,
2876
+ depth: 0,
2877
+ limit: 100,
2878
+ page,
2879
+ sort: "id",
2880
+ overrideAccess: true,
2881
+ select: { id: true },
2882
+ draft: true
2883
+ });
2884
+ for (const doc of result.docs) out.push({
2885
+ collection: slug,
2886
+ id: doc.id
2887
+ });
2888
+ if (!result.hasNextPage) break;
2889
+ page += 1;
2890
+ }
2891
+ }
2892
+ for (const slug of Object.keys(state.globals)) out.push({ global: slug });
2893
+ return out;
2894
+ }
2895
+ /**
2896
+ * Counts what a job would translate, reading each document's latest version
2897
+ * (the published copy, or the current draft when there is one) in every
2898
+ * ticked language. Changes nothing.
2899
+ */
2900
+ async function estimateJob(payload, settings, kind, words = []) {
2901
+ const state = readState(payload.config);
2902
+ const source = payload.config.localization ? payload.config.localization.defaultLocale : "en";
2903
+ const lost = /* @__PURE__ */ new Set();
2904
+ const force = kind === "frozen-fix" ? (source, existing) => {
2905
+ const missing = words.filter((word) => containsWord(source, word) && !(typeof existing === "string" && containsWord(existing, word)));
2906
+ missing.forEach((word) => lost.add(word));
2907
+ return missing.length > 0;
2908
+ } : void 0;
2909
+ let strings = 0;
2910
+ let calls = 0;
2911
+ const queue = [];
2912
+ if (!state || settings.languages.length === 0 || kind === "frozen-fix" && words.length === 0) return {
2913
+ documents: 0,
2914
+ strings: 0,
2915
+ cost: 0,
2916
+ queue,
2917
+ lostWords: []
2918
+ };
2919
+ for (const target of await allTargets(payload)) {
2920
+ const schema = schemaOf(payload, target);
2921
+ let from;
2922
+ try {
2923
+ from = await readLatest(payload, target, source, schema.drafts);
2924
+ } catch {
2925
+ continue;
2926
+ }
2927
+ let count = 0;
2928
+ for (const locale of settings.languages) {
2929
+ const into = await readLatest(payload, target, locale, schema.drafts, true);
2930
+ const job = translationJob({
2931
+ schema,
2932
+ source: from,
2933
+ target: into,
2934
+ ...force ? { force } : {}
2935
+ });
2936
+ if (job) {
2937
+ count += job.sources.length;
2938
+ calls += 1;
2939
+ }
2940
+ }
2941
+ if (count > 0) {
2942
+ queue.push(target);
2943
+ strings += count;
2944
+ }
2945
+ }
2946
+ const cost = estimateCost(resolveModel(settings.model, process.env.VERCEL_ENV === "production"), strings * TOKENS_IN_PER_STRING + calls * TOKENS_PER_CALL, strings * TOKENS_OUT_PER_STRING);
2947
+ return {
2948
+ documents: queue.length,
2949
+ strings,
2950
+ cost,
2951
+ queue,
2952
+ lostWords: words.filter((word) => lost.has(word))
2953
+ };
2954
+ }
2955
+ /** The hand-on signature: the job and the lease it carries, so a captured header cannot restart another runner. */
2956
+ function sign(secret, id, lease) {
2957
+ return createHmac("sha256", `bison-translation-job:${secret}`).update(`${id}:${lease}`).digest("hex");
2958
+ }
2959
+ function verifySignature(secret, id, lease, signature) {
2960
+ if (!signature || !lease) return false;
2961
+ const expected = Buffer.from(sign(secret, id, lease));
2962
+ const given = Buffer.from(signature);
2963
+ return expected.length === given.length && timingSafeEqual(expected, given);
2964
+ }
2965
+ async function loadJob(payload, id) {
2966
+ try {
2967
+ return await payload.findByID({
2968
+ collection: TRANSLATION_JOBS_SLUG,
2969
+ id,
2970
+ depth: 0,
2971
+ overrideAccess: true
2972
+ });
2973
+ } catch {
2974
+ return null;
2975
+ }
2976
+ }
2977
+ async function saveJob(payload, id, data) {
2978
+ await payload.update({
2979
+ collection: TRANSLATION_JOBS_SLUG,
2980
+ id,
2981
+ data,
2982
+ overrideAccess: true,
2983
+ context: { autoTranslate: false }
2984
+ });
2985
+ }
2986
+ /**
2987
+ * Writes `data` only if `where` still matches the job (a compare-and-set
2988
+ * through Payload's update-by-where). True when it did.
2989
+ */
2990
+ async function saveJobIf(payload, id, where, data) {
2991
+ return compareAndSet(payload, {
2992
+ collection: TRANSLATION_JOBS_SLUG,
2993
+ table: TRANSLATION_JOBS_TABLE,
2994
+ id,
2995
+ guard: Object.fromEntries(Object.entries(where).map(([field, clause]) => [field, clause.equals])),
2996
+ set: data
2997
+ });
2998
+ }
2999
+ const leaseUntil = () => new Date(Date.now() + LEASE_MS).toISOString();
3000
+ /**
3001
+ * Takes the job for `lease` if it is running and nobody else holds a live
3002
+ * claim. The claim is a compare-and-set on `leaseRev`, so of two runners
3003
+ * reading the same job only one can win.
3004
+ */
3005
+ async function claimJob(payload, id, lease) {
3006
+ const job = await loadJob(payload, id);
3007
+ if (!job || job.status !== "running") return false;
3008
+ if (job.lease === lease) return true;
3009
+ if (job.lease && job.leaseUntil && Date.parse(job.leaseUntil) > Date.now()) return false;
3010
+ return saveJobIf(payload, id, { leaseRev: { equals: job.leaseRev ?? null } }, {
3011
+ lease,
3012
+ leaseUntil: leaseUntil(),
3013
+ leaseRev: (job.leaseRev ?? 0) + 1,
3014
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
3015
+ });
3016
+ }
3017
+ /** "Stopped at 40 of 85", from the cursor as it is now. */
3018
+ function stoppedAt(job) {
3019
+ return `Stopped at ${job.cursor} of ${Array.isArray(job.queue) ? job.queue.length : 0}`;
3020
+ }
3021
+ /** A recorded failure that pauses a job: the next call would fail the same way. */
3022
+ const STOPPING_FAILURES = new Set([
3023
+ "out-of-credit",
3024
+ "key-rejected",
3025
+ "cap-reached"
3026
+ ]);
3027
+ /**
3028
+ * Runs one job for up to `budgetMs` while holding `lease`: one document at
3029
+ * a time. Before each document it renews the lease (and stops if another
3030
+ * runner has it), re-reads the job (stops if it was paused) and the switch
3031
+ * (pauses if it is off). A document's write and the cursor after it are
3032
+ * made only while the lease is still this runner's. When a document's
3033
+ * translation records a stopping failure (out of credit, a rejected key,
3034
+ * the cap) the job pauses on that document, which is not counted done, and
3035
+ * Resume picks it up after the Admin has fixed the cause. A document that
3036
+ * fails for any other reason is skipped and counted. Returns `true` when
3037
+ * work is left and the lease is still held, so the caller hands on.
3038
+ */
3039
+ async function runJobSlice(payload, id, lease, budgetMs = RUN_BUDGET_MS) {
3040
+ const deadline = Date.now() + budgetMs;
3041
+ const state = readState(payload.config);
3042
+ if (!await claimJob(payload, id, lease)) return false;
3043
+ for (;;) {
3044
+ const job = await loadJob(payload, id);
3045
+ if (!job || job.status !== "running" || job.lease !== lease) return false;
3046
+ const queue = Array.isArray(job.queue) ? job.queue : [];
3047
+ if (job.cursor >= queue.length) {
3048
+ const skipped = job.skipped ?? 0;
3049
+ await saveJobIf(payload, id, { lease: { equals: lease } }, {
3050
+ status: "done",
3051
+ lease: null,
3052
+ message: `Translated ${job.translated} string(s) on ${queue.length} document(s)${skipped ? `; ${skipped} document(s) failed and were skipped (Fill all blank picks them up)` : ""}`
3053
+ });
3054
+ return false;
3055
+ }
3056
+ invalidateTranslationSettings(payload);
3057
+ const settings = await readTranslationSettings(payload, state?.site);
3058
+ if (!settings.enabled) {
3059
+ await saveJobIf(payload, id, { lease: { equals: lease } }, {
3060
+ status: "paused",
3061
+ lease: null,
3062
+ reason: null
3063
+ });
3064
+ return false;
3065
+ }
3066
+ if (Date.now() >= deadline) return true;
3067
+ if (!await saveJobIf(payload, id, { lease: { equals: lease } }, {
3068
+ leaseUntil: leaseUntil(),
3069
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
3070
+ })) return false;
3071
+ const target = queue[job.cursor];
3072
+ let count = 0;
3073
+ let failed = false;
3074
+ try {
3075
+ const results = await translateDocument(payload, {
3076
+ ...target,
3077
+ locale: settings.languages,
3078
+ kind: job.kind === "frozen-fix" ? "frozen-fix" : "backfill",
3079
+ ...job.kind === "frozen-fix" ? { force: frozenWordForce(job.words ?? []) } : {}
3080
+ });
3081
+ count = results.reduce((sum, result) => sum + result.count, 0);
3082
+ failed = results.some((result) => result.status === "failed");
3083
+ } catch (error) {
3084
+ failed = true;
3085
+ payload.logger.warn({ err: error }, `translation job ${String(id)}: a document failed`);
3086
+ }
3087
+ if (failed) {
3088
+ invalidateTranslationSettings(payload);
3089
+ const failure = (await readTranslationSettings(payload, state?.site)).state.failure;
3090
+ if (failure && STOPPING_FAILURES.has(failure)) {
3091
+ await saveJobIf(payload, id, { lease: { equals: lease } }, {
3092
+ status: "paused",
3093
+ lease: null,
3094
+ reason: failure
3095
+ });
3096
+ return false;
3097
+ }
3098
+ }
3099
+ if (!await saveJobIf(payload, id, { lease: { equals: lease } }, {
3100
+ cursor: job.cursor + 1,
3101
+ translated: (job.translated ?? 0) + count,
3102
+ skipped: (job.skipped ?? 0) + (failed ? 1 : 0),
3103
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString()
3104
+ })) return false;
3105
+ }
3106
+ }
3107
+ /** The URL a run hands on to: the job's origin plus the API route. */
3108
+ function runUrl(payload, origin) {
3109
+ const api = payload.config.routes?.api ?? "/api";
3110
+ return `${origin.replace(/\/$/, "")}${api}/translation/jobs/run`;
3111
+ }
3112
+ /**
3113
+ * Runs a slice now under `lease` (kept alive with `waitUntil`) and, if
3114
+ * work is left, swaps in a fresh lease and hands that on to a fresh
3115
+ * invocation with a signed POST to `/api/translation/jobs/run`. Without an
3116
+ * origin the next slice runs in this process instead. A new chain passes no
3117
+ * lease and gets a fresh one, which it must win from any other claimant.
3118
+ */
3119
+ function continueJob(payload, id, initialLease = randomUUID()) {
3120
+ let lease = initialLease;
3121
+ const state = readState(payload.config);
3122
+ const work = (async () => {
3123
+ if (!await runJobSlice(payload, id, lease)) return;
3124
+ const next = randomUUID();
3125
+ if (!await saveJobIf(payload, id, { lease: { equals: lease } }, {
3126
+ lease: next,
3127
+ leaseUntil: leaseUntil()
3128
+ })) return;
3129
+ lease = next;
3130
+ const origin = (await loadJob(payload, id))?.origin || payload.config.serverURL || "";
3131
+ if (!origin) {
3132
+ await continueJob(payload, id, lease);
3133
+ return;
3134
+ }
3135
+ try {
3136
+ await fetch(runUrl(payload, origin), {
3137
+ method: "POST",
3138
+ headers: {
3139
+ "Content-Type": "application/json",
3140
+ "x-bison-translation-job": sign(payload.secret, String(id), lease)
3141
+ },
3142
+ body: JSON.stringify({
3143
+ id,
3144
+ lease
3145
+ })
3146
+ });
3147
+ } catch (error) {
3148
+ payload.logger.warn({ err: error }, `translation job ${String(id)}: hand-on failed; it resumes when the claim lapses`);
3149
+ }
3150
+ })().catch((error) => {
3151
+ payload.logger.error({ err: error }, `translation job ${String(id)} failed`);
3152
+ });
3153
+ (state?.waitUntil ?? vercelWaitUntil())?.(work);
3154
+ return work;
3155
+ }
3156
+ /**
3157
+ * Restarts running jobs whose runner is gone (its claim lapsed, e.g. a
3158
+ * redeploy broke the chain). Safe to call from every poll and every cold
3159
+ * start: a fresh runner must win the claim, so at most one picks a job up.
3160
+ */
3161
+ async function resumeStaleJobs(payload) {
3162
+ let docs;
3163
+ try {
3164
+ docs = (await payload.find({
3165
+ collection: TRANSLATION_JOBS_SLUG,
3166
+ where: { status: { equals: "running" } },
3167
+ depth: 0,
3168
+ limit: 10,
3169
+ overrideAccess: true
3170
+ })).docs;
3171
+ } catch {
3172
+ return 0;
3173
+ }
3174
+ let resumed = 0;
3175
+ for (const job of docs) {
3176
+ if (job.lease && job.leaseUntil && Date.parse(job.leaseUntil) > Date.now()) continue;
3177
+ const lease = randomUUID();
3178
+ if (!await claimJob(payload, job.id, lease)) continue;
3179
+ continueJob(payload, job.id, lease);
3180
+ resumed += 1;
3181
+ }
3182
+ return resumed;
3183
+ }
3184
+ function originOf(req) {
3185
+ try {
3186
+ if (req?.url) return new URL(req.url).origin;
3187
+ } catch {}
3188
+ const host = req?.headers?.get?.("host");
3189
+ if (!host) return null;
3190
+ return `${req?.headers?.get?.("x-forwarded-proto") ?? (host.startsWith("localhost") ? "http" : "https")}://${host}`;
3191
+ }
3192
+ /** The newest jobs, newest first. */
3193
+ async function latestJobs(payload, limit = 5) {
3194
+ try {
3195
+ return (await payload.find({
3196
+ collection: TRANSLATION_JOBS_SLUG,
3197
+ sort: "-createdAt",
3198
+ depth: 0,
3199
+ limit,
3200
+ overrideAccess: true
3201
+ })).docs;
3202
+ } catch {
3203
+ return [];
3204
+ }
3205
+ }
3206
+ /**
3207
+ * Creates a job from an estimate and starts it. Single-flight: a job
3208
+ * already running is returned instead, and if two starts race (switch-on
3209
+ * and a key save, two Admins), the newer one stands down for the older.
3210
+ */
3211
+ async function startJob(payload, input) {
3212
+ const running = (await latestJobs(payload, 10)).find((job) => job.status === "running");
3213
+ if (running) return running;
3214
+ const created = await payload.create({
3215
+ collection: TRANSLATION_JOBS_SLUG,
3216
+ data: {
3217
+ kind: input.kind,
3218
+ status: input.estimate.queue.length ? "running" : "done",
3219
+ queue: input.estimate.queue,
3220
+ cursor: 0,
3221
+ strings: input.estimate.strings,
3222
+ translated: 0,
3223
+ skipped: 0,
3224
+ leaseRev: 0,
3225
+ ...input.words ? { words: [...input.words] } : {},
3226
+ startedBy: who(input.user),
3227
+ origin: originOf(input.req),
3228
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString(),
3229
+ message: input.estimate.queue.length ? null : "Nothing to translate."
3230
+ },
3231
+ overrideAccess: true,
3232
+ context: { autoTranslate: false }
3233
+ });
3234
+ if (created.status !== "running") return created;
3235
+ const first = (await latestJobs(payload, 10)).filter((job) => job.status === "running").sort((a, b) => String(a.createdAt).localeCompare(String(b.createdAt)) || String(a.id).localeCompare(String(b.id)))[0];
3236
+ if (first && String(first.id) !== String(created.id)) {
3237
+ await saveJob(payload, created.id, {
3238
+ status: "done",
3239
+ message: "Another job was already running."
3240
+ });
3241
+ return first;
3242
+ }
3243
+ continueJob(payload, created.id);
3244
+ return created;
3245
+ }
3246
+ /** Pauses every running job; its runner stops after the current document. */
3247
+ async function pauseRunningJobs(payload) {
3248
+ for (const job of await latestJobs(payload, 10)) if (job.status === "running") await saveJob(payload, job.id, {
3249
+ status: "paused",
3250
+ lease: null,
3251
+ reason: null
3252
+ });
3253
+ }
3254
+ /**
3255
+ * The backfill when translation is switched on or a key is saved while it
3256
+ * is on: unless a paused job is waiting to be resumed (the screen offers
3257
+ * that instead), estimate every blank string and start filling it.
3258
+ */
3259
+ async function startBackfill(payload, input = {}) {
3260
+ if ((await latestJobs(payload, 10)).some((job) => job.status === "running" || job.status === "paused")) return null;
3261
+ const settings = await readTranslationSettings(payload, readState(payload.config)?.site);
3262
+ if (!settings.enabled) return null;
3263
+ return startJob(payload, {
3264
+ kind: "backfill",
3265
+ estimate: await estimateJob(payload, settings, "backfill"),
3266
+ ...input
3267
+ });
3268
+ }
3269
+ async function allowed$1(req) {
3270
+ if (!req.user) return false;
3271
+ return Boolean(await canUseFeature(TRANSLATION_GRANT)({ req }));
3272
+ }
3273
+ async function body(req) {
3274
+ try {
3275
+ const value = await req.json?.();
3276
+ return value && typeof value === "object" ? value : {};
3277
+ } catch {
3278
+ return {};
3279
+ }
3280
+ }
3281
+ function frozenWords(settings) {
3282
+ return settings.site?.keepVerbatim ?? [];
3283
+ }
3284
+ /** Public shape of a job for the screen. */
3285
+ function jobView(job) {
3286
+ const advice = job.reason ? failureAdvice({ failure: job.reason }) : null;
3287
+ const message = job.status === "paused" ? `${stoppedAt(job)}${advice ? `. ${advice}` : ""}` : job.message ?? null;
3288
+ return {
3289
+ id: job.id,
3290
+ kind: job.kind,
3291
+ status: job.status,
3292
+ done: job.cursor,
3293
+ total: Array.isArray(job.queue) ? job.queue.length : 0,
3294
+ strings: job.strings,
3295
+ translated: job.translated,
3296
+ skipped: job.skipped ?? 0,
3297
+ startedBy: job.startedBy ?? null,
3298
+ message,
3299
+ createdAt: job.createdAt ?? null
3300
+ };
3301
+ }
3302
+ /**
3303
+ * The job endpoints, behind the `translation` grant except `run`, which
3304
+ * takes only a request signed with `PAYLOAD_SECRET`:
3305
+ *
3306
+ * - `GET /api/translation/jobs`: the latest jobs (and resumes a stale one).
3307
+ * - `POST /api/translation/jobs/estimate` `{ kind }`: what a job would do; changes nothing.
3308
+ * - `POST /api/translation/jobs` `{ kind }`: estimates and starts it.
3309
+ * - `POST /api/translation/jobs/resume` `{ id }`: resumes a paused job.
3310
+ * - `POST /api/translation/jobs/run` `{ id }`: one slice, then the hand-on.
3311
+ */
3312
+ function translationJobEndpoints() {
3313
+ return [
3314
+ {
3315
+ path: "/translation/jobs",
3316
+ method: "get",
3317
+ handler: async (req) => {
3318
+ if (!await allowed$1(req)) return Response.json({ error: "Forbidden" }, { status: req.user ? 403 : 401 });
3319
+ await resumeStaleJobs(req.payload);
3320
+ return Response.json({ jobs: (await latestJobs(req.payload)).map(jobView) });
3321
+ }
3322
+ },
3323
+ {
3324
+ path: "/translation/jobs/estimate",
3325
+ method: "post",
3326
+ handler: async (req) => {
3327
+ if (!await allowed$1(req)) return Response.json({ error: "Forbidden" }, { status: req.user ? 403 : 401 });
3328
+ const kind = (await body(req)).kind;
3329
+ if (kind !== "fill-blank" && kind !== "frozen-fix") return Response.json({ error: "Unknown job." }, { status: 400 });
3330
+ const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
3331
+ const words = frozenWords(settings);
3332
+ const estimate = await estimateJob(req.payload, settings, kind, words);
3333
+ return Response.json({
3334
+ documents: estimate.documents,
3335
+ strings: estimate.strings,
3336
+ cost: estimate.cost,
3337
+ words: estimate.lostWords
3338
+ });
3339
+ }
3340
+ },
3341
+ {
3342
+ path: "/translation/jobs",
3343
+ method: "post",
3344
+ handler: async (req) => {
3345
+ if (!await allowed$1(req)) return Response.json({ error: "Forbidden" }, { status: req.user ? 403 : 401 });
3346
+ const kind = (await body(req)).kind;
3347
+ if (kind !== "fill-blank" && kind !== "frozen-fix") return Response.json({ error: "Unknown job." }, { status: 400 });
3348
+ const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
3349
+ if (!settings.enabled) return Response.json({ error: "Switch translation on first." }, { status: 409 });
3350
+ const words = frozenWords(settings);
3351
+ const estimate = await estimateJob(req.payload, settings, kind, words);
3352
+ const job = await startJob(req.payload, {
3353
+ kind,
3354
+ estimate,
3355
+ words,
3356
+ user: req.user,
3357
+ req
3358
+ });
3359
+ return Response.json({ job: jobView(job) });
3360
+ }
3361
+ },
3362
+ {
3363
+ path: "/translation/jobs/resume",
3364
+ method: "post",
3365
+ handler: async (req) => {
3366
+ if (!await allowed$1(req)) return Response.json({ error: "Forbidden" }, { status: req.user ? 403 : 401 });
3367
+ const id = (await body(req)).id;
3368
+ if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Which job?" }, { status: 400 });
3369
+ if (!(await readTranslationSettings(req.payload, readState(req.payload.config)?.site)).enabled) return Response.json({ error: "Switch translation on first." }, { status: 409 });
3370
+ const job = await loadJob(req.payload, id);
3371
+ if (!job || job.status !== "paused") return Response.json({ error: "That job is not paused." }, { status: 409 });
3372
+ await saveJob(req.payload, id, {
3373
+ status: "running",
3374
+ message: null,
3375
+ reason: null,
3376
+ lease: null,
3377
+ heartbeatAt: (/* @__PURE__ */ new Date()).toISOString(),
3378
+ origin: job.origin ?? originOf(req)
3379
+ });
3380
+ continueJob(req.payload, id);
3381
+ return Response.json({ job: jobView({
3382
+ ...job,
3383
+ status: "running"
3384
+ }) });
3385
+ }
3386
+ },
3387
+ {
3388
+ path: "/translation/jobs/run",
3389
+ method: "post",
3390
+ handler: async (req) => {
3391
+ const { id, lease } = await body(req);
3392
+ if (typeof id !== "string" && typeof id !== "number") return Response.json({ error: "Which job?" }, { status: 400 });
3393
+ if (typeof lease !== "string" || !verifySignature(req.payload.secret, String(id), lease, req.headers.get("x-bison-translation-job"))) return Response.json({ error: "Forbidden" }, { status: 403 });
3394
+ continueJob(req.payload, id, lease);
3395
+ return Response.json({ ok: true }, { status: 202 });
3396
+ }
3397
+ }
3398
+ ];
3399
+ }
3400
+ //#endregion
2354
3401
  //#region src/translate/settings-endpoints.ts
3402
+ /** Failures a working key settles. */
3403
+ function keyFailure(failure) {
3404
+ return failure === "out-of-credit" || failure === "key-rejected";
3405
+ }
2355
3406
  async function allowed(req) {
2356
3407
  if (!req.user) return false;
2357
3408
  return Boolean(await canUseFeature(TRANSLATION_GRANT)({ req }));
@@ -2377,9 +3428,23 @@ async function status(req) {
2377
3428
  source: key.source,
2378
3429
  last4: key.last4
2379
3430
  } : null,
2380
- ...key.note ? { note: key.note } : {}
3431
+ ...key.note ? { note: key.note } : {},
3432
+ usage: {
3433
+ month: await usageThisMonth(req.payload),
3434
+ history: await usageHistory(req.payload),
3435
+ cap: settings.monthlyCap
3436
+ },
3437
+ failure: failureOf(settings.state)
2381
3438
  };
2382
3439
  }
3440
+ function failureOf(state) {
3441
+ const advice = failureAdvice(state);
3442
+ return state.failure && advice ? {
3443
+ kind: state.failure,
3444
+ at: state.failureAt ?? null,
3445
+ advice
3446
+ } : null;
3447
+ }
2383
3448
  const STATUS_BY_CHECK = {
2384
3449
  valid: "valid",
2385
3450
  "out-of-credit": "out-of-credit",
@@ -2452,7 +3517,11 @@ function translationSettingsEndpoints(options = {}) {
2452
3517
  await writeState(req, {
2453
3518
  keyCipher: encryptApiKey(key, req.payload.secret),
2454
3519
  keyStatus: STATUS_BY_CHECK[check],
2455
- keyCheckedAt: check === "unreachable" ? null : now
3520
+ keyCheckedAt: check === "unreachable" ? null : now,
3521
+ ...keyFailure(before.state.failure) && check !== "out-of-credit" ? {
3522
+ failure: null,
3523
+ rateLimitStreak: 0
3524
+ } : {}
2456
3525
  });
2457
3526
  await writeKeyRecord(req, {
2458
3527
  keyLast4: lastFour(key),
@@ -2461,6 +3530,16 @@ function translationSettingsEndpoints(options = {}) {
2461
3530
  keyChange: `${replaced} (ends …${lastFour(key)}) by ${by}, ${today()}`
2462
3531
  });
2463
3532
  invalidateTranslationSettings(req.payload);
3533
+ if (before.enabled && check !== "out-of-credit") {
3534
+ const started = startBackfill(req.payload, {
3535
+ user: req.user,
3536
+ req: {
3537
+ url: req.url,
3538
+ headers: req.headers
3539
+ }
3540
+ }).catch(() => null);
3541
+ (readState(req.payload.config)?.waitUntil ?? vercelWaitUntil())?.(started);
3542
+ }
2464
3543
  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
3544
  return Response.json({
2466
3545
  message,
@@ -2469,6 +3548,22 @@ function translationSettingsEndpoints(options = {}) {
2469
3548
  });
2470
3549
  }
2471
3550
  },
3551
+ {
3552
+ path: "/translation/summary",
3553
+ method: "get",
3554
+ handler: async (req) => {
3555
+ if (!await allowed(req)) return Response.json({ visible: false }, { status: req.user ? 403 : 401 });
3556
+ const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);
3557
+ const month = await usageThisMonth(req.payload);
3558
+ return Response.json({
3559
+ visible: true,
3560
+ enabled: settings.enabled,
3561
+ month,
3562
+ cap: settings.monthlyCap,
3563
+ failure: failureOf(settings.state)
3564
+ });
3565
+ }
3566
+ },
2472
3567
  {
2473
3568
  path: "/translation/key/check",
2474
3569
  method: "post",
@@ -2481,7 +3576,11 @@ function translationSettingsEndpoints(options = {}) {
2481
3576
  const check = await verify(key);
2482
3577
  await writeState(req, {
2483
3578
  keyStatus: check === "rejected" ? "rejected" : STATUS_BY_CHECK[check],
2484
- keyCheckedAt: check === "unreachable" ? settings.state.keyCheckedAt ?? null : (/* @__PURE__ */ new Date()).toISOString()
3579
+ keyCheckedAt: check === "unreachable" ? settings.state.keyCheckedAt ?? null : (/* @__PURE__ */ new Date()).toISOString(),
3580
+ ...check === "valid" && keyFailure(settings.state.failure) ? {
3581
+ failure: null,
3582
+ rateLimitStreak: 0
3583
+ } : {}
2485
3584
  });
2486
3585
  invalidateTranslationSettings(req.payload);
2487
3586
  return Response.json({
@@ -2516,6 +3615,273 @@ function translationSettingsEndpoints(options = {}) {
2516
3615
  ];
2517
3616
  }
2518
3617
  //#endregion
3618
+ //#region src/translate/interface-text.ts
3619
+ /**
3620
+ * A site's interface text (the strings `next-intl` reads from
3621
+ * `messages/<locale>.json`) as a localized CMS document, so the same
3622
+ * translation (switch, key, instructions, fill-on-save, hand corrections
3623
+ * kept) covers it. One row per message: a stable dotted key (`nav.plans`,
3624
+ * `faq.items.0.question`) and its localized text.
3625
+ */
3626
+ const INTERFACE_TEXT_SLUG = "interface-text";
3627
+ /** `{ nav: { plans: "Plans" }, list: ["a"] }` → `{ "nav.plans": "Plans", "list.0": "a" }`. Non-string leaves are skipped. */
3628
+ function flattenMessages(messages, prefix = "") {
3629
+ const out = {};
3630
+ const walk = (value, path) => {
3631
+ if (typeof value === "string") out[path] = value;
3632
+ else if (Array.isArray(value)) value.forEach((item, index) => walk(item, path ? `${path}.${index}` : String(index)));
3633
+ else if (value && typeof value === "object") for (const [key, item] of Object.entries(value)) walk(item, path ? `${path}.${key}` : key);
3634
+ };
3635
+ walk(messages, prefix);
3636
+ return out;
3637
+ }
3638
+ /** The reverse of `flattenMessages`: a level whose keys are 0..n-1 becomes an array. */
3639
+ function unflattenMessages(flat) {
3640
+ const root = {};
3641
+ for (const [path, value] of Object.entries(flat)) {
3642
+ const parts = path.split(".");
3643
+ let node = root;
3644
+ parts.forEach((part, index) => {
3645
+ if (index === parts.length - 1) {
3646
+ node[part] = value;
3647
+ return;
3648
+ }
3649
+ if (!node[part] || typeof node[part] !== "object") node[part] = {};
3650
+ node = node[part];
3651
+ });
3652
+ }
3653
+ const arrays = (value) => {
3654
+ if (!value || typeof value !== "object") return value;
3655
+ const entries = Object.entries(value).map(([key, item]) => [key, arrays(item)]);
3656
+ const keys = entries.map(([key]) => key);
3657
+ if (keys.length > 0 && keys.every((key, index) => /^\d+$/.test(key)) && [...keys].map(Number).sort((a, b) => a - b).every((n, index) => n === index)) return [...entries].sort((a, b) => Number(a[0]) - Number(b[0])).map(([, item]) => item);
3658
+ return Object.fromEntries(entries);
3659
+ };
3660
+ return arrays(root);
3661
+ }
3662
+ /** How long `getMessages` reuses one read per locale. A save in the same process clears it at once. */
3663
+ const MESSAGES_CACHE_MS = 6e4;
3664
+ const cache = /* @__PURE__ */ new WeakMap();
3665
+ function invalidateMessages(payload) {
3666
+ cache.delete(payload);
3667
+ }
3668
+ /**
3669
+ * The interface text for `locale` as `next-intl` messages (nested JSON).
3670
+ * An empty translation reads as the default locale's text (Payload's
3671
+ * fallback), so a page never shows a blank. Cached per process for
3672
+ * `ttlMs` (60s by default): a request reads memory, and the database is
3673
+ * read only when the cache refreshes or after a save in the same process.
3674
+ *
3675
+ * ```ts
3676
+ * // src/i18n/request.ts
3677
+ * export default getRequestConfig(async ({ requestLocale }) => {
3678
+ * const locale = (await requestLocale) ?? "en";
3679
+ * return { locale, messages: await getMessages(await getPayload({ config }), locale) };
3680
+ * });
3681
+ * ```
3682
+ */
3683
+ function getMessages(payload, locale, options = {}) {
3684
+ const ttl = options.ttlMs ?? 6e4;
3685
+ const byLocale = cache.get(payload) ?? /* @__PURE__ */ new Map();
3686
+ cache.set(payload, byLocale);
3687
+ const hit = byLocale.get(locale);
3688
+ if (hit && Date.now() - hit.at < ttl) return hit.value;
3689
+ const value = (async () => {
3690
+ const doc = await payload.findGlobal({
3691
+ slug: INTERFACE_TEXT_SLUG,
3692
+ locale,
3693
+ depth: 0,
3694
+ overrideAccess: true
3695
+ });
3696
+ const flat = {};
3697
+ for (const row of doc.messages ?? []) if (row.key && typeof row.value === "string") flat[row.key] = row.value;
3698
+ return unflattenMessages(flat);
3699
+ })();
3700
+ byLocale.set(locale, {
3701
+ at: Date.now(),
3702
+ value
3703
+ });
3704
+ value.catch(() => byLocale.delete(locale));
3705
+ return value;
3706
+ }
3707
+ /** Publishing needs the Publish grant, as on Pages and the Header; Content alone saves drafts. */
3708
+ const refusePublishWithoutGrant = async ({ data, req }) => {
3709
+ if (data?._status !== "published" || !req.user) return data;
3710
+ if (await Promise.resolve(canPublish({ req }))) return data;
3711
+ throw new Forbidden();
3712
+ };
3713
+ const clearMessages = ({ doc, req }) => {
3714
+ invalidateMessages(req.payload);
3715
+ return doc;
3716
+ };
3717
+ /**
3718
+ * The Interface text Global: one row per message, key shared by every
3719
+ * locale, text localized. Drafts on, so a publish is what re-translates
3720
+ * changed English (the usual rules). The Content grant saves drafts; the
3721
+ * Publish grant publishes, as on Pages and the Header.
3722
+ */
3723
+ function interfaceTextGlobal() {
3724
+ return {
3725
+ slug: INTERFACE_TEXT_SLUG,
3726
+ label: "Interface text",
3727
+ admin: {
3728
+ group: "Content",
3729
+ description: "The words around the content: navigation, buttons, form labels and messages. Each row's key is what the site's code asks for; only the text is translated."
3730
+ },
3731
+ access: {
3732
+ read: ({ req }) => isAuthenticated(req.user),
3733
+ update: (args) => canUseFeature("content")(args)
3734
+ },
3735
+ versions: {
3736
+ drafts: true,
3737
+ max: 50
3738
+ },
3739
+ hooks: {
3740
+ beforeChange: [refusePublishWithoutGrant],
3741
+ afterChange: [clearMessages]
3742
+ },
3743
+ fields: [{
3744
+ name: "messages",
3745
+ type: "array",
3746
+ label: "Messages",
3747
+ labels: {
3748
+ singular: "Message",
3749
+ plural: "Messages"
3750
+ },
3751
+ dbName: "ui_messages",
3752
+ admin: { initCollapsed: true },
3753
+ validate: (value) => {
3754
+ const keys = (Array.isArray(value) ? value : []).map((row) => row?.key);
3755
+ const duplicate = keys.find((key, index) => key && keys.indexOf(key) !== index);
3756
+ return duplicate ? `The key "${duplicate}" is used twice.` : true;
3757
+ },
3758
+ fields: [{
3759
+ name: "key",
3760
+ type: "text",
3761
+ label: "Key",
3762
+ required: true,
3763
+ admin: { description: "What the code asks for, e.g. nav.plans. Do not change it unless the code changes." }
3764
+ }, {
3765
+ name: "value",
3766
+ type: "textarea",
3767
+ label: "Text",
3768
+ localized: true
3769
+ }]
3770
+ }]
3771
+ };
3772
+ }
3773
+ /**
3774
+ * The migration path from `messages/<locale>.json`: the source locale's
3775
+ * file sets the keys and fills blank English, every other file fills blank
3776
+ * text in its locale. Anything already in the CMS is kept, so running it
3777
+ * again (after an editor changed a string) overwrites nothing. It
3778
+ * publishes what it writes, so it refuses while the Global has an
3779
+ * unpublished draft: publishing on top would put that draft live. Writes with
3780
+ * `context: { autoTranslate: false }`, so importing translates nothing;
3781
+ * blank strings left over fill on the next publish or backfill.
3782
+ *
3783
+ * ```ts
3784
+ * import en from "../src/messages/en.json";
3785
+ * import es from "../src/messages/es.json";
3786
+ * await importMessages(payload, { en, es });
3787
+ * ```
3788
+ */
3789
+ async function importMessages(payload, files, options = {}) {
3790
+ const localization = payload.config.localization;
3791
+ const source = options.sourceLocale ?? (localization ? localization.defaultLocale : "en");
3792
+ const sourceFile = files[source];
3793
+ if (!sourceFile) throw new Error(`importMessages: no messages for the source locale "${source}"`);
3794
+ const result = {
3795
+ added: 0,
3796
+ filled: {},
3797
+ kept: {}
3798
+ };
3799
+ const read = async (locale) => (await payload.findGlobal({
3800
+ slug: "interface-text",
3801
+ locale,
3802
+ fallbackLocale: false,
3803
+ depth: 0,
3804
+ overrideAccess: true,
3805
+ draft: true
3806
+ })).messages ?? [];
3807
+ const write = async (locale, rows) => {
3808
+ await payload.updateGlobal({
3809
+ slug: INTERFACE_TEXT_SLUG,
3810
+ locale,
3811
+ data: {
3812
+ messages: rows,
3813
+ _status: "published"
3814
+ },
3815
+ depth: 0,
3816
+ overrideAccess: true,
3817
+ context: { autoTranslate: false }
3818
+ });
3819
+ };
3820
+ const blank = (value) => typeof value !== "string" || value.trim() === "";
3821
+ if ((await payload.findGlobal({
3822
+ slug: "interface-text",
3823
+ depth: 0,
3824
+ overrideAccess: true,
3825
+ draft: true
3826
+ }))?._status === "draft") throw new Error("importMessages: Interface text has an unpublished draft. Publish or discard it in the admin, then import again, so the import does not put that draft live.");
3827
+ const flatSource = flattenMessages(sourceFile);
3828
+ const rows = (await read(source)).map((row) => ({ ...row }));
3829
+ const byKey = new Map(rows.map((row) => [row.key, row]));
3830
+ result.filled[source] = 0;
3831
+ result.kept[source] = 0;
3832
+ for (const [key, value] of Object.entries(flatSource)) {
3833
+ const row = byKey.get(key);
3834
+ if (!row) {
3835
+ const added = {
3836
+ key,
3837
+ value
3838
+ };
3839
+ rows.push(added);
3840
+ byKey.set(key, added);
3841
+ result.added += 1;
3842
+ result.filled[source] += 1;
3843
+ } else if (blank(row.value)) {
3844
+ row.value = value;
3845
+ result.filled[source] += 1;
3846
+ } else result.kept[source] += 1;
3847
+ }
3848
+ await write(source, rows);
3849
+ const saved = await read(source);
3850
+ for (const [locale, file] of Object.entries(files)) {
3851
+ if (locale === source || !file) continue;
3852
+ const flat = flattenMessages(file);
3853
+ const current = new Map((await read(locale)).map((row) => [row.id, row.value]));
3854
+ result.filled[locale] = 0;
3855
+ result.kept[locale] = 0;
3856
+ await write(locale, saved.map((row) => {
3857
+ const existing = current.get(row.id);
3858
+ const incoming = row.key ? flat[row.key] : void 0;
3859
+ if (!blank(existing)) {
3860
+ if (incoming !== void 0) result.kept[locale] += 1;
3861
+ return {
3862
+ id: row.id,
3863
+ key: row.key,
3864
+ value: existing
3865
+ };
3866
+ }
3867
+ if (incoming !== void 0 && !blank(incoming)) {
3868
+ result.filled[locale] += 1;
3869
+ return {
3870
+ id: row.id,
3871
+ key: row.key,
3872
+ value: incoming
3873
+ };
3874
+ }
3875
+ return {
3876
+ id: row.id,
3877
+ key: row.key,
3878
+ value: existing ?? null
3879
+ };
3880
+ }));
3881
+ }
3882
+ return result;
3883
+ }
3884
+ //#endregion
2519
3885
  //#region src/translate/capability.ts
2520
3886
  /** True when any field, at any depth, is localized: the entity has copy to translate. */
2521
3887
  function hasLocalizedFields(fields, blocks = []) {
@@ -2614,7 +3980,12 @@ function applyTranslation(config, options = {}) {
2614
3980
  };
2615
3981
  const translatable = codes.length >= 2;
2616
3982
  const blocks = config.blocks ?? [];
2617
- const collections = (config.collections ?? []).map((collection) => {
3983
+ const hasCollection = (slug) => (config.collections ?? []).some((entry) => entry.slug === slug);
3984
+ const collections = [
3985
+ ...config.collections ?? [],
3986
+ ...hasCollection("translation-usage") ? [] : [translationUsageCollection()],
3987
+ ...hasCollection("translation-jobs") ? [] : [translationJobsCollection()]
3988
+ ].map((collection) => {
2618
3989
  const hint = entityHint(collection, options.hints);
2619
3990
  if (collection.slug in state.collections) {
2620
3991
  if (hint.context) state.collections[collection.slug] = hint;
@@ -2627,12 +3998,13 @@ function applyTranslation(config, options = {}) {
2627
3998
  const hasGlobal = (slug) => (config.globals ?? []).some((global) => global.slug === slug);
2628
3999
  const globals = [
2629
4000
  ...config.globals ?? [],
2630
- ...hasGlobal("translation-settings") ? [] : [translationSettingsGlobal({
4001
+ ...hasGlobal("translation-settings") ? [] : [withJobsOnSwitch(translationSettingsGlobal({
2631
4002
  site,
2632
4003
  targetLocales,
2633
4004
  defaultActive
2634
- })],
2635
- ...hasGlobal("translation-state") ? [] : [translationStateGlobal()]
4005
+ }))],
4006
+ ...hasGlobal("translation-state") ? [] : [translationStateGlobal()],
4007
+ ...hasGlobal("interface-text") ? [] : [interfaceTextGlobal()]
2636
4008
  ].map((global) => {
2637
4009
  const hint = entityHint(global, options.hints);
2638
4010
  if (global.slug in state.globals) {
@@ -2659,8 +4031,20 @@ function applyTranslation(config, options = {}) {
2659
4031
  ...endpoints,
2660
4032
  ...translationSettingsEndpoints(options.endpoints),
2661
4033
  translationAvailableEndpoint(),
2662
- activeLocalesEndpoint()
2663
- ]
4034
+ activeLocalesEndpoint(),
4035
+ ...translationJobEndpoints()
4036
+ ],
4037
+ onInit: hasEndpoints ? config.onInit : async (payload) => {
4038
+ await config.onInit?.(payload);
4039
+ resumeStaleJobs(payload).catch(() => void 0);
4040
+ },
4041
+ admin: hasEndpoints ? config.admin : {
4042
+ ...config.admin,
4043
+ components: {
4044
+ ...config.admin?.components,
4045
+ header: [...config.admin?.components?.header ?? [], TRANSLATION_STATUS_BAR]
4046
+ }
4047
+ }
2664
4048
  };
2665
4049
  }
2666
4050
  /** `applyTranslation` as a plugin, for a site that does not use `adminNav()`. */
@@ -2679,7 +4063,39 @@ function activeLocalesEndpoint() {
2679
4063
  handler: async (req) => Response.json(await activeLocales(req.payload), { headers: { "Cache-Control": "public, max-age=60, s-maxage=60" } })
2680
4064
  };
2681
4065
  }
4066
+ /**
4067
+ * Switching translation on starts the backfill (unless a paused job waits
4068
+ * to be resumed); switching it off pauses running jobs after their current
4069
+ * document. Both run once the save has committed.
4070
+ */
4071
+ function withJobsOnSwitch(global) {
4072
+ const onSwitch = ({ doc, previousDoc, req }) => {
4073
+ const was = previousDoc?.enabled === true;
4074
+ const now = doc?.enabled === true;
4075
+ if (was === now) return doc;
4076
+ const user = req.user;
4077
+ const from = {
4078
+ url: req.url,
4079
+ headers: req.headers
4080
+ };
4081
+ runAfterCommit(req, "translation-settings", async () => {
4082
+ if (now) await startBackfill(req.payload, {
4083
+ user,
4084
+ req: from
4085
+ });
4086
+ else await pauseRunningJobs(req.payload);
4087
+ });
4088
+ return doc;
4089
+ };
4090
+ return {
4091
+ ...global,
4092
+ hooks: {
4093
+ ...global.hooks,
4094
+ afterChange: [...global.hooks?.afterChange ?? [], onSwitch]
4095
+ }
4096
+ };
4097
+ }
2682
4098
  //#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 };
4099
+ export { LIBRARY_DEFAULT_LOCALE as $, seedRoleRows as $t, TRANSLATE_NOW as A, isAuthenticated as At, TRANSLATION_STATUS_BAR as B, LAST_USERS_TICK_MESSAGE as Bt, isAutosave as C, PACKAGE_FEATURES as Cn, getRolesMatrix as Ct, shouldSkipUndraftedTranslation as D, isLockedFeature as Dn, hideUnlessDeveloper as Dt, shouldSkipDraftedTranslation as E, isFeatureSlug as En, hasRole as Et, TRANSLATION_ACTIVITY_PANEL as F, DEFAULT_ROLE_MATRIX as Ft, FAILURE_ADVICE as G, applyRoleSlugsFromNames as Gt, readTranslationSettings as H, ROLES_FIELD_DESCRIPTION as Ht, TRANSLATION_GRANT as I, DEVELOPER_DESCRIPTION as It, monthKey as J, normalizeStoredRoles as Jt, RATE_LIMIT_STREAK as K, defaultRolesFieldValue as Kt, TRANSLATION_KEY_PANEL as L, DUPLICATE_ROLE_NAME_MESSAGE as Lt, BISON_TRANSLATION_CONTEXT as M, isDeveloperTab as Mt, readTranslateState as N, isPrivilegedRole as Nt, TRANSACTION_TIMEOUT_MS as O, isPackageFeatureSlug as On, isAdmin as Ot, withTranslator as P, storedRoles as Pt, ACTIVE_LOCALES_CACHE_MS as Q, roleSelectOptions as Qt, TRANSLATION_SETTINGS_SLUG as R, DUPLICATE_ROLE_SLUG_MESSAGE as Rt, startJob as S, FEATURE_GROUP_LABELS as Sn, developerOnlyAccess as St, localizedCopyUnchanged as T, isFeatureGroupId as Tn, hasGrant as Tt, resolveModel as U, ROLES_GLOBAL_DESCRIPTION as Ut, invalidateTranslationSettings as V, MISSING_SEED_ROLES_MESSAGE as Vt, siteFromInstructions as W, ROLES_SLUG as Wt, usageHistory as X, resetRolesMatrix as Xt, recordUsage as Y, parseRolesMatrix as Yt, usageThisMonth as Z, roleDescription as Zt, frozenWordForce as _, roleLabel as _n, hideUnlessFeature as _t, MESSAGES_CACHE_MS as a, parseFeaturesMatrix as an, invalidateActiveLocales as at, runJobSlice as b, FEATURES_SLUG as bn, canManageContent as bt, importMessages as c, CAPABILITIES as cn, encryptApiKey as ct, unflattenMessages as d, ROLES as dn, sameRow as dt, validateRolesMatrix as en, LIBRARY_LOCALES as et, translationSettingsEndpoints as f, ROLE_LABELS as fn, translationJob as ft, estimateJob as g, isRoleSlug as gn, hasFeature as gt, claimJob as h, isRoleName as hn, getFeaturesMatrix as ht, INTERFACE_TEXT_SLUG as i, featureGroupLabel as in, inactiveLocaleRedirect as it, translateDocument as j, isDeveloper as jt, runAfterCommit as k, isAdminOrSelf as kt, interfaceTextGlobal as l, CAPABILITY_FEATURES as ln, resolveApiKey as lt, TRANSLATION_JOBS_SLUG as m, isRole as mn, canUseFeature as mt, hasLocalizedFields as n, defaultFeaturesFieldValue as nn, activeAlternates as nt, flattenMessages as o, stampFeatureCatalogue as on, withLibraryLocales as ot, LEASE_MS as p, THEME_FEATURE_SLUGS as pn, allowedFeaturesForUser as pt, TRANSLATION_USAGE_SLUG as q, grantsFromStoredRole as qt, translation as r, featureCatalogue as rn, activeLocales as rt, getMessages as s, validateFeaturesMatrix as sn, decryptApiKey as st, applyTranslation as t, MISSING_PACKAGE_FEATURES_MESSAGE as tn, LIBRARY_LOCALE_CODES as tt, invalidateMessages as u, DEFAULT_ROLE_GRANTS as un, collectLocalizedStrings as ut, jobView as v, sanitizeRoleNameInput as vn, authenticatedOrPublished as vt, draftedTranslationDecision as w, PACKAGE_FEATURE_SLUGS as wn, hasCapability as wt, startBackfill as x, FEATURE_GROUPS as xn, canPublish as xt, resumeStaleJobs as y, slugifyRoleName as yn, canManageBrand as yt, TRANSLATION_STATE_SLUG as z, INVALID_ROLE_NAME_MESSAGE as zt };
2684
4100
 
2685
- //# sourceMappingURL=capability-DHPE2kon.mjs.map
4101
+ //# sourceMappingURL=capability-CAXtTcSU.mjs.map