@bison-lab/payload-core 5.0.0 → 5.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"file":"capability-DHPE2kon.mjs","names":["isAccessArgs","cache"],"sources":["../src/features/types.ts","../src/roles/types.ts","../src/features/matrix.ts","../src/roles/matrix.ts","../src/roles/access.ts","../src/features/access.ts","../src/translate/fields.ts","../src/translate/key.ts","../src/translate/languages.ts","../src/translate/settings.ts","../src/translate/state.ts","../src/translate/types.ts","../src/translate/document.ts","../src/translate/endpoint.ts","../src/translate/after-commit.ts","../src/translate/guards.ts","../src/translate/hooks.ts","../src/translate/settings-endpoints.ts","../src/translate/capability.ts"],"sourcesContent":["export const FEATURES_SLUG = \"features\";\n\nexport const FEATURE_GROUPS = [\"pages\", \"media\", \"theme\", \"users\"] as const;\n\nexport type FeatureGroupId = (typeof FEATURE_GROUPS)[number];\n\nexport const FEATURE_GROUP_LABELS: Record<FeatureGroupId, string> = {\n pages: \"Pages\",\n media: \"Media\",\n theme: \"Theme\",\n users: \"Users\",\n};\n\nexport const PACKAGE_FEATURE_SLUGS = [\n \"content\",\n \"publish\",\n \"media\",\n \"users\",\n \"roles\",\n] as const;\n\nexport type PackageFeatureSlug = (typeof PACKAGE_FEATURE_SLUGS)[number];\n\nexport interface PackageFeature {\n slug: PackageFeatureSlug;\n label: string;\n group: FeatureGroupId;\n defaultReleased: boolean;\n}\n\n/**\n * Package catalogue. Features itself is not a row — that screen is\n * Developer-only in code. Theme is not a row either: every site has the\n * Theme Global, and who may edit it is the Roles grant `theme`. Empty\n * Global falls back to these defaults.\n */\nexport const PACKAGE_FEATURES: readonly PackageFeature[] = [\n { slug: \"content\", label: \"Content\", group: \"pages\", defaultReleased: true },\n { slug: \"publish\", label: \"Publish\", group: \"pages\", defaultReleased: true },\n { slug: \"media\", label: \"Media\", group: \"media\", defaultReleased: true },\n { slug: \"users\", label: \"Users\", group: \"users\", defaultReleased: true },\n { slug: \"roles\", label: \"Roles\", group: \"users\", defaultReleased: true },\n];\n\n/** A site-only row. Other sites never see this slug. */\nexport interface FeatureExtra {\n slug: string;\n label: string;\n group?: FeatureGroupId;\n defaultReleased?: boolean;\n}\n\nexport interface FeatureRow {\n id?: string | null;\n slug: string;\n label?: string | null;\n group?: string | null;\n released: boolean;\n}\n\nexport interface FeaturesDoc {\n features?: FeatureRow[] | null;\n}\n\nexport function isFeatureGroupId(value: unknown): value is FeatureGroupId {\n return typeof value === \"string\" && (FEATURE_GROUPS as readonly string[]).includes(value);\n}\n\nexport function isPackageFeatureSlug(value: unknown): value is PackageFeatureSlug {\n return typeof value === \"string\" && (PACKAGE_FEATURE_SLUGS as readonly string[]).includes(value);\n}\n\nexport function isFeatureSlug(value: unknown): value is string {\n return typeof value === \"string\" && /^[a-z][a-z0-9]*(-[a-z0-9]+)*$/.test(value);\n}\n\n/** @deprecated Locks are gone; the release switch is the valve. */\nexport function isLockedFeature(_slug: string, _locked?: boolean | null): boolean {\n return false;\n}\n","/**\n * The Roles Global a site's generated types will describe. Optional and\n * nullable, no index signature: a generated Global is assignable to this,\n * never the reverse.\n */\n\nexport const ROLES = [\"developer\", \"admin\", \"designer\", \"author\"] as const;\n\nexport type Role = (typeof ROLES)[number];\n\nexport const ROLE_LABELS: Record<Role, string> = {\n developer: \"Developer\",\n admin: \"Admin\",\n designer: \"Designer\",\n author: \"Author\",\n};\n\n/** Capability aliases over feature grants. Brand is the Theme grant. */\nexport const CAPABILITIES = [\"content\", \"brand\", \"publish\", \"users\"] as const;\n\nexport type Capability = (typeof CAPABILITIES)[number];\n\n/** One Roles grant. Opens the Theme document and brand-assets. Not a Features row. */\nexport const THEME_FEATURE_SLUGS = [\"theme\"] as const;\n\n/**\n * Grants stored before Theme was one row. Reading any of them is the\n * Theme grant, so a Designer who already had Colors keeps Theme.\n */\nexport const LEGACY_THEME_FEATURE_SLUGS = [\n \"theme-colors\",\n \"theme-typography\",\n \"theme-appearance\",\n \"theme-identity\",\n \"brand-assets\",\n] as const;\n\n/**\n * The Roles grant that opens Settings → Translation. Not a Features row:\n * every site has the screen. Developer and Admin always hold it; any other\n * role holds it when ticked.\n */\nexport const TRANSLATION_GRANT_SLUG = \"translation\";\n\n/** Roles that hold the translation grant whatever their ticks say. */\nexport const ALWAYS_TRANSLATION_ROLES: readonly string[] = [\"admin\"];\n\nexport const CAPABILITY_FEATURES: Record<Capability, readonly string[]> = {\n content: [\"content\"],\n publish: [\"publish\"],\n users: [\"users\"],\n brand: THEME_FEATURE_SLUGS,\n};\n\nexport const DEFAULT_ROLE_GRANTS: Record<Role, readonly string[]> = {\n developer: [],\n admin: [\"content\", \"publish\", \"media\", \"users\", \"roles\", TRANSLATION_GRANT_SLUG],\n designer: [\n \"content\",\n \"media\",\n ...THEME_FEATURE_SLUGS,\n \"users\",\n \"roles\",\n ],\n author: [\"content\", \"media\"],\n};\n\n/**\n * A site-defined row passed into `createRoles({ extras })`. The slug is the\n * stored key; the label is what Settings → Roles and Users show.\n */\nexport interface RoleExtra {\n role: string;\n label: string;\n grants?: readonly string[];\n}\n\nexport interface RoleRow {\n id?: string | null;\n role: string;\n label?: string | null;\n grants: string[];\n}\n\nexport interface RolesDoc {\n roles?: RoleRow[] | null;\n}\n\n/**\n * `req.user` as Payload hands it over. Structural so this module never\n * imports a site's generated `User`. `roles` is optional because a row\n * that predates the field must come back powerless.\n */\nexport type MaybeUser = {\n id?: string | number;\n roles?: readonly string[] | null;\n /** Feature slugs this login may use, stamped onto the JWT at read. */\n allowedFeatures?: readonly string[] | null;\n} | null | undefined;\n\nexport function isRole(value: unknown): value is Role {\n return typeof value === \"string\" && (ROLES as readonly string[]).includes(value);\n}\n\n/** Lowercase slug from a letters-and-spaces name: `designer`, `the-designer`. */\nexport function isRoleSlug(value: unknown): value is string {\n return typeof value === \"string\" && /^[a-z]+(-[a-z]+)*$/.test(value);\n}\n\n/** Display name: letters and single spaces only. `The Greatest Designer`. */\nexport function isRoleName(value: unknown): value is string {\n return typeof value === \"string\" && /^[A-Za-z]+(?: [A-Za-z]+)*$/.test(value.trim());\n}\n\n/** Strip digits and punctuation as the name is typed. Trailing space stays. */\nexport function sanitizeRoleNameInput(value: string): string {\n return value.replace(/[^A-Za-z ]/g, \"\").replace(/ {2,}/g, \" \");\n}\n\n/** Name → stored key. `The Greatest Designer` → `the-greatest-designer`. */\nexport function slugifyRoleName(value: unknown): string {\n if (typeof value !== \"string\") return \"\";\n return value\n .trim()\n .toLowerCase()\n .replace(/[^a-z]+/g, \"-\")\n .replace(/^-|-$/g, \"\");\n}\n\nexport function roleLabel(role: string, label?: string | null): string {\n const trimmed = typeof label === \"string\" ? label.trim() : \"\";\n if (trimmed) return trimmed;\n return isRole(role) ? ROLE_LABELS[role] : role;\n}\n\nexport function defaultGrantsForRole(role: string, extraGrants?: readonly string[]): string[] {\n if (isRole(role)) return [...DEFAULT_ROLE_GRANTS[role]];\n return extraGrants ? [...extraGrants] : [];\n}\n","import {\n FEATURE_GROUP_LABELS,\n isFeatureGroupId,\n isFeatureSlug,\n PACKAGE_FEATURES,\n type FeatureExtra,\n type FeatureGroupId,\n type FeatureRow,\n type PackageFeature,\n} from \"./types\";\nimport { LEGACY_THEME_FEATURE_SLUGS, TRANSLATION_GRANT_SLUG } from \"../roles/types\";\n\nexport const MISSING_PACKAGE_FEATURES_MESSAGE =\n \"Features must include Content, Publish, Media, Users, and Roles.\";\n\nexport interface FeatureCatalogueEntry {\n slug: string;\n label: string;\n group: FeatureGroupId;\n defaultReleased: boolean;\n}\n\nexport function featureCatalogue(extras: readonly FeatureExtra[] = []): FeatureCatalogueEntry[] {\n return [\n ...PACKAGE_FEATURES.map((feature) => ({ ...feature })),\n ...extras.map((extra) => ({\n slug: extra.slug,\n label: extra.label,\n group: extra.group ?? \"users\",\n defaultReleased: extra.defaultReleased ?? false,\n })),\n ];\n}\n\nexport function defaultFeaturesFieldValue(extras: readonly FeatureExtra[] = []): FeatureRow[] {\n return featureCatalogue(extras).map((feature) => ({\n id: feature.slug,\n slug: feature.slug,\n label: feature.label,\n group: feature.group,\n released: feature.defaultReleased,\n }));\n}\n\nexport function stampFeatureCatalogue(\n value: unknown,\n extras: readonly FeatureExtra[] = [],\n): FeatureRow[] {\n const bySlug = new Map(featureCatalogue(extras).map((feature) => [feature.slug, feature]));\n if (!Array.isArray(value)) return defaultFeaturesFieldValue(extras);\n return value.flatMap((item) => {\n if (!item || typeof item !== \"object\") return [];\n const slug = \"slug\" in item && typeof item.slug === \"string\" ? item.slug : \"\";\n const feature = bySlug.get(slug);\n if (!feature) return [];\n return [\n {\n id: feature.slug,\n slug: feature.slug,\n label: feature.label,\n group: feature.group,\n released: Boolean(\"released\" in item && item.released),\n },\n ];\n });\n}\n\nexport function parseFeaturesMatrix(\n value: unknown,\n): { ok: true; rows: FeatureRow[] } | { ok: false; message: string } {\n if (!Array.isArray(value) || value.length === 0) {\n return { ok: false, message: MISSING_PACKAGE_FEATURES_MESSAGE };\n }\n\n const rows: FeatureRow[] = [];\n const seen = new Set<string>();\n\n for (const item of value) {\n if (!item || typeof item !== \"object\") continue;\n const slug = \"slug\" in item ? item.slug : undefined;\n if (!isFeatureSlug(slug) || seen.has(slug)) continue;\n seen.add(slug);\n const pack = PACKAGE_FEATURES.find((feature) => feature.slug === slug);\n const label =\n \"label\" in item && typeof item.label === \"string\"\n ? item.label\n : (pack?.label ?? slug);\n const group =\n \"group\" in item && isFeatureGroupId(item.group) ? item.group : (pack?.group ?? \"users\");\n rows.push({\n id: slug,\n slug,\n label,\n group,\n released: Boolean(\"released\" in item && item.released),\n });\n }\n\n if (PACKAGE_FEATURES.some((feature) => !seen.has(feature.slug))) {\n return { ok: false, message: MISSING_PACKAGE_FEATURES_MESSAGE };\n }\n return { ok: true, rows };\n}\n\nexport function validateFeaturesMatrix(\n value: unknown,\n extras: readonly FeatureExtra[] = [],\n): true | string {\n const parsed = parseFeaturesMatrix(value);\n if (!parsed.ok) return parsed.message;\n const allowed = new Set(featureCatalogue(extras).map((feature) => feature.slug));\n const legacy = new Set<string>(LEGACY_THEME_FEATURE_SLUGS);\n // Retired Theme rows stay valid until beforeChange drops them. The admin\n // form calls validate without field hooks, so rejecting them blocks Save.\n if (parsed.rows.some((row) => !allowed.has(row.slug) && !legacy.has(row.slug))) {\n return MISSING_PACKAGE_FEATURES_MESSAGE;\n }\n return true;\n}\n\nexport function featureGroupLabel(group: string): string {\n return isFeatureGroupId(group) ? FEATURE_GROUP_LABELS[group] : group;\n}\n\nexport function packageFeatureLabel(slug: string, extras: readonly FeatureExtra[] = []): string {\n if (slug === \"theme\") return \"Theme\";\n if (slug === TRANSLATION_GRANT_SLUG) return \"Translation settings\";\n const pack = PACKAGE_FEATURES.find((feature) => feature.slug === slug);\n if (pack) return pack.label;\n const extra = extras.find((feature) => feature.slug === slug);\n return extra?.label ?? slug;\n}\n\nexport function isGroupOnlySlug(slug: string): boolean {\n return isFeatureGroupId(slug) && !PACKAGE_FEATURES.some((feature) => feature.slug === slug);\n}\n\nexport type { PackageFeature };\n","import { packageFeatureLabel } from \"../features/matrix\";\nimport { isFeatureSlug } from \"../features/types\";\nimport {\n CAPABILITY_FEATURES,\n defaultGrantsForRole,\n isRole,\n isRoleName,\n isRoleSlug,\n LEGACY_THEME_FEATURE_SLUGS,\n ROLE_LABELS,\n roleLabel,\n ROLES,\n slugifyRoleName,\n type Capability,\n type RoleExtra,\n type RoleRow,\n} from \"./types\";\n\nexport const ROLES_SLUG = \"roles\";\n\nexport const ROLES_GLOBAL_DESCRIPTION = \"Who may do what. Drag to change rank.\";\n\nexport const ROLES_FIELD_DESCRIPTION =\n \"Drag to change rank. Ticks are features released on Features, plus Theme. Developer has the whole catalogue.\"\n\n/**\n * Default rank and grants. Developer is implicit (empty grants). The\n * Theme grant defaults to Designer.\n */\nexport const DEFAULT_ROLE_MATRIX: readonly RoleRow[] = ROLES.map((role) => ({\n role,\n grants: defaultGrantsForRole(role),\n}));\n\nexport const DEVELOPER_DESCRIPTION =\n \"Everything, including features not released for assignment.\";\n\nexport const LAST_USERS_TICK_MESSAGE =\n \"Keep Users granted on at least one of Admin or Developer.\";\n\nexport const MISSING_SEED_ROLES_MESSAGE = \"Roles must include Developer.\";\n\nexport const DUPLICATE_ROLE_SLUG_MESSAGE = \"Each role needs a unique slug.\";\n\nexport const DUPLICATE_ROLE_NAME_MESSAGE = \"Each role needs a unique name.\";\n\nexport const INVALID_ROLE_NAME_MESSAGE = \"Use letters and spaces only.\";\n\nconst LEGACY_THEME_GRANTS = new Set<string>(LEGACY_THEME_FEATURE_SLUGS);\n\nfunction uniqueSlugs(values: readonly unknown[]): string[] {\n const slugs: string[] = [];\n for (const value of values) {\n if (typeof value === \"string\" && isFeatureSlug(value) && !slugs.includes(value)) slugs.push(value);\n }\n return slugs;\n}\n\n/** One Theme grant. A stored Colors or brand-assets tick is that grant. */\nfunction collapseThemeGrant(slugs: readonly string[]): string[] {\n let theme = false;\n const next: string[] = [];\n for (const slug of slugs) {\n if (slug === \"theme\" || LEGACY_THEME_GRANTS.has(slug)) {\n theme = true;\n continue;\n }\n next.push(slug);\n }\n if (theme) next.push(\"theme\");\n return next;\n}\n\n/** Read stored grants, or rebuild them from the old capability ticks. */\nexport function grantsFromStoredRole(item: object): string[] {\n if (\"grants\" in item && Array.isArray(item.grants)) return collapseThemeGrant(uniqueSlugs(item.grants));\n const grants: string[] = [];\n if (\"content\" in item && item.content) {\n grants.push(\"content\", \"media\");\n }\n if (\"publish\" in item && item.publish) grants.push(\"publish\");\n if (\"users\" in item && item.users) grants.push(\"users\", \"roles\");\n if (\"brand\" in item && item.brand) grants.push(\"theme\");\n return collapseThemeGrant(uniqueSlugs(grants));\n}\n\nexport function seedRoleRows(extras: readonly RoleExtra[] = []): RoleRow[] {\n return [\n ...DEFAULT_ROLE_MATRIX.map((row) => ({\n ...row,\n grants: [...row.grants],\n label: isRole(row.role) ? ROLE_LABELS[row.role] : row.role,\n })),\n ...extras.map((extra) => ({\n role: extra.role,\n label: extra.label,\n grants: extra.grants ? [...extra.grants] : [],\n })),\n ];\n}\n\nexport function defaultRolesFieldValue(extras: readonly RoleExtra[] = []): RoleRow[] {\n return seedRoleRows(extras).map((row) => ({ id: row.role, ...row }));\n}\n\nfunction readRoleRow(item: object): RoleRow | { error: string } {\n const role = \"role\" in item ? item.role : undefined;\n if (typeof role !== \"string\" || role.trim() === \"\") return { error: DUPLICATE_ROLE_SLUG_MESSAGE };\n if (!isRoleSlug(role)) return { error: DUPLICATE_ROLE_SLUG_MESSAGE };\n const label = \"label\" in item && typeof item.label === \"string\" ? item.label : undefined;\n return {\n id: role,\n role,\n label: roleLabel(role, label),\n grants: grantsFromStoredRole(item),\n };\n}\n\nexport function parseRolesMatrix(\n value: unknown,\n): { ok: true; rows: RoleRow[] } | { ok: false; message: string } {\n if (!Array.isArray(value)) {\n return { ok: false, message: MISSING_SEED_ROLES_MESSAGE };\n }\n\n const rows: RoleRow[] = [];\n const seen = new Set<string>();\n for (const item of value) {\n if (!item || typeof item !== \"object\") continue;\n // An Add Role row starts with no slug. Skip it so form-state can\n // build the fields; the slug field still refuses an empty save.\n const role = \"role\" in item ? item.role : undefined;\n if (typeof role !== \"string\" || role.trim() === \"\") continue;\n const parsed = readRoleRow(item);\n if (\"error\" in parsed) return { ok: false, message: parsed.error };\n if (seen.has(parsed.role)) return { ok: false, message: DUPLICATE_ROLE_SLUG_MESSAGE };\n seen.add(parsed.role);\n rows.push(parsed);\n }\n\n if (!seen.has(\"developer\")) {\n return { ok: false, message: MISSING_SEED_ROLES_MESSAGE };\n }\n return { ok: true, rows };\n}\n\nexport function roleHasGrant(row: RoleRow, slug: string): boolean {\n if (row.role === \"developer\") return true;\n return row.grants.includes(slug);\n}\n\nexport function roleHasCapability(row: RoleRow, capability: Capability): boolean {\n if (row.role === \"developer\") return true;\n return CAPABILITY_FEATURES[capability].some((slug) => row.grants.includes(slug));\n}\n\n/**\n * Mint a slug from the name only when the row has none yet. An existing\n * key — seed or custom — stays put so a rename cannot orphan users.\n */\nexport function applyRoleSlugsFromNames(value: unknown): unknown {\n if (!Array.isArray(value)) return value;\n return value.map((item) => {\n if (!item || typeof item !== \"object\") return item;\n const row = item as RoleRow;\n if (isRoleSlug(row.role)) return item;\n const slug = slugifyRoleName(row.label);\n return isRoleSlug(slug) ? { ...row, role: slug } : item;\n });\n}\n\nfunction hasDuplicateRoleNames(value: unknown): boolean {\n if (!Array.isArray(value)) return false;\n const seen = new Set<string>();\n for (const item of value) {\n if (!item || typeof item !== \"object\") continue;\n const role = \"role\" in item && typeof item.role === \"string\" ? item.role : \"\";\n const raw = \"label\" in item && typeof item.label === \"string\" ? item.label : \"\";\n const name = raw.trim() || (isRole(role) ? ROLE_LABELS[role] : \"\");\n if (!name) continue;\n const key = name.toLowerCase();\n if (seen.has(key)) return true;\n seen.add(key);\n }\n return false;\n}\n\nfunction hasInvalidRoleName(value: unknown): boolean {\n if (!Array.isArray(value)) return false;\n for (const item of value) {\n if (!item || typeof item !== \"object\") continue;\n const label = \"label\" in item && typeof item.label === \"string\" ? item.label.trim() : \"\";\n if (!label) continue;\n if (!isRoleName(label)) return true;\n }\n return false;\n}\n\nexport function validateRolesMatrix(value: unknown): true | string {\n if (hasDuplicateRoleNames(value)) return DUPLICATE_ROLE_NAME_MESSAGE;\n if (hasInvalidRoleName(value)) return INVALID_ROLE_NAME_MESSAGE;\n const parsed = parseRolesMatrix(applyRoleSlugsFromNames(value));\n if (!parsed.ok) return parsed.message;\n return true;\n}\n\n/**\n * Developer is exclusive. Admin does not swallow Designer: both store.\n * Unknown slugs (dropped catalogue keys such as `approver`) fall away unless\n * they appear on the matrix.\n */\nexport function normalizeStoredRoles(\n value: unknown,\n matrix: readonly RoleRow[] = DEFAULT_ROLE_MATRIX,\n): string[] {\n if (!Array.isArray(value)) return [];\n const allowed = new Set(matrix.map((row) => row.role));\n const roles = [...new Set(value.filter((entry): entry is string => typeof entry === \"string\" && allowed.has(entry)))];\n if (roles.includes(\"developer\")) return [\"developer\"];\n return roles;\n}\n\nexport function roleSelectOptions(matrix: readonly RoleRow[] = DEFAULT_ROLE_MATRIX) {\n return matrix.map((row) => ({ label: roleLabel(row.role, row.label), value: row.role }));\n}\n\n/** Grant copy only. Developer names the unreleased catalogue; nothing about MCP or seed. */\nexport function roleDescription(role: string, matrix: readonly RoleRow[] = DEFAULT_ROLE_MATRIX): string {\n if (role === \"developer\") return DEVELOPER_DESCRIPTION;\n const row = matrix.find((entry) => entry.role === role);\n if (!row) return \"No capabilities\";\n const ticks = row.grants.map((slug) => packageFeatureLabel(slug));\n return ticks.join(\", \") || \"No capabilities\";\n}\n\n/**\n * Seed grants and package labels come back; extra rows stay as they are.\n */\nexport function resetRolesMatrix(current: unknown): RoleRow[] {\n const extras: RoleRow[] = [];\n if (Array.isArray(current)) {\n for (const item of current) {\n if (!item || typeof item !== \"object\") continue;\n const parsed = readRoleRow(item);\n if (\"error\" in parsed || isRole(parsed.role)) continue;\n extras.push(parsed);\n }\n }\n return [...defaultRolesFieldValue(), ...extras];\n}\n","import type { Access, PayloadRequest } from \"payload\";\n\nimport { DEFAULT_ROLE_MATRIX, parseRolesMatrix, roleHasCapability, roleHasGrant, ROLES_SLUG, seedRoleRows } from \"./matrix\";\nimport { type Capability, type MaybeUser, type RoleExtra, type RoleRow } from \"./types\";\n\nexport type { MaybeUser } from \"./types\";\n\ntype AccessArgs = {\n req: {\n user?: MaybeUser;\n payload?: Pick<NonNullable<PayloadRequest[\"payload\"]>, \"findGlobal\">;\n };\n};\n\ntype CapabilityPredicate = {\n (user: MaybeUser, matrix?: readonly RoleRow[]): boolean;\n (args: AccessArgs): boolean | Promise<boolean>;\n};\n\nfunction isAccessArgs(value: unknown): value is AccessArgs {\n return typeof value === \"object\" && value !== null && \"req\" in value;\n}\n\nexport function storedRoles(user: MaybeUser): readonly string[] {\n return Array.isArray(user?.roles) ? user.roles : [];\n}\n\nexport function hasRole(user: MaybeUser, role: string): boolean {\n return storedRoles(user).includes(role);\n}\n\n/** Not a tick. True only when `developer` is stored on the row. */\nexport function isDeveloper(user: MaybeUser): boolean {\n return hasRole(user, \"developer\");\n}\n\nexport function hasCapability(\n user: MaybeUser,\n capability: Capability,\n matrix: readonly RoleRow[] = DEFAULT_ROLE_MATRIX,\n): boolean {\n if (isDeveloper(user)) return true;\n return storedRoles(user).some((role) => {\n const row = matrix.find((entry) => entry.role === role);\n return row ? roleHasCapability(row, capability) : false;\n });\n}\n\nexport function hasGrant(\n user: MaybeUser,\n slug: string,\n matrix: readonly RoleRow[] = DEFAULT_ROLE_MATRIX,\n): boolean {\n if (isDeveloper(user)) return true;\n return storedRoles(user).some((role) => {\n const row = matrix.find((entry) => entry.role === role);\n return row ? roleHasGrant(row, slug) : false;\n });\n}\n\n/**\n * Reads the saved Roles Global, falling back to the seed when the row is\n * empty, missing, or unreadable. Always override-access so a Designer\n * evaluating Theme does not have to read Settings → Roles.\n */\nexport async function getRolesMatrix(\n req: AccessArgs[\"req\"] = {},\n extras: readonly RoleExtra[] = [],\n): Promise<RoleRow[]> {\n const fallback = seedRoleRows(extras);\n const findGlobal = req.payload?.findGlobal;\n if (typeof findGlobal !== \"function\") return fallback;\n try {\n const doc = await findGlobal({\n slug: ROLES_SLUG,\n overrideAccess: true,\n req: req as PayloadRequest,\n });\n const parsed = parseRolesMatrix(doc && typeof doc === \"object\" && \"roles\" in doc ? doc.roles : undefined);\n return parsed.ok ? parsed.rows : fallback;\n } catch {\n return fallback;\n }\n}\n\nfunction capabilityPredicate(capability: Capability): CapabilityPredicate {\n function predicate(\n userOrArgs: MaybeUser | AccessArgs,\n matrix?: readonly RoleRow[],\n ): boolean | Promise<boolean> {\n if (isAccessArgs(userOrArgs)) {\n const user = userOrArgs.req.user as MaybeUser;\n if (matrix) return hasCapability(user, capability, matrix);\n return getRolesMatrix(userOrArgs.req).then((rows) => hasCapability(user, capability, rows));\n }\n return hasCapability(userOrArgs, capability, matrix ?? DEFAULT_ROLE_MATRIX);\n }\n return predicate as CapabilityPredicate;\n}\n\nexport const canManageContent = capabilityPredicate(\"content\");\nexport const canManageBrand = capabilityPredicate(\"brand\");\nexport const canPublish = capabilityPredicate(\"publish\");\n\n/** Users grant on any held role (Developer is implicit). */\nexport const isAdmin = capabilityPredicate(\"users\");\n\n/** This role id currently has the Users grant, or is Developer. */\nexport function isPrivilegedRole(\n role: unknown,\n matrix: readonly RoleRow[] = DEFAULT_ROLE_MATRIX,\n): boolean {\n if (typeof role !== \"string\") return false;\n if (role === \"developer\") return true;\n const row = matrix.find((entry) => entry.role === role);\n return row ? roleHasGrant(row, \"users\") : false;\n}\n\nexport function isAuthenticated(user: MaybeUser): boolean;\nexport function isAuthenticated(args: AccessArgs): boolean;\nexport function isAuthenticated(userOrArgs: MaybeUser | AccessArgs): boolean {\n if (isAccessArgs(userOrArgs)) return Boolean(userOrArgs.req.user);\n return Boolean(userOrArgs);\n}\n\nexport const isAdminOrSelf: Access = async ({ req }) => {\n if (!req.user) return false;\n if (await isAdmin({ req })) return true;\n return { id: { equals: req.user.id } };\n};\n\nexport const authenticatedOrPublished: Access = ({ req: { user } }) => {\n if (isAuthenticated(user as MaybeUser)) return true;\n return { _status: { equals: \"published\" } };\n};\n\n/**\n * API tab condition. Code-locked to the `developer` slug — not a Features\n * row and not a Role tick a client can grant.\n */\nexport function isDeveloperTab({ req }: AccessArgs): boolean {\n return isDeveloper(req.user as MaybeUser);\n}\n\n/** Access for chrome globals (Features, Better Editor settings). */\nexport function developerOnlyAccess(): { read: Access; update: Access } {\n return {\n read: ({ req }) => isDeveloper(req.user as MaybeUser),\n update: ({ req }) => isDeveloper(req.user as MaybeUser),\n };\n}\n\n/** `admin.hidden`: hide unless the login is Developer. */\nexport function hideUnlessDeveloper({ user }: { user?: MaybeUser }): boolean {\n return !isDeveloper(user);\n}\n","import type { PayloadRequest } from \"payload\";\n\nimport { getRolesMatrix, hasGrant, hasRole, isDeveloper, type MaybeUser } from \"../roles/access\";\nimport { DEFAULT_ROLE_MATRIX } from \"../roles/matrix\";\nimport type { RoleRow } from \"../roles/types\";\nimport { ALWAYS_TRANSLATION_ROLES, LEGACY_THEME_FEATURE_SLUGS, TRANSLATION_GRANT_SLUG } from \"../roles/types\";\nimport { defaultFeaturesFieldValue, isGroupOnlySlug, parseFeaturesMatrix } from \"./matrix\";\nimport { FEATURE_GROUPS, FEATURES_SLUG, type FeatureRow } from \"./types\";\n\ntype AccessArgs = {\n req: {\n user?: MaybeUser;\n payload?: Pick<NonNullable<PayloadRequest[\"payload\"]>, \"findGlobal\">;\n };\n};\n\ntype FeaturePredicate = {\n (user: MaybeUser, features?: readonly FeatureRow[] | null, roles?: readonly RoleRow[]): boolean;\n (args: AccessArgs): boolean | Promise<boolean>;\n};\n\nfunction isAccessArgs(value: unknown): value is AccessArgs {\n return typeof value === \"object\" && value !== null && \"req\" in value;\n}\n\nfunction grantedOnReleased(\n user: MaybeUser,\n slug: string,\n row: FeatureRow,\n matrix: readonly RoleRow[],\n): boolean {\n if (!row.released) return false;\n return hasGrant(user, slug, matrix);\n}\n\n/**\n * True when the feature is released and a held role is granted it.\n * Developer is always allowed. An empty Global falls back to catalogue\n * defaults. A group slug (`pages`) is true when any child is.\n * `theme` is the Roles grant: Features cannot release or withhold it.\n */\nexport function hasFeature(\n user: MaybeUser,\n slug: string,\n features: readonly FeatureRow[] | null = null,\n matrix: readonly RoleRow[] = DEFAULT_ROLE_MATRIX,\n): boolean {\n if (isDeveloper(user)) return true;\n if (!user) return false;\n // Retired slugs (`brand-assets`, `theme-colors`, …) are the Theme grant.\n // Sites that still pass canUseFeature(\"brand-assets\") keep Designer access.\n if (slug === \"theme\" || (LEGACY_THEME_FEATURE_SLUGS as readonly string[]).includes(slug)) {\n return hasGrant(user, \"theme\", matrix);\n }\n // Translation is a Roles grant too, and Admin holds it whatever its ticks say.\n if (slug === TRANSLATION_GRANT_SLUG) {\n return ALWAYS_TRANSLATION_ROLES.some((role) => hasRole(user, role)) || hasGrant(user, slug, matrix);\n }\n const rows = features && features.length > 0 ? features : defaultFeaturesFieldValue();\n const leaf = rows.find((entry) => entry.slug === slug);\n if (leaf) return grantedOnReleased(user, slug, leaf, matrix);\n if (!isGroupOnlySlug(slug)) return false;\n return rows.some((entry) => entry.group === slug && grantedOnReleased(user, entry.slug, entry, matrix));\n}\n\n/**\n * Reads the saved Features Global. `null` means empty or unreadable — callers\n * fall back to catalogue defaults. Always override-access.\n */\nexport async function getFeaturesMatrix(req: AccessArgs[\"req\"] = {}): Promise<FeatureRow[] | null> {\n const findGlobal = req.payload?.findGlobal;\n if (typeof findGlobal !== \"function\") return null;\n try {\n const doc = await findGlobal({\n slug: FEATURES_SLUG,\n overrideAccess: true,\n req: req as PayloadRequest,\n });\n const parsed = parseFeaturesMatrix(\n doc && typeof doc === \"object\" && \"features\" in doc ? doc.features : undefined,\n );\n return parsed.ok ? parsed.rows : null;\n } catch {\n return null;\n }\n}\n\n/**\n * Access / nav helper for one catalogue slug. Sync against a passed grid;\n * async when given `req` so it can read both Globals.\n */\nexport function canUseFeature(slug: string): FeaturePredicate {\n function predicate(\n userOrArgs: MaybeUser | AccessArgs,\n features?: readonly FeatureRow[] | null,\n roles?: readonly RoleRow[],\n ): boolean | Promise<boolean> {\n if (isAccessArgs(userOrArgs)) {\n const user = userOrArgs.req.user as MaybeUser;\n if (features !== undefined) return hasFeature(user, slug, features, roles ?? DEFAULT_ROLE_MATRIX);\n return Promise.all([getFeaturesMatrix(userOrArgs.req), getRolesMatrix(userOrArgs.req)]).then(\n ([grid, matrix]) => hasFeature(user, slug, grid, matrix),\n );\n }\n return hasFeature(userOrArgs, slug, features ?? null, roles ?? DEFAULT_ROLE_MATRIX);\n }\n return predicate as FeaturePredicate;\n}\n\n/**\n * Feature slugs (and group slugs) this login may use. Written onto the\n * user at afterRead so `admin.hidden({ user })` can follow the saved\n * Features and Roles Globals without a `req`.\n */\nexport async function allowedFeaturesForUser(\n user: MaybeUser,\n req: AccessArgs[\"req\"] = {},\n): Promise<string[]> {\n const [features, roles] = await Promise.all([getFeaturesMatrix(req), getRolesMatrix(req)]);\n const rows = features && features.length > 0 ? features : defaultFeaturesFieldValue();\n const slugs = [...rows.map((row) => row.slug), ...FEATURE_GROUPS, TRANSLATION_GRANT_SLUG];\n return slugs.filter((slug) => hasFeature(user, slug, features, roles));\n}\n\nfunction userHasAllowedFeature(user: MaybeUser, slug: string): boolean {\n if (isDeveloper(user)) return true;\n const allowed = user?.allowedFeatures;\n if (!Array.isArray(allowed)) return false;\n return allowed.includes(slug);\n}\n\n/** `admin.hidden`: hide when the login cannot use the feature. */\nexport function hideUnlessFeature(slug: string) {\n return (args: { user?: MaybeUser; req?: AccessArgs[\"req\"] }) => {\n const user = args.user ?? null;\n if (isDeveloper(user)) return false;\n if (user && Array.isArray(user.allowedFeatures)) {\n return !userHasAllowedFeature(user, slug);\n }\n if (args.req) {\n const result = canUseFeature(slug)({ req: { ...args.req, user } });\n if (result instanceof Promise) return result.then((ok) => !ok);\n return !result;\n }\n return !canUseFeature(slug)(user);\n };\n}\n","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 custom?: { translate?: 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\n/**\n * Skipped by every walk: hidden fields (derived values a hook writes) and a\n * field a site opts out with `custom: { translate: false }`, which is then\n * never read as copy, never sent to the model and never written.\n */\nfunction isHidden(field: WalkField): boolean {\n return field.hidden === true || field.admin?.hidden === true || field.custom?.translate === false;\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 { createCipheriv, createDecipheriv, createHash, randomBytes } from \"node:crypto\";\n\n/**\n * The site's own Anthropic key, as an Admin pastes it on Settings →\n * Translation. Stored AES-256-GCM encrypted under a key derived from\n * `PAYLOAD_SECRET`, in the unversioned, unreadable `translation-state`\n * Global, so it is in no version row and no API response. Only its last 4\n * characters are ever shown.\n */\n\nconst VERSION = \"v1\";\n\nfunction cipherKey(secret: string): Buffer {\n return createHash(\"sha256\").update(`bison-translation-key:${secret}`).digest();\n}\n\n/** `v1:<iv>:<tag>:<ciphertext>`, base64 parts. */\nexport function encryptApiKey(apiKey: string, secret: string): string {\n if (!secret) throw new Error(\"encryptApiKey: PAYLOAD_SECRET is empty\");\n const iv = randomBytes(12);\n const cipher = createCipheriv(\"aes-256-gcm\", cipherKey(secret), iv);\n const body = Buffer.concat([cipher.update(apiKey, \"utf8\"), cipher.final()]);\n return [VERSION, iv.toString(\"base64\"), cipher.getAuthTag().toString(\"base64\"), body.toString(\"base64\")].join(\":\");\n}\n\n/** The key, or `null` when the value is malformed or `secret` is not the one it was sealed with. */\nexport function decryptApiKey(sealed: string, secret: string): string | null {\n const [version, iv, tag, body] = sealed.split(\":\");\n if (version !== VERSION || !iv || !tag || !body || !secret) return null;\n try {\n const decipher = createDecipheriv(\"aes-256-gcm\", cipherKey(secret), Buffer.from(iv, \"base64\"));\n decipher.setAuthTag(Buffer.from(tag, \"base64\"));\n return Buffer.concat([decipher.update(Buffer.from(body, \"base64\")), decipher.final()]).toString(\"utf8\");\n } catch {\n return null;\n }\n}\n\n/** The last 4 characters, the only part of a key the admin ever shows. */\nexport function lastFour(apiKey: string): string {\n return apiKey.trim().slice(-4);\n}\n\n/** True on Vercel's production environment, the only place the stored key is used. */\nexport function isProductionEnvironment(): boolean {\n return process.env.VERCEL_ENV === \"production\";\n}\n\n/** Where the key a translation would use comes from. */\nexport type KeySource = \"admin\" | \"environment\";\n\nexport interface ResolvedKey {\n /** The key to call Anthropic with, or `undefined` when translation cannot run here. */\n apiKey?: string;\n source?: KeySource;\n /** Last 4 characters of the key in use. */\n last4?: string;\n /** Why the stored key is not in use, in words for the screen. */\n note?: string;\n}\n\n/**\n * Which key a translation uses. Only on production (`VERCEL_ENV=production`)\n * is the stored key considered, and there it wins over the environment's\n * `ANTHROPIC_API_KEY`. Everywhere else (local, previews, a cloned database)\n * only the environment key is used, so a copy of production's data never\n * spends production's money. A stored key that cannot be decrypted reads\n * as no key, with a note.\n */\nexport function resolveApiKey(input: {\n sealed?: string | null;\n secret: string;\n env?: string | null;\n production?: boolean;\n}): ResolvedKey {\n const production = input.production ?? isProductionEnvironment();\n const env = input.env?.trim() || undefined;\n const fromEnv = (note?: string): ResolvedKey =>\n env\n ? { apiKey: env, source: \"environment\", last4: lastFour(env), ...(note ? { note } : {}) }\n : note\n ? { note }\n : {};\n if (!input.sealed) return fromEnv();\n if (!production) {\n return fromEnv(\"The stored key is used only on production. Here only the server's ANTHROPIC_API_KEY is used.\");\n }\n const apiKey = decryptApiKey(input.sealed, input.secret);\n if (!apiKey) {\n return fromEnv(\n \"The stored key could not be decrypted (PAYLOAD_SECRET may have changed), so it reads as no key. Paste it again.\",\n );\n }\n return { apiKey, source: \"admin\", last4: lastFour(apiKey) };\n}\n","import type { Config, Payload } from \"payload\";\n\n/**\n * The languages every Bison site carries. The library owns this list: a new\n * language is a library release that sites take by updating the package\n * (and running the migration it brings). The first entry is the default\n * locale of a site that declares no localization of its own.\n */\nexport const LIBRARY_LOCALES = [\n { code: \"en\", label: \"English\" },\n { code: \"es\", label: \"Español\" },\n] as const;\n\nexport type LibraryLocaleCode = (typeof LIBRARY_LOCALES)[number][\"code\"];\n\nexport const LIBRARY_DEFAULT_LOCALE: LibraryLocaleCode = \"en\";\n\n/** The codes of `LIBRARY_LOCALES`, in order. */\nexport const LIBRARY_LOCALE_CODES: readonly string[] = LIBRARY_LOCALES.map((locale) => locale.code);\n\ntype LocaleEntry = string | { code: string; label?: unknown };\n\nfunction codeOf(entry: LocaleEntry): string {\n return typeof entry === \"string\" ? entry : entry.code;\n}\n\n/**\n * A config's `localization` with every library language in it. A site with\n * none gets the library's (English default, `fallback: true`, so an empty\n * Spanish field reads as English). A site with its own keeps its locales,\n * labels and default, and gains any library language it lacks.\n */\nexport function withLibraryLocales(\n localization: Config[\"localization\"],\n): Exclude<Config[\"localization\"], false | undefined> {\n if (!localization) {\n return {\n locales: LIBRARY_LOCALES.map((locale) => ({ ...locale })),\n defaultLocale: LIBRARY_DEFAULT_LOCALE,\n fallback: true,\n };\n }\n const own = localization.locales as LocaleEntry[];\n const have = new Set(own.map(codeOf));\n const missing = LIBRARY_LOCALES.filter((locale) => !have.has(locale.code));\n if (missing.length === 0) return localization;\n // Payload reads the list as strings or as objects by its first entry, so\n // the result is all objects: a string entry becomes `{ code, label: code }`.\n const locales = [\n ...own.map((entry) => (typeof entry === \"string\" ? { code: entry, label: entry } : entry)),\n ...missing.map((locale) => ({ ...locale })),\n ];\n return { ...localization, locales: locales as never[] };\n}\n\n// ---------------------------------------------------------------------------\n// Which target languages are switched on\n\n/** What `activeLocales` answers. */\nexport interface ActiveLocales {\n /** The default (source) locale. Always active. */\n defaultLocale: string;\n /** The default locale and every ticked target locale, in config order. */\n active: string[];\n /** Target locales that are not ticked: no translation, no URL, no switcher entry, no hreflang. */\n inactive: string[];\n}\n\n/** How long `activeLocales` reuses one read. A save of Settings → Translation in the same process clears it at once. */\nexport const ACTIVE_LOCALES_CACHE_MS = 60_000;\n\ntype SettingsReader = Pick<Payload, \"findGlobal\" | \"config\">;\n\nconst cache = new WeakMap<object, { at: number; ttl?: number; value: Promise<ActiveLocales> }>();\n\n/** The last answer read from the database, kept for when a later read fails. */\nconst lastGood = new WeakMap<object, ActiveLocales>();\n\n/** After a failed read, how soon to try the database again. */\nexport const ACTIVE_LOCALES_RETRY_MS = 5_000;\n\n/** Drops the cached answer, so the next `activeLocales` reads again. */\nexport function invalidateActiveLocales(payload: object): void {\n cache.delete(payload);\n}\n\n/**\n * The ticked target languages, as the Translation screen stores them.\n * `null` or absent (never saved) means the defaults: the target locales the\n * site declared itself before the library's were added.\n */\nexport function resolveActiveTargets(\n stored: readonly string[] | null | undefined,\n targets: readonly string[],\n defaults: readonly string[],\n): string[] {\n const chosen = Array.isArray(stored) ? stored : defaults;\n return targets.filter((code) => chosen.includes(code));\n}\n\n/**\n * The site's active languages, for routing and middleware: the default\n * locale plus each target language ticked on Settings → Translation. Cached\n * per process for `ttlMs` (60s by default): a request reads memory, and the\n * database is read only when the cache refreshes, or after a save of the\n * screen in the same process. Never throws. When a read fails it answers\n * with the last good read (or, before the first one, the defaults) and\n * tries the database again after `ACTIVE_LOCALES_RETRY_MS`, so one timeout\n * never stands in for the Admin's ticks for a whole cache period, which\n * would send a ticked language's visitors permanent redirects.\n */\nexport function activeLocales(payload: SettingsReader, options: { ttlMs?: number } = {}): Promise<ActiveLocales> {\n const ttl = options.ttlMs ?? ACTIVE_LOCALES_CACHE_MS;\n const hit = cache.get(payload);\n if (hit && Date.now() - hit.at < (hit.ttl ?? ttl)) return hit.value;\n const entry: { at: number; ttl?: number; value: Promise<ActiveLocales> } = { at: Date.now(), value: undefined as never };\n entry.value = readActiveLocales(payload).then((read) => {\n if (read.ok) {\n lastGood.set(payload, read.value);\n return read.value;\n }\n entry.ttl = ACTIVE_LOCALES_RETRY_MS;\n return lastGood.get(payload) ?? read.value;\n });\n cache.set(payload, entry);\n return entry.value;\n}\n\n/** The slug `activeLocales` reads; the Translation screen's. */\nconst SETTINGS_SLUG = \"translation-settings\";\n\n/** Where `applyTranslation` leaves the default ticks: the site's own target locales. */\nexport const DEFAULT_ACTIVE_LOCALES = \"bisonDefaultActiveLocales\";\n\nasync function readActiveLocales(payload: SettingsReader): Promise<{ ok: boolean; value: ActiveLocales }> {\n const localization = payload.config.localization;\n const codes = localization ? (localization.locales as LocaleEntry[]).map(codeOf) : [LIBRARY_DEFAULT_LOCALE];\n const defaultLocale = localization ? localization.defaultLocale : LIBRARY_DEFAULT_LOCALE;\n const targets = codes.filter((code) => code !== defaultLocale);\n const defaults = ((payload.config.custom as Record<string, unknown> | undefined)?.[DEFAULT_ACTIVE_LOCALES] ??\n targets) as string[];\n let stored: string[] | null | undefined;\n let ok = true;\n try {\n const doc = (await payload.findGlobal({ slug: SETTINGS_SLUG as never, depth: 0, overrideAccess: true })) as {\n languages?: string[] | null;\n languagesChosen?: boolean | null;\n };\n stored = doc?.languagesChosen ? (doc.languages ?? []) : undefined;\n } catch {\n stored = undefined;\n ok = false;\n }\n const ticked = resolveActiveTargets(stored, targets, defaults);\n return {\n ok,\n value: {\n defaultLocale,\n active: codes.filter((code) => code === defaultLocale || ticked.includes(code)),\n inactive: targets.filter((code) => !ticked.includes(code)),\n },\n };\n}\n\n/**\n * Where a request for an inactive language goes: the same path without\n * its locale prefix, for a 308. `null` when the path is not under an\n * inactive locale. In a site's middleware:\n *\n * ```ts\n * const to = inactiveLocaleRedirect(url.pathname, await activeLocales(payload));\n * if (to) {\n * const response = NextResponse.redirect(new URL(to + url.search, url), 308);\n * response.headers.set(\"Cache-Control\", \"no-store\"); // so ticking the language again works for these visitors\n * return response;\n * }\n * ```\n */\nexport function inactiveLocaleRedirect(\n pathname: string,\n locales: Pick<ActiveLocales, \"inactive\" | \"defaultLocale\">,\n): string | null {\n const [, first, ...rest] = pathname.split(\"/\");\n if (!first || !locales.inactive.includes(first)) return null;\n // Always a path on this site: leading slashes and backslashes collapse to\n // one \"/\", so \"/es//evil.com\" or \"/es/\\\\evil.com\" can never become a\n // protocol-relative redirect to another host.\n const path = `/${rest.join(\"/\").replace(/^[\\\\/]+/, \"\")}`;\n return path;\n}\n\n/**\n * A page's language alternates (for hreflang and a language switcher),\n * keeping only active languages. `paths` maps each locale to that\n * language's URL for the page.\n */\nexport function activeAlternates(\n paths: Readonly<Record<string, string>>,\n locales: Pick<ActiveLocales, \"active\">,\n): Record<string, string> {\n return Object.fromEntries(Object.entries(paths).filter(([code]) => locales.active.includes(code)));\n}\n","import type { Field, GlobalAfterChangeHook, GlobalBeforeChangeHook, GlobalConfig, Payload } from \"payload\";\nimport { APIError } from \"payload\";\n\nimport { canUseFeature, hideUnlessFeature } from \"../features/access\";\nimport {\n anthropicTranslator,\n DEFAULT_TRANSLATE_MODEL,\n ECONOMY_TRANSLATE_MODEL,\n type AnthropicMessagesClient,\n type TranslatorCallEvent,\n} from \"./anthropic\";\nimport { isProductionEnvironment, resolveApiKey, type ResolvedKey } from \"./key\";\nimport { DEFAULT_ACTIVE_LOCALES, invalidateActiveLocales, LIBRARY_LOCALES, resolveActiveTargets } from \"./languages\";\nimport type { TranslateSite, Translator } from \"./types\";\n\n/** Settings → Translation: the switch, model, instructions and the key's public record. Versioned. */\nexport const TRANSLATION_SETTINGS_SLUG = \"translation-settings\";\n\n/**\n * Server-only state beside it: the encrypted key and what the last check\n * found. Unversioned and unreadable through the API, so the key is in no\n * version row and no response.\n */\nexport const TRANSLATION_STATE_SLUG = \"translation-state\";\n\n/** The Roles grant that opens Settings → Translation. Developer and Admin always hold it. */\nexport const TRANSLATION_GRANT = \"translation\";\n\n/** The admin component for the key panel on Settings → Translation. */\nexport const TRANSLATION_KEY_PANEL = \"@bison-lab/payload-core/admin#TranslationKeyPanel\";\n\n/** The model choice on the screen. */\nexport type TranslationModelChoice = \"quality\" | \"economy\";\n\n/** What the last key check found. `unchecked`: Anthropic did not answer; checked again on first use. */\nexport type KeyStatus = \"valid\" | \"out-of-credit\" | \"rejected\" | \"unchecked\";\n\n/** The saved Settings → Translation document, as this package reads it. Optional and nullable. */\nexport interface TranslationSettingsDoc {\n enabled?: boolean | null;\n /** Ticked target languages. */\n languages?: string[] | null;\n /** Set by the server once someone has saved the ticks; until then the defaults apply. */\n languagesChosen?: boolean | null;\n model?: TranslationModelChoice | null;\n keyLast4?: string | null;\n keySetAt?: string | null;\n keySetBy?: string | null;\n keyChange?: string | null;\n changedBy?: string | null;\n instructions?: {\n businessName?: string | null;\n about?: string | null;\n voice?: string | null;\n dialects?: Array<{ locale?: string | null; name?: string | null }> | null;\n frozenWords?: Array<{ word?: string | null }> | null;\n } | null;\n updatedAt?: string | null;\n}\n\nexport interface TranslationStateDoc {\n keyCipher?: string | null;\n keyStatus?: KeyStatus | null;\n keyCheckedAt?: string | null;\n}\n\n/** Settings → Translation, resolved for a translation run. */\nexport interface ResolvedTranslationSettings {\n enabled: boolean;\n model: TranslationModelChoice;\n /** The instructions the model gets: the saved ones once the screen was saved, else the site's code `site`. */\n site?: TranslateSite;\n /** True once the document has been saved. */\n saved: boolean;\n /** The ticked target languages, the only ones translated into. */\n languages: string[];\n doc: TranslationSettingsDoc;\n state: TranslationStateDoc;\n}\n\n\n/** \"Español\" for `es`: the library's label, else the code. */\nfunction localeLabel(code: string): string {\n return LIBRARY_LOCALES.find((locale) => locale.code === code)?.label ?? code;\n}\n\nconst MODEL_IDS: Record<TranslationModelChoice, string> = {\n quality: DEFAULT_TRANSLATE_MODEL,\n economy: ECONOMY_TRANSLATE_MODEL,\n};\n\n/**\n * The model id for a choice. `ANTHROPIC_TRANSLATE_MODEL` overrides the\n * screen off production, so a developer can try a model locally without\n * touching the setting.\n */\nexport function resolveModel(choice: TranslationModelChoice | null | undefined, production: boolean): string {\n const override = process.env.ANTHROPIC_TRANSLATE_MODEL?.trim();\n if (override && !production) return override;\n return MODEL_IDS[choice ?? \"quality\"] ?? DEFAULT_TRANSLATE_MODEL;\n}\n\nconst trimmed = (value: unknown): string | undefined =>\n typeof value === \"string\" && value.trim() !== \"\" ? value.trim() : undefined;\n\n/**\n * The saved instructions as a `TranslateSite`, or `undefined` when every\n * field is blank. A blank business name drops only the name: frozen words,\n * voice and dialects still reach the model.\n */\nexport function siteFromInstructions(instructions: TranslationSettingsDoc[\"instructions\"]): TranslateSite | undefined {\n const name = trimmed(instructions?.businessName);\n const about = trimmed(instructions?.about);\n const voice = trimmed(instructions?.voice);\n const keepVerbatim = (instructions?.frozenWords ?? [])\n .map((row) => trimmed(row?.word))\n .filter((word): word is string => Boolean(word));\n const languages = Object.fromEntries(\n (instructions?.dialects ?? [])\n .map((row) => [trimmed(row?.locale), trimmed(row?.name)] as const)\n .filter((pair): pair is readonly [string, string] => Boolean(pair[0] && pair[1])),\n );\n const site: TranslateSite = {\n ...(name ? { name } : {}),\n ...(about ? { about } : {}),\n ...(voice ? { voice } : {}),\n ...(keepVerbatim.length ? { keepVerbatim } : {}),\n ...(Object.keys(languages).length ? { languages } : {}),\n };\n return Object.keys(site).length > 0 ? site : undefined;\n}\n\n// ---------------------------------------------------------------------------\n// Reading, with a short per-process cache\n\n/** How long a read of the two Globals is reused within one process. A save in the same process clears it at once. */\nexport const SETTINGS_CACHE_MS = 5_000;\n\nconst cache = new WeakMap<object, { at: number; value: Promise<ResolvedTranslationSettings> }>();\n\n/** Drops the cached read, so the next one sees a save at once. */\nexport function invalidateTranslationSettings(payload: object): void {\n cache.delete(payload);\n}\n\ntype ReadPayload = Pick<Payload, \"findGlobal\"> & { config?: Pick<Payload[\"config\"], \"localization\" | \"custom\"> };\n\nasync function readGlobal<T>(payload: ReadPayload, slug: string): Promise<T> {\n try {\n return ((await payload.findGlobal({ slug: slug as never, depth: 0, overrideAccess: true })) ?? {}) as T;\n } catch {\n return {} as T;\n }\n}\n\n/**\n * Settings → Translation and its server state, read once per\n * `SETTINGS_CACHE_MS` per process. A missing Global (a site that has not\n * migrated yet) reads as \"off\".\n */\nexport function readTranslationSettings(\n payload: ReadPayload,\n codeSite?: TranslateSite,\n): Promise<ResolvedTranslationSettings> {\n const hit = cache.get(payload);\n if (hit && Date.now() - hit.at < SETTINGS_CACHE_MS) return hit.value;\n const value = (async (): Promise<ResolvedTranslationSettings> => {\n const [doc, state] = await Promise.all([\n readGlobal<TranslationSettingsDoc>(payload, TRANSLATION_SETTINGS_SLUG),\n readGlobal<TranslationStateDoc>(payload, TRANSLATION_STATE_SLUG),\n ]);\n const saved = typeof doc.updatedAt === \"string\" && doc.updatedAt !== \"\";\n const site = saved ? siteFromInstructions(doc.instructions) : codeSite;\n const localization = payload.config?.localization;\n const targets = localization\n ? localization.locales\n .map((locale) => (typeof locale === \"string\" ? locale : locale.code))\n .filter((code) => code !== localization.defaultLocale)\n : [];\n const defaults =\n ((payload.config?.custom as Record<string, unknown> | undefined)?.[DEFAULT_ACTIVE_LOCALES] as\n | string[]\n | undefined) ?? targets;\n return {\n enabled: doc.enabled === true,\n languages: resolveActiveTargets(doc.languagesChosen ? (doc.languages ?? []) : undefined, targets, defaults),\n model: doc.model === \"economy\" ? \"economy\" : \"quality\",\n ...(site ? { site } : {}),\n saved,\n doc,\n state,\n };\n })();\n cache.set(payload, { at: Date.now(), value });\n value.catch(() => cache.delete(payload));\n return value;\n}\n\n/** The key a translation would use right now, from the stored key and the environment. */\nexport function keyFor(payload: Pick<Payload, \"secret\">, settings: ResolvedTranslationSettings): ResolvedKey {\n return resolveApiKey({\n sealed: settings.state.keyCipher,\n secret: payload.secret,\n env: process.env.ANTHROPIC_API_KEY,\n });\n}\n\n/**\n * Records what a call found about the stored key: a key saved while\n * Anthropic was unreachable is checked on its first use.\n */\nasync function recordKeyOutcome(payload: Payload, settings: ResolvedTranslationSettings, event: TranslatorCallEvent) {\n const status = settings.state.keyStatus;\n let next: KeyStatus | undefined;\n if (event.ok) next = status === \"valid\" ? undefined : \"valid\";\n else if (event.failure === \"key-rejected\") next = \"rejected\";\n else if (event.failure === \"out-of-credit\") next = \"out-of-credit\";\n if (!next) return;\n await payload.updateGlobal({\n slug: TRANSLATION_STATE_SLUG as never,\n data: { keyStatus: next, keyCheckedAt: new Date().toISOString() } as never,\n overrideAccess: true,\n context: { autoTranslate: false },\n });\n invalidateTranslationSettings(payload);\n}\n\n/**\n * The translator Settings → Translation describes: its key (see\n * `resolveApiKey`), its model and its instructions. `configured: false`\n * when there is no key to use here.\n */\nexport function settingsTranslator(\n payload: Payload,\n settings: ResolvedTranslationSettings,\n seam: { client?: AnthropicMessagesClient } = {},\n): Translator {\n const key = keyFor(payload, settings);\n const production = key.source === \"admin\" || process.env.VERCEL_ENV === \"production\";\n return anthropicTranslator({\n apiKey: key.apiKey ?? null,\n ...(seam.client && key.apiKey ? { client: seam.client } : {}),\n model: resolveModel(settings.model, production),\n ...(settings.site ? { site: settings.site } : {}),\n onCall: (event) => (key.source === \"admin\" ? recordKeyOutcome(payload, settings, event) : undefined),\n });\n}\n\n// ---------------------------------------------------------------------------\n// The Globals\n\nconst FROZEN_WORDS_DESCRIPTION =\n 'Kept exactly as written in every language. Matching is whole-word and case-sensitive: \"ProtectIQ\" does not match \"protectiq\".';\n\nconst OUT_OF_CREDIT_MESSAGE =\n \"The Anthropic account behind this key is out of credit, so translation cannot be switched on. Add credit, press Check again, then switch it on.\";\n\n/**\n * Switching on is refused while the stored key's account is out of credit,\n * where that key is the one in use (production). Off stays possible.\n */\nconst refuseOutOfCredit: GlobalBeforeChangeHook = async ({ data, originalDoc, req }) => {\n if (data?.enabled !== true || (originalDoc as TranslationSettingsDoc | undefined)?.enabled === true) return data;\n if (!isProductionEnvironment()) return data;\n const state = await readGlobal<TranslationStateDoc>(req.payload, TRANSLATION_STATE_SLUG);\n if (state.keyCipher && state.keyStatus === \"out-of-credit\") throw new APIError(OUT_OF_CREDIT_MESSAGE, 400);\n return data;\n};\n\n/**\n * Who made each save, so every version in the history names them, and\n * whether the language ticks have been chosen. Set by the server, never by\n * the form.\n */\nconst stampChangedBy: GlobalBeforeChangeHook = ({ data, req }) => {\n if (!data) return data;\n return {\n ...data,\n changedBy: who(req.user),\n ...(Array.isArray(data.languages) ? { languagesChosen: true } : {}),\n };\n};\n\n/** A name for the user on a request: their name, else email, else id. */\nexport function who(user: unknown): string {\n const record = (user ?? {}) as { name?: unknown; email?: unknown; id?: unknown };\n if (typeof record.name === \"string\" && record.name.trim()) return record.name.trim();\n if (typeof record.email === \"string\" && record.email) return record.email;\n return record.id !== undefined && record.id !== null ? `user ${String(record.id)}` : \"the server\";\n}\n\n/** Fields only the server writes: the form and the REST API cannot change them. */\nconst serverOnly = { update: () => false };\n\nconst clearCache: GlobalAfterChangeHook = ({ doc, req }) => {\n invalidateTranslationSettings(req.payload);\n invalidateActiveLocales(req.payload);\n return doc;\n};\n\nexport interface TranslationSettingsOptions {\n /** The site's code `site` option: the instructions' first values, until an Admin saves the screen. */\n site?: TranslateSite;\n /** Target locale codes, for the dialect rows and the language ticks. */\n targetLocales: readonly string[];\n /** The ticks a never-saved screen starts with. */\n defaultActive?: readonly string[];\n}\n\nfunction instructionFields(options: TranslationSettingsOptions): Field[] {\n const site = options.site;\n return [\n {\n name: \"businessName\",\n type: \"text\",\n label: \"Business name\",\n defaultValue: site?.name,\n admin: { description: \"Kept exactly as written in every language.\" },\n },\n {\n name: \"about\",\n type: \"text\",\n label: \"What the business is, in one line\",\n defaultValue: site?.about,\n admin: { description: 'For word choice, e.g. \"a gigabit fiber provider in Kansas\".' },\n },\n {\n name: \"voice\",\n type: \"text\",\n label: \"Voice\",\n defaultValue: site?.voice,\n admin: { description: 'E.g. \"confident, friendly, speed-first\".' },\n },\n {\n name: \"dialects\",\n type: \"array\",\n // Short table names: the derived ones push Payload's index names past\n // Postgres's 63 characters (they would be truncated silently).\n dbName: \"tr_dialects\",\n label: \"Dialect per language\",\n labels: { singular: \"Dialect\", plural: \"Dialects\" },\n defaultValue: Object.entries(site?.languages ?? {}).map(([locale, name]) => ({ locale, name })),\n fields: [\n {\n name: \"locale\",\n type: \"select\",\n label: \"Language\",\n required: true,\n // Postgres caps identifiers at 63 characters, and the versioned\n // name Payload derives (enum__translation_settings_v_version_…) is 64.\n enumName: \"enum_translation_dialect_locale\",\n options: options.targetLocales.map((code) => ({ label: localeLabel(code), value: code })),\n },\n {\n name: \"name\",\n type: \"text\",\n label: \"Dialect\",\n required: true,\n admin: { description: 'E.g. \"Latin American Spanish\".' },\n },\n ],\n },\n {\n name: \"frozenWords\",\n type: \"array\",\n dbName: \"tr_frozen_words\",\n label: \"Frozen words\",\n labels: { singular: \"Frozen word\", plural: \"Frozen words\" },\n defaultValue: (site?.keepVerbatim ?? []).map((word) => ({ word })),\n admin: { description: FROZEN_WORDS_DESCRIPTION },\n fields: [{ name: \"word\", type: \"text\", label: \"Word\", required: true }],\n },\n ];\n}\n\n/**\n * Settings → Translation. Opened by the `translation` grant (Developer and\n * Admin always). Versioned with no drafts: its history shows who changed\n * the switch, model and instructions, and every key change as a line of\n * text (\"key replaced (ends …a1b2) by …\"), never the key.\n */\nexport function translationSettingsGlobal(options: TranslationSettingsOptions): GlobalConfig {\n const canUse = canUseFeature(TRANSLATION_GRANT);\n return {\n slug: TRANSLATION_SETTINGS_SLUG,\n label: \"Translation\",\n admin: {\n group: \"Settings\",\n hidden: hideUnlessFeature(TRANSLATION_GRANT) as (args: { user: unknown }) => boolean,\n description:\n \"Translates published copy into the site's other languages with your own Anthropic key. Hand corrections are never overwritten.\",\n },\n access: {\n read: (args) => canUse(args),\n update: (args) => canUse(args),\n },\n versions: { max: 100 },\n hooks: { beforeChange: [refuseOutOfCredit, stampChangedBy], afterChange: [clearCache] },\n fields: [\n {\n name: \"keyPanel\",\n type: \"ui\",\n admin: { components: { Field: TRANSLATION_KEY_PANEL } },\n },\n {\n name: \"enabled\",\n type: \"checkbox\",\n label: \"Translate content\",\n defaultValue: false,\n admin: {\n description:\n \"On: blank translations fill when copy is saved or published, and changed copy is re-translated on publish. Off: nothing translates; the key and existing translations are kept.\",\n },\n },\n {\n name: \"languages\",\n type: \"select\",\n label: \"Translate into\",\n hasMany: true,\n defaultValue: [...(options.defaultActive ?? [])],\n options: options.targetLocales.map((code) => ({ label: localeLabel(code), value: code })),\n // Until someone saves the ticks, the screen shows (and the site uses)\n // the defaults, even on a document saved before this field existed,\n // whose stored list reads as empty.\n hooks: {\n afterRead: [\n ({ value, siblingData }) =>\n (siblingData as TranslationSettingsDoc | undefined)?.languagesChosen\n ? value\n : [...(options.defaultActive ?? [])],\n ],\n },\n admin: {\n description:\n \"Only ticked languages are translated and served. An unticked language costs nothing and has no pages: its URLs redirect to English.\",\n },\n },\n {\n name: \"model\",\n type: \"radio\",\n label: \"Model\",\n defaultValue: \"quality\",\n options: [\n { label: \"Quality (Sonnet)\", value: \"quality\" },\n { label: \"Economy (Haiku)\", value: \"economy\" },\n ],\n },\n // The key's public record and the saver are written by the server only\n // (the key endpoints write with overrideAccess), so a stale form or a\n // direct API write cannot put back an old \"…1111\" or forge history.\n {\n name: \"keyChange\",\n type: \"text\",\n label: \"Last key change\",\n access: serverOnly,\n admin: { readOnly: true },\n },\n {\n name: \"changedBy\",\n type: \"text\",\n label: \"Saved by\",\n access: serverOnly,\n admin: { readOnly: true, description: \"Who made this save. Each version in the history keeps it.\" },\n },\n { name: \"languagesChosen\", type: \"checkbox\", access: serverOnly, admin: { hidden: true } },\n { name: \"keyLast4\", type: \"text\", access: serverOnly, admin: { hidden: true } },\n { name: \"keySetAt\", type: \"date\", access: serverOnly, admin: { hidden: true } },\n { name: \"keySetBy\", type: \"text\", access: serverOnly, admin: { hidden: true } },\n {\n name: \"instructions\",\n type: \"group\",\n label: \"Instructions\",\n admin: {\n description:\n \"What the translator is told about the business. Changes apply to translations from now on; existing translations are not touched.\",\n },\n fields: instructionFields(options),\n },\n ],\n };\n}\n\n/** The encrypted key and its last check. Hidden, unreadable through the API, unversioned. */\nexport function translationStateGlobal(): GlobalConfig {\n return {\n slug: TRANSLATION_STATE_SLUG,\n label: \"Translation state\",\n admin: { hidden: true },\n access: { read: () => false, update: () => false },\n hooks: { afterChange: [clearCache] },\n fields: [\n { name: \"keyCipher\", type: \"text\" },\n {\n name: \"keyStatus\",\n type: \"select\",\n options: [\"valid\", \"out-of-credit\", \"rejected\", \"unchecked\"],\n },\n { name: \"keyCheckedAt\", type: \"date\" },\n ],\n };\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 /**\n * A translator that replaces the one Settings → Translation describes\n * (its key, model and instructions). For tests and scripts; a site leaves\n * it out. The screen's switch still governs it.\n */\n translator?: Translator;\n /** The site's code `site` option: the instructions until an Admin saves the screen. */\n site?: TranslateSite;\n waitUntil?: (promise: Promise<unknown>) => void;\n sourceLocale: string;\n targetLocales: string[];\n /** Per translated collection slug (every one with localized fields), its prompt hint builder. */\n collections: Record<string, { context?: (doc: Doc) => string }>;\n /** Per translated 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","/** A document as one locale's depth-0 read returns it. */\nexport type Doc = Record<string, unknown>;\n\n/** Why a translation write happened. */\nexport type BisonTranslationKind = \"auto\" | \"backfill\" | \"frozen-fix\" | \"manual\";\n\n/**\n * Set as `context.bisonTranslation` (so `req.context.bisonTranslation` in\n * every hook) on each write the library makes to land a translation, and on\n * no other write. `locale` is the target locale, the write's own `locale`,\n * never the default locale. A site's hooks read it to let a translation\n * through a rule meant for people (a publish gate), and nothing else should\n * set it.\n *\n * - `auto`: a save or publish filled or re-translated copy.\n * - `backfill`: a background job filling blank copy.\n * - `frozen-fix`: a background job re-translating strings that dropped a frozen word.\n * - `manual`: \"Translate now\", or a script calling `translateDocument`.\n */\nexport interface BisonTranslationMarker {\n locale: string;\n kind: BisonTranslationKind;\n}\n\n/** The `context` key that carries a `BisonTranslationMarker`. */\nexport const BISON_TRANSLATION_CONTEXT = \"bisonTranslation\";\n\n/**\n * What a site tells the model about itself. The library owns the generic\n * rules (JSON in and out, placeholders, tags, URLs, literal legal copy);\n * these are the facts only a site has.\n */\nexport interface TranslateSite {\n /** The brand name, kept verbatim. Optional: a site may give only frozen words or a voice. */\n name?: string;\n /** One line on what the site is, for word choice (\"a gigabit fiber provider in Kansas\"). */\n about?: string;\n /** The voice to keep (\"confident, friendly, speed-first\"). */\n voice?: string;\n /** Brand, product and place names the model must never translate. */\n keepVerbatim?: string[];\n /**\n * How to name a locale's language in the prompt, per locale code\n * (`{ es: \"Latin American Spanish\" }`). A code left out is named by\n * `Intl.DisplayNames`.\n */\n languages?: Record<string, string>;\n}\n\n/** One translation call: from which locale, into which, and where the strings appear. */\nexport interface TranslateRequest {\n from: string;\n to: string;\n /** A short hint about where the strings appear, to improve word choice. */\n context?: string;\n /** The plugin's `site`, when it was given one. */\n site?: TranslateSite;\n}\n\n/**\n * Translates a batch of strings, returning them in the same order and the\n * same length, or `null` on any failure. It never throws on purpose; a\n * throw is caught and read as `null`.\n *\n * `configured: false` says the translator cannot run (no API key): the\n * plugin then logs a warning on publish instead of deferring work, and\n * hides \"Translate now\". Leave it unset on a translator that always runs.\n */\nexport type Translator = ((strings: string[], request: TranslateRequest) => Promise<string[] | null>) & {\n configured?: boolean;\n};\n\n/** A collection or global the plugin translates, by slug or with a prompt hint. */\nexport type TranslatedEntity =\n | string\n | {\n slug: string;\n /** The prompt hint for one document, from its source-locale read (`Internet plan: Fiber 1000`). */\n context?: (doc: Doc) => string;\n };\n\nexport interface AutoTranslateOptions {\n /**\n * The per-site switch. `false` registers nothing at all: no hooks,\n * endpoints, admin components or config, the same config as leaving the\n * plugin out.\n */\n enabled: boolean;\n /** Collections whose source-locale publishes fill every other locale. */\n collections?: TranslatedEntity[];\n /** Globals whose source-locale publishes fill every other locale. */\n globals?: TranslatedEntity[];\n /**\n * Replaces the translator Settings → Translation describes (its key and\n * model). Leave it out to use the screen's; pass a fake in tests.\n */\n translator?: Translator;\n /**\n * Keeps the deferred translation alive after the response is sent, e.g.\n * `waitUntil` from `@vercel/functions`. Off a serverless host leave it\n * out; the work runs in the same process either way.\n */\n waitUntil?: (promise: Promise<unknown>) => void;\n /** Site facts passed to the translator on every call (see `TranslateSite`). */\n site?: TranslateSite;\n}\n\n/** Where `translateDocument` reads and writes. */\nexport type TranslateTarget = { collection: string; id: number | string } | { global: string };\n\n/** What happened in one target locale. */\nexport interface TranslateLocaleResult {\n locale: string;\n /** `nothing`: every string already in step; `failed`: the translator gave no usable result. */\n status: \"translated\" | \"nothing\" | \"failed\";\n /** Strings written. */\n count: number;\n}\n","import type { Payload, PayloadRequest } from \"payload\";\n\nimport { translationJob, type FieldSchema } from \"./fields\";\nimport { readTranslationSettings, settingsTranslator } from \"./settings\";\nimport { localeCodes, readState } from \"./state\";\nimport { translateStrings } from \"./strings\";\nimport {\n BISON_TRANSLATION_CONTEXT,\n type BisonTranslationKind,\n type BisonTranslationMarker,\n type Doc,\n type TranslateLocaleResult,\n type TranslateSite,\n type Translator,\n} from \"./types\";\n\nexport type TranslateDocumentOptions = ({ collection: string; id: number | string } | { global: string }) & {\n /** Target locale or locales. Omitted: every ticked target language on Settings → Translation. */\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 /**\n * Defaults to the test translator a config registered (`autoTranslate({\n * translator })`), else the one Settings → Translation describes: its key,\n * model and instructions.\n */\n translator?: Translator;\n /** The prompt hint; defaults to the collection's `context` hint, else the slug and the title. */\n context?: string;\n /** Defaults to Settings → Translation's instructions (the site's code `site` until the screen is saved). */\n site?: TranslateSite;\n /** Why this write happens, carried on each write as `context.bisonTranslation.kind`. Defaults to `manual`. */\n kind?: BisonTranslationKind;\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 given = options.translator ?? state?.translator;\n // The screen supplies whatever the caller did not: the translator, the\n // instructions and the languages.\n const settings =\n given && options.site && options.locale !== undefined\n ? undefined\n : await readTranslationSettings(payload, state?.site);\n const translator = given ?? settingsTranslator(payload, settings!);\n const kind: BisonTranslationKind = options.kind ?? \"manual\";\n const sourceLocale = localization.defaultLocale;\n const codes = localeCodes(localization);\n const targets =\n options.locale === undefined\n ? (settings?.languages ?? 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 // Once the screen is saved its instructions decide, even when every field\n // is blank; until then readTranslationSettings answers with the code site.\n const site = options.site ?? (settings ? settings.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 marker: BisonTranslationMarker = { locale, kind };\n // A `req` passed to the Local API has its `context` and `locale`\n // overwritten in place (createLocalReq), so writing through the\n // caller's own `req` would leave the marker on it for every later\n // write in that request. Each write gets a shallow copy: the same\n // transaction, user and payload, its own context.\n // A Local API req is a plain object and is copied; any other (an HTTP\n // request with getters on its prototype) is used as it is and has its\n // context, locale and fallback locale put back after the write.\n const plain = req !== undefined && Object.getPrototypeOf(req) === Object.prototype;\n const writeReq = req && plain ? ({ ...req, context: { ...(req.context ?? {}) } } as PayloadRequest) : req;\n const restore =\n req && !plain ? { context: req.context, locale: req.locale, fallbackLocale: req.fallbackLocale } : undefined;\n const common = {\n locale,\n data: data as never,\n depth: 0,\n ...(writeDraft ? { draft: true } : {}),\n context: { autoTranslate: false, [BISON_TRANSLATION_CONTEXT]: marker },\n ...writeAs,\n ...(writeReq ? { req: writeReq } : {}),\n };\n try {\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 } finally {\n if (req && restore) {\n req.context = restore.context;\n req.locale = restore.locale;\n req.fallbackLocale = restore.fallbackLocale;\n }\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 { readTranslationSettings, settingsTranslator } from \"./settings\";\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) return Response.json({ error: \"Translation is not set up on this site.\" }, { status: 503 });\n const settings = await readTranslationSettings(req.payload, state.site);\n if (!settings.enabled) {\n return Response.json({ error: \"Translation is switched off in Settings → Translation.\" }, { status: 409 });\n }\n if (settings.languages.length === 0) {\n return Response.json({ error: \"No language is ticked in Settings → Translation.\" }, { status: 409 });\n }\n const translator = state.translator ?? settingsTranslator(req.payload, settings);\n if (!isTranslatorConfigured(translator)) {\n return Response.json({ error: \"Translation has no API key here.\" }, { 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 && !settings.languages.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 translator,\n kind: \"manual\",\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\n/**\n * `GET /api/translation/available`: whether \"Translate now\" can run, for\n * any signed-in editor. Says only yes or no; the screen's details are\n * behind the `translation` grant.\n */\nexport function translationAvailableEndpoint(): Endpoint {\n return {\n path: \"/translation/available\",\n method: \"get\",\n handler: async (req) => {\n if (!req.user) return Response.json({ available: false }, { status: 401 });\n const state = readState(req.payload.config);\n if (!state) return Response.json({ available: false });\n const settings = await readTranslationSettings(req.payload, state.site);\n const translator = state.translator ?? settingsTranslator(req.payload, settings);\n return Response.json({\n available: settings.enabled && settings.languages.length > 0 && isTranslatorConfigured(translator),\n languages: settings.languages,\n });\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 } from \"./guards\";\nimport { readTranslationSettings, settingsTranslator } from \"./settings\";\nimport { readState } from \"./state\";\nimport { isTranslatorConfigured } from \"./strings\";\nimport type { Doc, TranslateLocaleResult } from \"./types\";\n\n/** True for the admin's autosave (`?autosave=true`), which never translates. */\nexport function isAutosave(req: PayloadRequest): boolean {\n const query = req.query as Record<string, unknown> | undefined;\n return (\n req.searchParams?.get?.(\"autosave\") === \"true\" || query?.autosave === \"true\" || query?.autosave === true\n );\n}\n\n/**\n * Vercel's `waitUntil` for the current request, when there is one. It is\n * what `@vercel/functions` reads; using it directly keeps that package off\n * every site. Without it the deferred work still runs in the same process.\n */\nexport function vercelWaitUntil(): ((promise: Promise<unknown>) => void) | undefined {\n const context = (globalThis as Record<symbol, unknown>)[Symbol.for(\"@vercel/request-context\")] as\n | { get?: () => { waitUntil?: (promise: Promise<unknown>) => void } | undefined }\n | undefined;\n const waitUntil = context?.get?.()?.waitUntil;\n return typeof waitUntil === \"function\" ? waitUntil : undefined;\n}\n\n/**\n * Fills the other locales from the source locale when copy is saved, while\n * Settings → Translation is switched on. Every collection and global with\n * localized fields has this hook; there is no exclude list. Rules, in order:\n *\n * - `autoTranslate: false` context skips it (seeds and scripts, and the\n * translation's own write, so it never re-fires itself).\n * - Edits in a target locale are ignored: a hand edit there is never\n * clobbered by a machine pass.\n * - Autosave never translates (Live Preview autosaves every ~375ms).\n * - Switch off: nothing translates.\n * - Save draft: blank target strings fill, written into the draft.\n * - Publish (or any save on a collection without drafts): blank target\n * strings fill, and source strings changed since the last published\n * version (the previous document, without drafts) are re-translated.\n * Target copy whose source did not change is kept, so a hand correction\n * survives every publish that does not change its English.\n * - No key: the save goes through and a warning is logged.\n *\n * The write is made as the user who saved (`overrideAccess: false`), with\n * `context.bisonTranslation = { locale, kind: \"auto\" }`. Failures log and\n * never fail the save, and the work starts only once the save has committed\n * (runAfterCommit), so a save never waits on the model.\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 if (isAutosave(req)) return {};\n const status = drafted ? doc._status : undefined;\n if (drafted && status !== \"published\" && status !== \"draft\") 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 let translator;\n let targets: string[];\n try {\n const settings = await readTranslationSettings(payload, state.site);\n if (!settings.enabled || settings.languages.length === 0) return {};\n targets = settings.languages;\n if (drafted && status === \"draft\") {\n // A draft fills blanks only; changed copy is re-translated on publish.\n previous = null;\n } else if (drafted) {\n previous = (\n await draftedTranslationDecision({ req, entity, doc, schema, sourceLocale: state.sourceLocale })\n ).previous;\n } else {\n const previousDoc = args.operation === \"create\" ? undefined : args.previousDoc;\n previous = previousDoc && Object.keys(previousDoc).length > 0 ? previousDoc : null;\n }\n translator = state.translator ?? settingsTranslator(payload, settings);\n } catch (error) {\n // The save must never fail for translation's sake.\n payload.logger.error({ err: error }, `${label}: auto-translation check failed; targets left as-is`);\n return {};\n }\n\n if (!isTranslatorConfigured(translator)) {\n payload.logger.warn(`${label}: copy saved but translation has no API key here; targets not translated`);\n return {};\n }\n\n const user = req.user ?? undefined;\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 translator,\n locale: targets,\n kind: \"auto\",\n ...(user ? { user } : {}),\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 ?? vercelWaitUntil(),\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 { Endpoint, PayloadRequest } from \"payload\";\n\nimport { canUseFeature } from \"../features/access\";\nimport { verifyAnthropicKey, type AnthropicMessagesClient, type KeyCheck } from \"./anthropic\";\nimport { decryptApiKey, encryptApiKey, isProductionEnvironment, lastFour } from \"./key\";\nimport {\n invalidateTranslationSettings,\n keyFor,\n readTranslationSettings,\n TRANSLATION_GRANT,\n TRANSLATION_SETTINGS_SLUG,\n TRANSLATION_STATE_SLUG,\n type KeyStatus,\n type TranslationSettingsDoc,\n type TranslationStateDoc,\n who,\n} from \"./settings\";\nimport { readState } from \"./state\";\n\n/** What `GET /api/translation/status` answers: everything the key panel shows, never the key. */\nexport interface TranslationStatus {\n enabled: boolean;\n production: boolean;\n /** The stored key's public record. */\n stored: { last4: string; setAt?: string | null; setBy?: string | null; status?: KeyStatus | null } | null;\n /** The key a translation would use here, by source and last 4. */\n inUse: { source: \"admin\" | \"environment\"; last4: string } | null;\n /** Why the stored key is not in use, when it is not. */\n note?: string;\n}\n\n/** A test seam: replaces the Anthropic client the key check uses. */\nexport interface TranslationEndpointOptions {\n verifyClient?: AnthropicMessagesClient;\n}\n\nasync function allowed(req: PayloadRequest): Promise<boolean> {\n if (!req.user) return false;\n return Boolean(await canUseFeature(TRANSLATION_GRANT)({ req }));\n}\n\nfunction forbidden(req: PayloadRequest): Response {\n return Response.json({ error: \"You cannot manage translation.\" }, { status: req.user ? 403 : 401 });\n}\n\nasync function status(req: PayloadRequest): Promise<TranslationStatus> {\n invalidateTranslationSettings(req.payload);\n const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);\n const key = keyFor(req.payload, settings);\n const doc = settings.doc;\n return {\n enabled: settings.enabled,\n production: isProductionEnvironment(),\n stored:\n settings.state.keyCipher && doc.keyLast4\n ? { last4: doc.keyLast4, setAt: doc.keySetAt, setBy: doc.keySetBy, status: settings.state.keyStatus }\n : null,\n inUse: key.apiKey && key.source && key.last4 ? { source: key.source, last4: key.last4 } : null,\n ...(key.note ? { note: key.note } : {}),\n };\n}\n\nconst STATUS_BY_CHECK: Record<Exclude<KeyCheck, \"rejected\">, KeyStatus> = {\n valid: \"valid\",\n \"out-of-credit\": \"out-of-credit\",\n unreachable: \"unchecked\",\n};\n\nasync function writeState(req: PayloadRequest, data: TranslationStateDoc): Promise<void> {\n await req.payload.updateGlobal({\n slug: TRANSLATION_STATE_SLUG as never,\n data: data as never,\n overrideAccess: true,\n req,\n context: { autoTranslate: false },\n });\n}\n\n/** Writes the key's public record as a version of Settings → Translation, so its history shows the change. */\nasync function writeKeyRecord(req: PayloadRequest, data: TranslationSettingsDoc): Promise<void> {\n await req.payload.updateGlobal({\n slug: TRANSLATION_SETTINGS_SLUG as never,\n data: data as never,\n overrideAccess: true,\n req,\n context: { autoTranslate: false },\n });\n}\n\nconst today = () => new Date().toISOString().slice(0, 10);\n\n/**\n * The key endpoints of Settings → Translation, all behind the `translation`\n * grant:\n *\n * - `GET /api/translation/status`: what the key panel shows.\n * - `POST /api/translation/key` `{ key }`: checks the key with one tiny call.\n * A 401 refuses it and keeps the previous key. Out of credit saves it\n * (switching on is then refused). No answer saves it as unchecked.\n * - `POST /api/translation/key/check`: checks the stored key again.\n * - `DELETE /api/translation/key`: removes the stored key.\n */\nexport function translationSettingsEndpoints(options: TranslationEndpointOptions = {}): Endpoint[] {\n const verify = (key: string) =>\n verifyAnthropicKey(key, options.verifyClient ? { client: options.verifyClient } : {});\n return [\n {\n path: \"/translation/status\",\n method: \"get\",\n handler: async (req) => {\n if (!(await allowed(req))) return forbidden(req);\n return Response.json(await status(req));\n },\n },\n {\n path: \"/translation/key\",\n method: \"post\",\n handler: async (req) => {\n if (!(await allowed(req))) return forbidden(req);\n let body: unknown;\n try {\n body = await req.json?.();\n } catch {\n body = undefined;\n }\n const key = typeof (body as { key?: unknown })?.key === \"string\" ? (body as { key: string }).key.trim() : \"\";\n if (!key) return Response.json({ error: \"Paste a key first.\" }, { status: 400 });\n const check = await verify(key);\n if (check === \"rejected\") {\n return Response.json(\n { error: \"Anthropic rejected this key (401). The previous key is kept.\", status: await status(req) },\n { status: 400 },\n );\n }\n const before = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);\n const now = new Date().toISOString();\n const by = who(req.user);\n const replaced = before.state.keyCipher ? \"key replaced\" : \"key set\";\n await writeState(req, {\n keyCipher: encryptApiKey(key, req.payload.secret),\n keyStatus: STATUS_BY_CHECK[check],\n keyCheckedAt: check === \"unreachable\" ? null : now,\n });\n await writeKeyRecord(req, {\n keyLast4: lastFour(key),\n keySetAt: now,\n keySetBy: by,\n keyChange: `${replaced} (ends …${lastFour(key)}) by ${by}, ${today()}`,\n });\n invalidateTranslationSettings(req.payload);\n const message =\n check === \"out-of-credit\"\n ? \"Key saved, but its Anthropic account is out of credit. Translation cannot be switched on until credit is added.\"\n : check === \"unreachable\"\n ? \"Key saved. Anthropic did not answer, so it will be checked on first use.\"\n : \"Key saved and checked.\";\n return Response.json({ message, check, status: await status(req) });\n },\n },\n {\n path: \"/translation/key/check\",\n method: \"post\",\n handler: async (req) => {\n if (!(await allowed(req))) return forbidden(req);\n const settings = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);\n const sealed = settings.state.keyCipher;\n const key = sealed ? decryptApiKey(sealed, req.payload.secret) : null;\n if (!key) return Response.json({ error: \"There is no stored key to check.\" }, { status: 400 });\n const check = await verify(key);\n await writeState(req, {\n keyStatus: check === \"rejected\" ? \"rejected\" : STATUS_BY_CHECK[check],\n keyCheckedAt: check === \"unreachable\" ? settings.state.keyCheckedAt ?? null : new Date().toISOString(),\n });\n invalidateTranslationSettings(req.payload);\n return Response.json({ check, status: await status(req) });\n },\n },\n {\n path: \"/translation/key\",\n method: \"delete\",\n handler: async (req) => {\n if (!(await allowed(req))) return forbidden(req);\n const before = await readTranslationSettings(req.payload, readState(req.payload.config)?.site);\n if (!before.state.keyCipher) return Response.json({ status: await status(req) });\n const last4 = before.doc.keyLast4 ?? \"\";\n await writeState(req, { keyCipher: null, keyStatus: null, keyCheckedAt: null });\n await writeKeyRecord(req, {\n keyLast4: null,\n keySetAt: null,\n keySetBy: null,\n keyChange: `key removed (ended …${last4}) by ${who(req.user)}, ${today()}`,\n });\n invalidateTranslationSettings(req.payload);\n return Response.json({ status: await status(req) });\n },\n },\n ];\n}\n","import type { Block, CollectionConfig, Config, Endpoint, Field, GlobalConfig } from \"payload\";\n\nimport { TRANSLATE_NOW, translateNowEndpoint, translationAvailableEndpoint } from \"./endpoint\";\nimport { collectionAutoTranslateHook, globalAutoTranslateHook } from \"./hooks\";\nimport {\n TRANSLATION_SETTINGS_SLUG,\n TRANSLATION_STATE_SLUG,\n translationSettingsGlobal,\n translationStateGlobal,\n} from \"./settings\";\nimport { translationSettingsEndpoints, type TranslationEndpointOptions } from \"./settings-endpoints\";\nimport {\n activeLocales,\n DEFAULT_ACTIVE_LOCALES,\n withLibraryLocales,\n} from \"./languages\";\nimport { AUTO_TRANSLATE_STATE, localeCodes, readState, type AutoTranslateState } from \"./state\";\nimport type { Doc, TranslateSite, Translator } from \"./types\";\n\n/**\n * A collection's or global's own hint for the model, set in its config:\n * `custom: { bisonTranslation: { context: (doc) => \"Internet plan: \" + doc.name } }`.\n * `doc` is its source-locale read at depth 0.\n */\nexport interface TranslationEntityHint {\n context?: (doc: Doc) => string;\n}\n\n/** What a site may pass; every option is optional. */\nexport interface TranslationOptions {\n /** The site's facts: the instructions on Settings → Translation until an Admin saves the screen. */\n site?: TranslateSite;\n /** Keeps deferred work alive past the response. Defaults to Vercel's request context when there is one. */\n waitUntil?: (promise: Promise<unknown>) => void;\n /** Replaces the screen's translator (tests). The switch still governs it. */\n translator?: Translator;\n /** Prompt hints by collection or global slug, beside each entity's own `custom.bisonTranslation`. */\n hints?: Record<string, TranslationEntityHint>;\n /** Test seam for the key check's Anthropic client. */\n endpoints?: TranslationEndpointOptions;\n}\n\ninterface WalkField {\n type: string;\n localized?: boolean;\n fields?: WalkField[];\n tabs?: Array<{ localized?: boolean; fields: WalkField[] }>;\n blocks?: Array<{ fields: WalkField[] }>;\n blockReferences?: Array<string | { fields: WalkField[] }>;\n}\n\n/** True when any field, at any depth, is localized: the entity has copy to translate. */\nexport function hasLocalizedFields(fields: readonly Field[], blocks: readonly Block[] = []): boolean {\n const seen = new Set<unknown>();\n const walk = (list: readonly WalkField[]): boolean =>\n list.some((field) => {\n if (field.localized === true) return true;\n if (field.fields && walk(field.fields)) return true;\n if (field.tabs?.some((tab) => tab.localized === true || walk(tab.fields))) return true;\n const own = field.blocks ?? [];\n const referenced = (field.blockReferences ?? []).map((ref) =>\n typeof ref === \"string\" ? (blocks as unknown as Array<{ slug: string; fields: WalkField[] }>).find((b) => b.slug === ref) : ref,\n );\n return [...own, ...referenced].some((block) => {\n if (!block || seen.has(block)) return false;\n seen.add(block);\n return walk(block.fields);\n });\n });\n return walk(fields as unknown as WalkField[]);\n}\n\nfunction entityHint(\n entity: { slug: string; custom?: Record<string, unknown> },\n hints: TranslationOptions[\"hints\"],\n): TranslationEntityHint {\n const own = (entity.custom?.bisonTranslation ?? undefined) as TranslationEntityHint | undefined;\n const context = hints?.[entity.slug]?.context ?? own?.context;\n return context ? { context } : {};\n}\n\nfunction withCollection(collection: CollectionConfig, sourceLocale: string, targetLocales: string[]): 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 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 } },\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 * Gives a config the translation capability: Settings → Translation (and\n * its hidden state Global), the key endpoints, and on every collection and\n * global with localized fields the save hook, plus \"Translate now\" on each\n * collection. `adminNav()` applies it, so a site gets it with no line of\n * its own; `translation()` is the same for a site without `adminNav()`.\n *\n * Safe to apply more than once: options merge (later wins), the Globals\n * and endpoints are added once, and each entity is hooked once, so a second\n * pass only picks up entities a later plugin registered.\n *\n * It also puts every library language (`LIBRARY_LOCALES`) into the\n * config's `localization`, adding it when the site has none, so every site\n * carries every language in its schema. A target language is translated\n * and served only once it is ticked on the screen (`activeLocales`).\n */\nexport function applyTranslation(config: Config, options: TranslationOptions = {}): Config {\n const prior = readState(config);\n const custom = (config.custom ?? {}) as Record<string, unknown>;\n // The ticks a never-saved screen starts with: the target locales the site\n // declared itself, before the library's languages were added. Kept from\n // the first pass, which is the only one that sees the site's own list.\n const siteDefault = config.localization ? config.localization.defaultLocale : undefined;\n const defaultActive =\n (custom[DEFAULT_ACTIVE_LOCALES] as string[] | undefined) ??\n localeCodes(config.localization).filter((code) => code !== siteDefault);\n const localization = withLibraryLocales(config.localization);\n const codes = localeCodes(localization);\n const sourceLocale = localization ? localization.defaultLocale : \"en\";\n const targetLocales = codes.filter((code) => code !== sourceLocale);\n const translator = options.translator ?? prior?.translator;\n const site = options.site ?? prior?.site;\n const waitUntil = options.waitUntil ?? prior?.waitUntil;\n\n const state: AutoTranslateState = {\n ...(translator ? { translator } : {}),\n ...(site ? { site } : {}),\n ...(waitUntil ? { waitUntil } : {}),\n sourceLocale,\n targetLocales,\n collections: { ...(prior?.collections ?? {}) },\n globals: { ...(prior?.globals ?? {}) },\n };\n\n const translatable = codes.length >= 2;\n const blocks = (config.blocks ?? []) as Block[];\n const collections = (config.collections ?? []).map((collection) => {\n const hint = entityHint(collection, options.hints);\n if (collection.slug in state.collections) {\n if (hint.context) state.collections[collection.slug] = hint;\n return collection;\n }\n if (!translatable || !hasLocalizedFields(collection.fields, blocks)) return collection;\n state.collections[collection.slug] = hint;\n return withCollection(collection, sourceLocale, targetLocales);\n });\n\n const hasGlobal = (slug: string) => (config.globals ?? []).some((global) => global.slug === slug);\n const globals = [\n ...(config.globals ?? []),\n ...(hasGlobal(TRANSLATION_SETTINGS_SLUG)\n ? []\n : [translationSettingsGlobal({ site, targetLocales, defaultActive })]),\n ...(hasGlobal(TRANSLATION_STATE_SLUG) ? [] : [translationStateGlobal()]),\n ].map((global) => {\n const hint = entityHint(global, options.hints);\n if (global.slug in state.globals) {\n if (hint.context) state.globals[global.slug] = hint;\n return global;\n }\n if (!translatable || !hasLocalizedFields(global.fields, blocks)) return global;\n state.globals[global.slug] = hint;\n return withGlobal(global);\n });\n\n const endpoints = config.endpoints ?? [];\n const hasEndpoints = endpoints.some((endpoint) => endpoint.path === \"/translation/status\");\n\n return {\n ...config,\n localization,\n custom: { ...custom, [AUTO_TRANSLATE_STATE]: state, [DEFAULT_ACTIVE_LOCALES]: defaultActive },\n collections,\n globals,\n endpoints: hasEndpoints\n ? endpoints\n : [\n ...endpoints,\n ...translationSettingsEndpoints(options.endpoints),\n translationAvailableEndpoint(),\n activeLocalesEndpoint(),\n ],\n };\n}\n\n/** `applyTranslation` as a plugin, for a site that does not use `adminNav()`. */\nexport function translation(options: TranslationOptions = {}) {\n return (config: Config): Config => applyTranslation(config, options);\n}\n\n/**\n * `GET /api/translation/locales`: the site's active languages, public and\n * cacheable for a minute, for middleware that cannot load Payload (an edge\n * runtime). Node middleware calls `activeLocales(payload)` directly.\n */\nfunction activeLocalesEndpoint(): Endpoint {\n return {\n path: \"/translation/locales\",\n method: \"get\",\n handler: async (req) =>\n Response.json(await activeLocales(req.payload), {\n // A CDN in front keeps it no longer than a browser would.\n headers: { \"Cache-Control\": \"public, max-age=60, s-maxage=60\" },\n }),\n };\n}\n"],"mappings":";;;;AAAA,MAAa,gBAAgB;AAE7B,MAAa,iBAAiB;CAAC;CAAS;CAAS;CAAS;CAAQ;AAIlE,MAAa,uBAAuD;CAClE,OAAO;CACP,OAAO;CACP,OAAO;CACP,OAAO;CACR;AAED,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACD;;;;;;;AAiBD,MAAa,mBAA8C;CACzD;EAAE,MAAM;EAAW,OAAO;EAAW,OAAO;EAAS,iBAAiB;EAAM;CAC5E;EAAE,MAAM;EAAW,OAAO;EAAW,OAAO;EAAS,iBAAiB;EAAM;CAC5E;EAAE,MAAM;EAAS,OAAO;EAAS,OAAO;EAAS,iBAAiB;EAAM;CACxE;EAAE,MAAM;EAAS,OAAO;EAAS,OAAO;EAAS,iBAAiB;EAAM;CACxE;EAAE,MAAM;EAAS,OAAO;EAAS,OAAO;EAAS,iBAAiB;EAAM;CACzE;AAsBD,SAAgB,iBAAiB,OAAyC;AACxE,QAAO,OAAO,UAAU,YAAa,eAAqC,SAAS,MAAM;;AAG3F,SAAgB,qBAAqB,OAA6C;AAChF,QAAO,OAAO,UAAU,YAAa,sBAA4C,SAAS,MAAM;;AAGlG,SAAgB,cAAc,OAAiC;AAC7D,QAAO,OAAO,UAAU,YAAY,gCAAgC,KAAK,MAAM;;;AAIjF,SAAgB,gBAAgB,OAAe,SAAmC;AAChF,QAAO;;;;;;;;;ACxET,MAAa,QAAQ;CAAC;CAAa;CAAS;CAAY;CAAS;AAIjE,MA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