@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
@@ -1 +1 @@
1
- {"version":3,"file":"translate.mjs","names":[],"sources":["../src/translate/fields.ts","../src/translate/state.ts","../src/translate/document.ts","../src/translate/endpoint.ts","../src/translate/after-commit.ts","../src/translate/guards.ts","../src/translate/hooks.ts","../src/translate/plugin.ts"],"sourcesContent":["import type { Block, Field } from \"payload\";\n\nimport type { Doc } from \"./types\";\n\n/**\n * Which strings in a document are copy, read off the field config rather\n * than a list of key names. ZoomFiber's first version kept a hand list\n * (`LOCALIZED_KEYS`), which silently missed every field a shared block\n * added later (`description`, `summary`, `quote`, `caption`, `content`).\n * Walking the config cannot miss one: a `text` or `textarea` that is\n * `localized` (or sits inside a localized container) is copy, and so is\n * every Lexical text node inside a localized `richText`. Everything else\n * (links, selects, uploads, block settings) is carried as it is.\n *\n * Hidden fields are skipped: they are derived values a hook writes\n * (`answerText` is `answer` flattened for search), not copy an editor\n * sees, and their hook rewrites them from the translated source.\n */\n\n/** The parts of a field config the walk reads. Structural, so sanitized and raw configs both fit. */\ninterface WalkField {\n type: string;\n name?: string;\n localized?: boolean;\n hasMany?: boolean;\n hidden?: boolean;\n admin?: { hidden?: unknown } | null;\n fields?: WalkField[];\n tabs?: Array<{ name?: string; localized?: boolean; fields: WalkField[] }>;\n blocks?: WalkBlock[];\n blockReferences?: Array<string | WalkBlock>;\n}\n\ninterface WalkBlock {\n slug: string;\n fields: WalkField[];\n}\n\n/** Field configs plus the config-level blocks a `blockReferences` field points at. */\nexport interface FieldSchema {\n fields: readonly Field[];\n /** `config.blocks`, for blocks fields that use `blockReferences`. */\n blocks?: readonly Block[];\n}\n\nconst isDoc = (value: unknown): value is Doc => value !== null && typeof value === \"object\" && !Array.isArray(value);\n\nconst asRows = (value: unknown): Doc[] | undefined =>\n Array.isArray(value) ? (value.filter(isDoc) as Doc[]) : undefined;\n\n/** A string with something in it. Blank and whitespace-only strings are not copy to translate. */\nexport const filled = (value: unknown): value is string => typeof value === \"string\" && value.trim() !== \"\";\n\nfunction isHidden(field: WalkField): boolean {\n return field.hidden === true || field.admin?.hidden === true;\n}\n\nfunction blocksOf(field: WalkField, configBlocks: readonly WalkBlock[] | undefined): WalkBlock[] {\n const own = field.blocks ?? [];\n const referenced = (field.blockReferences ?? []).flatMap((ref) => {\n if (typeof ref !== \"string\") return [ref];\n const found = configBlocks?.find((block) => block.slug === ref);\n return found ? [found] : [];\n });\n return [...own, ...referenced];\n}\n\n/**\n * The row of `rows` that is the same row as `row`, where the two lists are\n * one Payload array read twice (in two locales, or before and after a\n * save): by id when the row has one, else by position.\n *\n * Payload gives every stored array row an id and keeps it across locales, so\n * a row with an id is matched by it and by nothing else: a row that has an id\n * and no partner has no partner, whatever sits at its position. Position is\n * for rows that have no id yet (a row not saved, a fixture), and for rows of\n * a localized array, whose ids differ per locale.\n */\nexport function sameRow(\n rows: readonly Doc[] | undefined,\n row: Doc,\n index: number,\n byPosition = false,\n): Doc | undefined {\n if (!rows) return undefined;\n if (byPosition) return rows[index];\n const id = row.id;\n return typeof id === \"string\" || typeof id === \"number\" ? rows.find((other) => other.id === id) : rows[index];\n}\n\n// ---------------------------------------------------------------------------\n// Lexical\n\ninterface TextNodeRef {\n path: string;\n node: Doc;\n}\n\n/** Every Lexical text node in document order, with its child-index path. */\nfunction textNodes(state: unknown): TextNodeRef[] | null {\n if (!isDoc(state) || !isDoc(state.root)) return null;\n const out: TextNodeRef[] = [];\n const visit = (node: Doc, path: string) => {\n if (node.type === \"text\" && typeof node.text === \"string\") out.push({ path, node });\n const children = node.children;\n if (Array.isArray(children)) {\n children.forEach((child, index) => {\n if (isDoc(child)) visit(child, `${path}.${index}`);\n });\n }\n };\n visit(state.root, \"root\");\n return out;\n}\n\nconst sameShape = (a: TextNodeRef[] | null, b: TextNodeRef[] | null): boolean =>\n a !== null && b !== null && a.length === b.length && a.every((ref, i) => ref.path === b[i]!.path);\n\nconst sameText = (a: TextNodeRef[] | null, b: TextNodeRef[] | null): boolean =>\n sameShape(a, b) && a!.every((ref, i) => ref.node.text === b![i]!.node.text);\n\n// ---------------------------------------------------------------------------\n// Collect: the copy of one document, for the no-op guard\n\n/**\n * Every localized string in `doc`, each prefixed with its path, in config\n * order. Two reads of a document compare equal exactly when no copy\n * changed; the path keeps a string moved from one field to another from\n * reading as unchanged.\n */\nexport function collectLocalizedStrings(schema: FieldSchema, doc: unknown): string[] {\n const out: string[] = [];\n if (isDoc(doc)) {\n collectFields(\n schema.fields as unknown as WalkField[],\n doc,\n \"\",\n false,\n schema.blocks as unknown as WalkBlock[],\n out,\n );\n }\n return out;\n}\n\nfunction collectFields(\n fields: WalkField[],\n value: Doc,\n prefix: string,\n inLocalized: boolean,\n configBlocks: WalkBlock[] | undefined,\n out: string[],\n): void {\n for (const field of fields) {\n if (isHidden(field)) continue;\n const localized = inLocalized || field.localized === true;\n const path = field.name ? `${prefix}${field.name}` : prefix;\n switch (field.type) {\n case \"tabs\":\n for (const tab of field.tabs ?? []) {\n if (tab.name) {\n const nested = value[tab.name];\n if (isDoc(nested)) {\n collectFields(\n tab.fields,\n nested,\n `${prefix}${tab.name}.`,\n inLocalized || tab.localized === true,\n configBlocks,\n out,\n );\n }\n } else {\n collectFields(tab.fields, value, prefix, inLocalized, configBlocks, out);\n }\n }\n break;\n case \"row\":\n case \"collapsible\":\n collectFields(field.fields ?? [], value, prefix, inLocalized, configBlocks, out);\n break;\n case \"group\":\n if (!field.name) {\n collectFields(field.fields ?? [], value, prefix, inLocalized, configBlocks, out);\n } else if (isDoc(value[field.name])) {\n collectFields(field.fields ?? [], value[field.name] as Doc, `${path}.`, localized, configBlocks, out);\n }\n break;\n case \"array\":\n if (!field.name) break;\n (asRows(value[field.name]) ?? []).forEach((row, index) => {\n const key = typeof row.id === \"string\" && !localized ? row.id : String(index);\n collectFields(field.fields ?? [], row, `${path}.${key}.`, localized, configBlocks, out);\n });\n break;\n case \"blocks\": {\n if (!field.name) break;\n const blocks = blocksOf(field, configBlocks);\n (asRows(value[field.name]) ?? []).forEach((row, index) => {\n const block = blocks.find((candidate) => candidate.slug === row.blockType);\n if (!block) return;\n const key = typeof row.id === \"string\" && !localized ? row.id : String(index);\n collectFields(block.fields, row, `${path}.${key}.`, localized, configBlocks, out);\n });\n break;\n }\n case \"text\":\n case \"textarea\":\n if (localized && field.name && !field.hasMany && filled(value[field.name])) {\n out.push(`${path}=${value[field.name] as string}`);\n }\n break;\n case \"richText\":\n if (localized && field.name) {\n for (const ref of textNodes(value[field.name]) ?? []) {\n if (filled(ref.node.text)) out.push(`${path}:${ref.path}=${ref.node.text as string}`);\n }\n }\n break;\n default:\n break;\n }\n }\n}\n\n// ---------------------------------------------------------------------------\n// Plan: what to translate in one target locale, and the write that lands it\n\n/** The strings to translate for one target locale, and the write that lands them. */\nexport interface TranslationJob {\n /** Source-locale strings to translate, in order. May repeat; `translateStrings` dedupes. */\n sources: string[];\n /** The target-locale `data` for an update, given the translations of `sources` in the same order. */\n patch: (translated: readonly string[]) => Doc;\n}\n\ninterface PlanContext {\n overwrite: boolean;\n /** An earlier source exists to compare with. Without one, filled target copy stands. */\n hasPrevious: boolean;\n configBlocks: WalkBlock[] | undefined;\n sources: string[];\n setters: Array<(value: string) => void>;\n}\n\n/**\n * The per-string rule, the one every write follows. A string is translated\n * when its source is filled and its target is blank, or its source changed\n * since `previous`, or the call says `overwrite`. Everything else keeps the\n * target it already has, so a string a person corrected by hand in the\n * target locale survives every later publish that does not touch its\n * source.\n */\nfunction wants(ctx: PlanContext, source: unknown, existing: unknown, before: unknown): source is string {\n if (!filled(source)) return false;\n if (ctx.overwrite || !filled(existing)) return true;\n // No earlier source to compare with (the button without overwrite, a\n // first publish): filled target copy stands.\n return ctx.hasPrevious && source !== before;\n}\n\nfunction enqueue(ctx: PlanContext, source: string, set: (value: string) => void): void {\n ctx.sources.push(source);\n ctx.setters.push(set);\n}\n\n/**\n * What to translate in one target locale, or `null` when the target is\n * already in step with the source.\n *\n * - `source`: the document in the source locale, read at depth 0 so\n * uploads are ids and array rows carry their real ids.\n * - `target`: the document in the target locale, read with\n * `fallbackLocale: false`. With fallback on, a blank target reads as the\n * source, looks \"already translated\", and nothing is ever written.\n * - `previous`: the source as it was before this change (the last\n * published version, or the hook's `previousDoc` on a collection without\n * drafts). `null` or omitted: there is none.\n *\n * The write carries only the top-level fields that hold a translated\n * string. Inside them it is built from the source's structure (so\n * non-localized values such as links and images are kept, and each array\n * row keeps the source row's id, which is how Payload lands the target copy\n * on the right row), with every localized string set to its translation or\n * to the target copy it already had.\n */\nexport function translationJob(input: {\n schema: FieldSchema;\n source: Doc;\n target?: Doc | null;\n previous?: Doc | null;\n overwrite?: boolean;\n}): TranslationJob | null {\n const ctx: PlanContext = {\n overwrite: input.overwrite === true,\n hasPrevious: input.previous != null,\n configBlocks: input.schema.blocks as unknown as WalkBlock[] | undefined,\n sources: [],\n setters: [],\n };\n const out: Doc = {};\n const touched = planFields(\n input.schema.fields as unknown as WalkField[],\n input.source,\n input.target ?? undefined,\n input.previous ?? undefined,\n out,\n ctx,\n false,\n );\n if (ctx.sources.length === 0) return null;\n return {\n sources: ctx.sources,\n patch: (translated) => {\n translated.forEach((value, index) => ctx.setters[index]?.(value));\n const data: Doc = {};\n for (const name of touched) data[name] = out[name];\n return data;\n },\n };\n}\n\n/**\n * Walks `fields` over one level of the source, writing into `out` (which\n * starts as a copy of the source level) and returning the names at this\n * level that hold a string being translated.\n */\nfunction planFields(\n fields: WalkField[],\n source: Doc,\n target: Doc | undefined,\n previous: Doc | undefined,\n out: Doc,\n ctx: PlanContext,\n inLocalized: boolean,\n): Set<string> {\n const touched = new Set<string>();\n const nested = (name: string, subFields: WalkField[], localized: boolean) => {\n const value = source[name];\n if (!isDoc(value)) return;\n const copy: Doc = { ...value };\n const prevValue = previous?.[name];\n const targetValue = target?.[name];\n const inner = planFields(\n subFields,\n value,\n isDoc(targetValue) ? targetValue : undefined,\n isDoc(prevValue) ? prevValue : undefined,\n copy,\n ctx,\n localized,\n );\n out[name] = copy;\n if (inner.size > 0) touched.add(name);\n };\n\n for (const field of fields) {\n if (isHidden(field)) continue;\n const localized = inLocalized || field.localized === true;\n switch (field.type) {\n case \"tabs\":\n for (const tab of field.tabs ?? []) {\n if (tab.name) nested(tab.name, tab.fields, inLocalized || tab.localized === true);\n else\n for (const name of planFields(tab.fields, source, target, previous, out, ctx, inLocalized))\n touched.add(name);\n }\n break;\n case \"row\":\n case \"collapsible\":\n for (const name of planFields(field.fields ?? [], source, target, previous, out, ctx, inLocalized)) {\n touched.add(name);\n }\n break;\n case \"group\":\n if (field.name) nested(field.name, field.fields ?? [], localized);\n else\n for (const name of planFields(field.fields ?? [], source, target, previous, out, ctx, inLocalized))\n touched.add(name);\n break;\n case \"array\":\n case \"blocks\": {\n if (!field.name) break;\n const rows = asRows(source[field.name]);\n if (!rows) break;\n const targetRows = asRows(target?.[field.name]);\n const previousRows = asRows(previous?.[field.name]);\n const blocks = field.type === \"blocks\" ? blocksOf(field, ctx.configBlocks) : [];\n let any = false;\n out[field.name] = rows.map((row, index) => {\n const rowFields =\n field.type === \"blocks\" ? blocks.find((block) => block.slug === row.blockType)?.fields : field.fields;\n const copy: Doc = { ...row };\n // A localized array keeps separate rows (and ids) per locale: its\n // target rows pair by position, and the write leaves ids to Payload.\n if (localized) delete copy.id;\n if (!rowFields) return copy;\n const inner = planFields(\n rowFields,\n row,\n sameRow(targetRows, row, index, localized),\n sameRow(previousRows, row, index),\n copy,\n ctx,\n localized,\n );\n if (inner.size > 0) any = true;\n return copy;\n });\n if (any) touched.add(field.name);\n break;\n }\n case \"text\":\n case \"textarea\": {\n if (!localized || !field.name || field.hasMany) break;\n const name = field.name;\n const value = source[name];\n const existing = target?.[name];\n if (wants(ctx, value, existing, previous?.[name])) {\n enqueue(ctx, value, (translated) => (out[name] = translated));\n out[name] = value;\n touched.add(name);\n } else {\n out[name] = filled(existing) ? existing : value;\n }\n break;\n }\n case \"richText\": {\n if (!localized || !field.name) break;\n const name = field.name;\n const result = planRichText(ctx, source[name], target?.[name], previous?.[name]);\n out[name] = result.value;\n if (result.touched) touched.add(name);\n break;\n }\n default:\n break;\n }\n }\n return touched;\n}\n\n/**\n * Rich text is translated per Lexical text node (sentence context across\n * formatting runs is out of scope). When the target tree has the same\n * shape as the source, each node follows the per-string rule. When a\n * person restructured the target (split a run to bold a word), node paths\n * no longer pair: the field is then kept whole unless its source changed,\n * in which case it is rebuilt from the source and every node translated.\n */\nfunction planRichText(\n ctx: PlanContext,\n source: unknown,\n target: unknown,\n previous: unknown,\n): { value: unknown; touched: boolean } {\n const sourceNodes = textNodes(source);\n if (!sourceNodes || !sourceNodes.some((ref) => filled(ref.node.text))) {\n return { value: target ?? source, touched: false };\n }\n const targetNodes = textNodes(target);\n const previousNodes = textNodes(previous);\n const clone = structuredClone(source) as Doc;\n const cloneNodes = textNodes(clone)!;\n let touched = false;\n\n if (sameShape(sourceNodes, targetNodes)) {\n const previousPairs = sameShape(sourceNodes, previousNodes);\n sourceNodes.forEach((ref, index) => {\n const node = cloneNodes[index]!.node;\n const existing = targetNodes![index]!.node.text;\n const before = previousPairs ? previousNodes![index]!.node.text : undefined;\n if (wants(ctx, ref.node.text, existing, before)) {\n enqueue(ctx, ref.node.text, (translated) => (node.text = translated));\n touched = true;\n } else if (filled(existing)) {\n node.text = existing;\n }\n });\n return { value: clone, touched };\n }\n\n const targetFilled = targetNodes?.some((ref) => filled(ref.node.text)) ?? false;\n const changed = ctx.overwrite || !targetFilled || (ctx.hasPrevious && !sameText(sourceNodes, previousNodes));\n if (!changed) return { value: target, touched: false };\n sourceNodes.forEach((ref, index) => {\n if (!filled(ref.node.text)) return;\n const node = cloneNodes[index]!.node;\n enqueue(ctx, ref.node.text, (translated) => (node.text = translated));\n touched = true;\n });\n return { value: clone, touched };\n}\n","import type { Config, Payload, SanitizedConfig } from \"payload\";\n\nimport type { Doc, TranslateSite, Translator } from \"./types\";\n\n/**\n * Where an enabled plugin leaves its options for `translateDocument` and the\n * endpoint to find. Root `config.custom` is server-only in Payload, so the\n * translator never reaches the admin bundle.\n */\nexport const AUTO_TRANSLATE_STATE = \"bisonAutoTranslate\";\n\nexport interface AutoTranslateState {\n translator: Translator;\n site?: TranslateSite;\n waitUntil?: (promise: Promise<unknown>) => void;\n sourceLocale: string;\n targetLocales: string[];\n /** Per collection slug, its prompt hint builder. */\n collections: Record<string, { context?: (doc: Doc) => string }>;\n /** Per global slug, its prompt hint builder. */\n globals: Record<string, { context?: (doc: Doc) => string }>;\n}\n\nexport function readState(config: Config | SanitizedConfig | Payload[\"config\"]): AutoTranslateState | undefined {\n const custom = config.custom as Record<string, unknown> | undefined;\n return custom?.[AUTO_TRANSLATE_STATE] as AutoTranslateState | undefined;\n}\n\n/**\n * The test seam: the plugin's state (translator, site, locales, listed\n * collections and globals) on a config that went through `autoTranslate`,\n * or `undefined` when the plugin is off or was not applied. Read it instead\n * of reaching into `config.custom` by key.\n */\nexport function readTranslateState(\n config: Config | SanitizedConfig | Payload[\"config\"],\n): Readonly<AutoTranslateState> | undefined {\n return readState(config);\n}\n\n/**\n * The test seam: a copy of `config` whose plugin uses `translator` (a fake in\n * a test) in place of the one it was registered with. The input is not\n * changed. Throws when the config did not go through an enabled\n * `autoTranslate`, so a test cannot silently translate nothing.\n */\nexport function withTranslator<T extends Config | SanitizedConfig>(config: T, translator: Translator): T {\n const state = readState(config);\n if (!state) throw new Error(\"withTranslator: the config has no autoTranslate state; is the plugin enabled?\");\n return {\n ...config,\n custom: { ...(config.custom as Record<string, unknown>), [AUTO_TRANSLATE_STATE]: { ...state, translator } },\n };\n}\n\n/** The locale codes of a localization config, in order. */\nexport function localeCodes(localization: Config[\"localization\"]): string[] {\n if (!localization) return [];\n return localization.locales.map((locale) => (typeof locale === \"string\" ? locale : locale.code));\n}\n","import type { Payload, PayloadRequest } from \"payload\";\n\nimport { translationJob, type FieldSchema } from \"./fields\";\nimport { localeCodes, readState } from \"./state\";\nimport { translateStrings } from \"./strings\";\nimport type { Doc, TranslateLocaleResult, TranslateSite, Translator } from \"./types\";\n\nexport type TranslateDocumentOptions = ({ collection: string; id: number | string } | { global: string }) & {\n /** Target locale or locales. Omitted: every locale but the default. */\n locale?: string | readonly string[];\n /** Re-translate every filled source string, replacing target copy a person may have corrected. */\n overwrite?: boolean;\n /**\n * The source copy before the change being translated: the last published\n * version, or the previous document on a collection without drafts. A\n * source string that differs from it is re-translated. Omitted: there is\n * nothing to compare with, so only blank target strings are filled.\n */\n previous?: Doc | null;\n /** Defaults to the translator the enabled `autoTranslate` plugin registered. */\n translator?: Translator;\n /** The prompt hint; defaults to the plugin's `context` for the slug, else the slug and the title. */\n context?: string;\n /** Defaults to the plugin's `site`. */\n site?: TranslateSite;\n /**\n * Pass only while the caller's transaction is still open (a seed inside its\n * own transaction): the reads and writes then join it instead of opening a\n * new one, which would deadlock against the outer operation's row locks.\n * The plugin's hooks pass nothing, because they run past their commit.\n */\n req?: PayloadRequest;\n /**\n * Write as this person: the target-locale write runs with\n * `overrideAccess: false`, so the collection's `access.update` and every\n * hook see them in `req.user`, and a refusal throws. Omitted: a server\n * write, as the publish hook and scripts do. Opens its own transaction\n * (it is not a `req`), so it is safe past a commit. On a collection with\n * drafts, a document whose latest version is a draft is read and written\n * as that draft (`draft: true`); one whose latest is published is\n * written as a normal update. With or without a user, a target is never\n * written live over a draft that is the latest version when the write\n * happens: it goes into that draft instead (see the write).\n */\n user?: PayloadRequest[\"user\"];\n};\n\nfunction schemaFor(payload: Payload, options: TranslateDocumentOptions): FieldSchema & { useAsTitle?: string } {\n if (\"collection\" in options) {\n const collection = payload.collections[options.collection as never] as\n | { config: { fields: FieldSchema[\"fields\"]; admin?: { useAsTitle?: string } } }\n | undefined;\n if (!collection) throw new Error(`translateDocument: no collection \"${options.collection}\"`);\n return {\n fields: collection.config.fields,\n blocks: payload.config.blocks,\n useAsTitle: collection.config.admin?.useAsTitle,\n };\n }\n const global = payload.config.globals.find((candidate) => candidate.slug === options.global);\n if (!global) throw new Error(`translateDocument: no global \"${options.global}\"`);\n return { fields: global.fields, blocks: payload.config.blocks };\n}\n\n/** How many times a write is planned again because the source changed during the model call. */\nconst REPLANS = 2;\n\nfunction defaultContext(slug: string, doc: Doc, useAsTitle: string | undefined): string {\n const meta = doc.meta as { title?: unknown } | undefined;\n const title = [useAsTitle ? doc[useAsTitle] : undefined, meta?.title, doc.title, doc.name].find(\n (value): value is string => typeof value === \"string\" && value.trim() !== \"\",\n );\n return title ? `${slug}: ${title}` : slug;\n}\n\n/**\n * Brings one document's target locales in step with its source locale (the\n * config's default locale), string by string: blank target strings are\n * filled, source strings that changed since `previous` are re-translated,\n * and with `overwrite` every filled string is. Anything else keeps the\n * target copy a person may have corrected.\n *\n * Reads the source at depth 0 (uploads as ids, array rows with their real\n * ids) and each target with `fallbackLocale: false`, sends one batch per\n * target locale, and writes the target with `context: { autoTranslate:\n * false }` so the write cannot start another round.\n *\n * Returns one result per target locale. A translator failure is a `failed`\n * result and leaves that locale as it was; it only throws on Payload errors\n * or a misconfiguration (no localization, no translator, unknown slug).\n */\nexport async function translateDocument(\n payload: Payload,\n options: TranslateDocumentOptions,\n): Promise<TranslateLocaleResult[]> {\n const localization = payload.config.localization;\n if (!localization) throw new Error(\"translateDocument: the Payload config has no localization\");\n const state = readState(payload.config);\n const translator = options.translator ?? state?.translator;\n if (!translator) {\n throw new Error(\"translateDocument: no translator; register autoTranslate({ enabled: true }) or pass one\");\n }\n const sourceLocale = localization.defaultLocale;\n const codes = localeCodes(localization);\n const targets =\n options.locale === undefined\n ? codes.filter((code) => code !== sourceLocale)\n : typeof options.locale === \"string\"\n ? [options.locale]\n : [...options.locale];\n for (const locale of targets) {\n if (locale === sourceLocale || !codes.includes(locale)) {\n throw new Error(`translateDocument: \"${locale}\" is not a target locale`);\n }\n }\n\n const schema = schemaFor(payload, options);\n const { req, user } = options;\n // Reads stay server-side: the source copy is needed whatever the caller may\n // see. Only the write is judged as the caller.\n const writeAs = user ? { user, overrideAccess: false } : { overrideAccess: true };\n // A caller on a drafts collection works on the document's latest version, the\n // one the editor sees. When that is a draft, source and target are read from\n // it and the target is written as a draft (`draft: true` saves a new draft\n // version and never touches `_status` or the live copy), which is the only\n // write a site may let a non-publisher make. When the latest is published\n // the write is an ordinary update, so a publisher's button still refreshes\n // the live copy and a site can refuse everyone else. The server path (no\n // user) reads the published document; how each write lands is decided\n // again just before it (`writeLatest` below).\n const versions =\n \"collection\" in options\n ? (payload.collections[options.collection as never] as { config: { versions?: unknown } } | undefined)?.config\n .versions\n : payload.config.globals.find((candidate) => candidate.slug === options.global)?.versions;\n const hasDrafts = Boolean(versions && typeof versions === \"object\" && (versions as { drafts?: unknown }).drafts);\n const drafted = user !== undefined && user !== null && \"collection\" in options && hasDrafts;\n let draftMode = false;\n if (drafted && \"collection\" in options) {\n const latest = (await payload.findByID({\n collection: options.collection as never,\n id: options.id,\n locale: sourceLocale,\n draft: true,\n depth: 0,\n overrideAccess: true,\n req,\n })) as unknown as Doc;\n draftMode = latest._status === \"draft\";\n }\n const read = async (locale: string, opts: { draft: boolean; fallbackLocale?: false }): Promise<Doc> =>\n (\"collection\" in options\n ? await payload.findByID({\n collection: options.collection as never,\n id: options.id,\n locale,\n ...(opts.draft ? { draft: true } : {}),\n ...(opts.fallbackLocale === false ? { fallbackLocale: false } : {}),\n depth: 0,\n overrideAccess: true,\n req,\n })\n : await payload.findGlobal({\n slug: options.global as never,\n locale,\n ...(opts.draft ? { draft: true } : {}),\n ...(opts.fallbackLocale === false ? { fallbackLocale: false } : {}),\n depth: 0,\n overrideAccess: true,\n req,\n })) as unknown as Doc;\n\n const source = await read(sourceLocale, { draft: draftMode });\n const slug = \"collection\" in options ? options.collection : options.global;\n const label = \"collection\" in options ? `${slug}/${String(options.id)}` : `globals/${slug}`;\n const configured = \"collection\" in options ? state?.collections[slug] : state?.globals[slug];\n const context = options.context ?? configured?.context?.(source) ?? defaultContext(slug, source, schema.useAsTitle);\n const site = options.site ?? state?.site;\n const plan = (from: Doc, target: Doc) =>\n translationJob({ schema, source: from, target, previous: options.previous, overwrite: options.overwrite });\n\n const results: TranslateLocaleResult[] = [];\n for (const locale of targets) {\n const first = plan(source, await read(locale, { draft: draftMode, fallbackLocale: false }));\n if (!first) {\n results.push({ locale, status: \"nothing\", count: 0 });\n continue;\n }\n // Translations by source string, so a re-plan only sends what is new.\n const known = new Map<string, string>();\n const translate = async (strings: string[]): Promise<boolean> => {\n const translated = await translateStrings(strings, {\n translator,\n from: sourceLocale,\n to: locale,\n context,\n ...(site ? { site } : {}),\n });\n if (!translated) return false;\n strings.forEach((value, index) => known.set(value, translated[index]!));\n return true;\n };\n if (!(await translate(first.sources))) {\n results.push({ locale, status: \"failed\", count: 0 });\n continue;\n }\n results.push(await writeLatest(locale));\n\n /**\n * Plans the write again from the latest version as it is now, then\n * writes it. The model call takes seconds (up to 90s plus a retry), and\n * the document may have moved on meanwhile, in two ways that matter.\n *\n * 1. Payload's update merges into the latest version row\n * (`getLatestCollectionVersion` / `getLatestGlobalVersion`), draft or\n * not: `beforeValidate` fills every field the write omits from it and\n * `beforeChange` fills every localized field's other locales from it,\n * and a non-draft update writes that to the live row and saves it as\n * a version. So a live write after an autosave would publish the\n * draft's copy with no Publish click. A newer draft is therefore\n * written as a draft (`draft: true` leaves the live row and `_status`\n * alone), and its target reaches the site with the next publish. A\n * caller already on a draft stays on drafts even if the latest was\n * published meanwhile, so the button never escalates to a live write.\n * 2. The write carries whole top-level fields built from the planned\n * source's structure (`translationJob`), and a non-localized array or\n * blocks field (`layout`, `hero`) is one row list for every locale. A\n * patch planned from an older version would replace the newer row\n * list: rows the editor added dropped, removed ones restored, links\n * and images reverted. So the job is planned again from the latest\n * source and target, with the same `previous`, which keeps the\n * per-string rule: strings changed since the last publish translate,\n * filled target copy whose source did not change stays.\n *\n * Strings the re-plan meets for the first time go to the model, and the\n * latest version is read again after that call, up to `REPLANS` times.\n * What is left is the gap between the last read and Payload's own read\n * inside the update: milliseconds, against the seconds to minutes of a\n * model call. Closing it would need a row lock Payload's update does not\n * take, so a save landing in exactly that gap can still be overwritten.\n */\n async function writeLatest(locale: string): Promise<TranslateLocaleResult> {\n for (let round = 0; ; round++) {\n const latest = await read(sourceLocale, { draft: hasDrafts || draftMode });\n const writeDraft = draftMode || (hasDrafts && latest._status === \"draft\");\n const job = plan(latest, await read(locale, { draft: writeDraft, fallbackLocale: false }));\n if (!job) return { locale, status: \"nothing\", count: 0 };\n const missing = job.sources.filter((value) => !known.has(value));\n if (missing.length > 0) {\n if (round >= REPLANS) {\n payload.logger.warn(`${label}: ${locale} source kept changing during translation; ${locale} left as-is`);\n return { locale, status: \"failed\", count: 0 };\n }\n if (!(await translate(missing))) return { locale, status: \"failed\", count: 0 };\n continue;\n }\n const data = job.patch(job.sources.map((value) => known.get(value)!));\n if (writeDraft && !draftMode) {\n payload.logger.info(\n `${label}: latest version is a draft; ${locale} translation written into the draft, the live ${locale} copy updates on the next publish`,\n );\n }\n const common = {\n locale,\n data: data as never,\n depth: 0,\n ...(writeDraft ? { draft: true } : {}),\n context: { autoTranslate: false },\n ...writeAs,\n req,\n };\n if (\"collection\" in options) {\n await payload.update({ collection: options.collection as never, id: options.id, ...common });\n } else {\n await payload.updateGlobal({ slug: options.global as never, ...common });\n }\n return { locale, status: \"translated\", count: job.sources.length };\n }\n }\n }\n return results;\n}\n","import type { Endpoint, PayloadRequest, Where } from \"payload\";\n\nimport { translateDocument } from \"./document\";\nimport { readState } from \"./state\";\nimport { isTranslatorConfigured } from \"./strings\";\n\n/** The admin component key for the \"Translate now\" document menu item. */\nexport const TRANSLATE_NOW = \"@bison-lab/payload-core/admin#TranslateNowMenuItem\";\n\n/**\n * True when the request's user may update this document, by the collection's\n * own `access.update`. A query result (`Where`) counts only when it matches\n * this document. It counts against the main document, as Payload's own update\n * does for a draft save, even when the latest version is a newer draft: the\n * write that follows is judged by Payload again, so this is only the early\n * refusal.\n */\nasync function canUpdate(req: PayloadRequest, slug: string, id: string): Promise<boolean> {\n if (!req.user) return false;\n const collection = req.payload.collections[slug as never] as\n | { config: { access?: { update?: (args: { req: PayloadRequest; id: string }) => unknown } } }\n | undefined;\n const access = collection?.config.access?.update;\n if (!access) return true;\n const result = await access({ req, id });\n if (typeof result === \"boolean\") return result;\n if (!result || typeof result !== \"object\") return false;\n const { totalDocs } = await req.payload.count({\n collection: slug as never,\n where: { and: [result as Where, { id: { equals: id } }] },\n overrideAccess: true,\n });\n return totalDocs > 0;\n}\n\n/**\n * `POST /api/<slug>/:id/translate?locale=<code>`: the \"Translate now\"\n * action. Re-translates one document with `overwrite`, replacing the target\n * locale's copy (every target locale when `locale` is omitted). Needs update\n * access to the document. Awaits the model, unlike the publish hook: a\n * person pressed the button and is waiting for the answer.\n */\nexport function translateNowEndpoint(slug: string): Endpoint {\n return {\n path: \"/:id/translate\",\n method: \"post\",\n handler: async (req) => {\n if (!req.user) return Response.json({ error: \"Unauthorized\" }, { status: 401 });\n const state = readState(req.payload.config);\n if (!state || !isTranslatorConfigured(state.translator)) {\n return Response.json({ error: \"Translation is not configured on the server.\" }, { status: 503 });\n }\n const id = req.routeParams?.id;\n if (typeof id !== \"string\" && typeof id !== \"number\") {\n return Response.json({ error: \"Missing document id\" }, { status: 400 });\n }\n const locale = req.searchParams?.get(\"locale\") || undefined;\n if (locale !== undefined && !state.targetLocales.includes(locale)) {\n return Response.json({ error: `\"${locale}\" is not a locale this site translates into.` }, { status: 400 });\n }\n if (!(await canUpdate(req, slug, String(id)))) {\n return Response.json({ error: \"You are not allowed to update this document.\" }, { status: 403 });\n }\n\n // Written as the caller, so the collection's access and hooks judge it\n // like any edit they could have made by hand. A refusal throws with a\n // status, and nothing is written for the locale it refused.\n let results;\n try {\n results = await translateDocument(req.payload, {\n collection: slug,\n id,\n ...(locale ? { locale } : {}),\n overwrite: true,\n user: req.user,\n });\n } catch (error) {\n const status = (error as { status?: unknown }).status;\n if (typeof status === \"number\" && status >= 400 && status < 500) {\n const message = error instanceof Error && error.message ? error.message : \"Not allowed.\";\n return Response.json({ error: message }, { status });\n }\n throw error;\n }\n const failed = results.filter((result) => result.status === \"failed\");\n const count = results.reduce((sum, result) => sum + result.count, 0);\n if (failed.length > 0 && failed.length === results.length) {\n req.payload.logger.warn(`${slug}/${id}: \"Translate now\" returned no result`);\n return Response.json(\n { error: \"The translation service gave no result. Try again in a minute.\", results },\n { status: 502 },\n );\n }\n const message =\n count === 0\n ? \"Nothing to translate.\"\n : `Translated ${count} string(s) into ${results\n .filter((result) => result.status === \"translated\")\n .map((result) => result.locale)\n .join(\", \")}.${failed.length ? ` ${failed.map((result) => result.locale).join(\", \")} failed.` : \"\"}`;\n return Response.json({ count, message, results });\n },\n };\n}\n","import type { PayloadRequest } from \"payload\";\n\n/** How often to re-check whether the request's transaction has ended. */\nconst POLL_INTERVAL_MS = 25;\n\n/**\n * How long to wait for the transaction to end before abandoning the work. Far\n * above any real publish, so reaching it means the request itself hung rather\n * than that the work was slow.\n */\nexport const TRANSACTION_TIMEOUT_MS = 30_000;\n\nconst sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));\n\n/**\n * Resolves true once the request's transaction has ended, false if it never\n * does. Polling is the mechanism because there is nothing to subscribe to:\n * Payload has no post-commit hook, and `req.transactionID` is the only\n * in-process signal that the transaction is over — both commitTransaction and\n * killTransaction finish with `delete req.transactionID`. The alternative,\n * patching payload.db.commitTransaction, is global and order-dependent, and\n * would affect every operation in the process to serve one hook.\n *\n * An absent transactionID means there is nothing to wait for: a script running\n * with `disableTransaction`, or a unit test.\n */\nasync function waitForTransactionEnd(req: PayloadRequest): Promise<boolean> {\n const deadline = Date.now() + TRANSACTION_TIMEOUT_MS;\n while (req.transactionID !== undefined) {\n if (Date.now() >= deadline) return false;\n await sleep(POLL_INTERVAL_MS);\n }\n return true;\n}\n\n/**\n * Run `work` once the request's database transaction has ended, so an expensive\n * or failure-prone tail never holds that transaction open.\n *\n * Payload runs `afterOperation` BEFORE commitTransaction (see updateByID.js), so\n * no hook is late enough to do this on its own. Anything scheduled here must\n * also open its own transaction rather than joining `req`'s: joining is\n * mandatory only while the outer transaction is still live — once it has\n * committed, its row locks are released and a fresh transaction is both safe\n * and required. So `work` must pass no `req` to the Local API.\n *\n * The returned promise is handed to `waitUntil` (the site's, e.g. Vercel's),\n * without which a serverless instance may be frozen the moment the response is\n * flushed and the work would never finish. It is also returned to the caller,\n * so tests and scripts can await the deferred work instead of sleeping.\n *\n * Deliberately not awaited by its callers: not awaiting is what removes the\n * hold, and `waitUntil` is what keeps the work alive afterwards.\n *\n * Never rejects. The final catch is a backstop only — callers own their own\n * error reporting — so that a defect in this helper cannot escape as an\n * unhandled rejection and take the process down.\n */\nexport function runAfterCommit(\n req: PayloadRequest,\n label: string,\n work: () => Promise<void>,\n waitUntil?: (promise: Promise<unknown>) => void,\n): Promise<void> {\n const deferred = waitForTransactionEnd(req)\n .then((ended) => {\n if (ended) return work();\n // Skip rather than proceed. Opening a new transaction while the outer one\n // still holds its row locks is the exact deadlock this helper exists to\n // avoid, so a request that never commits must not do the work at all.\n req.payload.logger.warn(\n `${label}: transaction still open after ${TRANSACTION_TIMEOUT_MS}ms; deferred work skipped`,\n );\n })\n .catch((error: unknown) => {\n req.payload.logger.error({ err: error }, `${label}: deferred post-commit work threw`);\n });\n\n try {\n waitUntil?.(deferred);\n } catch (error) {\n req.payload.logger.error({ err: error }, `${label}: waitUntil threw; the deferred work still runs`);\n }\n return deferred;\n}\n","import type { PayloadRequest } from \"payload\";\n\nimport { collectLocalizedStrings, type FieldSchema } from \"./fields\";\nimport type { Doc } from \"./types\";\n\n// Built rather than written as an escape sequence on purpose: a literal U+0000\n// typed into source has repeatedly landed as a raw control byte, which makes git\n// store the file as a binary blob with no diffs. The separator must not be a\n// space: a space lets neighboring strings shift across the boundary and hash\n// identical, silently skipping a translation (ZoomFiber commit 70e8971).\nconst FIELD_SEPARATOR = String.fromCharCode(0);\n\n/**\n * Any document shape: the guard reads `_status` (absent on collections without\n * a draft workflow) plus whatever localized fields the schema names, so it must\n * not constrain the rest of the document.\n */\ntype MaybeDraft = (Doc & { _status?: string | null }) | null | undefined;\n\n/** True when no localized copy differs between the two documents. */\nexport function localizedCopyUnchanged(previousDoc: unknown, doc: unknown, schema: FieldSchema): boolean {\n const before = collectLocalizedStrings(schema, previousDoc ?? {});\n const after = collectLocalizedStrings(schema, doc ?? {});\n return before.join(FIELD_SEPARATOR) === after.join(FIELD_SEPARATOR);\n}\n\n/**\n * The no-op decision for a collection or global WITHOUT a draft workflow:\n * every write is live, so the incoming `previousDoc` is the right thing to\n * diff. A create (no previous document) always translates.\n */\nexport function shouldSkipUndraftedTranslation(opts: {\n previousDoc?: MaybeDraft;\n doc: MaybeDraft;\n schema: FieldSchema;\n}): boolean {\n const { previousDoc, doc, schema } = opts;\n if (!previousDoc || Object.keys(previousDoc).length === 0) return false;\n return localizedCopyUnchanged(previousDoc, doc, schema);\n}\n\n/** A drafted collection document, or a drafted global. */\nexport type DraftedEntity = { collection: string } | { global: string };\n\nexport interface DraftedDecision {\n /** True for a draft save or a publish that changed no copy. */\n skip: boolean;\n /** The last published version's source copy, or `null` for a first publish. */\n previous: Doc | null;\n}\n\n/**\n * The no-op decision for a drafts-enabled collection or global, which must\n * NOT use the hook's `previousDoc`.\n *\n * Payload hands `afterChange` the most recently saved version, and with autosave\n * on (375ms) that is the draft the editor was just typing into, carrying copy\n * identical to what is being published. Diffing against it therefore reported\n * \"nothing changed\" on essentially every admin publish, so auto-translation\n * never ran from the admin at all. Diffing against the LAST PUBLISHED version\n * is the question actually worth asking: did the published copy change?\n *\n * That also keeps the property the naive fix broke, namely that a publish which\n * touches no localized copy (an image swap, a reordering) leaves a hand-edited\n * target locale alone. A document with no earlier published version is a first\n * publish and always translates, even one written entirely as a draft.\n *\n * Returns that previous published version too: it is the \"before\" the\n * per-string rule compares each source string with.\n */\nexport async function draftedTranslationDecision(opts: {\n req: PayloadRequest;\n entity: DraftedEntity;\n doc: MaybeDraft & { id?: number | string };\n schema: FieldSchema;\n sourceLocale: string;\n}): Promise<DraftedDecision> {\n const { req, entity, doc, schema, sourceLocale } = opts;\n if (doc?._status !== \"published\") return { skip: true, previous: null };\n\n // Exclude the publish currently in flight by timestamp rather than by content\n // or position. Payload stamps the parent doc's updatedAt (update.js) before\n // the version row's (saveVersion.js), so the version row's stamp is always\n // >= the doc's. `less_than` therefore excludes the in-flight row on either a\n // later OR an equal timestamp, and excludes nothing when the row has not\n // landed yet. Both orderings yield the genuinely previous published state.\n // Do NOT relax this to less_than_equal: that would admit the in-flight row,\n // compare the document against itself, and silently stop translating.\n const docUpdatedAt = doc.updatedAt;\n if (typeof docUpdatedAt !== \"string\") return { skip: false, previous: null };\n\n const where = {\n \"version._status\": { equals: \"published\" },\n updatedAt: { less_than: docUpdatedAt },\n };\n const common = {\n sort: \"-updatedAt\",\n limit: 1,\n pagination: false,\n depth: 0,\n locale: sourceLocale,\n overrideAccess: true,\n req,\n } as const;\n const { docs } =\n \"collection\" in entity\n ? await req.payload.findVersions({\n ...common,\n collection: entity.collection as never,\n where: { parent: { equals: doc.id }, ...where },\n })\n : await req.payload.findGlobalVersions({ ...common, slug: entity.global as never, where });\n\n const previousPublished = (docs[0] as unknown as { version?: unknown } | undefined)?.version;\n if (!previousPublished || typeof previousPublished !== \"object\") return { skip: false, previous: null };\n\n // Both sides must be read at the same depth. The version snapshot above is\n // depth 0, but `doc` arrives at whatever depth the writing request used, and\n // config.defaultDepth is 2. A programmatic publish would therefore populate\n // relationships inside blocks whose fields are themselves copy, making the\n // two sides diverge and re-translating on every publish. Re-reading the\n // current doc at depth 0 removes the asymmetry regardless of caller.\n const current =\n \"collection\" in entity\n ? await req.payload.findByID({\n collection: entity.collection as never,\n id: doc.id as number | string,\n locale: sourceLocale,\n depth: 0,\n overrideAccess: true,\n req,\n })\n : await req.payload.findGlobal({\n slug: entity.global as never,\n locale: sourceLocale,\n depth: 0,\n overrideAccess: true,\n req,\n });\n const previous = previousPublished as Doc;\n return { skip: localizedCopyUnchanged(previous, current, schema), previous };\n}\n\n/** `draftedTranslationDecision`, answering only whether to skip. */\nexport async function shouldSkipDraftedTranslation(\n opts: Parameters<typeof draftedTranslationDecision>[0],\n): Promise<boolean> {\n return (await draftedTranslationDecision(opts)).skip;\n}\n","import type { CollectionAfterChangeHook, GlobalAfterChangeHook, Payload, PayloadRequest } from \"payload\";\n\nimport { runAfterCommit } from \"./after-commit\";\nimport { translateDocument } from \"./document\";\nimport type { FieldSchema } from \"./fields\";\nimport { draftedTranslationDecision, shouldSkipUndraftedTranslation } from \"./guards\";\nimport { readState } from \"./state\";\nimport { isTranslatorConfigured } from \"./strings\";\nimport type { Doc, TranslateLocaleResult } from \"./types\";\n\n/**\n * Fill every other locale whenever source-locale copy is PUBLISHED with actual\n * changes, so staff never have to think about translation. Guards, in order:\n *\n * - `autoTranslate: false` context skips the hook entirely (set by seed\n * scripts, which run their own pass, and by the plugin's own target write\n * so it can never re-fire itself).\n * - Edits in a target locale are ignored: a hand edit there must never be\n * clobbered by a machine pass.\n * - Drafts are ignored; Live Preview autosaves every ~375ms and translating\n * each keystroke would be absurd. Publish is the commit point.\n * - No-op RE-publishes are ignored: if no localized string differs from the\n * previously published version (e.g. an image swap), targets stay\n * untouched. A FIRST publish is never a no-op, even though a doc written\n * entirely as a draft carries identical copy either side of the transition:\n * its targets have never been generated. See draftedTranslationDecision.\n * - No API key: the publish goes through and a warning is logged.\n *\n * Failures log a warning and never block or fail the publish; the source goes\n * live and each target stays as it was until the next publish. That holds\n * structurally: the translation does not even begin until the publish is\n * durable.\n *\n * Only the guards run inside the publish's transaction — two cheap indexed\n * reads that need to see the publish's own state. The model round trip and the\n * target writes are deferred past the commit by runAfterCommit, so a publish\n * never holds its transaction open for the seconds a long document takes. The\n * deferred call passes no `req`: it must open its own transaction, and safely\n * can, because the outer one has released its row locks by then.\n */\nasync function afterSourceChange(args: {\n entity: { collection: string } | { global: string };\n drafted: boolean;\n schema: FieldSchema;\n doc: Doc & { id?: number | string };\n previousDoc: Doc | undefined;\n operation: string | undefined;\n req: PayloadRequest;\n context: Record<string, unknown> | undefined;\n}): Promise<{ deferred?: Promise<void> }> {\n const { entity, drafted, schema, doc, req, context } = args;\n if (context?.autoTranslate === false) return {};\n const state = readState(req.payload.config);\n if (!state) return {};\n if (req.locale && req.locale !== state.sourceLocale) return {};\n\n const slug = \"collection\" in entity ? entity.collection : entity.global;\n const label = \"collection\" in entity ? `${slug}/${String(doc.id)}` : `globals/${slug}`;\n const { payload } = req;\n\n let previous: Doc | null;\n try {\n if (drafted) {\n const decision = await draftedTranslationDecision({\n req,\n entity,\n doc,\n schema,\n sourceLocale: state.sourceLocale,\n });\n if (decision.skip) return {};\n previous = decision.previous;\n } else {\n const previousDoc = args.operation === \"create\" ? undefined : args.previousDoc;\n if (shouldSkipUndraftedTranslation({ previousDoc, doc, schema })) return {};\n previous = previousDoc && Object.keys(previousDoc).length > 0 ? previousDoc : null;\n }\n } catch (error) {\n // The publish must never fail for translation's sake.\n payload.logger.error({ err: error }, `${label}: auto-translation guard failed; targets left as-is`);\n return {};\n }\n\n if (!isTranslatorConfigured(state.translator)) {\n payload.logger.warn(`${label}: source copy changed but the translator has no API key; targets not translated`);\n return {};\n }\n\n const deferred = runAfterCommit(\n req,\n label,\n async () => {\n try {\n const results = await translateDocument(payload, {\n ...(\"collection\" in entity ? { collection: slug, id: doc.id as number | string } : { global: slug }),\n previous,\n });\n logResults(payload, label, results);\n } catch (error) {\n payload.logger.error({ err: error }, `${label}: auto-translation failed; targets left as-is`);\n }\n },\n state.waitUntil,\n );\n return { deferred };\n}\n\nfunction logResults(payload: Payload, label: string, results: TranslateLocaleResult[]): void {\n for (const result of results) {\n if (result.status === \"translated\") {\n payload.logger.info(`${label}: auto-translated ${result.count} string(s) to ${result.locale}`);\n } else if (result.status === \"failed\") {\n payload.logger.warn(\n `${label}: ${result.locale} auto-translation returned no result; ${result.locale} left as-is`,\n );\n }\n }\n}\n\n/**\n * The hook body a test can drive: resolves once the guards have run, with\n * the deferred work's promise when one was scheduled. The registered hooks\n * await the guards (they must see the publish's own transaction) and drop\n * `deferred` on purpose: not awaiting it is what keeps the publish from\n * waiting on the model.\n */\nexport const autoTranslateAfterChange = afterSourceChange;\n\nexport function collectionAutoTranslateHook(slug: string): CollectionAfterChangeHook {\n return async ({ collection, doc, previousDoc, operation, req, context }) => {\n await afterSourceChange({\n entity: { collection: slug },\n drafted: Boolean(collection.versions && collection.versions.drafts),\n schema: { fields: collection.fields, blocks: req.payload.config.blocks },\n doc,\n previousDoc,\n operation,\n req,\n context,\n });\n return doc;\n };\n}\n\nexport function globalAutoTranslateHook(slug: string): GlobalAfterChangeHook {\n return async ({ global, doc, previousDoc, req, context }) => {\n await afterSourceChange({\n entity: { global: slug },\n drafted: Boolean(global.versions && global.versions.drafts),\n schema: { fields: global.fields, blocks: req.payload.config.blocks },\n doc,\n previousDoc,\n operation: \"update\",\n req,\n context,\n });\n return doc;\n };\n}\n","import type { CollectionConfig, Config, GlobalConfig, Plugin } from \"payload\";\n\nimport { TRANSLATE_NOW, translateNowEndpoint } from \"./endpoint\";\nimport { collectionAutoTranslateHook, globalAutoTranslateHook } from \"./hooks\";\nimport { AUTO_TRANSLATE_STATE, localeCodes, type AutoTranslateState } from \"./state\";\nimport { isTranslatorConfigured } from \"./strings\";\nimport type { AutoTranslateOptions, Doc, TranslatedEntity } from \"./types\";\n\nfunction entries(list: TranslatedEntity[] | undefined): Array<{ slug: string; context?: (doc: Doc) => string }> {\n return (list ?? []).map((entry) => (typeof entry === \"string\" ? { slug: entry } : entry));\n}\n\nfunction withCollection(\n collection: CollectionConfig,\n configured: boolean,\n sourceLocale: string,\n targetLocales: string[],\n): CollectionConfig {\n const edit = collection.admin?.components?.edit;\n return {\n ...collection,\n hooks: {\n ...collection.hooks,\n afterChange: [...(collection.hooks?.afterChange ?? []), collectionAutoTranslateHook(collection.slug)],\n },\n endpoints: [...(collection.endpoints || []), translateNowEndpoint(collection.slug)],\n // Always registered, so `generate:importmap` lists it with or without a key.\n admin: {\n ...collection.admin,\n components: {\n ...collection.admin?.components,\n edit: {\n ...edit,\n editMenuItems: [\n ...(edit?.editMenuItems ?? []),\n { path: TRANSLATE_NOW, clientProps: { sourceLocale, targetLocales, configured } },\n ],\n },\n },\n },\n };\n}\n\nfunction withGlobal(global: GlobalConfig): GlobalConfig {\n return {\n ...global,\n hooks: {\n ...global.hooks,\n afterChange: [...(global.hooks?.afterChange ?? []), globalAutoTranslateHook(global.slug)],\n },\n };\n}\n\n/**\n * Fills every locale but the default from the default whenever copy is\n * published, without overwriting a translation a person corrected. Each site\n * switches it on or off in its own `payload.config.ts`:\n *\n * ```ts\n * autoTranslate({\n * enabled: true,\n * collections: [\"pages\", { slug: \"plans\", context: (doc) => `Internet plan: ${doc.name}` }],\n * translator: anthropicTranslator({ apiKey: process.env.ANTHROPIC_API_KEY, site: { name: \"ZoomFiber\" } }),\n * waitUntil,\n * })\n * ```\n *\n * `enabled: false` returns the config untouched. Without `localization` (or\n * with one locale) it logs one warning and registers nothing. Otherwise each\n * listed collection gets an `afterChange` hook, `POST /api/<slug>/:id/translate`\n * and a \"Translate now\" item in the document menu (`TRANSLATE_NOW`, run\n * `payload generate:importmap`). The item is registered whether or not the\n * translator has a key, so the import map never depends on the environment;\n * it renders nothing when there is no key. Each listed\n * global gets the hook.\n */\nexport function autoTranslate(options: AutoTranslateOptions): Plugin {\n return (config: Config): Config => {\n if (!options.enabled) return config;\n const localization = config.localization;\n const codes = localeCodes(localization);\n if (!localization || codes.length < 2) {\n console.warn(\n \"[@bison-lab/payload-core] autoTranslate is enabled but the config has no localization with two or more locales; it registers nothing.\",\n );\n return config;\n }\n const sourceLocale = localization.defaultLocale;\n const targetLocales = codes.filter((code) => code !== sourceLocale);\n const collections = entries(options.collections);\n const globals = entries(options.globals);\n\n for (const { slug } of collections) {\n if (!config.collections?.some((collection) => collection.slug === slug)) {\n throw new Error(`autoTranslate: no collection \"${slug}\" in the config`);\n }\n }\n for (const { slug } of globals) {\n if (!config.globals?.some((global) => global.slug === slug)) {\n throw new Error(`autoTranslate: no global \"${slug}\" in the config`);\n }\n }\n\n const state: AutoTranslateState = {\n translator: options.translator,\n ...(options.site ? { site: options.site } : {}),\n ...(options.waitUntil ? { waitUntil: options.waitUntil } : {}),\n sourceLocale,\n targetLocales,\n collections: Object.fromEntries(collections.map(({ slug, context }) => [slug, context ? { context } : {}])),\n globals: Object.fromEntries(globals.map(({ slug, context }) => [slug, context ? { context } : {}])),\n };\n const configured = isTranslatorConfigured(options.translator);\n const collectionSlugs = new Set(collections.map(({ slug }) => slug));\n const globalSlugs = new Set(globals.map(({ slug }) => slug));\n\n return {\n ...config,\n custom: { ...config.custom, [AUTO_TRANSLATE_STATE]: state },\n collections: (config.collections ?? []).map((collection) =>\n collectionSlugs.has(collection.slug)\n ? withCollection(collection, configured, sourceLocale, targetLocales)\n : collection,\n ),\n globals: (config.globals ?? []).map((global) => (globalSlugs.has(global.slug) ? withGlobal(global) : global)),\n };\n };\n}\n"],"mappings":";;AA6CA,MAAM,SAAS,UAAiC,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM;AAEpH,MAAM,UAAU,UACd,MAAM,QAAQ,MAAM,GAAI,MAAM,OAAO,MAAM,GAAa,KAAA;;AAG1D,MAAa,UAAU,UAAoC,OAAO,UAAU,YAAY,MAAM,MAAM,KAAK;AAEzG,SAAS,SAAS,OAA2B;AAC3C,QAAO,MAAM,WAAW,QAAQ,MAAM,OAAO,WAAW;;AAG1D,SAAS,SAAS,OAAkB,cAA6D;CAC/F,MAAM,MAAM,MAAM,UAAU,EAAE;CAC9B,MAAM,cAAc,MAAM,mBAAmB,EAAE,EAAE,SAAS,QAAQ;AAChE,MAAI,OAAO,QAAQ,SAAU,QAAO,CAAC,IAAI;EACzC,MAAM,QAAQ,cAAc,MAAM,UAAU,MAAM,SAAS,IAAI;AAC/D,SAAO,QAAQ,CAAC,MAAM,GAAG,EAAE;GAC3B;AACF,QAAO,CAAC,GAAG,KAAK,GAAG,WAAW;;;;;;;;;;;;;AAchC,SAAgB,QACd,MACA,KACA,OACA,aAAa,OACI;AACjB,KAAI,CAAC,KAAM,QAAO,KAAA;AAClB,KAAI,WAAY,QAAO,KAAK;CAC5B,MAAM,KAAK,IAAI;AACf,QAAO,OAAO,OAAO,YAAY,OAAO,OAAO,WAAW,KAAK,MAAM,UAAU,MAAM,OAAO,GAAG,GAAG,KAAK;;;AAYzG,SAAS,UAAU,OAAsC;AACvD,KAAI,CAAC,MAAM,MAAM,IAAI,CAAC,MAAM,MAAM,KAAK,CAAE,QAAO;CAChD,MAAM,MAAqB,EAAE;CAC7B,MAAM,SAAS,MAAW,SAAiB;AACzC,MAAI,KAAK,SAAS,UAAU,OAAO,KAAK,SAAS,SAAU,KAAI,KAAK;GAAE;GAAM;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G,OAAQ;GAC9G"}
1
+ {"version":3,"file":"translate.mjs","names":[],"sources":["../src/translate/plugin.ts","../src/translate/migrate-locales.ts"],"sourcesContent":["import type { Config, Plugin } from \"payload\";\n\nimport { applyTranslation, type TranslationEntityHint } from \"./capability\";\nimport type { AutoTranslateOptions, TranslatedEntity } from \"./types\";\n\nfunction hints(list: TranslatedEntity[] | undefined): Array<[string, TranslationEntityHint]> {\n return (list ?? []).map((entry) =>\n typeof entry === \"string\" ? [entry, {}] : [entry.slug, entry.context ? { context: entry.context } : {}],\n );\n}\n\n/**\n * @deprecated Every site now has translation through `adminNav()` (or\n * `translation()`), switched on by an Admin in Settings → Translation, and\n * it covers every collection and global with localized fields. This keeps\n * an existing `autoTranslate({ ... })` line working: `enabled: false`\n * returns the config untouched; `enabled: true` applies the capability with\n * its `site` (the instructions' first values), `waitUntil`, the listed\n * entities' `context` hints, and `translator`, which then replaces the\n * screen's key and model (tests). The listed slugs must exist. The screen's\n * switch governs it either way.\n */\nexport function autoTranslate(options: AutoTranslateOptions): Plugin {\n return (config: Config): Config => {\n if (!options.enabled) return config;\n for (const [slug] of hints(options.collections)) {\n if (!config.collections?.some((collection) => collection.slug === slug)) {\n throw new Error(`autoTranslate: no collection \"${slug}\" in the config`);\n }\n }\n for (const [slug] of hints(options.globals)) {\n if (!config.globals?.some((global) => global.slug === slug)) {\n throw new Error(`autoTranslate: no global \"${slug}\" in the config`);\n }\n }\n return applyTranslation(config, {\n translator: options.translator,\n ...(options.site ? { site: options.site } : {}),\n ...(options.waitUntil ? { waitUntil: options.waitUntil } : {}),\n hints: Object.fromEntries([...hints(options.collections), ...hints(options.globals)]),\n });\n };\n}\n","/**\n * The data migration for a Postgres site going from one locale to several.\n *\n * Turning localization on moves every localized column out of its table\n * into a `<table>_locales` table (one row per locale). `payload\n * migrate:create` writes that as SQL that creates the new tables and then\n * drops the old columns, which throws the copy away. This runs the same\n * SQL with one step in between: after everything else and before any column\n * or type is dropped, each column that moves is copied into its locale\n * table as the default locale's row. Nothing else changes, so the result is\n * exactly the schema Payload generated, holding the content it held before.\n *\n * In the generated migration, replace the body of `up`:\n *\n * ```ts\n * import { localizeExistingContent } from \"@bison-lab/payload-core/translate\";\n *\n * export async function up({ db, payload }: MigrateUpArgs): Promise<void> {\n * await localizeExistingContent({ db, payload, sql, statements: `\n * ...the SQL migrate:create wrote inside sql`...`, unchanged...\n * ` });\n * }\n * ```\n *\n * Postgres only. The migration has no `down`: going back to one locale\n * would drop every other locale's copy.\n */\n\n/** The slice of Payload's `db` (Drizzle) this uses. */\nexport interface MigrationDb {\n // Method syntax on purpose: its parameter is checked bivariantly, so\n // Payload's `PostgresDB` (whose `execute` takes `SQLWrapper | string`)\n // is accepted as it is, with no cast in the site's migration.\n execute(query: never): Promise<unknown>;\n}\n\n/** `sql` from `@payloadcms/db-postgres`, for `sql.raw`. */\nexport interface MigrationSql {\n raw: (text: string) => unknown;\n}\n\n/** The slice of the site's Payload config the relationship step reads (`payload` from the migration's `up`). */\nexport interface MigrationPayload {\n /** The adapter's table-name suffixes, when a site changed them (`postgresAdapter({ localesSuffix })`). */\n db?: { localesSuffix?: string; relationshipsSuffix?: string; versionsSuffix?: string };\n config: {\n collections?: ReadonlyArray<{ slug: string; dbName?: unknown; fields: readonly unknown[] }>;\n globals?: ReadonlyArray<{ slug: string; dbName?: unknown; fields: readonly unknown[] }>;\n /** Config-level blocks, for blocks fields that use `blockReferences`. */\n blocks?: ReadonlyArray<{ slug: string; fields: readonly unknown[] }>;\n };\n}\n\nexport interface LocalizeExistingContentOptions {\n db: MigrationDb;\n sql: MigrationSql;\n /**\n * The migration's `payload`. Needed when a localized relationship, upload\n * or hasMany text/number field already holds rows: Payload keeps those in\n * shared `_rels` / `_texts` / `_numbers` tables with a `locale` column it\n * adds now, and only the config says which rows belong to a localized\n * field. Without it, such rows make the migration stop with an error\n * rather than lose them.\n */\n payload?: MigrationPayload;\n /** The SQL `migrate:create` generated for this change, as text. */\n statements: string;\n /** The locale existing content is in. Defaults to `en`. */\n locale?: string;\n /** The Postgres schema Payload's tables are in. Defaults to `public`. */\n schema?: string;\n /** Progress lines; defaults to `console.log`. */\n log?: (line: string) => void;\n}\n\nexport interface LocalizedTableCopy {\n table: string;\n into: string;\n columns: string[];\n rows: number;\n}\n\n/**\n * Splits generated SQL into statements at a `;` that ends a line, keeping a\n * `DO $$ ... $$;` block whole.\n */\nexport function splitStatements(text: string): string[] {\n const out: string[] = [];\n let current: string[] = [];\n let inDollar = false;\n for (const line of text.split(\"\\n\")) {\n if (line.trim() === \"\" && current.length === 0) continue;\n current.push(line);\n const dollars = line.match(/\\$\\$/g)?.length ?? 0;\n if (dollars % 2 === 1) inDollar = !inDollar;\n if (!inDollar && /;\\s*$/.test(line)) {\n out.push(current.join(\"\\n\").trim());\n current = [];\n }\n }\n const rest = current.join(\"\\n\").trim();\n if (rest) out.push(rest);\n return out;\n}\n\nconst DROP_COLUMN = /^ALTER TABLE\\s+(?:\"[^\"]+\"\\.)?\"([^\"]+)\"\\s+DROP COLUMN\\s+(?:IF EXISTS\\s+)?\"([^\"]+)\"/i;\nconst DROP_TYPE = /^DROP TYPE\\b/i;\n/** The bare name of a type in `DROP TYPE` / `CREATE TYPE` (`\"public\".\"enum_x\"` → `enum_x`). */\nconst TYPE_NAME = /^(?:DROP|CREATE) TYPE\\s+(?:IF EXISTS\\s+)?(?:\"[^\"]+\"\\.)?\"?([^\"\\s(]+)\"?/i;\nconst ADD_LOCALE = /^ALTER TABLE\\s+(?:\"[^\"]+\"\\.)?\"([^\"]+)\"\\s+ADD COLUMN\\s+\"locale\"\\s/i;\n/**\n * A NOT NULL locale column added to a table that already has rows: `_locale`\n * on a localized array or blocks table, or `locale` on a localized hasMany\n * select's own table. Either would fail on the first existing row.\n */\nconst ADD_LOCALE_NOT_NULL =\n /^(ALTER TABLE\\s+((?:\"[^\"]+\"\\.)?\"[^\"]+\")\\s+ADD COLUMN\\s+\"(_?locale)\"\\s+(\\S+)\\s+NOT NULL)(\\s*;)$/i;\n\nexport interface PartitionedStatements {\n /** Everything that does not drop: creates, adds, indexes, constraints. */\n first: string[];\n /** Tables that gain a nullable `locale` column (shared relationship / hasMany tables). */\n localeColumns: string[];\n /** The columns dropped, by table. */\n drops: Map<string, string[]>;\n /** The drops themselves, run last. */\n last: string[];\n}\n\n/**\n * Sorts statements into what runs before the copy and the drops that run\n * after it. A `_locale NOT NULL` column added to an existing table (a\n * localized array or blocks field) gets the default locale as a default\n * while it is added, so existing rows are kept as that locale's.\n */\nexport function partitionStatements(statements: readonly string[], locale = \"en\"): PartitionedStatements {\n const first: string[] = [];\n const last: string[] = [];\n const localeColumns: string[] = [];\n const drops = new Map<string, string[]>();\n // drizzle-kit drops and re-creates a type under the same name when an\n // enum loses a value; that drop must stay where it is, before its CREATE.\n const recreated = new Set(\n statements\n .filter((statement) => /^CREATE TYPE\\b/i.test(statement))\n .map((statement) => statement.match(TYPE_NAME)?.[1])\n .filter((name): name is string => Boolean(name)),\n );\n for (const statement of statements) {\n const addLocaleColumn = statement.match(ADD_LOCALE);\n if (addLocaleColumn) localeColumns.push(addLocaleColumn[1]!);\n const drop = statement.match(DROP_COLUMN);\n if (drop) {\n const [, table, column] = drop as unknown as [string, string, string];\n drops.set(table, [...(drops.get(table) ?? []), column]);\n last.push(statement);\n continue;\n }\n if (DROP_TYPE.test(statement)) {\n const name = statement.match(TYPE_NAME)?.[1];\n if (name && recreated.has(name)) first.push(statement);\n else last.push(statement);\n continue;\n }\n const addLocale = statement.match(ADD_LOCALE_NOT_NULL);\n if (addLocale && !/DEFAULT/i.test(statement)) {\n const [, head, table, columnName, type] = addLocale as unknown as [string, string, string, string, string];\n first.push(`${head} DEFAULT '${locale}'::text::${type};`);\n first.push(`ALTER TABLE ${table} ALTER COLUMN \"${columnName}\" DROP DEFAULT;`);\n continue;\n }\n first.push(statement);\n }\n return { first, localeColumns, drops, last };\n}\n\n// ---------------------------------------------------------------------------\n// Rows of localized relationships, uploads and hasMany fields\n\ninterface ConfigField {\n type?: string;\n name?: string;\n localized?: boolean;\n fields?: ConfigField[];\n tabs?: Array<{ name?: string; localized?: boolean; fields: ConfigField[] }>;\n blocks?: Array<{ slug: string; fields: ConfigField[] }>;\n blockReferences?: Array<string | { slug: string; fields: ConfigField[] }>;\n}\n\n/** Payload's default table name for a slug (`toSnakeCase`). */\nfunction snake(value: string): string {\n return value\n .replace(/([a-z0-9])([A-Z])/g, \"$1_$2\")\n .replace(/[-\\s]+/g, \"_\")\n .toLowerCase();\n}\n\n/** Named fields at this level, looking through rows, collapsibles, unnamed groups and unnamed tabs. */\nfunction named(fields: readonly ConfigField[]): ConfigField[] {\n return fields.flatMap((field) => {\n if (field.type === \"tabs\") {\n return (field.tabs ?? []).flatMap((tab) =>\n tab.name ? [{ type: \"group\", name: tab.name, localized: tab.localized, fields: tab.fields }] : named(tab.fields),\n );\n }\n if (!field.name && field.fields) return named(field.fields);\n return field.name ? [field] : [];\n });\n}\n\n/**\n * Whether the stored `path` of a relationship / hasMany row (`related`,\n * `layout.1.items.0.ref`) is a localized field, or sits inside one.\n * `undefined` when the path is not in the config. Throws when blocks\n * disagree (two block types with the same sub-path, one localized).\n */\nexport function isLocalizedPath(\n fields: readonly ConfigField[],\n segments: readonly string[],\n inherited = false,\n configBlocks: ReadonlyArray<{ slug: string; fields: readonly unknown[] }> = [],\n): boolean | undefined {\n const [head, ...rest] = segments;\n const field = named(fields).find((candidate) => candidate.name === head);\n if (!field) return undefined;\n const localized = inherited || field.localized === true;\n if (rest.length === 0) return localized;\n if (field.type === \"array\") return isLocalizedPath(field.fields ?? [], rest.slice(1), localized, configBlocks);\n if (field.type === \"blocks\") {\n // Inline blocks, plus blocks named by slug in `blockReferences` and declared once in `config.blocks`.\n const referenced = (field.blockReferences ?? []).flatMap((ref) =>\n typeof ref === \"string\" ? configBlocks.filter((block) => block.slug === ref) : [ref],\n ) as Array<{ slug: string; fields: ConfigField[] }>;\n const answers = [...(field.blocks ?? []), ...referenced]\n .map((block) => isLocalizedPath(block.fields, rest.slice(1), localized, configBlocks))\n .filter((answer): answer is boolean => answer !== undefined);\n if (answers.length === 0) return undefined;\n if (answers.some((answer) => answer !== answers[0])) {\n throw new Error(`localizeExistingContent: \"${segments.join(\".\")}\" is localized in one block type and not another`);\n }\n return answers[0];\n }\n return isLocalizedPath(field.fields ?? [], rest, localized, configBlocks);\n}\n\n/** The adapter's table suffixes: Payload's defaults unless the site set its own. */\nfunction suffixes(payload: MigrationPayload | undefined) {\n return {\n locales: payload?.db?.localesSuffix ?? \"_locales\",\n rels: payload?.db?.relationshipsSuffix ?? \"_rels\",\n versions: payload?.db?.versionsSuffix ?? \"_v\",\n };\n}\n\nconst escapeRegExp = (value: string) => value.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n\n/** A shared relationship / hasMany table: `<base><relationshipsSuffix>`, `<base>_texts`, `<base>_numbers`. */\nfunction sharedSuffix(payload: MigrationPayload | undefined): RegExp {\n return new RegExp(`(${escapeRegExp(suffixes(payload).rels)}|_texts|_numbers)$`);\n}\n\nfunction entityFor(payload: MigrationPayload, table: string): { fields: readonly ConfigField[]; version: boolean } | null {\n const { versions } = suffixes(payload);\n const base = table.replace(sharedSuffix(payload), \"\");\n const version = base.startsWith(\"_\") && base.endsWith(versions);\n const name = version ? base.slice(1, -versions.length) : base;\n const entities = [...(payload.config.collections ?? []), ...(payload.config.globals ?? [])];\n const entity = entities.find((candidate) =>\n (typeof candidate.dbName === \"string\" ? candidate.dbName : snake(candidate.slug)) === name,\n );\n return entity ? { fields: entity.fields as readonly ConfigField[], version } : null;\n}\n\nconst quote = (name: string) => `\"${name.replace(/\"/g, '\"\"')}\"`;\nconst literal = (value: string) => `'${value.replace(/'/g, \"''\")}'`;\n\nfunction rowsOf(result: unknown): Array<Record<string, unknown>> {\n if (Array.isArray(result)) return result as Array<Record<string, unknown>>;\n const rows = (result as { rows?: unknown } | null)?.rows;\n return Array.isArray(rows) ? (rows as Array<Record<string, unknown>>) : [];\n}\n\ninterface ColumnInfo {\n column_name: string;\n data_type: string;\n udt_schema: string;\n udt_name: string;\n}\n\n/**\n * Runs a localization migration without losing content: see the module\n * comment. Returns what it copied. Throws (and Payload rolls the migration\n * back) on any SQL error.\n */\nexport async function localizeExistingContent(options: LocalizeExistingContentOptions): Promise<LocalizedTableCopy[]> {\n const { db, sql } = options;\n const locale = options.locale ?? \"en\";\n const schema = options.schema ?? \"public\";\n const log = options.log ?? ((line: string) => console.log(line));\n const run = (text: string) => db.execute(sql.raw(text) as never);\n\n const { first, localeColumns, drops, last } = partitionStatements(splitStatements(options.statements), locale);\n for (const statement of first) await run(statement);\n\n // Relationship, upload and hasMany rows: the new `locale` column is the\n // default locale on rows of a localized field, and stays empty on the\n // rest (Payload reads a non-localized row only when it has no locale).\n for (const table of localeColumns) {\n const qualifiedTable = `${quote(schema)}.${quote(table)}`;\n const tableColumns = rowsOf(\n await run(\n `SELECT column_name, udt_schema, udt_name FROM information_schema.columns WHERE table_schema = ${literal(schema)} AND table_name = ${literal(table)} AND column_name IN ('locale', 'path')`,\n ),\n ) as unknown as ColumnInfo[];\n const localeInfo = tableColumns.find((info) => info.column_name === \"locale\");\n const value = localeInfo\n ? `${literal(locale)}::text::${quote(localeInfo.udt_schema)}.${quote(localeInfo.udt_name)}`\n : literal(locale);\n // Shared by structure, not by name: a relationship / hasMany table keeps\n // each row's field `path`; a hasMany select's own table (which may well be\n // called `pages_phone_numbers`) has none.\n const shared = tableColumns.some((info) => info.column_name === \"path\");\n if (!shared) {\n // A hasMany select keeps its own table, which gains `locale` only when the field is localized.\n const result = await run(`UPDATE ${qualifiedTable} SET \"locale\" = ${value} WHERE \"locale\" IS NULL`);\n log(`[localize] ${table}: locale set on ${(result as { rowCount?: number } | null)?.rowCount ?? \"?\"} rows`);\n continue;\n }\n const paths = rowsOf(await run(`SELECT DISTINCT \"path\" FROM ${qualifiedTable} WHERE \"locale\" IS NULL`)).map((row) =>\n String(row.path),\n );\n if (paths.length === 0) continue;\n if (!options.payload) {\n throw new Error(\n `localizeExistingContent: ${table} holds relationship or hasMany rows that may belong to localized fields. Pass the migration's payload ({ db, payload, sql, statements }) so they keep their content.`,\n );\n }\n const entity = entityFor(options.payload, table);\n if (!entity) {\n throw new Error(\n `localizeExistingContent: no collection or global stores its relationships in ${table}. If one does under a custom table name, give that collection or global a dbName matching ${table.replace(sharedSuffix(options.payload), \"\")}.`,\n );\n }\n const localized = paths.filter((path) => {\n const segments = path.split(\".\");\n const own = entity.version && segments[0] === \"version\" ? segments.slice(1) : segments;\n const answer = isLocalizedPath(entity.fields, own, false, options.payload!.config.blocks ?? []);\n // A row the config cannot place may be exactly the content this exists\n // to keep: stop rather than guess.\n if (answer === undefined) {\n throw new Error(`localizeExistingContent: ${table} has rows at \"${path}\", which is not a field in the config passed`);\n }\n return answer;\n });\n if (localized.length === 0) continue;\n const result = await run(\n `UPDATE ${qualifiedTable} SET \"locale\" = ${value} WHERE \"locale\" IS NULL AND \"path\" IN (${localized.map(literal).join(\", \")})`,\n );\n log(`[localize] ${table}: locale set on ${(result as { rowCount?: number } | null)?.rowCount ?? \"?\"} rows (${localized.join(\", \")})`);\n }\n\n const columnsOf = async (table: string): Promise<ColumnInfo[]> =>\n rowsOf(\n await run(\n `SELECT column_name, data_type, udt_schema, udt_name FROM information_schema.columns WHERE table_schema = ${literal(\n schema,\n )} AND table_name = ${literal(table)}`,\n ),\n ) as unknown as ColumnInfo[];\n\n const copies: LocalizedTableCopy[] = [];\n for (const [table, dropped] of drops) {\n const into = `${table}${suffixes(options.payload).locales}`;\n const target = await columnsOf(into);\n if (target.length === 0) {\n log(`[localize] ${table}: ${dropped.join(\", \")} dropped with no locale table to keep them; not copied`);\n continue;\n }\n const byName = new Map(target.map((column) => [column.column_name, column]));\n const moving = dropped.filter((column) => byName.has(column));\n const lost = dropped.filter((column) => !byName.has(column));\n if (lost.length) log(`[localize] ${table}: ${lost.join(\", \")} dropped, not localized; not copied`);\n if (moving.length === 0) continue;\n const cast = (column: string) => {\n const info = byName.get(column)!;\n return info.data_type === \"USER-DEFINED\"\n ? `${quote(column)}::text::${quote(info.udt_schema)}.${quote(info.udt_name)}`\n : quote(column);\n };\n const localeColumn = byName.get(\"_locale\");\n if (!localeColumn || !byName.has(\"_parent_id\")) {\n throw new Error(`localizeExistingContent: ${into} has no _locale / _parent_id column`);\n }\n const localeValue = `${literal(locale)}::text::${quote(localeColumn.udt_schema)}.${quote(localeColumn.udt_name)}`;\n const qualified = (name: string) => `${quote(schema)}.${quote(name)}`;\n const statement = `INSERT INTO ${qualified(into)} (${[...moving.map(quote), '\"_locale\"', '\"_parent_id\"'].join(\", \")})\nSELECT ${[...moving.map((column) => `p.${cast(column)}`), localeValue, 'p.\"id\"'].join(\", \")}\nFROM ${qualified(table)} p\nWHERE NOT EXISTS (SELECT 1 FROM ${qualified(into)} l WHERE l.\"_parent_id\" = p.\"id\" AND l.\"_locale\"::text = ${literal(\n locale,\n )})`;\n // A locale row that already exists (a site that had localization makes\n // another field localized) gets the moved values; any other parent gets\n // a new English row.\n const updated = await run(`UPDATE ${qualified(into)} l SET ${moving\n .map((column) => `${quote(column)} = p.${cast(column)}`)\n .join(\", \")}\nFROM ${qualified(table)} p\nWHERE l.\"_parent_id\" = p.\"id\" AND l.\"_locale\"::text = ${literal(locale)}`);\n const result = await run(statement);\n const rows =\n ((result as { rowCount?: number } | null)?.rowCount ?? 0) + ((updated as { rowCount?: number } | null)?.rowCount ?? 0);\n copies.push({ table, into, columns: moving, rows });\n log(`[localize] ${table} -> ${into}: ${moving.join(\", \")} (${rows} rows)`);\n }\n\n for (const statement of last) await run(statement);\n return copies;\n}\n"],"mappings":";;;;AAKA,SAAS,MAAM,MAA8E;AAC3F,SAAQ,QAAQ,EAAE,EAAE,KAAK,UACvB,OAAO,UAAU,WAAW,CAAC,OAAO,EAAE,CAAC,GAAG,CAAC,MAAM,MAAM,MAAM,UAAU,EAAE,SAAS,MAAM,SAAS,GAAG,EAAE,CAAC,CACxG;;;;;;;;;;;;;AAcH,S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YAAY,MAAO,SAA0C,YAAY;AACtH,SAAO,KAAK;GAAE;GAAO;GAAM,SAAS;GAAQ;GAAM,CAAC;AACnD,MAAI,cAAc,MAAM,MAAM,KAAK,IAAI,OAAO,KAAK,KAAK,CAAC,IAAI,KAAK,QAAQ;;AAG5E,MAAK,MAAM,aAAa,KAAM,OAAM,IAAI,UAAU;AAClD,QAAO"}
@@ -258,4 +258,4 @@ declare const SYSTEM_COLOR_KEYS: readonly ["primary", "secondary", "accent", "hi
258
258
  type SystemColorKey = (typeof SYSTEM_COLOR_KEYS)[number];
259
259
  //#endregion
260
260
  export { rewriteColorUsages as C, findColorUsages as S, ThemeIdentityFallback as _, THEME_APPEARANCE_SLUG as a, ColorUsagesList as b, THEME_SLUG as c, ThemeDoc as d, ThemeHead as f, ResolvedThemeIdentity as g, ThemeUploadDoc as h, SystemColorKey as i, THEME_TYPOGRAPHY_SLUG as l, ThemeLibraryColorDoc as m, EditableTheme as n, THEME_COLORS_SLUG as o, ThemeHeadOptions as p, SYSTEM_COLOR_KEYS as r, THEME_IDENTITY_SLUG as s, CreateThemeOptions as t, ThemeColorDoc as u, resolveThemeIdentity as v, ColorUsagesOption as x, ColorUsage as y };
261
- //# sourceMappingURL=types-Db6Iy3hJ.d.mts.map
261
+ //# sourceMappingURL=types-DLBlHZUd.d.mts.map
@@ -1 +1 @@
1
- {"version":3,"file":"types-Db6Iy3hJ.d.mts","names":[],"sources":["../src/theme/color-usages.ts","../src/theme/identity.ts","../src/theme/types.ts"],"mappings":";;;;;UAOiB,eAAA;EACf,WAAA;EACA,OAAA;AAAA;;;;AAQF;;KAAY,iBAAA,UAA2B,eAAA;AAAA,UAEtB,UAAA;EACf,UAAA;EACA,MAAA;EACA,EAAA;EACA,IAAA;EACA,KAAA;AAAA;AAAA,KAGG,UAAA;EAAe,IAAA,EAAM,MAAA;EAA2B,UAAA;EAAqB,IAAA;AAAA;AAAA,KAErE,OAAA;EAAY,IAAA;AAAA;AAAA,UAEA,iBAAA;EAC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;EE6CF,KAAA,YAAiB,SAAA;EF7CE;EE+CnB,YAAA;EFvCoB;EEyCpB,cAAA;;;;;EAKA,WAAA;EF1CQ;;;;;EEgDR,IAAA;IAAS,UAAA;EAAA;EFhDA;;;AAoBX;EEiCE,QAAA;IAAa,QAAA,GAAW,qBAAA;EAAA;EF/BhB;EEiCR,SAAA,IAAa,KAAA,EAAO,WAAA,EAAa,GAAA,EAAK,QAAA,YAAoB,OAAA;EF9BlD;;;;;;;;EEuCR,WAAA,GAAc,iBAAA;AAAA;AAAA,UAGC,gBAAA;EACf,YAAA;EACA,SAAA;EACA,QAAA,GAAW,qBAAA;ED/II;;;;ECoJf,OAAA,GAAU,oBAAA;AAAA;AAAA,UAGK,SAAA;EACf,GAAA;EACA,QAAA;IAAY,IAAA;IAAc,IAAA;EAAA;EAC1B,QAAA,GAAW,qBAAA;AAAA;AAAA,cAGA,UAAA;AAAA,cACA,iBAAA;AAAA,cACA,qBAAA;AAAA,cACA,qBAAA;AAAA,cACA,mBAAA;AAAA,cAEA,iBAAA;AAAA,KASD,cAAA,WAAyB,iBAAA"}
1
+ {"version":3,"file":"types-DLBlHZUd.d.mts","names":[],"sources":["../src/theme/color-usages.ts","../src/theme/identity.ts","../src/theme/types.ts"],"mappings":";;;;;UAOiB,eAAA;EACf,WAAA;EACA,OAAA;AAAA;;;;AAQF;;KAAY,iBAAA,UAA2B,eAAA;AAAA,UAEtB,UAAA;EACf,UAAA;EACA,MAAA;EACA,EAAA;EACA,IAAA;EACA,KAAA;AAAA;AAAA,KAGG,UAAA;EAAe,IAAA,EAAM,MAAA;EAA2B,UAAA;EAAqB,IAAA;AAAA;AAAA,KAErE,OAAA;EAAY,IAAA;AAAA;AAAA,UAEA,iBAAA;EACf,IAAA,GAAO,IAAA;IACL,UAAA;IACA,KAAA;IACA,KAAA;IACA,KAAA;IACA,IAAA;IACA,cAAA;EAAA,MACI,OAAA,CAAQ,UAAA;EACd,UAAA,GAAa,IAAA;IACX,IAAA;IACA,KAA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QAAA;IAAa,QAAA,GAAW,qBAAA;EAAA;EF/BhB;EEiCR,SAAA,IAAa,KAAA,EAAO,WAAA,EAAa,GAAA,EAAK,QAAA,YAAoB,OAAA;EF9BlD;;;;;;;;EEuCR,WAAA,GAAc,iBAAA;AAAA;AAAA,UAGC,gBAAA;EACf,YAAA;EACA,SAAA;EACA,QAAA,GAAW,qBAAA;ED/II;;;;ECoJf,OAAA,GAAU,oBAAA;AAAA;AAAA,UAGK,SAAA;EACf,GAAA;EACA,QAAA;IAAY,IAAA;IAAc,IAAA;EAAA;EAC1B,QAAA,GAAW,qBAAA;AAAA;AAAA,cAGA,UAAA;AAAA,cACA,iBAAA;AAAA,cACA,qBAAA;AAAA,cACA,qBAAA;AAAA,cACA,mBAAA;AAAA,cAEA,iBAAA;AAAA,KASD,cAAA,WAAyB,iBAAA"}
@@ -300,4 +300,4 @@ async function captureWireframes(page, previews, { selector = WIREFRAME_ROOT } =
300
300
  //#endregion
301
301
  export { captureWireframes as a, wireframeSvg as c, WIREFRAME_WIDTH as i, WIREFRAME_ROOT as n, extractWireframe as o, WIREFRAME_VIEWPORT as r, svgDataUri as s, WIREFRAME_HEIGHT as t };
302
302
 
303
- //# sourceMappingURL=wireframe-xcJNJzBf.mjs.map
303
+ //# sourceMappingURL=wireframe-CXorKFU_.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"wireframe-xcJNJzBf.mjs","names":[],"sources":["../src/wireframe.ts"],"sourcesContent":["/**\n * @deprecated since 4.16: the Add Block drawer shows screenshots now\n * (`@bison-lab/payload-core/block-thumbnails`, `bison-block-thumbnails`).\n * Kept working for this release so a site that calls it does not break;\n * it goes in the next major.\n *\n * Black-and-white wireframes of Block library samples, for Payload's Add\n * Block drawer (`admin.images.thumbnail`). React-free and Payload-free: a\n * script drives a browser to each block's preview (`previewPath(slug)`),\n * `extractWireframe` reads where the headings, text, images, buttons and\n * surfaces sit, and `wireframeSvg` draws those boxes as greyscale shapes.\n * No copy and no brand color reach the picture, so it does not go stale\n * when Theme changes; rerun it when a block's layout does.\n */\n\n/** Payload's drawer card is 3:2; 480 × 320 is the size its docs suggest. */\nexport const WIREFRAME_WIDTH = 480;\nexport const WIREFRAME_HEIGHT = 320;\n\n/** Desktop width, so the picture is the layout most visitors see. */\nexport const WIREFRAME_VIEWPORT = { width: 1280, height: 900 } as const;\n\n/** The element the Block library preview wraps each sample in (`BlockLibraryIsland`). */\nexport const WIREFRAME_ROOT = \"[data-block-library-island]\";\n\n/** `light` draws light marks (they sit on a dark surface); `dark` draws dark ones (on paper). */\nexport type WireframeTone = \"light\" | \"dark\";\n\nexport type WireframeShape =\n /** A band or panel the block paints. `dark` is a dark fill; `light` a pale tint. */\n | { kind: \"surface\"; x: number; y: number; w: number; h: number; tone: WireframeTone }\n /** A bordered card with no fill of its own. */\n | { kind: \"frame\"; x: number; y: number; w: number; h: number; tone: WireframeTone }\n | { kind: \"image\"; x: number; y: number; w: number; h: number }\n | { kind: \"heading\" | \"text\" | \"icon\"; x: number; y: number; w: number; h: number; tone: WireframeTone }\n | { kind: \"button\"; x: number; y: number; w: number; h: number; filled: boolean; tone: WireframeTone }\n | { kind: \"field\"; x: number; y: number; w: number; h: number };\n\nexport type WireframeCapture = { width: number; height: number; shapes: WireframeShape[] };\n\n/**\n * Runs in the page (Playwright's `page.evaluate`), so it closes over\n * nothing: every helper is declared inside. Boxes are relative to the\n * element `selector` names (the preview's island), in CSS pixels.\n */\nexport function extractWireframe(selector: string): WireframeCapture {\n const root = document.querySelector(selector);\n // No sample on the page (a sign-in wall, a 404, a wrong selector): refuse,\n // rather than draw whatever page came back as the block's picture.\n if (!root) throw new Error(`no element matches ${selector}`);\n const origin = root.getBoundingClientRect();\n const shapes: WireframeShape[] = [];\n const taken = new Set<Element>();\n\n const parseColor = (value: string): [number, number, number, number] | null => {\n const match = value.match(/rgba?\\(([^)]+)\\)/);\n if (!match) return null;\n const parts = match[1]!.split(/[\\s,/]+/).filter(Boolean).map(Number);\n return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0, parts[3] ?? 1];\n };\n const luminance = (rgb: [number, number, number, number]) => (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255;\n const style = (element: Element) => getComputedStyle(element);\n const shown = (element: Element) => {\n const css = style(element);\n return css.display !== \"none\" && css.visibility !== \"hidden\" && Number(css.opacity || \"1\") > 0.05;\n };\n const box = (element: Element) => {\n const rect = element.getBoundingClientRect();\n return {\n x: Math.round(rect.left - origin.left),\n y: Math.round(rect.top - origin.top),\n w: Math.round(rect.width),\n h: Math.round(rect.height),\n };\n };\n /** The fill an element paints, if any: a solid color, or a gradient's first stop. */\n const fillOf = (element: Element) => {\n const css = style(element);\n const solid = parseColor(css.backgroundColor);\n if (solid && solid[3] >= 0.5) return solid;\n if (css.backgroundImage.includes(\"gradient\")) return parseColor(css.backgroundImage);\n return null;\n };\n /** Light marks when the nearest painted ancestor is dark. */\n const toneUnder = (element: Element): WireframeTone => {\n for (let node: Element | null = element; node; node = node.parentElement) {\n const fill = fillOf(node);\n if (fill) return luminance(fill) < 0.45 ? \"light\" : \"dark\";\n if (node === root) break;\n }\n return \"dark\";\n };\n const insideTaken = (element: Element | null) => {\n for (let node = element; node && node !== root; node = node.parentElement) if (taken.has(node)) return true;\n return false;\n };\n\n const page = parseColor(style(document.body).backgroundColor);\n const pageLum = page && page[3] >= 0.5 ? luminance(page) : 1;\n\n const elements = root.querySelectorAll(\"*\");\n for (const element of Array.from(elements)) {\n if (insideTaken(element.parentElement) || !shown(element)) continue;\n const at = box(element);\n if (at.w < 2 || at.h < 2) continue;\n const tag = element.tagName.toLowerCase();\n const css = style(element);\n\n if (tag === \"img\" || tag === \"picture\" || tag === \"video\" || tag === \"canvas\" || tag === \"iframe\") {\n shapes.push({ kind: \"image\", ...at });\n taken.add(element);\n continue;\n }\n if (tag === \"svg\") {\n if (at.w >= 48 && at.h >= 48) shapes.push({ kind: \"image\", ...at });\n else {\n const color = parseColor(css.color);\n shapes.push({ kind: \"icon\", ...at, tone: color && luminance(color) > 0.5 ? \"light\" : \"dark\" });\n }\n taken.add(element);\n continue;\n }\n if (tag === \"input\" || tag === \"select\" || tag === \"textarea\") {\n if ((element as HTMLInputElement).type !== \"hidden\") shapes.push({ kind: \"field\", ...at });\n taken.add(element);\n continue;\n }\n\n const fill = fillOf(element);\n const border = parseFloat(css.borderTopWidth) >= 1 && css.borderTopStyle !== \"none\";\n const action = tag === \"a\" || tag === \"button\" || element.getAttribute(\"role\") === \"button\";\n if (action && (fill || border) && at.h >= 24 && at.h <= 80 && at.w <= 480) {\n shapes.push({ kind: \"button\", ...at, filled: Boolean(fill), tone: toneUnder(element.parentElement ?? element) });\n taken.add(element);\n continue;\n }\n if (/url\\(/.test(css.backgroundImage) && at.w >= 48 && at.h >= 48) {\n shapes.push({ kind: \"image\", ...at });\n continue;\n }\n if (fill && at.w >= 160 && at.h >= 80) {\n const lum = luminance(fill);\n if (lum < 0.45) shapes.push({ kind: \"surface\", ...at, tone: \"dark\" });\n else if (Math.abs(lum - pageLum) > 0.03) shapes.push({ kind: \"surface\", ...at, tone: \"light\" });\n continue;\n }\n if (!fill && border && at.w >= 120 && at.h >= 60) {\n shapes.push({ kind: \"frame\", ...at, tone: toneUnder(element) });\n }\n }\n\n // Text, one bar per rendered line, merged along the line.\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n const lines: WireframeShape[] = [];\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const parent = node.parentElement;\n if (!parent || !node.textContent?.trim() || insideTaken(parent) || !shown(parent)) continue;\n const css = style(parent);\n const size = parseFloat(css.fontSize) || 16;\n const heading = Boolean(parent.closest(\"h1,h2,h3,h4,h5,h6\")) || size >= 22;\n const color = parseColor(css.color);\n const tone: WireframeTone = color && luminance(color) > 0.5 ? \"light\" : \"dark\";\n const range = document.createRange();\n range.selectNodeContents(node);\n for (const rect of Array.from(range.getClientRects())) {\n if (rect.width < 2 || rect.height < 2) continue;\n const bar = Math.max(3, Math.round(size * (heading ? 0.62 : 0.5)));\n const y = Math.round(rect.top - origin.top + (rect.height - bar) / 2);\n const x = Math.round(rect.left - origin.left);\n const w = Math.round(rect.width);\n const kind = heading ? \"heading\" : \"text\";\n const previous = lines[lines.length - 1];\n if (\n previous &&\n previous.kind === kind &&\n \"tone\" in previous &&\n previous.tone === tone &&\n Math.abs(previous.y - y) <= 3 &&\n x - (previous.x + previous.w) <= 14\n ) {\n previous.w = Math.max(previous.x + previous.w, x + w) - previous.x;\n continue;\n }\n lines.push({ kind, x, y, w, h: bar, tone });\n }\n }\n\n return { width: Math.round(origin.width), height: Math.round(origin.height), shapes: [...shapes, ...lines] };\n}\n\nconst PAPER = \"#ffffff\";\nconst INK = \"#262626\";\nconst LIGHT_INK = \"#f5f5f5\";\nconst PALETTE = {\n frame: \"#d4d4d4\",\n imageFill: \"#e5e5e5\",\n imageLine: \"#a3a3a3\",\n tint: \"#f0f0f0\",\n textOnPaper: \"#a3a3a3\",\n textOnDark: \"#8a8a8a\",\n buttonOnPaper: \"#525252\",\n buttonOnDark: \"#d4d4d4\",\n} as const;\n\nconst DRAW_ORDER: Record<WireframeShape[\"kind\"], number> = {\n surface: 0,\n frame: 1,\n image: 2,\n field: 3,\n button: 4,\n icon: 5,\n heading: 6,\n text: 7,\n};\n\nconst n = (value: number) => String(Math.round(value * 10) / 10);\n\n/**\n * A capture as a 480 × 320 greyscale SVG. The block is scaled to the\n * width; a short block is centered, a tall one keeps its top and is clipped.\n * Surfaces first, text last, so marks sit on what they sit on in the page.\n */\nexport function wireframeSvg(capture: WireframeCapture): string {\n const scale = capture.width > 0 ? WIREFRAME_WIDTH / capture.width : 1;\n const drawn = capture.height * scale;\n const offset = drawn < WIREFRAME_HEIGHT ? (WIREFRAME_HEIGHT - drawn) / 2 : 0;\n const at = (shape: { x: number; y: number; w: number; h: number }) => ({\n x: n(shape.x * scale),\n y: n(shape.y * scale + offset),\n w: n(Math.max(shape.w * scale, 1)),\n h: n(Math.max(shape.h * scale, 1)),\n });\n const shapes = [...capture.shapes].sort((a, b) => DRAW_ORDER[a.kind] - DRAW_ORDER[b.kind]);\n\n const marks = shapes.map((shape) => {\n const { x, y, w, h } = at(shape);\n const r = (radius: number) => `rx='${n(radius)}'`;\n switch (shape.kind) {\n case \"surface\":\n return `<rect data-k='surface' x='${x}' y='${y}' width='${w}' height='${h}' fill='${shape.tone === \"dark\" ? INK : PALETTE.tint}'/>`;\n case \"frame\":\n return `<rect data-k='frame' x='${x}' y='${y}' width='${w}' height='${h}' ${r(4)} fill='none' stroke='${shape.tone === \"light\" ? PALETTE.textOnDark : PALETTE.frame}'/>`;\n case \"image\": {\n const x2 = n(Number(x) + Number(w));\n const y2 = n(Number(y) + Number(h));\n return (\n `<rect data-k='image' x='${x}' y='${y}' width='${w}' height='${h}' ${r(3)} fill='${PALETTE.imageFill}' stroke='${PALETTE.imageLine}'/>` +\n `<path data-k='image-x' d='M${x} ${y}L${x2} ${y2}M${x2} ${y}L${x} ${y2}' stroke='${PALETTE.imageLine}' stroke-width='0.75'/>`\n );\n }\n case \"field\":\n return `<rect data-k='field' x='${x}' y='${y}' width='${w}' height='${h}' ${r(3)} fill='${PAPER}' stroke='${PALETTE.imageLine}'/>`;\n case \"button\": {\n const color = shape.tone === \"light\" ? PALETTE.buttonOnDark : PALETTE.buttonOnPaper;\n const pill = r(Number(h) / 2);\n return shape.filled\n ? `<rect data-k='button' x='${x}' y='${y}' width='${w}' height='${h}' ${pill} fill='${color}'/>`\n : `<rect data-k='button' x='${x}' y='${y}' width='${w}' height='${h}' ${pill} fill='none' stroke='${color}' stroke-width='1.25'/>`;\n }\n case \"icon\":\n return `<circle data-k='icon' cx='${n(Number(x) + Number(w) / 2)}' cy='${n(Number(y) + Number(h) / 2)}' r='${n(Math.min(Number(w), Number(h)) / 2)}' fill='${shape.tone === \"light\" ? PALETTE.textOnDark : PALETTE.textOnPaper}'/>`;\n case \"heading\":\n return `<rect data-k='heading' x='${x}' y='${y}' width='${w}' height='${h}' ${r(Number(h) / 2)} fill='${shape.tone === \"light\" ? LIGHT_INK : INK}'/>`;\n case \"text\":\n return `<rect data-k='text' x='${x}' y='${y}' width='${w}' height='${h}' ${r(Number(h) / 2)} fill='${shape.tone === \"light\" ? PALETTE.textOnDark : PALETTE.textOnPaper}'/>`;\n }\n });\n\n return (\n `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${WIREFRAME_WIDTH} ${WIREFRAME_HEIGHT}'>` +\n `<defs><clipPath id='c'><rect width='${WIREFRAME_WIDTH}' height='${WIREFRAME_HEIGHT}'/></clipPath></defs>` +\n `<rect width='${WIREFRAME_WIDTH}' height='${WIREFRAME_HEIGHT}' fill='${PAPER}'/>` +\n `<g clip-path='url(#c)'>` +\n marks.join(\"\") +\n `</g></svg>`\n );\n}\n\n/**\n * An SVG as a `data:` URI for `admin.images.thumbnail`. Only the characters\n * a URI cannot carry are escaped, so the string stays close to the SVG's\n * own size; the SVG must use single quotes.\n */\nexport function svgDataUri(svg: string): string {\n const body = svg\n .replace(/\"/g, \"'\")\n .replace(/\\s+/g, \" \")\n .replace(/[%#<>{}|\\\\^`\\r\\n]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, \"0\")}`);\n return `data:image/svg+xml,${body}`;\n}\n\n/** The slice of Playwright's `Page` this needs; a site passes its own. */\nexport interface WireframePage {\n setViewportSize(size: { width: number; height: number }): Promise<void>;\n /** Playwright's `Response` (or `null`); a status of 400 or more refuses the capture. */\n goto(\n url: string,\n options?: { waitUntil?: \"load\" | \"domcontentloaded\" | \"networkidle\" },\n ): Promise<{ status(): number } | null | void>;\n evaluate<R, A>(fn: (arg: A) => R | Promise<R>, arg: A): Promise<R>;\n}\n\n/**\n * Opens each preview at desktop width, waits for its fonts, and returns\n * one SVG per slug. The page must already be signed in when the preview\n * route needs it (the Block library's does). A preview that answers 400 or\n * more, or renders no element `selector` matches, throws: nothing is\n * written for a page that did not draw its sample.\n */\nexport async function captureWireframes(\n page: WireframePage,\n previews: readonly { slug: string; url: string }[],\n { selector = WIREFRAME_ROOT }: { selector?: string } = {},\n): Promise<Record<string, string>> {\n await page.setViewportSize({ ...WIREFRAME_VIEWPORT });\n const out: Record<string, string> = {};\n for (const { slug, url } of previews) {\n const response = await page.goto(url, { waitUntil: \"networkidle\" });\n const status = response ? response.status() : 200;\n if (status >= 400) throw new Error(`${slug}: ${url} answered ${status}; is the server up, the slug right, and the login one the route accepts?`);\n await page.evaluate(() => document.fonts.ready.then(() => undefined), undefined);\n let capture: WireframeCapture;\n try {\n capture = await page.evaluate(extractWireframe, selector);\n } catch (error) {\n throw new Error(`${slug}: ${url} has no ${selector}; it did not render the sample`, { cause: error });\n }\n out[slug] = wireframeSvg(capture);\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAa,kBAAkB;AAC/B,MAAa,mBAAmB;;AAGhC,MAAa,qBAAqB;CAAE,OAAO;CAAM,QAAQ;CAAK;;AAG9D,MAAa,iBAAiB;;;;;;AAsB9B,SAAgB,iBAAiB,UAAoC;CACnE,MAAM,OAAO,SAAS,cAAc,SAAS;AAG7C,KAAI,CAAC,KAAM,OAAM,IAAI,MAAM,sBAAsB,WAAW;CAC5D,MAAM,SAAS,KAAK,uBAAuB;CAC3C,MAAM,SAA2B,EAAE;CACnC,MAAM,wBAAQ,IAAI,KAAc;CAEhC,MAAM,cAAc,UAA2D;EAC7E,MAAM,QAAQ,MAAM,MAAM,mBAAmB;AAC7C,MAAI,CAAC,MAAO,QAAO;EACnB,MAAM,QAAQ,MAAM,GAAI,MAAM,UAAU,CAAC,OAAO,QAAQ,CAAC,IAAI,OAAO;AACpE,SAAO;GAAC,MAAM,MAAM;GAAG,MAAM,MAAM;GAAG,MAAM,MAAM;GAAG,MAAM,MAAM;GAAE;;CAErE,MAAM,aAAa,SAA2C,QAAS,IAAI,KAAK,QAAS,IAAI,KAAK,QAAS,IAAI,MAAM;CACrH,MAAM,SAAS,YAAqB,iBAAiB,Q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;;;;AAsBlH,eAAsB,kBACpB,MACA,UACA,EAAE,WAAW,mBAA0C,EAAE,EACxB;AACjC,OAAM,KAAK,gBAAgB,EAAE,GAAG,oBAAoB,CAAC;CACrD,MAAM,MAA8B,EAAE;AACtC,MAAK,MAAM,EAAE,MAAM,SAAS,UAAU;EACpC,MAAM,WAAW,MAAM,KAAK,KAAK,KAAK,EAAE,WAAW,eAAe,CAAC;EACnE,MAAM,SAAS,WAAW,SAAS,QAAQ,GAAG;AAC9C,MAAI,UAAU,IAAK,OAAM,IAAI,MAAM,GAAG,KAAK,IAAI,IAAI,YAAY,OAAO,0EAA0E;AAChJ,QAAM,KAAK,eAAe,SAAS,MAAM,MAAM,WAAW,KAAA,EAAU,EAAE,KAAA,EAAU;EAChF,IAAI;AACJ,MAAI;AACF,aAAU,MAAM,KAAK,SAAS,kBAAkB,SAAS;WAClD,OAAO;AACd,SAAM,IAAI,MAAM,GAAG,KAAK,IAAI,IAAI,UAAU,SAAS,iCAAiC,EAAE,OAAO,OAAO,CAAC;;AAEvG,MAAI,QAAQ,aAAa,QAAQ;;AAEnC,QAAO"}
1
+ {"version":3,"file":"wireframe-CXorKFU_.mjs","names":[],"sources":["../src/wireframe.ts"],"sourcesContent":["/**\n * @deprecated since 4.16: the Add Block drawer shows screenshots now\n * (`@bison-lab/payload-core/block-thumbnails`, `bison-block-thumbnails`).\n * Kept working for this release so a site that calls it does not break;\n * it goes in the next major.\n *\n * Black-and-white wireframes of Block library samples, for Payload's Add\n * Block drawer (`admin.images.thumbnail`). React-free and Payload-free: a\n * script drives a browser to each block's preview (`previewPath(slug)`),\n * `extractWireframe` reads where the headings, text, images, buttons and\n * surfaces sit, and `wireframeSvg` draws those boxes as greyscale shapes.\n * No copy and no brand color reach the picture, so it does not go stale\n * when Theme changes; rerun it when a block's layout does.\n */\n\n/** Payload's drawer card is 3:2; 480 × 320 is the size its docs suggest. */\nexport const WIREFRAME_WIDTH = 480;\nexport const WIREFRAME_HEIGHT = 320;\n\n/** Desktop width, so the picture is the layout most visitors see. */\nexport const WIREFRAME_VIEWPORT = { width: 1280, height: 900 } as const;\n\n/** The element the Block library preview wraps each sample in (`BlockLibraryIsland`). */\nexport const WIREFRAME_ROOT = \"[data-block-library-island]\";\n\n/** `light` draws light marks (they sit on a dark surface); `dark` draws dark ones (on paper). */\nexport type WireframeTone = \"light\" | \"dark\";\n\nexport type WireframeShape =\n /** A band or panel the block paints. `dark` is a dark fill; `light` a pale tint. */\n | { kind: \"surface\"; x: number; y: number; w: number; h: number; tone: WireframeTone }\n /** A bordered card with no fill of its own. */\n | { kind: \"frame\"; x: number; y: number; w: number; h: number; tone: WireframeTone }\n | { kind: \"image\"; x: number; y: number; w: number; h: number }\n | { kind: \"heading\" | \"text\" | \"icon\"; x: number; y: number; w: number; h: number; tone: WireframeTone }\n | { kind: \"button\"; x: number; y: number; w: number; h: number; filled: boolean; tone: WireframeTone }\n | { kind: \"field\"; x: number; y: number; w: number; h: number };\n\nexport type WireframeCapture = { width: number; height: number; shapes: WireframeShape[] };\n\n/**\n * Runs in the page (Playwright's `page.evaluate`), so it closes over\n * nothing: every helper is declared inside. Boxes are relative to the\n * element `selector` names (the preview's island), in CSS pixels.\n */\nexport function extractWireframe(selector: string): WireframeCapture {\n const root = document.querySelector(selector);\n // No sample on the page (a sign-in wall, a 404, a wrong selector): refuse,\n // rather than draw whatever page came back as the block's picture.\n if (!root) throw new Error(`no element matches ${selector}`);\n const origin = root.getBoundingClientRect();\n const shapes: WireframeShape[] = [];\n const taken = new Set<Element>();\n\n const parseColor = (value: string): [number, number, number, number] | null => {\n const match = value.match(/rgba?\\(([^)]+)\\)/);\n if (!match) return null;\n const parts = match[1]!.split(/[\\s,/]+/).filter(Boolean).map(Number);\n return [parts[0] ?? 0, parts[1] ?? 0, parts[2] ?? 0, parts[3] ?? 1];\n };\n const luminance = (rgb: [number, number, number, number]) => (0.2126 * rgb[0] + 0.7152 * rgb[1] + 0.0722 * rgb[2]) / 255;\n const style = (element: Element) => getComputedStyle(element);\n const shown = (element: Element) => {\n const css = style(element);\n return css.display !== \"none\" && css.visibility !== \"hidden\" && Number(css.opacity || \"1\") > 0.05;\n };\n const box = (element: Element) => {\n const rect = element.getBoundingClientRect();\n return {\n x: Math.round(rect.left - origin.left),\n y: Math.round(rect.top - origin.top),\n w: Math.round(rect.width),\n h: Math.round(rect.height),\n };\n };\n /** The fill an element paints, if any: a solid color, or a gradient's first stop. */\n const fillOf = (element: Element) => {\n const css = style(element);\n const solid = parseColor(css.backgroundColor);\n if (solid && solid[3] >= 0.5) return solid;\n if (css.backgroundImage.includes(\"gradient\")) return parseColor(css.backgroundImage);\n return null;\n };\n /** Light marks when the nearest painted ancestor is dark. */\n const toneUnder = (element: Element): WireframeTone => {\n for (let node: Element | null = element; node; node = node.parentElement) {\n const fill = fillOf(node);\n if (fill) return luminance(fill) < 0.45 ? \"light\" : \"dark\";\n if (node === root) break;\n }\n return \"dark\";\n };\n const insideTaken = (element: Element | null) => {\n for (let node = element; node && node !== root; node = node.parentElement) if (taken.has(node)) return true;\n return false;\n };\n\n const page = parseColor(style(document.body).backgroundColor);\n const pageLum = page && page[3] >= 0.5 ? luminance(page) : 1;\n\n const elements = root.querySelectorAll(\"*\");\n for (const element of Array.from(elements)) {\n if (insideTaken(element.parentElement) || !shown(element)) continue;\n const at = box(element);\n if (at.w < 2 || at.h < 2) continue;\n const tag = element.tagName.toLowerCase();\n const css = style(element);\n\n if (tag === \"img\" || tag === \"picture\" || tag === \"video\" || tag === \"canvas\" || tag === \"iframe\") {\n shapes.push({ kind: \"image\", ...at });\n taken.add(element);\n continue;\n }\n if (tag === \"svg\") {\n if (at.w >= 48 && at.h >= 48) shapes.push({ kind: \"image\", ...at });\n else {\n const color = parseColor(css.color);\n shapes.push({ kind: \"icon\", ...at, tone: color && luminance(color) > 0.5 ? \"light\" : \"dark\" });\n }\n taken.add(element);\n continue;\n }\n if (tag === \"input\" || tag === \"select\" || tag === \"textarea\") {\n if ((element as HTMLInputElement).type !== \"hidden\") shapes.push({ kind: \"field\", ...at });\n taken.add(element);\n continue;\n }\n\n const fill = fillOf(element);\n const border = parseFloat(css.borderTopWidth) >= 1 && css.borderTopStyle !== \"none\";\n const action = tag === \"a\" || tag === \"button\" || element.getAttribute(\"role\") === \"button\";\n if (action && (fill || border) && at.h >= 24 && at.h <= 80 && at.w <= 480) {\n shapes.push({ kind: \"button\", ...at, filled: Boolean(fill), tone: toneUnder(element.parentElement ?? element) });\n taken.add(element);\n continue;\n }\n if (/url\\(/.test(css.backgroundImage) && at.w >= 48 && at.h >= 48) {\n shapes.push({ kind: \"image\", ...at });\n continue;\n }\n if (fill && at.w >= 160 && at.h >= 80) {\n const lum = luminance(fill);\n if (lum < 0.45) shapes.push({ kind: \"surface\", ...at, tone: \"dark\" });\n else if (Math.abs(lum - pageLum) > 0.03) shapes.push({ kind: \"surface\", ...at, tone: \"light\" });\n continue;\n }\n if (!fill && border && at.w >= 120 && at.h >= 60) {\n shapes.push({ kind: \"frame\", ...at, tone: toneUnder(element) });\n }\n }\n\n // Text, one bar per rendered line, merged along the line.\n const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);\n const lines: WireframeShape[] = [];\n for (let node = walker.nextNode(); node; node = walker.nextNode()) {\n const parent = node.parentElement;\n if (!parent || !node.textContent?.trim() || insideTaken(parent) || !shown(parent)) continue;\n const css = style(parent);\n const size = parseFloat(css.fontSize) || 16;\n const heading = Boolean(parent.closest(\"h1,h2,h3,h4,h5,h6\")) || size >= 22;\n const color = parseColor(css.color);\n const tone: WireframeTone = color && luminance(color) > 0.5 ? \"light\" : \"dark\";\n const range = document.createRange();\n range.selectNodeContents(node);\n for (const rect of Array.from(range.getClientRects())) {\n if (rect.width < 2 || rect.height < 2) continue;\n const bar = Math.max(3, Math.round(size * (heading ? 0.62 : 0.5)));\n const y = Math.round(rect.top - origin.top + (rect.height - bar) / 2);\n const x = Math.round(rect.left - origin.left);\n const w = Math.round(rect.width);\n const kind = heading ? \"heading\" : \"text\";\n const previous = lines[lines.length - 1];\n if (\n previous &&\n previous.kind === kind &&\n \"tone\" in previous &&\n previous.tone === tone &&\n Math.abs(previous.y - y) <= 3 &&\n x - (previous.x + previous.w) <= 14\n ) {\n previous.w = Math.max(previous.x + previous.w, x + w) - previous.x;\n continue;\n }\n lines.push({ kind, x, y, w, h: bar, tone });\n }\n }\n\n return { width: Math.round(origin.width), height: Math.round(origin.height), shapes: [...shapes, ...lines] };\n}\n\nconst PAPER = \"#ffffff\";\nconst INK = \"#262626\";\nconst LIGHT_INK = \"#f5f5f5\";\nconst PALETTE = {\n frame: \"#d4d4d4\",\n imageFill: \"#e5e5e5\",\n imageLine: \"#a3a3a3\",\n tint: \"#f0f0f0\",\n textOnPaper: \"#a3a3a3\",\n textOnDark: \"#8a8a8a\",\n buttonOnPaper: \"#525252\",\n buttonOnDark: \"#d4d4d4\",\n} as const;\n\nconst DRAW_ORDER: Record<WireframeShape[\"kind\"], number> = {\n surface: 0,\n frame: 1,\n image: 2,\n field: 3,\n button: 4,\n icon: 5,\n heading: 6,\n text: 7,\n};\n\nconst n = (value: number) => String(Math.round(value * 10) / 10);\n\n/**\n * A capture as a 480 × 320 greyscale SVG. The block is scaled to the\n * width; a short block is centered, a tall one keeps its top and is clipped.\n * Surfaces first, text last, so marks sit on what they sit on in the page.\n */\nexport function wireframeSvg(capture: WireframeCapture): string {\n const scale = capture.width > 0 ? WIREFRAME_WIDTH / capture.width : 1;\n const drawn = capture.height * scale;\n const offset = drawn < WIREFRAME_HEIGHT ? (WIREFRAME_HEIGHT - drawn) / 2 : 0;\n const at = (shape: { x: number; y: number; w: number; h: number }) => ({\n x: n(shape.x * scale),\n y: n(shape.y * scale + offset),\n w: n(Math.max(shape.w * scale, 1)),\n h: n(Math.max(shape.h * scale, 1)),\n });\n const shapes = [...capture.shapes].sort((a, b) => DRAW_ORDER[a.kind] - DRAW_ORDER[b.kind]);\n\n const marks = shapes.map((shape) => {\n const { x, y, w, h } = at(shape);\n const r = (radius: number) => `rx='${n(radius)}'`;\n switch (shape.kind) {\n case \"surface\":\n return `<rect data-k='surface' x='${x}' y='${y}' width='${w}' height='${h}' fill='${shape.tone === \"dark\" ? INK : PALETTE.tint}'/>`;\n case \"frame\":\n return `<rect data-k='frame' x='${x}' y='${y}' width='${w}' height='${h}' ${r(4)} fill='none' stroke='${shape.tone === \"light\" ? PALETTE.textOnDark : PALETTE.frame}'/>`;\n case \"image\": {\n const x2 = n(Number(x) + Number(w));\n const y2 = n(Number(y) + Number(h));\n return (\n `<rect data-k='image' x='${x}' y='${y}' width='${w}' height='${h}' ${r(3)} fill='${PALETTE.imageFill}' stroke='${PALETTE.imageLine}'/>` +\n `<path data-k='image-x' d='M${x} ${y}L${x2} ${y2}M${x2} ${y}L${x} ${y2}' stroke='${PALETTE.imageLine}' stroke-width='0.75'/>`\n );\n }\n case \"field\":\n return `<rect data-k='field' x='${x}' y='${y}' width='${w}' height='${h}' ${r(3)} fill='${PAPER}' stroke='${PALETTE.imageLine}'/>`;\n case \"button\": {\n const color = shape.tone === \"light\" ? PALETTE.buttonOnDark : PALETTE.buttonOnPaper;\n const pill = r(Number(h) / 2);\n return shape.filled\n ? `<rect data-k='button' x='${x}' y='${y}' width='${w}' height='${h}' ${pill} fill='${color}'/>`\n : `<rect data-k='button' x='${x}' y='${y}' width='${w}' height='${h}' ${pill} fill='none' stroke='${color}' stroke-width='1.25'/>`;\n }\n case \"icon\":\n return `<circle data-k='icon' cx='${n(Number(x) + Number(w) / 2)}' cy='${n(Number(y) + Number(h) / 2)}' r='${n(Math.min(Number(w), Number(h)) / 2)}' fill='${shape.tone === \"light\" ? PALETTE.textOnDark : PALETTE.textOnPaper}'/>`;\n case \"heading\":\n return `<rect data-k='heading' x='${x}' y='${y}' width='${w}' height='${h}' ${r(Number(h) / 2)} fill='${shape.tone === \"light\" ? LIGHT_INK : INK}'/>`;\n case \"text\":\n return `<rect data-k='text' x='${x}' y='${y}' width='${w}' height='${h}' ${r(Number(h) / 2)} fill='${shape.tone === \"light\" ? PALETTE.textOnDark : PALETTE.textOnPaper}'/>`;\n }\n });\n\n return (\n `<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${WIREFRAME_WIDTH} ${WIREFRAME_HEIGHT}'>` +\n `<defs><clipPath id='c'><rect width='${WIREFRAME_WIDTH}' height='${WIREFRAME_HEIGHT}'/></clipPath></defs>` +\n `<rect width='${WIREFRAME_WIDTH}' height='${WIREFRAME_HEIGHT}' fill='${PAPER}'/>` +\n `<g clip-path='url(#c)'>` +\n marks.join(\"\") +\n `</g></svg>`\n );\n}\n\n/**\n * An SVG as a `data:` URI for `admin.images.thumbnail`. Only the characters\n * a URI cannot carry are escaped, so the string stays close to the SVG's\n * own size; the SVG must use single quotes.\n */\nexport function svgDataUri(svg: string): string {\n const body = svg\n .replace(/\"/g, \"'\")\n .replace(/\\s+/g, \" \")\n .replace(/[%#<>{}|\\\\^`\\r\\n]/g, (char) => `%${char.charCodeAt(0).toString(16).toUpperCase().padStart(2, \"0\")}`);\n return `data:image/svg+xml,${body}`;\n}\n\n/** The slice of Playwright's `Page` this needs; a site passes its own. */\nexport interface WireframePage {\n setViewportSize(size: { width: number; height: number }): Promise<void>;\n /** Playwright's `Response` (or `null`); a status of 400 or more refuses the capture. */\n goto(\n url: string,\n options?: { waitUntil?: \"load\" | \"domcontentloaded\" | \"networkidle\" },\n ): Promise<{ status(): number } | null | void>;\n evaluate<R, A>(fn: (arg: A) => R | Promise<R>, arg: A): Promise<R>;\n}\n\n/**\n * Opens each preview at desktop width, waits for its fonts, and returns\n * one SVG per slug. The page must already be signed in when the preview\n * route needs it (the Block library's does). A preview that answers 400 or\n * more, or renders no element `selector` matches, throws: nothing is\n * written for a page that did not draw its sample.\n */\nexport async function captureWireframes(\n page: WireframePage,\n previews: readonly { slug: string; url: string }[],\n { selector = WIREFRAME_ROOT }: { selector?: string } = {},\n): Promise<Record<string, string>> {\n await page.setViewportSize({ ...WIREFRAME_VIEWPORT });\n const out: Record<string, string> = {};\n for (const { slug, url } of previews) {\n const response = await page.goto(url, { waitUntil: \"networkidle\" });\n const status = response ? response.status() : 200;\n if (status >= 400) throw new Error(`${slug}: ${url} answered ${status}; is the server up, the slug right, and the login one the route accepts?`);\n await page.evaluate(() => document.fonts.ready.then(() => undefined), undefined);\n let capture: WireframeCapture;\n try {\n capture = await page.evaluate(extractWireframe, selector);\n } catch (error) {\n throw new Error(`${slug}: ${url} has no ${selector}; it did not render the sample`, { cause: error });\n }\n out[slug] = wireframeSvg(capture);\n }\n return out;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAgBA,MAAa,kBAAkB;AAC/B,MAAa,mBAAmB;;AAGhC,MAAa,qBAAqB;CAAE,OAAO;CAAM,QAAQ;CAAK;;AAG9D,MAAa,iBAAiB;;;;;;AAsB9B,SAAgB,iBAAiB,UAAoC;CACnE,MAAM,OAAO,SAAS,cAAc,SAAS;AAG7C,KAAI,CAAC,KAAM,OAAM,IAAI,MAAM,sBAAsB,WAAW;CAC5D,MAAM,SAAS,KAAK,uBAAuB;CAC3C,MAAM,SAA2B,EAAE;CACnC,MAAM,wBAAQ,IAAI,KAAc;CAEhC,MAAM,cAAc,UAA2D;EAC7E,MAAM,QAAQ,MAAM,MAAM,mBAAmB;AAC7C,MAAI,CAAC,MAAO,QAAO;EACnB,MAAM,QAAQ,MAAM,GAAI,MAAM,UAAU,CAAC,OAAO,QAAQ,CAAC,IAAI,OAAO;AACpE,SAAO;GAAC,MAAM,MAAM;GAAG,MAAM,MAAM;GAAG,MAAM,MAAM;GAAG,MAAM,MAAM;GAAE;;CAErE,MAAM,aAAa,SAA2C,QAAS,IAAI,KAAK,QAAS,IAAI,KAAK,QAAS,IAAI,MAAM;CACrH,MAAM,SAAS,YAAqB,iBAAiB,QAAQ;CAC7D,MAAM,SAAS,YAAqB;EAClC,MAAM,MAAM,MAAM,QAAQ;AAC1B,SAAO,IAAI,YAAY,UAAU,IAAI,eAAe,YAAY,OAAO,IAAI,WAAW,IAAI,GAAG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EAAE;AACtC,MAAK,MAAM,EAAE,MAAM,SAAS,UAAU;EACpC,MAAM,WAAW,MAAM,KAAK,KAAK,KAAK,EAAE,WAAW,eAAe,CAAC;EACnE,MAAM,SAAS,WAAW,SAAS,QAAQ,GAAG;AAC9C,MAAI,UAAU,IAAK,OAAM,IAAI,MAAM,GAAG,KAAK,IAAI,IAAI,YAAY,OAAO,0EAA0E;AAChJ,QAAM,KAAK,eAAe,SAAS,MAAM,MAAM,WAAW,KAAA,EAAU,EAAE,KAAA,EAAU;EAChF,IAAI;AACJ,MAAI;AACF,aAAU,MAAM,KAAK,SAAS,kBAAkB,SAAS;WAClD,OAAO;AACd,SAAM,IAAI,MAAM,GAAG,KAAK,IAAI,IAAI,UAAU,SAAS,iCAAiC,EAAE,OAAO,OAAO,CAAC;;AAEvG,MAAI,QAAQ,aAAa,QAAQ;;AAEnC,QAAO"}
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as captureWireframes, s as svgDataUri } from "./wireframe-xcJNJzBf.mjs";
2
+ import { a as captureWireframes, s as svgDataUri } from "./wireframe-CXorKFU_.mjs";
3
3
  import { createRequire } from "node:module";
4
4
  import { mkdirSync, writeFileSync } from "node:fs";
5
5
  import { dirname, join, resolve } from "node:path";
@@ -1,2 +1,2 @@
1
- import { a as captureWireframes, c as wireframeSvg, i as WIREFRAME_WIDTH, n as WIREFRAME_ROOT, o as extractWireframe, r as WIREFRAME_VIEWPORT, s as svgDataUri, t as WIREFRAME_HEIGHT } from "./wireframe-xcJNJzBf.mjs";
1
+ import { a as captureWireframes, c as wireframeSvg, i as WIREFRAME_WIDTH, n as WIREFRAME_ROOT, o as extractWireframe, r as WIREFRAME_VIEWPORT, s as svgDataUri, t as WIREFRAME_HEIGHT } from "./wireframe-CXorKFU_.mjs";
2
2
  export { WIREFRAME_HEIGHT, WIREFRAME_ROOT, WIREFRAME_VIEWPORT, WIREFRAME_WIDTH, captureWireframes, extractWireframe, svgDataUri, wireframeSvg };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bison-lab/payload-core",
3
- "version": "4.39.0",
3
+ "version": "5.0.0",
4
4
  "description": "Site-agnostic Payload CMS configuration for Bison Lab sites: the SEO tab, the Theme global, the Roles Global, the brand-assets cupboard, and the metadata and theme readers for the pages they describe",
5
5
  "keywords": [
6
6
  "bison-lab",
@@ -93,9 +93,9 @@
93
93
  },
94
94
  "peerDependencies": {
95
95
  "@anthropic-ai/sdk": ">=0.110.0",
96
- "@bison-lab/fonts": "^3.0.0 || ^4.0.0",
97
- "@bison-lab/tokens": "^3.0.0 || ^4.0.0",
98
- "@bison-lab/ui": "^4.0.0",
96
+ "@bison-lab/fonts": "^3.0.0 || ^4.0.0 || ^5.0.0",
97
+ "@bison-lab/tokens": "^3.0.0 || ^4.0.0 || ^5.0.0",
98
+ "@bison-lab/ui": "^4.0.0 || ^5.0.0",
99
99
  "@payloadcms/live-preview-react": "^3.0.0",
100
100
  "@payloadcms/plugin-redirects": "^3.0.0",
101
101
  "@payloadcms/plugin-seo": "^3.0.0",
@@ -108,9 +108,6 @@
108
108
  "satori": ">=0.10.0"
109
109
  },
110
110
  "peerDependenciesMeta": {
111
- "@anthropic-ai/sdk": {
112
- "optional": true
113
- },
114
111
  "@bison-lab/fonts": {
115
112
  "optional": false
116
113
  },
@@ -176,6 +173,7 @@
176
173
  "clean": "rm -rf dist",
177
174
  "typecheck": "tsc --noEmit",
178
175
  "test": "vitest run",
179
- "test:watch": "vitest"
176
+ "test:watch": "vitest",
177
+ "test:postgres": "BISON_PG_TEST=1 vitest run src/__tests__/translate-localize-postgres.test.ts"
180
178
  }
181
179
  }
@@ -1 +0,0 @@
1
- {"version":3,"file":"locale-CFWfB4wP.mjs","names":[],"sources":["../src/locale.ts"],"sourcesContent":["/**\n * Which locale a read returns, as Payload's Local API takes it. Omit both\n * on a single-locale site. On a multi-locale site pass the request's\n * locale, or a Spanish page renders the default locale's copy.\n * `fallbackLocale: false` returns empty where the locale has no value\n * instead of the default locale's.\n */\nexport interface LocaleRead {\n locale?: string;\n fallbackLocale?: string | false;\n}\n\n/** The `locale` / `fallbackLocale` arguments to spread into a read, only when set. */\nexport function localeArgs({ locale, fallbackLocale }: LocaleRead = {}): LocaleRead {\n return {\n ...(locale !== undefined ? { locale } : {}),\n ...(fallbackLocale !== undefined ? { fallbackLocale } : {}),\n };\n}\n"],"mappings":";;AAaA,SAAgB,WAAW,EAAE,QAAQ,mBAA+B,EAAE,EAAc;AAClF,QAAO;EACL,GAAI,WAAW,KAAA,IAAY,EAAE,QAAQ,GAAG,EAAE;EAC1C,GAAI,mBAAmB,KAAA,IAAY,EAAE,gBAAgB,GAAG,EAAE;EAC3D"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"locale-CWiIcGuU.d.mts","names":[],"sources":["../src/locale.ts"],"mappings":";;AAOA;;;;;;UAAiB,UAAA;EACf,MAAA;EACA,cAAA;AAAA"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"messages-Fl1spIwN.mjs","names":[],"sources":["../src/translate/strings.ts","../src/translate/anthropic.ts","../src/translate/messages.ts"],"sourcesContent":["import type { TranslateRequest, Translator } from \"./types\";\n\n/**\n * Translates `strings` with `translator` in one batch, preserving order.\n * Repeated strings are sent once. Returns `null` when the translator throws,\n * returns `null`, or returns anything but one string per string sent, so a\n * caller can leave the target as it was. Never throws.\n */\nexport async function translateStrings(\n strings: readonly string[],\n options: TranslateRequest & { translator: Translator },\n): Promise<string[] | null> {\n if (strings.length === 0) return [];\n const { translator, ...request } = options;\n const unique = [...new Set(strings)];\n let result: unknown;\n try {\n result = await translator(unique, request);\n } catch {\n return null;\n }\n if (!Array.isArray(result) || result.length !== unique.length) return null;\n if (!result.every((value) => typeof value === \"string\")) return null;\n const byString = new Map(unique.map((value, index) => [value, result[index] as string]));\n return strings.map((value) => byString.get(value) ?? value);\n}\n\n/** True unless the translator says it cannot run (an Anthropic translator with no API key). */\nexport function isTranslatorConfigured(translator: Translator | undefined): translator is Translator {\n return translator !== undefined && translator.configured !== false;\n}\n","import type { TranslateRequest, TranslateSite, Translator } from \"./types\";\n\n/**\n * The library's default model. Translating marketing copy does not need the\n * most capable model; a current Sonnet handles it well at a fraction of the\n * price. A site overrides it per environment (`ANTHROPIC_TRANSLATE_MODEL`).\n */\nexport const DEFAULT_TRANSLATE_MODEL = \"claude-sonnet-5-5\";\n\n/**\n * The SDK's defaults are a 10-minute timeout with retries. A translation\n * must stay bounded to seconds, not minutes: the manual endpoint awaits it\n * while an editor waits, and a deferred run must finish inside the host's\n * `waitUntil` window. One retry, 90s cap, then the target stays as it was.\n */\nconst TIMEOUT_MS = 90_000;\nconst MAX_RETRIES = 1;\n\n/** The slice of the Anthropic client this translator calls. */\nexport interface AnthropicMessagesClient {\n messages: {\n create(\n body: Record<string, unknown>,\n options?: { timeout?: number; maxRetries?: number },\n ): Promise<{ content: Array<{ type: string; text?: string }> }>;\n };\n}\n\nexport interface AnthropicTranslatorOptions {\n /**\n * The API key, usually `process.env.ANTHROPIC_API_KEY`. Without one the\n * translator reports `configured: false`: publishes still work, a\n * warning is logged, and \"Translate now\" is hidden.\n */\n apiKey?: string | null;\n /** The model id; omitted or blank uses `DEFAULT_TRANSLATE_MODEL`. */\n model?: string | null;\n /** The site facts the prompt carries. The plugin's own `site`, when given, wins. */\n site?: TranslateSite;\n /** A client to use instead of constructing one (tests, a proxied client). */\n client?: AnthropicMessagesClient;\n}\n\nfunction languageName(code: string, site: TranslateSite | undefined): string {\n const named = site?.languages?.[code];\n if (named) return named;\n try {\n return new Intl.DisplayNames([\"en\"], { type: \"language\" }).of(code) ?? code;\n } catch {\n return code;\n }\n}\n\n/**\n * The system prompt: the library's generic rules plus the site's own facts.\n * Exported so a site can read exactly what the model is told.\n */\nexport function translationSystemPrompt(request: Pick<TranslateRequest, \"from\" | \"to\" | \"site\">): string {\n const { site } = request;\n const from = languageName(request.from, site);\n const to = languageName(request.to, site);\n const who = site?.name\n ? `You are a professional translator for ${site.name}${site.about ? `, ${site.about}` : \"\"}.`\n : \"You are a professional translator for a business website.\";\n const voice = site?.voice ? ` Keep the ${site.voice} brand voice.` : \" Keep the brand voice.\";\n const verbatim = [site?.name, ...(site?.keepVerbatim ?? [])].filter(\n (value, index, all): value is string => Boolean(value) && all.indexOf(value) === index,\n );\n const keep = verbatim.length\n ? `- Keep these EXACTLY as written, untranslated: ${verbatim.join(\n \", \",\n )}. Also keep URLs, email addresses and phone numbers as written.`\n : \"- Keep URLs, email addresses and phone numbers exactly as written.\";\n\n return `${who} Translate website and UI copy from ${from} into clear, natural ${to}.${voice}\n\nHard rules:\n- You receive a JSON array of strings. Return ONLY a JSON array of the translated strings, in the SAME ORDER and SAME LENGTH. No prose, no markdown, no code fences.\n${keep}\n- Preserve any ICU/message placeholders such as {year}, {count}, {name} verbatim, including the braces.\n- Preserve any HTML tags (e.g. <em>...</em>, <strong>...</strong>) and their positions; translate only the text between them.\n- For legal, regulatory or compliance copy, translate faithfully and literally. This output is a first-pass draft for a native speaker to review, not final compliance copy.\n- If a string is empty or is only a placeholder/URL/number, return it unchanged.`;\n}\n\n/** Tolerant JSON-array parse: strips accidental ``` fences and prose around the array, and checks the shape. */\nexport function parseJsonArray(text: string): string[] | null {\n let candidate = text.trim();\n const fenced = candidate.match(/```(?:json)?\\s*([\\s\\S]*?)```/);\n if (fenced?.[1] !== undefined) candidate = fenced[1].trim();\n // If the model wrapped the array in prose, take the outermost [ ... ].\n const start = candidate.indexOf(\"[\");\n const end = candidate.lastIndexOf(\"]\");\n if (start !== -1 && end > start) candidate = candidate.slice(start, end + 1);\n try {\n const value: unknown = JSON.parse(candidate);\n if (Array.isArray(value) && value.every((item) => typeof item === \"string\")) return value as string[];\n } catch {\n // fall through\n }\n return null;\n}\n\n/**\n * The provided `Translator`: one Anthropic Messages call per batch, the\n * strings as a JSON array in and out. `@anthropic-ai/sdk` is an optional\n * peer, loaded on the first call, so a site with translation off installs\n * nothing. Every failure (no key, the SDK missing, a network error, a\n * refusal, a malformed or wrong-length reply) returns `null` and is logged\n * by the caller; it never throws.\n */\nexport function anthropicTranslator(options: AnthropicTranslatorOptions): Translator {\n const apiKey = options.apiKey || undefined;\n const model = options.model?.trim() || DEFAULT_TRANSLATE_MODEL;\n let client: AnthropicMessagesClient | undefined = options.client;\n\n const getClient = async (): Promise<AnthropicMessagesClient | null> => {\n if (client) return client;\n if (!apiKey) return null;\n const sdk = (await import(\"@anthropic-ai/sdk\")) as unknown as {\n default: new (init: { apiKey: string }) => AnthropicMessagesClient;\n };\n client = new sdk.default({ apiKey });\n return client;\n };\n\n const translate = async (strings: string[], request: TranslateRequest): Promise<string[] | null> => {\n if (strings.length === 0) return [];\n try {\n const anthropic = await getClient();\n if (!anthropic) return null;\n const site = request.site ?? options.site;\n const to = languageName(request.to, site);\n const content =\n (request.context ? `Context: ${request.context}\\n\\n` : \"\") +\n `Translate this JSON array of ${strings.length} strings to ${to}:\\n${JSON.stringify(strings)}`;\n const response = await anthropic.messages.create(\n {\n model,\n max_tokens: 16000,\n // A batch of copy is routine work; low effort keeps it fast and\n // inside the timeout without changing the result.\n output_config: { effort: \"low\" },\n system: translationSystemPrompt({ from: request.from, to: request.to, site }),\n messages: [{ role: \"user\", content }],\n },\n { timeout: TIMEOUT_MS, maxRetries: MAX_RETRIES },\n );\n const text = response.content\n .filter((block) => block.type === \"text\" && typeof block.text === \"string\")\n .map((block) => block.text)\n .join(\"\")\n .trim();\n const parsed = parseJsonArray(text);\n return parsed && parsed.length === strings.length ? parsed : null;\n } catch {\n return null;\n }\n };\n\n return Object.assign(translate, { configured: Boolean(apiKey || options.client) });\n}\n","import { translateStrings } from \"./strings\";\nimport type { TranslateSite, Translator } from \"./types\";\n\n/** A next-intl message file: nested objects and arrays with string leaves. */\nexport type MessagesJson = string | number | boolean | null | MessagesJson[] | { [key: string]: MessagesJson };\n\nconst BATCH_SIZE = 40;\n\n/** Every string leaf as [path, value]; array indexes are path segments. */\nfunction stringLeaves(\n node: MessagesJson,\n path: string[] = [],\n out: Array<[string[], string]> = [],\n): Array<[string[], string]> {\n if (typeof node === \"string\") out.push([path, node]);\n else if (Array.isArray(node)) node.forEach((item, index) => stringLeaves(item, [...path, String(index)], out));\n else if (node && typeof node === \"object\") {\n for (const [key, value] of Object.entries(node)) stringLeaves(value, [...path, key], out);\n }\n return out;\n}\n\nfunction getAtPath(root: MessagesJson, path: string[]): MessagesJson | undefined {\n let current: MessagesJson | undefined = root;\n for (const segment of path) {\n if (current == null || typeof current !== \"object\") return undefined;\n current = Array.isArray(current) ? current[Number(segment)] : current[segment];\n }\n return current;\n}\n\nfunction setAtPath(root: { [key: string]: MessagesJson }, path: string[], value: string): void {\n let current: { [key: string]: MessagesJson } | MessagesJson[] = root;\n for (let i = 0; i < path.length - 1; i++) {\n const segment = path[i]!;\n const wantArray = /^\\d+$/.test(path[i + 1]!);\n const container = current as Record<string, MessagesJson>;\n let child = container[segment];\n // Create the container when missing, and REPAIR it when the existing\n // target node has the opposite shape from the source (the source changed\n // an object into a list) so string keys never land in an array or the\n // reverse.\n if (child == null || typeof child !== \"object\" || Array.isArray(child) !== wantArray) {\n child = wantArray ? [] : {};\n container[segment] = child;\n }\n current = child as { [key: string]: MessagesJson } | MessagesJson[];\n }\n (current as Record<string, MessagesJson>)[path[path.length - 1]!] = value;\n}\n\n/**\n * The `{name}` arguments of a message, sorted. Plural and select messages are\n * skipped (their branch bodies are braced text the model rightly translates),\n * so this only checks plain interpolations.\n */\nfunction placeholderNames(message: string): string | null {\n if (/,\\s*(plural|select|selectordinal)\\s*,/.test(message)) return null;\n const names = [...message.matchAll(/\\{\\s*([A-Za-z_][\\w]*)\\s*\\}/g)].map((match) => match[1]!);\n return names.sort().join(\",\");\n}\n\n/** A translation that dropped or renamed a `{placeholder}` would break at render; keep the source instead. */\nexport function keepsPlaceholders(source: string, translated: string): boolean {\n const before = placeholderNames(source);\n return before === null || before === placeholderNames(translated);\n}\n\nexport interface FillMessagesResult {\n /** The target file to write. */\n messages: MessagesJson;\n /** Keys translated. */\n translated: number;\n /**\n * Keys whose batch failed, or whose translation lost a `{placeholder}`.\n * They hold the source text, so the file stays\n * complete (a hole renders as MISSING_MESSAGE); a plain re-run will not\n * retry them, `--force` (or a hand edit) will.\n */\n fellBack: number;\n}\n\n/**\n * Fills a target next-intl message file from the source file. The source is\n * the truth; only keys that are missing or empty in the target are\n * translated, so reviewed copy is never overwritten, unless `force`\n * re-translates every key. Batches of 40, so one failure costs at most 40\n * keys. `{placeholders}` survive because the translator's prompt keeps them.\n */\nexport async function fillMessages(options: {\n source: MessagesJson;\n target?: MessagesJson;\n translator: Translator;\n from: string;\n to: string;\n force?: boolean;\n context?: string;\n site?: TranslateSite;\n onProgress?: (done: number, total: number) => void;\n}): Promise<FillMessagesResult> {\n const base =\n !options.force && options.target && typeof options.target === \"object\" && !Array.isArray(options.target)\n ? (structuredClone(options.target) as { [key: string]: MessagesJson })\n : {};\n const missing = stringLeaves(options.source).filter(([path]) => {\n const existing = getAtPath(base, path);\n return typeof existing !== \"string\" || existing.trim() === \"\";\n });\n\n let translated = 0;\n let fellBack = 0;\n for (let i = 0; i < missing.length; i += BATCH_SIZE) {\n const batch = missing.slice(i, i + BATCH_SIZE);\n const sources = batch.map(([, value]) => value);\n const result = await translateStrings(sources, {\n translator: options.translator,\n from: options.from,\n to: options.to,\n context: options.context ?? \"Website UI strings\",\n ...(options.site ? { site: options.site } : {}),\n });\n batch.forEach(([path, source], index) => {\n const value = result?.[index];\n if (value !== undefined && keepsPlaceholders(source, value)) {\n translated += 1;\n setAtPath(base, path, value);\n } else {\n fellBack += 1;\n setAtPath(base, path, source);\n }\n });\n options.onProgress?.(Math.min(i + BATCH_SIZE, missing.length), missing.length);\n }\n return { messages: base, translated, fellBack };\n}\n"],"mappings":";;;;;;;AAQA,eAAsB,iBACpB,SACA,SAC0B;AAC1B,KAAI,QAAQ,WAAW,EAAG,QAAO,EAAE;CACnC,MAAM,EAAE,YAAY,GAAG,YAAY;CACnC,MAAM,SAAS,CAAC,G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