@textunited/sanity-plugin 0.1.0 → 0.1.1

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,"sources":["../src/core/textunited/client.ts","../src/core/document/apply.ts","../src/core/languages.ts","../src/server/translations.ts","../src/server/jobs.ts","../src/server/signing.ts","../src/server/sync.ts","../src/server/index.ts"],"names":["decodeHtmlEntities","joinTextChunks","applyBlockTranslation","setAtPath","getAtPath","getIntlItem","isPlainObject","cloneValue","readTargetValue","isMissingValue","valueHash","SanityConflictError","getBaseDocumentId","loadState","getPreferredDocument","getDocumentTypeConfig","extractTranslationUnits","loadTargets","recordBaseline","hasPendingTranslations","activeProjects","saveStateMutation","recordSentUnits","planTranslation","createProjectCustomId","createMissingTranslationDocuments","writeTargetsMutations","mergeState","projectLanguages","sentRecord","HttpSanityStore"],"mappings":";;;;;AAgCO,IAAM,sBAAA,GAAN,cAAqC,KAAA,CAAM;AAAA,EAChD,WAAA,CAAY,MAAA,EAAgB,IAAA,EAAc,SAAA,EAAmB;AAC3D,IAAA,KAAA,CAAM,CAAA,0BAAA,EAA6B,MAAM,CAAA,CAAA,EAAI,IAAI,CAAA,QAAA,EAAW,KAAK,KAAA,CAAM,SAAA,GAAY,GAAI,CAAC,CAAA,QAAA,CAAU,CAAA;AAClG,IAAA,IAAA,CAAK,IAAA,GAAO,wBAAA;AAAA,EACd;AACF;AAeO,IAAM,oBAAA,GAA+C,EAAC,cAAA,EAAgB,IAAA,EAAI;AAE1E,IAAM,kBAAA,GAAN,cAAiC,KAAA,CAAM;AAAA,EACnC,MAAA;AAAA,EACA,IAAA;AAAA,EAET,WAAA,CAAY,QAAgB,IAAA,EAAc;AACxC,IAAA,KAAA,CAAM,cAAA,CAAe,MAAA,EAAQ,IAAI,CAAC,CAAA;AAClC,IAAA,IAAA,CAAK,IAAA,GAAO,oBAAA;AACZ,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA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C7D,IAAA,MAAM,QAAA,GAAW,CAAA,OAAA,EAAU,OAAA,CAAQ,UAAA,IAAc,QAAQ,MAAM,CAAA,CAAA;AAC/D,IAAA,IAAI,OAAA,CAAQ,OAAA,CAAQ,GAAA,CAAI,eAAe,CAAA,KAAM,QAAA,EAAU,OAAO,IAAA,CAAK,EAAC,OAAA,EAAS,cAAA,EAAc,EAAG,GAAG,CAAA;AACjG,IAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAI,GAAA,CAAI,OAAA,CAAQ,GAAG,CAAA,CAAE,YAAA,CAAa,GAAA,CAAI,OAAO,CAAA,IAAK,EAAE,CAAA;AACzE,IAAA,MAAM,OAAA,GAAU,MAAM,oBAAA,CAAqB,UAAA,EAAY,MAAA,CAAO,QAAA,CAAS,KAAK,CAAA,GAAI,IAAA,CAAK,GAAA,CAAI,KAAA,EAAO,GAAG,IAAI,EAAE,CAAA;AACzG,IAAA,OAAO,KAAK,EAAC,OAAA,EAAS,OAAA,CAAQ,MAAA,EAAQ,SAAQ,CAAA;AAAA,EAChD;AACF;AAEA,SAAS,UAAU,IAAA,EAA8C;AAC/D,EAAA,IAAI;AACF,IAAA,MAAM,KAAA,GAAQ,IAAA,CAAK,KAAA,CAAM,IAAI,CAAA;AAC7B,IAAA,OAAO,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,KAAU,OAAQ,KAAA,GAAoC,IAAA;AAAA,EAC5F,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,IAAA;AAAA,EACT;AACF","file":"chunk-PC5SE6H6.cjs","sourcesContent":["import type {TextUnitedLanguage} from '../languages'\nimport type {\n CreateProjectRequest,\n ProjectResponse,\n ProjectSegment,\n SegmentWithTranslations,\n TeamCandidate,\n} from './types'\n\n/**\n * How the server authenticates with TextUnited. A personal access token (`tu_pat_...`, scopes\n * `projects:read` and `projects:write`) is the recommended option; company id plus API key is\n * kept for accounts that still use it.\n */\nexport type TextUnitedAuth =\n | {type: 'pat'; token: string}\n | {type: 'apiKey'; companyId: string; apiKey: string}\n\nexport type TextUnitedClientOptions = {\n auth: TextUnitedAuth\n /** Defaults to https://api.textunited.com */\n baseUrl?: string\n /** Injected in tests; defaults to the global fetch. */\n fetch?: typeof fetch\n /**\n * Longest wait for one TextUnited response. Instant machine translation can be slow, and an\n * update may not answer at all; the content is stored by then, so callers treat a timeout as\n * \"sent, translations follow later\". Defaults to 90 seconds.\n */\n timeoutMs?: number\n}\n\nexport class TextUnitedTimeoutError extends Error {\n constructor(method: string, path: string, timeoutMs: number) {\n super(`TextUnited did not answer ${method} ${path} within ${Math.round(timeoutMs / 1000)} seconds`)\n this.name = 'TextUnitedTimeoutError'\n }\n}\n\n/**\n * What the connected TextUnited API can do.\n *\n * `appendSegments`: `PUT /segments/projects` accepts `appendContent: true`, which adds the sent\n * segments as a new task and leaves the existing tasks (and their work) untouched. With it, an\n * update sends only new and changed texts, as one new task per request. Without it, an update\n * replaces whole tasks, so each changed part of the document is sent as its own task.\n */\nexport type TextUnitedCapabilities = {\n appendSegments: boolean\n}\n\n/** The production API supports appending segments since November 2026. */\nexport const DEFAULT_CAPABILITIES: TextUnitedCapabilities = {appendSegments: true}\n\nexport class TextUnitedApiError extends Error {\n readonly status: number\n readonly body: string\n\n constructor(status: number, body: string) {\n super(describeStatus(status, body))\n this.name = 'TextUnitedApiError'\n this.status = status\n this.body = body\n }\n}\n\nfunction describeStatus(status: number, body: string): string {\n if (status === 401) {\n return 'TextUnited rejected the access token. It may have expired or been revoked: create a new one in the TextUnited portal and update the server configuration.'\n }\n if (status === 403) {\n return 'The TextUnited access token lacks the required scopes. It needs projects:read and projects:write.'\n }\n const detail = body.trim().slice(0, 500)\n return `TextUnited request failed with status ${status}${detail ? `: ${detail}` : ''}`\n}\n\nfunction encodeBasic(value: string): string {\n if (typeof btoa === 'function') return btoa(value)\n return Buffer.from(value).toString('base64')\n}\n\nexport class TextUnitedClient {\n private readonly baseUrl: string\n private readonly authHeader: string\n private readonly fetchImpl: typeof fetch\n private readonly timeoutMs: number\n\n constructor(options: TextUnitedClientOptions) {\n this.baseUrl = (options.baseUrl ?? 'https://api.textunited.com').replace(/\\/+$/, '')\n this.fetchImpl = options.fetch ?? fetch\n this.timeoutMs = options.timeoutMs ?? 90_000\n this.authHeader =\n options.auth.type === 'pat'\n ? `Bearer ${options.auth.token}`\n : `Basic ${encodeBasic(`${options.auth.companyId}:${options.auth.apiKey}`)}`\n }\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T | null> {\n const controller = new AbortController()\n const timer = setTimeout(() => controller.abort(), this.timeoutMs)\n let response: Response\n let text: string\n try {\n response = await this.fetchImpl(`${this.baseUrl}${path}`, {\n method,\n headers: {\n Authorization: this.authHeader,\n Accept: 'application/json',\n ...(body === undefined ? {} : {'Content-Type': 'application/json'}),\n },\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: controller.signal,\n })\n text = await response.text()\n } catch (error) {\n if (controller.signal.aborted) throw new TextUnitedTimeoutError(method, path, this.timeoutMs)\n throw error\n } finally {\n clearTimeout(timer)\n }\n\n if (response.status === 404 && method === 'GET') return null\n if (!response.ok) throw new TextUnitedApiError(response.status, text)\n return text.trim() ? (JSON.parse(text) as T) : null\n }\n\n /** Returns the multilingual project with this custom id, or null when it does not exist. */\n getProject(customId: string): Promise<ProjectResponse | null> {\n return this.request<ProjectResponse>(\n 'GET',\n `/segments/projects/custom/${encodeURIComponent(customId)}`,\n )\n }\n\n async createProject(request: CreateProjectRequest): Promise<ProjectResponse> {\n const result = await this.request<ProjectResponse>('POST', '/segments/projects', request)\n return result ?? {customId: request.customId}\n }\n\n /**\n * Replaces the content of one task (virtual file) in every language project of the\n * multilingual project. With `instantTranslation`, unchanged segments get their text back\n * from TextUnited's translation memory, but with the status `automatic`.\n */\n async replaceTask(args: {\n customId: string\n taskId: string\n segments: ProjectSegment[]\n eventUrl?: string\n }): Promise<ProjectResponse> {\n const result = await this.request<ProjectResponse>('PUT', '/segments/projects', {\n customId: args.customId,\n taskId: args.taskId,\n segments: args.segments,\n appendContent: false,\n instantTranslation: true,\n eventUrl: args.eventUrl,\n })\n return result ?? {customId: args.customId}\n }\n\n /**\n * People who can join an in-house team: active company users and confirmed collaborators.\n * Needs the same token scopes as projects (projects:read).\n */\n async listTeamCandidates(): Promise<TeamCandidate[]> {\n type User = {id?: number; login?: string; email?: string; firstName?: string; lastName?: string; stateName?: string}\n type Collaborator = {userId?: number; id?: number; email?: string; firstName?: string; lastName?: string; confirmed?: boolean}\n const [users, collaborators] = await Promise.all([\n this.request<User[]>('GET', '/accounts/Users'),\n this.request<Collaborator[]>('GET', '/accounts/Collaborators'),\n ])\n const name = (first?: string, last?: string, fallback = '') =>\n [first, last].filter(Boolean).join(' ').trim() || fallback\n const candidates: TeamCandidate[] = []\n for (const user of users ?? []) {\n const username = user.login || user.email\n if (!user.id || !username || (user.stateName && user.stateName !== 'Normal')) continue\n candidates.push({id: user.id, username, name: name(user.firstName, user.lastName, username), kind: 'user'})\n }\n for (const collaborator of collaborators ?? []) {\n const id = collaborator.userId || collaborator.id\n if (!id || !collaborator.email || collaborator.confirmed === false) continue\n candidates.push({\n id,\n username: collaborator.email,\n name: name(collaborator.firstName, collaborator.lastName, collaborator.email),\n kind: 'collaborator',\n })\n }\n return candidates.sort((a, b) => a.name.localeCompare(b.name))\n }\n\n /**\n * Adds the segments as a new task in every language project of the multilingual project;\n * existing tasks stay as they are. The task id must not exist in the project yet (HTTP 400).\n */\n async appendTask(args: {\n customId: string\n taskId: string\n segments: ProjectSegment[]\n eventUrl?: string\n }): Promise<ProjectResponse> {\n const result = await this.request<ProjectResponse>('PUT', '/segments/projects', {\n customId: args.customId,\n taskId: args.taskId,\n segments: args.segments,\n appendContent: true,\n instantTranslation: true,\n eventUrl: args.eventUrl,\n })\n return result ?? {customId: args.customId, taskId: args.taskId}\n }\n\n /** Languages TextUnited supports (`GET /integrations/languages`, no token needed). */\n async listLanguages(): Promise<TextUnitedLanguage[]> {\n return (await this.request<TextUnitedLanguage[]>('GET', '/integrations/languages')) ?? []\n }\n\n /** Source segments with their translations in every target language. */\n async getSegments(customId: string, taskId?: string): Promise<SegmentWithTranslations[]> {\n const query = taskId ? `?taskId=${encodeURIComponent(taskId)}` : ''\n const result = await this.request<SegmentWithTranslations[]>(\n 'GET',\n `/segments/projects/custom/${encodeURIComponent(customId)}/segments${query}`,\n )\n return result ?? []\n }\n}\n","import type {TranslationState} from '../plan'\nimport type {TranslationUnit} from './extract'\nimport {getIntlItem} from './intl'\nimport {cloneValue, getAtPath, isPlainObject, setAtPath, type PlainObject} from './paths'\nimport {\n applyBlockTranslation,\n decodeHtmlEntities,\n joinTextChunks,\n type PortableTextBlock,\n} from './portableText'\nimport {isMissingValue, readTargetValue, valueHash, type TranslationTargets} from './target'\n\n/** Translation of one segment in one language, as returned by TextUnited. */\nexport type SegmentTranslation = {content: string; status?: string}\n\n/** customId → Sanity language id → translation */\nexport type TranslationsBySegment = Map<string, Map<string, SegmentTranslation>>\n\nexport type ApplyOutcome =\n /** Written to the document */\n | 'applied'\n /** The document already holds this text */\n | 'unchanged'\n /** Someone edited the translation in Sanity after the plugin wrote it; left as it is */\n | 'keptManualEdit'\n /** TextUnited has no translation (yet) for every chunk of the value */\n | 'incomplete'\n\nexport type ApplyResult = {\n targets: TranslationTargets\n state: TranslationState\n /** Top-level fields changed, per document: `''` for fieldLevel, the language for documentLevel */\n changedFields: Map<string, Set<string>>\n outcomes: Array<{unitId: string; language: string; outcome: ApplyOutcome}>\n}\n\nconst NOT_TRANSLATED = new Set(['untranslated'])\n\nfunction translatedValue(\n unit: TranslationUnit,\n language: string,\n translations: TranslationsBySegment,\n): {value: string | PortableTextBlock; status?: string} | null {\n const chunks: SegmentTranslation[] = []\n for (const segment of unit.segments) {\n const translation = translations.get(segment.customId)?.get(language)\n if (!translation || !translation.content || NOT_TRANSLATED.has(translation.status ?? '')) {\n return null\n }\n chunks.push(translation)\n }\n\n // The lowest status of the chunks describes the whole value.\n const status = chunks.map((chunk) => chunk.status).find((s) => s !== 'proofread') ?? chunks[0]?.status\n const contents = chunks.map((chunk) => chunk.content)\n\n if (unit.kind === 'text') {\n return {value: decodeHtmlEntities(joinTextChunks(contents)), status}\n }\n return {value: applyBlockTranslation(unit.source as PortableTextBlock, contents), status}\n}\n\nfunction writeValue(\n unit: TranslationUnit,\n language: string,\n value: unknown,\n targets: TranslationTargets,\n sourceDocument: PlainObject,\n sourceLanguage: string,\n): void {\n if (targets.model === 'documentLevel') {\n const document = targets.documents[language]\n if (!document) throw new Error(`No ${language} document to write the translation to`)\n setAtPath(document, sourceDocument, [...unit.fieldPath, ...unit.innerPath], value)\n return\n }\n\n const intlArray = getAtPath(targets.document, unit.fieldPath)\n if (!Array.isArray(intlArray)) throw new Error(`No internationalized field at ${unit.id}`)\n const sourceItem = getIntlItem(getAtPath(sourceDocument, unit.fieldPath), sourceLanguage)\n\n let item = getIntlItem(intlArray, language)\n if (!item) {\n item = {\n _key: language,\n ...(isPlainObject(sourceItem) && typeof sourceItem._type === 'string' ? {_type: sourceItem._type} : {}),\n value: unit.kind === 'text' ? '' : [],\n }\n intlArray.push(item)\n }\n\n if (unit.innerPath.length === 0) {\n item.value = value\n return\n }\n if (!Array.isArray(item.value)) item.value = []\n setAtPath(item, {value: sourceItem?.value ?? []}, ['value', ...unit.innerPath], value)\n}\n\n/**\n * Writes TextUnited translations into the target documents.\n *\n * A translation replaces the current value only when the value is missing, or when it is still\n * exactly what the plugin wrote last time. A value someone edited in Sanity is kept (outcome\n * `keptManualEdit`) unless the unit id is in `overwrite` (the `all` mode).\n *\n * The inputs are not modified: the result holds updated copies.\n */\nexport function applyTranslations(args: {\n units: TranslationUnit[]\n languages: string[]\n sourceLanguage: string\n sourceDocument: PlainObject\n targets: TranslationTargets\n translations: TranslationsBySegment\n state: TranslationState\n overwrite?: ReadonlySet<string>\n}): ApplyResult {\n const targets = cloneValue(args.targets)\n const state: TranslationState = cloneValue(args.state)\n const changedFields = new Map<string, Set<string>>()\n const outcomes: ApplyResult['outcomes'] = []\n\n for (const unit of args.units) {\n for (const language of args.languages) {\n const translated = translatedValue(unit, language, args.translations)\n if (!translated) {\n outcomes.push({unitId: unit.id, language, outcome: 'incomplete'})\n continue\n }\n\n const current = readTargetValue(unit, language, targets)\n const record = state.units[unit.id]\n const appliedHash = record?.languages[language]?.appliedHash\n const editedByHand =\n !isMissingValue(unit, current) && appliedHash !== valueHash(current)\n\n if (editedByHand && !args.overwrite?.has(unit.id)) {\n outcomes.push({unitId: unit.id, language, outcome: 'keptManualEdit'})\n continue\n }\n\n const unitState = (state.units[unit.id] ??= {sourceHash: unit.sourceHash, languages: {}})\n unitState.languages[language] = {\n appliedHash: valueHash(translated.value),\n status: translated.status,\n }\n\n if (valueHash(current) === valueHash(translated.value)) {\n outcomes.push({unitId: unit.id, language, outcome: 'unchanged'})\n continue\n }\n\n writeValue(unit, language, translated.value, targets, args.sourceDocument, args.sourceLanguage)\n const documentKey = targets.model === 'fieldLevel' ? '' : language\n const fields = changedFields.get(documentKey) ?? new Set<string>()\n fields.add(String(unit.fieldPath[0]))\n changedFields.set(documentKey, fields)\n outcomes.push({unitId: unit.id, language, outcome: 'applied'})\n }\n }\n\n return {targets, state, changedFields, outcomes}\n}\n","/**\n * TextUnited language codes.\n *\n * TextUnited accepts a few common codes that are not in its language list and stores them as its\n * own code (TextUnited `Languages.GetLanguageByCode`): a project ordered for `zh-cn` comes back as\n * `CN-CN`. Codes are therefore compared in this canonical form, never as written.\n */\nconst ALIASES: Record<string, string> = {\n 'en-gb': 'en-en',\n 'en-uk': 'en-en',\n 'zh-cn': 'cn-cn',\n 'zh-tw': 'ct-ct',\n}\n\n/** The code as TextUnited stores it, lower case, e.g. `zh-CN` → `cn-cn`. */\nexport function canonicalLanguageCode(code: string | null | undefined): string {\n const lower = String(code ?? '').trim().toLowerCase()\n return ALIASES[lower] ?? lower\n}\n\n/** True when both codes mean the same TextUnited language. */\nexport function sameLanguageCode(a: string | null | undefined, b: string | null | undefined): boolean {\n return canonicalLanguageCode(a) === canonicalLanguageCode(b)\n}\n\n/** One language of `GET /integrations/languages`. */\nexport type TextUnitedLanguage = {\n id: number\n systemName: string\n langCode: string\n generalLangCode?: string\n}\n\n/**\n * Codes of a configuration that TextUnited does not know, with suggestions of known codes for the\n * same language (same first part, e.g. `de-de`, `de-at` for `de-xx`).\n */\nexport function findUnknownLanguageCodes(\n codes: Array<{label: string; code: string}>,\n known: TextUnitedLanguage[],\n): Array<{label: string; code: string; suggestions: string[]}> {\n const knownCodes = new Set(known.map((language) => language.langCode.toLowerCase()))\n const unknown: Array<{label: string; code: string; suggestions: string[]}> = []\n for (const {label, code} of codes) {\n if (knownCodes.has(canonicalLanguageCode(code))) continue\n const general = canonicalLanguageCode(code).split('-')[0]\n const suggestions = known\n .filter((language) => language.langCode.toLowerCase().split('-')[0] === general)\n .slice(0, 5)\n .map((language) => `${language.langCode.toLowerCase()} (${language.systemName})`)\n unknown.push({label, code, suggestions})\n }\n return unknown\n}\n","import type {TranslationConfig} from '../core/config'\nimport type {TranslationsBySegment} from '../core/document/apply'\nimport {canonicalLanguageCode} from '../core/languages'\n\ntype Entry = {\n source?: {customId?: string; taskId?: string | null}\n translations?: Array<{languageCode?: string; content?: string; status?: string}>\n}\n\n/**\n * Maps TextUnited segments (instant translations or `GET …/segments`) to the shape\n * `applyTranslations` reads, translating TextUnited language codes to Sanity language ids.\n *\n * In append mode the same segment can exist in several tasks (each update adds a task with the\n * changed texts). `taskOf` names, per segment, the task that holds its current source; copies in\n * other tasks are ignored. Without an entry, a later copy wins over an earlier one.\n */\nexport function toTranslationsBySegment(\n entries: Iterable<Entry>,\n config: TranslationConfig,\n taskOf?: ReadonlyMap<string, string>,\n): TranslationsBySegment {\n const languageByCode = new Map(\n config.targetLanguages.map((language) => [canonicalLanguageCode(language.textUnitedCode), language.id]),\n )\n const result: TranslationsBySegment = new Map()\n for (const entry of entries) {\n const customId = entry.source?.customId\n if (!customId) continue\n const wantedTask = taskOf?.get(customId)\n if (wantedTask !== undefined && (entry.source?.taskId ?? '') !== wantedTask) continue\n const perLanguage = result.get(customId) ?? new Map()\n for (const translation of entry.translations ?? []) {\n const language = languageByCode.get(canonicalLanguageCode(translation.languageCode))\n if (!language || typeof translation.content !== 'string') continue\n perLanguage.set(language, {content: translation.content, status: translation.status})\n }\n result.set(customId, perLanguage)\n }\n return result\n}\n\n/** Statuses after which TextUnited will not change a translation on its own. */\nconst FINAL_STATUSES = new Set(['translated', 'proofread'])\n\nexport function isFinalStatus(status: string | undefined): boolean {\n return FINAL_STATUSES.has(String(status ?? '').toLowerCase())\n}\n","import {getDocumentTypeConfig, type DocumentTypeConfig, type TranslationConfig} from '../core/config'\nimport {applyTranslations, type ApplyOutcome, type TranslationsBySegment} from '../core/document/apply'\nimport {extractTranslationUnits, type TranslationUnit} from '../core/document/extract'\nimport {getIntlItem} from '../core/document/intl'\nimport type {PlainObject} from '../core/document/paths'\nimport {createProjectCustomId, getBaseDocumentId} from '../core/ids'\nimport {canonicalLanguageCode, findUnknownLanguageCodes, type TextUnitedLanguage} from '../core/languages'\nimport {\n hasPendingTranslations,\n mergeState,\n planTranslation,\n recordBaseline,\n recordSentUnits,\n type TranslationMode,\n type TranslationPlan,\n type TranslationState,\n} from '../core/plan'\nimport {\n TextUnitedTimeoutError,\n type TextUnitedCapabilities,\n type TextUnitedClient,\n} from '../core/textunited/client'\nimport type {TranslationTargets} from '../core/document/target'\nimport {activeProjects, type ProjectRecord} from '../core/projects'\nimport type {\n ProjectResponse,\n ProjectSegment,\n ProjectTargetLanguage,\n ProjectTeamMember,\n} from '../core/textunited/types'\nimport {\n createMissingTranslationDocuments,\n loadState,\n loadTargets,\n saveStateMutation,\n writeTargetsMutations,\n type StoredState,\n} from './documents'\nimport {getPreferredDocument, SanityConflictError, type SanityStore} from './sanityStore'\nimport {isFinalStatus, toTranslationsBySegment} from './translations'\n\n/** Services ordered for every target language of a new project. */\nexport type ProjectSettings = Omit<ProjectTargetLanguage, 'targetLanguageCode'>\n\nexport const DEFAULT_PROJECT_SETTINGS: ProjectSettings = {\n managedProject: true,\n serviceTranslation: true,\n serviceProofreading: false,\n serviceAutomaticTranslation: true,\n serviceAdaptiveTranslation: false,\n serviceScoring: false,\n}\n\n/** In-house projects: the company's own team works on them, so TextUnited needs that team. */\nexport const DEFAULT_IN_HOUSE_SETTINGS: ProjectSettings = {\n managedProject: false,\n serviceTranslation: true,\n serviceProofreading: false,\n serviceAutomaticTranslation: true,\n serviceAdaptiveTranslation: false,\n serviceScoring: false,\n}\n\nexport type ProjectType = 'outsourced' | 'inHouse'\n\n/** One person of an in-house team, as the Studio sends it in the request document. */\ntype RequestedTeamMember = {\n id?: number\n username?: string\n translator?: boolean\n proofreader?: boolean\n projectManager?: boolean\n}\n\nfunction teamFromRequest(value: unknown): ProjectTeamMember[] {\n if (!Array.isArray(value)) return []\n return (value as RequestedTeamMember[])\n .filter((member) => typeof member?.username === 'string' && member.username !== '')\n .map((member) => ({\n ...(typeof member.id === 'number' ? {id: member.id} : {}),\n username: member.username as string,\n isTranslator: member.translator === true,\n isProofreader: member.proofreader === true,\n isProjectManager: member.projectManager === true,\n isInCountryReviewer: false,\n }))\n .filter((member) => member.isTranslator || member.isProofreader || member.isProjectManager)\n}\n\n/** Settings for the target languages of a new project of the requested type. */\nfunction projectSettingsFor(\n request: PlainObject,\n context: JobContext,\n): {projectType: ProjectType; settings: ProjectSettings} {\n if (request.projectType !== 'inHouse') return {projectType: 'outsourced', settings: context.projectSettings}\n const team = teamFromRequest(request.team)\n if (!team.some((member) => member.isTranslator)) {\n throw new Error('An in-house project needs at least one translator in the team.')\n }\n return {\n projectType: 'inHouse',\n settings: {\n ...context.inHouseSettings,\n serviceProofreading: team.some((member) => member.isProofreader),\n team,\n },\n }\n}\n\nexport type JobContext = {\n config: TranslationConfig\n store: SanityStore\n textUnited: TextUnitedClient\n sanityProjectId: string\n dataset: string\n projectSettings: ProjectSettings\n inHouseSettings: ProjectSettings\n /** Languages TextUnited supports, to check the configured codes; null when unavailable */\n knownLanguages?: () => Promise<TextUnitedLanguage[] | null>\n /** What the TextUnited API supports; see `TextUnitedCapabilities` */\n capabilities?: TextUnitedCapabilities\n /** Builds the notification URL TextUnited calls for one document; none in local development */\n eventUrl: (baseDocumentId: string) => Promise<string | undefined>\n newId?: () => string\n now?: () => Date\n}\n\nexport type JobSummary = {\n tasksSent: string[]\n /** Sent, but TextUnited did not answer in time; their translations arrive later */\n tasksAwaitingTranslation?: string[]\n unitsSelected: number\n /** Texts sent to TextUnited (all of them for a new project after a reset) */\n textsSent?: number\n outcomes: Partial<Record<ApplyOutcome, number>>\n projectCreated: boolean\n /** For a stop or resume request: what changed */\n action?: 'stop' | 'resume'\n languages?: string[]\n}\n\nexport type JobResult =\n | {status: 'ignored'; reason: string}\n | {status: 'done'; summary: JobSummary}\n | {status: 'failed'; error: string}\n\nconst VALID_MODES: ReadonlySet<string> = new Set(['missing', 'changed', 'all'])\n\nfunction documentTitle(source: PlainObject, sourceLanguage: string): string {\n const title = source.title\n if (typeof title === 'string') return title\n const localized = getIntlItem(title, sourceLanguage)?.value\n return typeof localized === 'string' ? localized : ''\n}\n\n/** Name of a project; projects added later name their languages, e.g. \"Pricing – JA, IT (page-1)\". */\nfunction projectName(source: PlainObject, baseId: string, sourceLanguage: string, languages?: string[]): string {\n const title = documentTitle(source, sourceLanguage).replace(/\\s+/g, ' ').trim()\n const suffix = languages?.length ? ` – ${languages.map((language) => language.toUpperCase()).join(', ')}` : ''\n return title ? `${title.slice(0, 160)}${suffix} (${baseId})` : `${baseId}${suffix}`\n}\n\n/** Maps TextUnited instant translations to the shape `applyTranslations` reads. */\nfunction collectInstantTranslations(\n responses: ProjectResponse[],\n config: TranslationConfig,\n): TranslationsBySegment {\n return toTranslationsBySegment(\n responses.flatMap((response) => response.instantTranslationSegments ?? []),\n config,\n )\n}\n\nexport function countOutcomes(outcomes: Array<{outcome: ApplyOutcome}>): JobSummary['outcomes'] {\n const counts: JobSummary['outcomes'] = {}\n for (const {outcome} of outcomes) counts[outcome] = (counts[outcome] ?? 0) + 1\n return counts\n}\n\n/**\n * Processes one translation request document. Safe to call more than once for the same request:\n * only a `queued` request is processed, and it is claimed with a revision check first.\n */\nexport async function processTranslationRequest(\n requestId: string,\n context: JobContext,\n): Promise<JobResult> {\n const now = context.now ?? (() => new Date())\n const newId = context.newId ?? (() => crypto.randomUUID())\n const request = await context.store.getDocument(requestId)\n if (!request) return {status: 'ignored', reason: 'Request not found'}\n if (request.status !== 'queued') return {status: 'ignored', reason: `Request is ${String(request.status)}`}\n\n try {\n await context.store.mutate([\n {\n patch: {\n id: requestId,\n ifRevisionID: String(request._rev),\n set: {status: 'running', startedAt: now().toISOString()},\n },\n },\n ])\n } catch (error) {\n if (error instanceof SanityConflictError) return {status: 'ignored', reason: 'Already being processed'}\n throw error\n }\n\n try {\n const summary = await runRequest(request, context, newId)\n await context.store.mutate([\n {\n patch: {\n id: requestId,\n set: {status: 'done', finishedAt: now().toISOString(), summaryJson: JSON.stringify(summary), error: null},\n },\n },\n ])\n return {status: 'done', summary}\n } catch (error) {\n const message = error instanceof Error ? error.message : 'Translation request failed'\n await context.store.mutate([\n {patch: {id: requestId, set: {status: 'failed', finishedAt: now().toISOString(), error: message}}},\n ])\n return {status: 'failed', error: message}\n }\n}\n\nasync function runRequest(request: PlainObject, context: JobContext, newId: () => string): Promise<JobSummary> {\n const {config} = context\n const now = context.now ?? (() => new Date())\n const baseId = getBaseDocumentId(String(request.documentId ?? ''))\n const mode = String(request.mode ?? 'missing') as TranslationMode\n const reset = request.reset === true\n if (!baseId) throw new Error('The request has no document id')\n if (!VALID_MODES.has(mode)) throw new Error(`Unknown translation mode: ${mode}`)\n\n const configured = new Set(config.targetLanguages.map((language) => language.id))\n const requestedLanguages = (Array.isArray(request.languages) ? request.languages : [])\n .map(String)\n .filter((language) => configured.has(language))\n if (requestedLanguages.length === 0) throw new Error('No configured target language was requested')\n\n if (request.action === 'stop' || request.action === 'resume') {\n return changeStoppedLanguages(baseId, requestedLanguages, request.action, context)\n }\n\n // Stopped languages are not sent, written or restored until an editor resumes them.\n const stored = await loadState(context.store, baseId)\n const languages = requestedLanguages.filter((language) => !stored.stopped.includes(language))\n if (languages.length === 0) {\n throw new Error('Translation is stopped for the requested languages. Resume them in the TextUnited panel first.')\n }\n\n const source = await getPreferredDocument(context.store, baseId)\n if (!source) throw new Error(`Document ${baseId} not found`)\n const typeConfig = getDocumentTypeConfig(config, String(source._type))\n if (!typeConfig) throw new Error(`Documents of type ${String(source._type)} are not configured for translation`)\n\n const units = extractTranslationUnits(source, typeConfig, config)\n const loaded = await loadTargets({store: context.store, source, typeConfig, languages})\n const baseState = recordBaseline(stored.state, units)\n\n // A reset starts over: the current projects are archived and a new one takes the languages.\n const currentProjects = reset ? [] : stored.projects\n const archived = reset ? [...stored.archived, ...stored.projects] : stored.archived\n const groups = planGroups({\n units,\n languages,\n targets: loaded.targets,\n state: baseState,\n mode,\n reset,\n append: context.capabilities?.appendSegments === true,\n projects: currentProjects,\n newCustomId: () => projectCustomIdFor(context, baseId, currentProjects.length + archived.length),\n })\n\n const selectedIds = new Set(groups.flatMap((group) => group.apply.selected.map(({unit}) => unit.id)))\n const summary: JobSummary = {\n tasksSent: [],\n unitsSelected: selectedIds.size,\n outcomes: {},\n projectCreated: false,\n }\n summary.textsSent = new Set(groups.flatMap((group) => group.sendUnits.map((unit) => unit.id))).size\n if (groups.every((group) => group.sendUnits.length === 0)) {\n try {\n const pending = hasPendingTranslations(baseState, activeProjects(stored.projects, stored.stopped), isFinalStatus)\n await context.store.mutate([saveStateMutation(baseId, {...stored, state: baseState}, pending)])\n } catch (error) {\n // The baseline is only a convenience; a concurrent save already holds a newer state.\n if (!(error instanceof SanityConflictError)) throw error\n }\n return summary\n }\n\n await assertKnownLanguageCodes(context, languages)\n const eventUrl = await context.eventUrl(baseId)\n const sentAt = now().toISOString()\n const isFirst = currentProjects.length === 0 && archived.length === 0\n\n // Each project is sent to separately; they do not depend on each other.\n const results = await Promise.all(\n groups\n .filter((group) => group.sendUnits.length > 0)\n .map((group) => sendToProject({context, request, group, source, baseId, eventUrl, newId, now, isFirst})),\n )\n\n let sentState = baseState\n const projects = [...currentProjects]\n const responses: ProjectResponse[] = []\n for (const result of results) {\n responses.push(...result.responses)\n summary.tasksSent.push(...result.tasksSent)\n if (result.awaiting.length > 0) {\n summary.tasksAwaitingTranslation = [...(summary.tasksAwaitingTranslation ?? []), ...result.awaiting]\n }\n if (result.created) summary.projectCreated = true\n const index = projects.findIndex((project) => project.customId === result.project.customId)\n if (index >= 0) projects[index] = result.project\n else projects.push(result.project)\n for (const sent of result.sent) {\n sentState = recordSentUnits(sentState, sent.units, sentAt, sent.taskId, result.project.customId)\n }\n }\n\n // Only selected units take the instant (machine) translation; in replace mode other units of\n // the same tasks were resent only because the API replaces whole tasks. A translation of an\n // edited source no longer fits, so it is replaced even if edited by hand; so is every value in\n // `all` mode.\n const selected = new Map<string, TranslationUnit>()\n const overwrite = new Set<string>()\n for (const group of groups) {\n for (const {unit, reason} of group.apply.selected) {\n selected.set(unit.id, unit)\n if (mode === 'all' || reason === 'sourceChanged') overwrite.add(unit.id)\n }\n }\n\n return finishRequest({\n context,\n source,\n typeConfig,\n loaded,\n languages,\n units,\n stored,\n baseId,\n newId,\n summary,\n selectedUnits: [...selected.values()],\n overwrite,\n responses,\n sentState,\n projects,\n archived,\n })\n}\n\n/** One TextUnited project a request sends to, with what it sends and what it applies. */\ntype SendGroup = {\n project: ProjectRecord\n /** Requested languages that belong to this project */\n languages: string[]\n /** Units whose instant translation is written, and why they were chosen */\n apply: TranslationPlan\n /** What is sent: whole parts in replace mode; every text for a new project after a reset */\n sendPlan: TranslationPlan\n sendUnits: TranslationUnit[]\n}\n\n/**\n * Splits a request by project: requested languages of an existing project go to that project;\n * languages in no project go together to one new project.\n */\nfunction planGroups(args: {\n units: TranslationUnit[]\n languages: string[]\n targets: TranslationTargets\n state: TranslationState\n mode: TranslationMode\n reset: boolean\n /** Append mode sends the selected texts; replace mode sends whole parts (tasks) */\n append: boolean\n projects: ProjectRecord[]\n newCustomId: () => string\n}): SendGroup[] {\n const groups: SendGroup[] = []\n const plan = (languages: string[], projectCustomId: string | undefined, mode: TranslationMode) =>\n planTranslation({units: args.units, languages, targets: args.targets, state: args.state, mode, projectCustomId})\n const unitsToSend = (sendPlan: TranslationPlan) => {\n if (args.append) return sendPlan.selected.map(({unit}) => unit)\n const taskIds = new Set(sendPlan.tasks.map((task) => task.taskId))\n return args.units.filter((unit) => taskIds.has(unit.taskId))\n }\n\n for (const project of args.projects) {\n const languages = args.languages.filter((language) => project.languages.includes(language))\n if (languages.length === 0) continue\n const apply = plan(languages, project.customId, args.mode)\n groups.push({project, languages, apply, sendPlan: apply, sendUnits: unitsToSend(apply)})\n }\n\n const covered = new Set(args.projects.flatMap((project) => project.languages))\n const newLanguages = args.languages.filter((language) => !covered.has(language))\n if (newLanguages.length > 0) {\n const project: ProjectRecord = {customId: args.newCustomId(), languages: newLanguages}\n const apply = plan(newLanguages, undefined, args.mode)\n // After a reset the new project receives every text, so it holds the whole document.\n const sendPlan = args.reset ? plan(newLanguages, undefined, 'all') : apply\n groups.push({project, languages: newLanguages, apply, sendPlan, sendUnits: unitsToSend(sendPlan)})\n }\n return groups\n}\n\n/** Custom id of a document's next project: the plain id for the first, then `-2`, `-3`… */\nfunction projectCustomIdFor(context: JobContext, baseId: string, existingCount: number): string {\n const customId = createProjectCustomId({\n sanityProjectId: context.sanityProjectId,\n dataset: context.dataset,\n documentId: baseId,\n })\n return existingCount === 0 ? customId : `${customId}-${existingCount + 1}`\n}\n\ntype SendResult = {\n project: ProjectRecord\n created: boolean\n responses: ProjectResponse[]\n tasksSent: string[]\n awaiting: string[]\n /** Units sent, with the task holding them (append mode) */\n sent: Array<{units: TranslationUnit[]; taskId?: string}>\n}\n\n/** Creates or updates one TextUnited project. */\nasync function sendToProject(args: {\n context: JobContext\n request: PlainObject\n group: SendGroup\n source: PlainObject\n baseId: string\n eventUrl: string | undefined\n newId: () => string\n now: () => Date\n /** The document's first project ever: its name has no language suffix */\n isFirst: boolean\n}): Promise<SendResult> {\n const {context, request, group, source, baseId, eventUrl, newId, now} = args\n const {config} = context\n const codeOf = new Map(config.targetLanguages.map((language) => [language.id, language.textUnitedCode]))\n const customId = group.project.customId\n const result: SendResult = {\n project: {...group.project},\n created: false,\n responses: [],\n tasksSent: [],\n awaiting: [],\n sent: [],\n }\n\n const existing = await context.textUnited.getProject(customId)\n if (typeof existing?.id === 'number') result.project.projectId = existing.id\n if (existing) assertProjectLanguages(existing, group.languages, codeOf)\n\n const create = async (taskId: string, segments: ProjectSegment[]) => {\n const chosen = projectSettingsFor(request, context)\n result.project.projectType = chosen.projectType\n result.project.createdAt = now().toISOString()\n const created = await context.textUnited\n .createProject({\n customId,\n taskId,\n name: projectName(source, baseId, config.sourceLanguage.id, args.isFirst ? undefined : group.project.languages),\n sourceLanguageCode: config.sourceLanguage.textUnitedCode,\n targetLanguages: group.project.languages.map((language) => ({\n ...chosen.settings,\n targetLanguageCode: codeOf.get(language) as string,\n })),\n segments,\n instantTranslation: true,\n eventUrl,\n referenceNumber: baseId,\n })\n .catch(async (error: unknown) => {\n // The project may have been created even though the answer never came.\n if (error instanceof TextUnitedTimeoutError && (await context.textUnited.getProject(customId))) {\n result.awaiting.push(taskId)\n return null\n }\n throw error\n })\n if (created) {\n result.responses.push(created)\n if (typeof created.id === 'number') result.project.projectId = created.id\n }\n result.created = true\n }\n\n if (context.capabilities?.appendSegments) {\n // Append mode: the chosen texts go out as one new task; nothing in the project is replaced.\n const segments = group.sendUnits.flatMap((unit) => unit.segments.map((segment) => ({...segment})))\n let taskId = existing ? appendTaskId(now(), newId) : 'content'\n if (!existing) {\n await create(taskId, segments)\n } else {\n try {\n const response = await context.textUnited.appendTask({customId, taskId, segments, eventUrl})\n if (response.taskId) taskId = response.taskId\n result.responses.push(response)\n } catch (error) {\n // The task may have been added even though the answer never came; if it was, its\n // translations arrive through notifications or the periodic check.\n if (!(error instanceof TextUnitedTimeoutError)) throw error\n result.awaiting.push(taskId)\n }\n }\n result.tasksSent.push(taskId)\n result.sent.push({units: group.sendUnits, taskId})\n return result\n }\n\n // Replace mode: each changed part of the document is its own task, sent complete.\n let tasks = group.sendPlan.tasks\n if (!existing) {\n // The create call handles formatted (HTML) segments reliably, while an update with instant\n // translation may not answer for them, so a task with formatted text goes first.\n const formatted = tasks.findIndex((task) => task.segments.some((s) => s.content.includes('data-tu-id')))\n if (formatted > 0) tasks = [tasks[formatted]!, ...tasks.filter((_, index) => index !== formatted)]\n const [first, ...rest] = tasks\n if (first) {\n await create(first.taskId, first.segments)\n result.tasksSent.push(first.taskId)\n }\n tasks = rest\n }\n for (const task of tasks) {\n try {\n result.responses.push(\n await context.textUnited.replaceTask({customId, taskId: task.taskId, segments: task.segments, eventUrl}),\n )\n } catch (error) {\n // An update stores the segments before TextUnited prepares the instant translation, so a\n // missing answer still means the task was sent; its translations arrive later.\n if (!(error instanceof TextUnitedTimeoutError)) throw error\n result.awaiting.push(task.taskId)\n }\n result.tasksSent.push(task.taskId)\n }\n result.sent.push({units: group.sendUnits})\n return result\n}\n\n/**\n * Stops or resumes languages for a document. Nothing is sent to TextUnited: the languages stay in\n * their projects, the plugin only stops (or starts again) sending, writing and restoring them.\n */\nasync function changeStoppedLanguages(\n baseId: string,\n languages: string[],\n action: 'stop' | 'resume',\n context: JobContext,\n): Promise<JobSummary> {\n for (let attempt = 1; ; attempt += 1) {\n const stored = await loadState(context.store, baseId)\n const stopped =\n action === 'stop'\n ? [...new Set([...stored.stopped, ...languages])]\n : stored.stopped.filter((language) => !languages.includes(language))\n try {\n await context.store.mutate([\n saveStateMutation(\n baseId,\n {...stored, stopped},\n hasPendingTranslations(stored.state, activeProjects(stored.projects, stopped), isFinalStatus),\n ),\n ])\n return {tasksSent: [], unitsSelected: 0, textsSent: 0, outcomes: {}, projectCreated: false, action, languages}\n } catch (error) {\n if (!(error instanceof SanityConflictError) || attempt >= 3) throw error\n }\n }\n}\n\nfunction appendTaskId(date: Date, newId: () => string): string {\n const stamp = date.toISOString().replace(/[-:]/g, '').replace('T', '-').slice(0, 15)\n const suffix = newId().replace(/[^a-z0-9]/gi, '').slice(0, 6).toLowerCase()\n return `update-${stamp}-${suffix}`\n}\n\n/**\n * Refuses a request whose configured TextUnited codes TextUnited does not know, before anything\n * is sent. Skipped when the language list cannot be loaded.\n */\nasync function assertKnownLanguageCodes(context: JobContext, languages: string[]): Promise<void> {\n const known = await context.knownLanguages?.()\n if (!known?.length) return\n const {config} = context\n const codes = [\n {label: config.sourceLanguage.title, code: config.sourceLanguage.textUnitedCode},\n ...config.targetLanguages\n .filter((language) => languages.includes(language.id))\n .map((language) => ({label: language.title, code: language.textUnitedCode})),\n ]\n const unknown = findUnknownLanguageCodes(codes, known)\n if (unknown.length === 0) return\n const details = unknown\n .map(({label, code, suggestions}) =>\n `\"${code}\" (${label})` + (suggestions.length ? ` – known codes: ${suggestions.join(', ')}` : ''),\n )\n .join('; ')\n throw new Error(\n `TextUnited does not know these language codes: ${details}. ` +\n 'Fix textUnitedCode in the translation configuration.',\n )\n}\n\nfunction assertProjectLanguages(\n existing: ProjectResponse,\n languages: string[],\n codeOf: Map<string, string>,\n): void {\n const inProject = new Set(\n (existing.targetLanguages ?? []).map((target) => canonicalLanguageCode(target.targetLanguageCode)),\n )\n const missing = languages.filter((language) => !inProject.has(canonicalLanguageCode(codeOf.get(language))))\n if (missing.length > 0) {\n throw new Error(\n `The TextUnited project for this document has no ${missing.join(', ')} translation. ` +\n 'Adding a language to an existing project is not supported by the TextUnited API yet.',\n )\n }\n}\n\n/** Writes the instant translations to the drafts and saves the plugin's state. */\nasync function finishRequest(args: {\n context: JobContext\n source: PlainObject\n typeConfig: DocumentTypeConfig\n loaded: Awaited<ReturnType<typeof loadTargets>>\n languages: string[]\n units: TranslationUnit[]\n stored: StoredState\n baseId: string\n newId: () => string\n summary: JobSummary\n selectedUnits: TranslationUnit[]\n overwrite: ReadonlySet<string>\n responses: ProjectResponse[]\n sentState: TranslationState\n projects: ProjectRecord[]\n archived: ProjectRecord[]\n}): Promise<JobSummary> {\n const {context, source, typeConfig, loaded, languages, units, stored, baseId, newId, summary} = args\n const {config} = context\n const createdLanguages = createMissingTranslationDocuments({\n targets: loaded.targets,\n source,\n typeConfig,\n languages,\n newId,\n })\n const applied = applyTranslations({\n units: args.selectedUnits,\n languages,\n sourceLanguage: config.sourceLanguage.id,\n sourceDocument: source,\n targets: loaded.targets,\n translations: collectInstantTranslations(args.responses, config),\n state: args.sentState,\n overwrite: args.overwrite,\n })\n summary.outcomes = countOutcomes(applied.outcomes)\n\n const targetMutations = writeTargetsMutations({\n loaded,\n targets: applied.targets,\n source,\n typeConfig,\n sourceLanguage: config.sourceLanguage.id,\n changedFields: applied.changedFields,\n createdLanguages,\n newId,\n })\n const touchedUnits = units.map((unit) => unit.id)\n let current = stored\n for (let attempt = 1; ; attempt += 1) {\n const state = mergeState(current.state, applied.state, touchedUnits)\n try {\n await context.store.mutate([\n ...targetMutations,\n saveStateMutation(\n baseId,\n {state, projects: args.projects, archived: args.archived, stopped: current.stopped, revision: current.revision},\n hasPendingTranslations(state, activeProjects(args.projects, current.stopped), isFinalStatus),\n ),\n ])\n return summary\n } catch (error) {\n // A notification saved the state meanwhile: re-read it and keep this request's units.\n if (!(error instanceof SanityConflictError) || attempt >= 3) throw error\n current = await loadState(context.store, baseId)\n }\n }\n}\n","// HMAC helpers on Web Crypto, available in Node 20+, edge runtimes, Bun and Deno.\n\nconst encoder = new TextEncoder()\n\nasync function hmac(secret: string, data: string): Promise<Uint8Array> {\n const key = await crypto.subtle.importKey(\n 'raw',\n encoder.encode(secret),\n {name: 'HMAC', hash: 'SHA-256'},\n false,\n ['sign'],\n )\n return new Uint8Array(await crypto.subtle.sign('HMAC', key, encoder.encode(data)))\n}\n\nfunction toHex(bytes: Uint8Array): string {\n return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('')\n}\n\nfunction toBase64Url(bytes: Uint8Array): string {\n let binary = ''\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '')\n}\n\n/** Compares two strings in time that does not depend on where they differ. */\nfunction safeEqual(a: string, b: string): boolean {\n if (a.length !== b.length) return false\n let difference = 0\n for (let i = 0; i < a.length; i += 1) difference |= a.charCodeAt(i) ^ b.charCodeAt(i)\n return difference === 0\n}\n\n/** Signature for a TextUnited notification URL of one document. */\nexport async function signDocumentId(secret: string, baseDocumentId: string): Promise<string> {\n return toHex(await hmac(secret, `textunited-events:${baseDocumentId}`))\n}\n\nexport async function verifyDocumentSignature(\n secret: string,\n baseDocumentId: string,\n signature: string,\n): Promise<boolean> {\n return safeEqual(await signDocumentId(secret, baseDocumentId), signature)\n}\n\n/**\n * Verifies the `sanity-webhook-signature` header of a Sanity GROQ webhook:\n * `t=<timestamp>,v1=<base64url HMAC-SHA256 of \"<timestamp>.<body>\">`.\n */\nexport async function verifySanityWebhookSignature(\n secret: string,\n header: string | null,\n body: string,\n maxAgeMs = 5 * 60 * 1000,\n): Promise<boolean> {\n if (!header) return false\n const parts = Object.fromEntries(\n header.split(',').map((part) => {\n const index = part.indexOf('=')\n return [part.slice(0, index).trim(), part.slice(index + 1).trim()]\n }),\n )\n const timestamp = Number(parts.t)\n if (!parts.v1 || !Number.isFinite(timestamp)) return false\n if (Math.abs(Date.now() - timestamp) > maxAgeMs) return false\n const expected = toBase64Url(await hmac(secret, `${timestamp}.${body}`))\n return safeEqual(expected, parts.v1)\n}\n\n/** Builds a header the way Sanity does; used in tests and local tools. */\nexport async function createSanityWebhookSignature(\n secret: string,\n body: string,\n timestamp = Date.now(),\n): Promise<string> {\n return `t=${timestamp},v1=${toBase64Url(await hmac(secret, `${timestamp}.${body}`))}`\n}\n","import {getDocumentTypeConfig} from '../core/config'\nimport {applyTranslations, type ApplyOutcome} from '../core/document/apply'\nimport {extractTranslationUnits, type TranslationUnit} from '../core/document/extract'\nimport {hasPendingTranslations, sentRecord} from '../core/plan'\nimport {activeProjects, projectLanguages} from '../core/projects'\nimport {\n createMissingTranslationDocuments,\n loadState,\n loadTargets,\n saveStateMutation,\n writeTargetsMutations,\n} from './documents'\nimport {countOutcomes, type JobContext, type JobSummary} from './jobs'\nimport {getPreferredDocument, SanityConflictError} from './sanityStore'\nimport {isFinalStatus, toTranslationsBySegment} from './translations'\n\nexport type SyncResult =\n | {status: 'ignored'; reason: string}\n | {\n status: 'synced'\n outcomes: JobSummary['outcomes']\n /** Units whose source was edited after it was sent; they wait for a new request */\n sourceChanged: number\n pending: boolean\n }\n\nconst MAX_ATTEMPTS = 3\n\n/**\n * Fetches the current translations of one document from TextUnited and writes them to Sanity.\n * Called for every TextUnited notification and by the periodic check, so it must be idempotent:\n * it always starts from what TextUnited and Sanity hold now.\n */\nexport async function syncDocument(baseId: string, context: JobContext): Promise<SyncResult> {\n const newId = context.newId ?? (() => crypto.randomUUID())\n\n for (let attempt = 1; ; attempt += 1) {\n const stored = await loadState(context.store, baseId)\n if (stored.projects.length === 0) return {status: 'ignored', reason: 'No TextUnited project for this document'}\n // Stopped languages are left alone: nothing is written or restored for them.\n const projects = activeProjects(stored.projects, stored.stopped)\n const languages = projectLanguages(projects)\n\n const source = await getPreferredDocument(context.store, baseId)\n if (!source) return {status: 'ignored', reason: 'Document not found'}\n const typeConfig = getDocumentTypeConfig(context.config, String(source._type))\n if (!typeConfig) return {status: 'ignored', reason: 'Document type is not configured'}\n\n const units = extractTranslationUnits(source, typeConfig, context.config)\n const loaded = await loadTargets({store: context.store, source, typeConfig, languages})\n const createdLanguages = createMissingTranslationDocuments({\n targets: loaded.targets,\n source,\n typeConfig,\n languages,\n newId,\n })\n\n // Each project holds its own languages; read them one project at a time.\n let targets = loaded.targets\n let state = stored.state\n const changedFields = new Map<string, Set<string>>()\n const outcomes: Array<{outcome: ApplyOutcome}> = []\n const changedUnits = new Set<string>()\n for (const project of projects) {\n const sentOf = (unit: TranslationUnit) => sentRecord(state.units[unit.id], project.customId)\n // In append mode a segment may be in several tasks; read it from the task it was last sent in.\n const taskOf = new Map<string, string>()\n for (const unit of units) {\n const taskId = sentOf(unit)?.taskId\n if (taskId) for (const segment of unit.segments) taskOf.set(segment.customId, taskId)\n }\n const translations = toTranslationsBySegment(\n await context.textUnited.getSegments(project.customId),\n context.config,\n taskOf,\n )\n\n // A translation in TextUnited belongs to the source that was sent. If the source was edited\n // since, the translation no longer fits; it waits for the next translation request.\n const eligible = units.filter((unit) => {\n const sent = sentOf(unit)\n if (!sent) return false\n if (sent.sourceHash !== unit.sourceHash) {\n changedUnits.add(unit.id)\n return false\n }\n return unit.segments.every((segment) => translations.has(segment.customId))\n })\n\n const applied = applyTranslations({\n units: eligible,\n languages: project.languages,\n sourceLanguage: context.config.sourceLanguage.id,\n sourceDocument: source,\n targets,\n translations,\n state,\n })\n targets = applied.targets\n state = applied.state\n outcomes.push(...applied.outcomes)\n for (const [key, fields] of applied.changedFields) {\n const all = changedFields.get(key) ?? new Set<string>()\n for (const field of fields) all.add(field)\n changedFields.set(key, all)\n }\n }\n const pending = hasPendingTranslations(state, projects, isFinalStatus)\n\n try {\n await context.store.mutate([\n ...writeTargetsMutations({\n loaded,\n targets,\n source,\n typeConfig,\n sourceLanguage: context.config.sourceLanguage.id,\n changedFields,\n createdLanguages,\n newId,\n }),\n saveStateMutation(baseId, {...stored, state}, pending),\n ])\n return {status: 'synced', outcomes: countOutcomes(outcomes), sourceChanged: changedUnits.size, pending}\n } catch (error) {\n // Another notification for the same document was saved first: start again from it.\n if (!(error instanceof SanityConflictError) || attempt >= MAX_ATTEMPTS) throw error\n }\n }\n}\n\n/** Periodic check: syncs documents that may still receive translations, oldest first. */\nexport async function syncPendingDocuments(\n context: JobContext,\n limit = 20,\n): Promise<Array<{documentId: string; result: SyncResult | {status: 'failed'; error: string}}>> {\n const results = []\n for (const documentId of await context.store.listPendingDocuments(limit)) {\n try {\n results.push({documentId, result: await syncDocument(documentId, context)})\n } catch (error) {\n results.push({\n documentId,\n result: {status: 'failed' as const, error: error instanceof Error ? error.message : 'Sync failed'},\n })\n }\n }\n return results\n}\n","import type {TranslationConfig} from '../core/config'\nimport type {TextUnitedLanguage} from '../core/languages'\nimport {\n DEFAULT_CAPABILITIES,\n TextUnitedClient,\n type TextUnitedAuth,\n type TextUnitedCapabilities,\n} from '../core/textunited/client'\nimport {\n DEFAULT_IN_HOUSE_SETTINGS,\n DEFAULT_PROJECT_SETTINGS,\n processTranslationRequest,\n type ProjectSettings,\n} from './jobs'\nimport {HttpSanityStore, type SanityStore} from './sanityStore'\nimport {signDocumentId, verifyDocumentSignature, verifySanityWebhookSignature} from './signing'\nimport {syncDocument, syncPendingDocuments} from './sync'\n\nexport type {TranslationConfig, DocumentTypeConfig, TranslationLanguage} from '../core/config'\nexport type {TextUnitedAuth, TextUnitedCapabilities} from '../core/textunited/client'\nexport {TextUnitedClient, TextUnitedApiError, TextUnitedTimeoutError} from '../core/textunited/client'\nexport type {JobResult, JobSummary, ProjectSettings} from './jobs'\nexport type {SyncResult} from './sync'\nexport type {SanityStore, Mutation} from './sanityStore'\n\nexport const REQUEST_ID_PREFIX = 'textunited.request.'\nexport const TEAM_QUERY_ID_PREFIX = 'textunited.teamQuery.'\nconst TEAM_QUERY_MAX_AGE_MS = 10 * 60 * 1000\n\nexport type TextUnitedHandlerOptions = {\n translation: TranslationConfig\n textUnited: {\n auth: TextUnitedAuth\n baseUrl?: string\n capabilities?: TextUnitedCapabilities\n /** Services ordered for each language of a new outsourced project */\n project?: Partial<ProjectSettings>\n /** Services of a new in-house project; the team comes from the Studio request */\n inHouse?: Partial<ProjectSettings>\n /** Longest wait for one TextUnited response; defaults to 90 seconds */\n timeoutMs?: number\n }\n sanity: {\n projectId: string\n dataset: string\n /** Token with write access, used to save translations. Server side only. */\n token: string\n apiVersion?: string\n }\n /**\n * Public HTTPS origin of the site that hosts this handler, e.g. https://www.example.com.\n * TextUnited sends its notifications here, so it must be reachable from the internet and\n * should not change: TextUnited caches the address for up to 24 hours.\n */\n publicBaseUrl: string\n /** Path the handler is mounted at, e.g. /api/textunited */\n basePath: string\n /** Random secret used to sign notification URLs */\n secret: string\n /**\n * Origins of the Studios allowed to trigger requests directly, e.g.\n * ['https://example.sanity.studio', 'http://localhost:3333']\n */\n studioOrigins?: string[]\n /** Secret of an optional Sanity GROQ webhook on `textunited.translationRequest` documents */\n webhookSecret?: string\n /**\n * Bearer token for the periodic check (`{basePath}/sync`), e.g. Vercel's CRON_SECRET.\n * Defaults to `secret`.\n */\n cronSecret?: string\n /** Replaces the Sanity HTTP client, e.g. in tests */\n store?: SanityStore\n /** Replaces fetch for TextUnited calls, e.g. in tests */\n fetch?: typeof fetch\n}\n\nfunction json(body: unknown, status = 200, headers: Record<string, string> = {}): Response {\n return new Response(JSON.stringify(body), {\n status,\n headers: {'Content-Type': 'application/json', ...headers},\n })\n}\n\n/**\n * Framework-independent request handler built on the web-standard Request and Response, so it\n * runs in Next.js route handlers, Remix, Hono, Bun, Deno and Node 20+.\n *\n * Routes, relative to `basePath`:\n * - `POST /jobs` process a translation request: `{requestId}` from the Studio, or the body of a\n * signed Sanity webhook\n * - `GET|POST /events` a notification from TextUnited\n * - `GET|POST /sync` periodic check of documents still being translated (Bearer token)\n */\nexport function createTextUnitedRequestHandler(options: TextUnitedHandlerOptions) {\n const basePath = options.basePath.replace(/\\/+$/, '')\n const publicBaseUrl = options.publicBaseUrl.replace(/\\/+$/, '')\n // Local development may use http://localhost: translation requests work, but TextUnited\n // cannot reach the notification URL, so translations arrive only through `/sync`.\n const isLocal = /^http:\\/\\/(localhost|127\\.0\\.0\\.1)(:\\d+)?$/.test(publicBaseUrl)\n if (!publicBaseUrl.startsWith('https://') && !isLocal) {\n throw new Error('publicBaseUrl must start with https:// (TextUnited only calls HTTPS addresses)')\n }\n\n const textUnited = new TextUnitedClient({\n auth: options.textUnited.auth,\n baseUrl: options.textUnited.baseUrl,\n fetch: options.fetch,\n timeoutMs: options.textUnited.timeoutMs,\n })\n const capabilities = options.textUnited.capabilities ?? DEFAULT_CAPABILITIES\n // The language list changes rarely: load it once, and try again later if it failed.\n let languagesPromise: Promise<TextUnitedLanguage[] | null> | null = null\n const knownLanguages = () => {\n languagesPromise ??= textUnited.listLanguages().catch(() => {\n languagesPromise = null\n return null\n })\n return languagesPromise\n }\n const store =\n options.store ??\n new HttpSanityStore({\n projectId: options.sanity.projectId,\n dataset: options.sanity.dataset,\n token: options.sanity.token,\n apiVersion: options.sanity.apiVersion,\n })\n const studioOrigins = new Set(options.studioOrigins ?? [])\n\n const jobContext = {\n config: options.translation,\n store,\n textUnited,\n sanityProjectId: options.sanity.projectId,\n dataset: options.sanity.dataset,\n projectSettings: {...DEFAULT_PROJECT_SETTINGS, ...options.textUnited.project},\n inHouseSettings: {\n ...DEFAULT_IN_HOUSE_SETTINGS,\n // The style guide is a property of the content, whoever translates it.\n ...(options.textUnited.project?.styleGuideId ? {styleGuideId: options.textUnited.project.styleGuideId} : {}),\n ...options.textUnited.inHouse,\n },\n capabilities,\n knownLanguages,\n eventUrl: async (baseDocumentId: string): Promise<string | undefined> => {\n // TextUnited rejects a non-HTTPS event URL, so none is sent in local development.\n if (isLocal) return undefined\n const url = new URL(`${publicBaseUrl}${basePath}/events`)\n url.searchParams.set('doc', baseDocumentId)\n url.searchParams.set('sig', await signDocumentId(options.secret, baseDocumentId))\n return url.toString()\n },\n }\n\n function corsHeaders(request: Request): Record<string, string> {\n const origin = request.headers.get('origin')\n if (!origin || !studioOrigins.has(origin)) return {}\n return {\n 'Access-Control-Allow-Origin': origin,\n 'Access-Control-Allow-Methods': 'POST, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type',\n Vary: 'Origin',\n }\n }\n\n async function handleJobs(request: Request): Promise<Response> {\n const cors = corsHeaders(request)\n const body = await request.text()\n const signature = request.headers.get('sanity-webhook-signature')\n\n let requestId: unknown\n if (signature) {\n if (!options.webhookSecret || !(await verifySanityWebhookSignature(options.webhookSecret, signature, body))) {\n return json({message: 'Invalid webhook signature'}, 401)\n }\n requestId = safeParse(body)?._id\n } else {\n if (request.headers.get('origin') && Object.keys(cors).length === 0) {\n return json({message: 'Origin not allowed'}, 403)\n }\n requestId = safeParse(body)?.requestId\n }\n\n // Only request documents created in Sanity are processed: creating one needs write access\n // to the dataset, which is what makes this route safe to call without a secret.\n if (typeof requestId !== 'string' || !requestId.startsWith(REQUEST_ID_PREFIX)) {\n return json({message: 'Missing or invalid requestId'}, 400, cors)\n }\n const result = await processTranslationRequest(requestId, jobContext)\n return json(result, result.status === 'failed' ? 500 : 200, cors)\n }\n\n return async function handle(request: Request): Promise<Response> {\n const {pathname} = new URL(request.url)\n const route = pathname.startsWith(basePath) ? pathname.slice(basePath.length) : pathname\n\n if (route === '/jobs') {\n if (request.method === 'OPTIONS') {\n const cors = corsHeaders(request)\n return new Response(null, {status: Object.keys(cors).length ? 204 : 403, headers: cors})\n }\n if (request.method === 'POST') return handleJobs(request)\n }\n if (route === '/team') {\n if (request.method === 'OPTIONS') {\n const cors = corsHeaders(request)\n return new Response(null, {status: Object.keys(cors).length ? 204 : 403, headers: cors})\n }\n if (request.method === 'POST') return handleTeam(request)\n }\n if (route === '/events' && (request.method === 'GET' || request.method === 'POST')) {\n return handleEvent(request)\n }\n if (route === '/sync' && (request.method === 'GET' || request.method === 'POST')) {\n return handleSync(request)\n }\n return json({message: 'Not found'}, 404)\n }\n\n /**\n * A TextUnited notification. TextUnited calls the URL given at project creation, adding\n * `event`, `segment` and `project`; `doc` and `sig` identify and authenticate the document.\n */\n async function handleEvent(request: Request): Promise<Response> {\n const params = new URL(request.url).searchParams\n const documentId = params.get('doc')\n const signature = params.get('sig')\n if (!documentId || !signature) return json({message: 'Missing doc or sig'}, 400)\n if (!(await verifyDocumentSignature(options.secret, documentId, signature))) {\n return json({message: 'Invalid signature'}, 401)\n }\n try {\n return json(await syncDocument(documentId, jobContext))\n } catch (error) {\n return json({message: error instanceof Error ? error.message : 'Sync failed'}, 500)\n }\n }\n\n /**\n * People who can form an in-house team. The list holds names and e-mail addresses, so it is\n * returned only for a fresh `textunited.teamQuery.*` document the Studio created: creating it\n * needs write access to the dataset. The query document is deleted right away.\n */\n async function handleTeam(request: Request): Promise<Response> {\n const cors = corsHeaders(request)\n if (request.headers.get('origin') && Object.keys(cors).length === 0) {\n return json({message: 'Origin not allowed'}, 403)\n }\n const queryId = safeParse(await request.text())?.queryId\n if (typeof queryId !== 'string' || !queryId.startsWith(TEAM_QUERY_ID_PREFIX)) {\n return json({message: 'Missing or invalid queryId'}, 400, cors)\n }\n const query = await store.getDocument(queryId)\n const createdAt = Date.parse(String(query?._createdAt ?? query?.requestedAt ?? ''))\n if (!query || !Number.isFinite(createdAt) || Date.now() - createdAt > TEAM_QUERY_MAX_AGE_MS) {\n return json({message: 'Unknown or expired team query'}, 403, cors)\n }\n await store.mutate([{delete: {id: queryId}}])\n try {\n return json({members: await textUnited.listTeamCandidates()}, 200, cors)\n } catch (error) {\n return json({message: error instanceof Error ? error.message : 'Could not load the team'}, 502, cors)\n }\n }\n\n /** Periodic check for notifications TextUnited did not send (e.g. after \"approve all\"). */\n async function handleSync(request: Request): Promise<Response> {\n const expected = `Bearer ${options.cronSecret ?? options.secret}`\n if (request.headers.get('authorization') !== expected) return json({message: 'Unauthorized'}, 401)\n const limit = Number(new URL(request.url).searchParams.get('limit') ?? 20)\n const results = await syncPendingDocuments(jobContext, Number.isFinite(limit) ? Math.min(limit, 100) : 20)\n return json({checked: results.length, results})\n }\n}\n\nfunction safeParse(body: string): Record<string, unknown> | null {\n try {\n const value = JSON.parse(body) as unknown\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : null\n } catch {\n return null\n }\n}\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/server/sanityStore.ts","../src/core/hash.ts","../src/core/ids.ts","../src/core/projects.ts","../src/core/document/paths.ts","../src/core/document/intl.ts","../src/core/document/portableText.ts","../src/core/document/target.ts","../src/core/plan.ts","../src/core/config.ts","../src/core/document/extract.ts","../src/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AAI,CAAC,GAAA,KAAQ,GAAA,CAAI,IAAI,CAAC,CAAA;AACvD,IAAA,MAAM,IAAA,GAAA,CAAQ,MAAM,OAAA,CAAQ,QAAA,CAAS,YAAY,CAAA,GAAI,QAAA,CAAS,YAAA,GAAe,EAAC,EAAG,MAAA;AAAA,MAC/E,CAAC,KAAA,KAAU,EAAE,aAAA,CAAc,KAAK,CAAA,IAAK,QAAA,CAAS,GAAA,CAAI,MAAA,CAAO,KAAA,CAAM,IAAI,CAAC,CAAA;AAAA,KACtE;AACA,IAAA,MAAM,IAAA,GAAO,IAAI,GAAA,CAAI,IAAA,CAAK,GAAA,CAAI,CAAC,KAAA,KAAW,aAAA,CAAc,KAAK,CAAA,GAAI,KAAA,CAAM,IAAA,GAAO,MAAU,CAAC,CAAA;AACzF,IAAA,MAAM,SAAA,GAAY,CAAC,SAAA,EAAW,GAAG,OAAO,CAAA,CAAE,MAAA,CAAO,CAAC,GAAA,KAAQ,CAAC,IAAA,CAAK,GAAA,CAAI,GAAA,CAAI,IAAI,CAAC,CAAA;AAC7E,IAAA,SAAA,CAAU,IAAA,CAAK,EAAC,KAAA,EAAO,EAAC,IAAI,MAAA,CAAO,QAAA,CAAS,GAAG,CAAA,EAAG,GAAA,EAAK,EAAC,YAAA,EAAc,CAAC,GAAG,IAAA,EAAM,GAAG,SAAS,CAAA,EAAC,IAAG,CAAA;AAAA,EAClG;AACA,EAAA,OAAO,SAAA;AACT","file":"chunk-RIWABEFI.cjs","sourcesContent":["import type {PlainObject} from '../core/document/paths'\n\nexport type Mutation =\n | {create: PlainObject}\n | {createOrReplace: PlainObject}\n | {createIfNotExists: PlainObject}\n | {delete: {id: string}}\n | {\n patch: {\n id: string\n set?: PlainObject\n setIfMissing?: PlainObject\n ifRevisionID?: string\n }\n }\n\n/**\n * The few Sanity operations the server needs. The HTTP implementation below talks to the Sanity\n * API directly; tests use an in-memory implementation.\n */\nexport interface SanityStore {\n /** Exact document by id (`drafts.` ids included), or null */\n getDocument(id: string): Promise<PlainObject | null>\n /** Translation metadata (@sanity/document-internationalization) that references the document */\n findTranslationMetadata(baseDocumentId: string): Promise<PlainObject | null>\n /** Applies mutations in one transaction */\n mutate(mutations: Mutation[]): Promise<void>\n /** Ids of source documents whose translations TextUnited may still change, oldest check first */\n listPendingDocuments(limit: number): Promise<string[]>\n}\n\nexport class SanityConflictError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'SanityConflictError'\n }\n}\n\nexport type HttpSanityStoreOptions = {\n projectId: string\n dataset: string\n token: string\n apiVersion?: string\n fetch?: typeof fetch\n}\n\nexport class HttpSanityStore implements SanityStore {\n private readonly base: string\n private readonly dataset: string\n private readonly token: string\n private readonly fetchImpl: typeof fetch\n\n constructor(options: HttpSanityStoreOptions) {\n const apiVersion = options.apiVersion ?? '2025-02-19'\n this.base = `https://${options.projectId}.api.sanity.io/v${apiVersion}/data`\n this.dataset = options.dataset\n this.token = options.token\n this.fetchImpl = options.fetch ?? fetch\n }\n\n private async query<T>(query: string, params: Record<string, unknown>): Promise<T> {\n const response = await this.fetchImpl(`${this.base}/query/${this.dataset}?perspective=raw`, {\n method: 'POST',\n headers: {Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json'},\n body: JSON.stringify({query, params}),\n })\n if (!response.ok) {\n throw new Error(`Sanity query failed with status ${response.status}: ${await response.text()}`)\n }\n return ((await response.json()) as {result: T}).result\n }\n\n getDocument(id: string): Promise<PlainObject | null> {\n return this.query<PlainObject | null>('*[_id == $id][0]', {id})\n }\n\n findTranslationMetadata(baseDocumentId: string): Promise<PlainObject | null> {\n return this.query<PlainObject | null>(\n '*[_type == \"translation.metadata\" && $id in translations[].value._ref][0]',\n {id: baseDocumentId},\n )\n }\n\n listPendingDocuments(limit: number): Promise<string[]> {\n return this.query<string[]>(\n '*[_type == \"textunited.translationState\" && pending == true] | order(updatedAt asc) [0...$limit].documentId',\n {limit},\n )\n }\n\n async mutate(mutations: Mutation[]): Promise<void> {\n if (mutations.length === 0) return\n const response = await this.fetchImpl(\n `${this.base}/mutate/${this.dataset}?visibility=sync`,\n {\n method: 'POST',\n headers: {Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json'},\n body: JSON.stringify({mutations}),\n },\n )\n if (response.status === 409) {\n throw new SanityConflictError(await response.text())\n }\n if (!response.ok) {\n throw new Error(`Sanity mutation failed with status ${response.status}: ${await response.text()}`)\n }\n }\n}\n\n/** Draft if it exists, otherwise the published document. */\nexport async function getPreferredDocument(\n store: SanityStore,\n baseDocumentId: string,\n): Promise<PlainObject | null> {\n const draft = await store.getDocument(`drafts.${baseDocumentId}`)\n return draft ?? store.getDocument(baseDocumentId)\n}\n","// A small, synchronous, dependency-free hash that gives the same result in the browser\n// (Studio) and on the server. It is used only to derive stable identifiers, never for\n// security: two independent 64-bit FNV-1a passes give a 128-bit value, which keeps the\n// chance of two paths in one document colliding negligible.\n\nconst FNV_PRIME = 0x100000001b3n\nconst MASK_64 = 0xffffffffffffffffn\n\nfunction fnv1a64(input: string, offsetBasis: bigint): bigint {\n let hash = offsetBasis\n // Hash UTF-8 bytes so the result does not depend on the platform's string encoding.\n for (const byte of new TextEncoder().encode(input)) {\n hash ^= BigInt(byte)\n hash = (hash * FNV_PRIME) & MASK_64\n }\n return hash\n}\n\n/** Returns a 32-character lowercase hex digest of the input. */\nexport function stableHash(input: string): string {\n const first = fnv1a64(input, 0xcbf29ce484222325n)\n const second = fnv1a64(input, 0x84222325cbf29ce4n)\n return first.toString(16).padStart(16, '0') + second.toString(16).padStart(16, '0')\n}\n","import {stableHash} from './hash'\n\n/**\n * One step in a path to a value inside a Sanity document.\n *\n * Array items are addressed by their `_key`, which Sanity keeps stable when items are moved,\n * inserted or removed. A numeric index is only a fallback for arrays whose items have no\n * `_key` (rare in Sanity content); identifiers derived from an index change when items move.\n */\nexport type PathSegment = string | number | {_key: string}\n\n/** Serialises a path the way Sanity's GROQ and patch APIs write it, e.g. `sections[_key==\"a1\"].title`. */\nexport function pathToString(path: readonly PathSegment[]): string {\n let result = ''\n for (const segment of path) {\n if (typeof segment === 'string') {\n result += result ? `.${segment}` : segment\n } else if (typeof segment === 'number') {\n result += `[${segment}]`\n } else {\n result += `[_key==${JSON.stringify(segment._key)}]`\n }\n }\n return result\n}\n\n/** Removes the `drafts.` (or any `versions.<release>.`) prefix from a Sanity document id. */\nexport function getBaseDocumentId(documentId: string): string {\n if (documentId.startsWith('drafts.')) return documentId.slice('drafts.'.length)\n if (documentId.startsWith('versions.')) {\n const rest = documentId.slice('versions.'.length)\n const dot = rest.indexOf('.')\n return dot === -1 ? rest : rest.slice(dot + 1)\n }\n return documentId\n}\n\n/**\n * Custom ID of the TextUnited multilingual project for one Sanity document.\n *\n * It is derived from the document alone, so every translation request for the same document\n * targets the same project instead of creating a new one. The Sanity project and dataset are\n * part of the id because one TextUnited company may connect several Sanity projects.\n */\nexport function createProjectCustomId(args: {\n sanityProjectId: string\n dataset: string\n documentId: string\n}): string {\n return `sanity-${args.sanityProjectId}-${args.dataset}-${getBaseDocumentId(args.documentId)}`\n}\n\n/** Task that groups all short top-level fields (title, excerpt, SEO, …) of a document. */\nexport const FIELDS_TASK_ID = 'fields'\n\n/**\n * Task ID (a virtual file inside the TextUnited project) for one part of a document.\n *\n * While the TextUnited `PUT` endpoint replaces a whole task on every update, splitting a\n * document into parts limits each update to the part that changed: one task per item of a\n * page-builder array (`sections.a1`), one per rich-text field (`body`), and one for all short\n * fields together. The id is readable on purpose: translators see it as a file name.\n */\nexport function createTaskId(field: string, item?: PathSegment): string {\n if (item === undefined) return field\n if (typeof item === 'object') return `${field}.${item._key}`\n return `${field}.${item}`\n}\n\n/**\n * Custom ID of one segment. It depends only on where the text lives in the document, never on\n * the text itself or on the translation request, so an edited text keeps its id and the\n * TextUnited segment can be updated in place once the API supports it.\n */\nexport function createSegmentCustomId(path: readonly PathSegment[], chunk = 0): string {\n // Chunk 0 has no suffix, so a text that later grows past the length limit keeps the id of\n // its first part.\n const suffix = chunk > 0 ? `#${chunk}` : ''\n return `seg-${stableHash(pathToString(path) + suffix)}`\n}\n","/**\n * The TextUnited projects of one Sanity document.\n *\n * A document starts with one project. TextUnited cannot add a language to an existing project, so\n * languages added later get a project of their own; each language belongs to exactly one project.\n * A reset moves the current projects to `archived` and starts again with a new one.\n */\nexport type ProjectType = 'outsourced' | 'inHouse'\n\nexport type ProjectRecord = {\n /** Custom id of the TextUnited multilingual project */\n customId: string\n /** Sanity language ids of the project */\n languages: string[]\n projectType?: ProjectType\n /** Numeric id of the TextUnited project, for links to the portal */\n projectId?: number\n createdAt?: string\n}\n\nexport type DocumentProjects = {\n projects: ProjectRecord[]\n archived: ProjectRecord[]\n /**\n * Languages an editor stopped for this document: nothing is sent, written or restored for them\n * any more. They stay in their TextUnited project.\n */\n stopped: string[]\n}\n\nfunction isProjectType(value: unknown): value is ProjectType {\n return value === 'outsourced' || value === 'inHouse'\n}\n\nfunction toRecord(value: unknown): ProjectRecord | null {\n const record = value as Record<string, unknown> | null\n if (!record || typeof record.customId !== 'string') return null\n return {\n customId: record.customId,\n languages: Array.isArray(record.languages) ? record.languages.map(String) : [],\n ...(isProjectType(record.projectType) ? {projectType: record.projectType} : {}),\n ...(typeof record.projectId === 'number' ? {projectId: record.projectId} : {}),\n ...(typeof record.createdAt === 'string' ? {createdAt: record.createdAt} : {}),\n }\n}\n\n/**\n * Projects stored in the plugin's state document: `projectsJson`, or the single-project fields of\n * states written before documents could have several projects.\n */\nexport function readProjects(document: Record<string, unknown> | null | undefined): DocumentProjects {\n if (!document) return {projects: [], archived: [], stopped: []}\n if (typeof document.projectsJson === 'string') {\n try {\n const parsed = JSON.parse(document.projectsJson) as {projects?: unknown[]; archived?: unknown[]; stopped?: unknown[]}\n return {\n projects: (parsed.projects ?? []).map(toRecord).filter((p): p is ProjectRecord => p !== null),\n archived: (parsed.archived ?? []).map(toRecord).filter((p): p is ProjectRecord => p !== null),\n stopped: Array.isArray(parsed.stopped) ? parsed.stopped.map(String) : [],\n }\n } catch {\n // fall back to the single-project fields\n }\n }\n if (typeof document.projectCustomId !== 'string') return {projects: [], archived: [], stopped: []}\n const legacy = toRecord({\n customId: document.projectCustomId,\n languages: document.projectLanguages,\n projectType: document.projectType,\n projectId: document.projectId,\n })\n return {projects: legacy ? [legacy] : [], archived: [], stopped: []}\n}\n\n/** The projects with only the languages that are not stopped; projects left with none are dropped. */\nexport function activeProjects(projects: ProjectRecord[], stopped: string[]): ProjectRecord[] {\n if (stopped.length === 0) return projects\n return projects\n .map((project) => ({...project, languages: project.languages.filter((language) => !stopped.includes(language))}))\n .filter((project) => project.languages.length > 0)\n}\n\n/** The project a language belongs to, if any. */\nexport function projectForLanguage(projects: ProjectRecord[], language: string): ProjectRecord | undefined {\n return projects.find((project) => project.languages.includes(language))\n}\n\n/** All languages of the document's projects. */\nexport function projectLanguages(projects: ProjectRecord[]): string[] {\n return [...new Set(projects.flatMap((project) => project.languages))]\n}\n","import type {PathSegment} from '../ids'\n\nexport type PlainObject = Record<string, unknown>\n\nexport function isPlainObject(value: unknown): value is PlainObject {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n\nexport function cloneValue<T>(value: T): T {\n return structuredClone(value)\n}\n\n/** Builds the path step for one array item: its `_key` when present, else its index. */\nexport function arrayItemSegment(item: unknown, index: number): PathSegment {\n return isPlainObject(item) && typeof item._key === 'string' ? {_key: item._key} : index\n}\n\nfunction findArrayIndex(array: unknown[], segment: PathSegment): number {\n if (typeof segment === 'number') return segment < array.length ? segment : -1\n if (typeof segment === 'object') {\n return array.findIndex((item) => isPlainObject(item) && item._key === segment._key)\n }\n return -1\n}\n\n/** Reads the value at a path, or undefined when any step is missing. */\nexport function getAtPath(root: unknown, path: readonly PathSegment[]): unknown {\n let current: unknown = root\n for (const segment of path) {\n if (Array.isArray(current)) {\n const index = findArrayIndex(current, segment)\n if (index === -1) return undefined\n current = current[index]\n } else if (isPlainObject(current) && typeof segment === 'string') {\n current = current[segment]\n } else {\n return undefined\n }\n }\n return current\n}\n\n/**\n * Writes a value at a path inside `target`, creating missing parents by copying them from\n * `source` at the same path. Missing array items are inserted at the position they have in\n * `source`, so a translated document keeps the structure of the original.\n */\nexport function setAtPath(\n target: PlainObject,\n source: unknown,\n path: readonly PathSegment[],\n value: unknown,\n): void {\n if (path.length === 0) throw new Error('Cannot set a value at an empty path')\n\n let current: unknown = target\n let currentSource: unknown = source\n\n for (let depth = 0; depth < path.length; depth += 1) {\n const segment = path[depth] as PathSegment\n const isLast = depth === path.length - 1\n const nextSource = getAtPath(currentSource, [segment])\n\n if (Array.isArray(current)) {\n let index = findArrayIndex(current, segment)\n if (index === -1) {\n if (isLast) {\n current.push(value)\n return\n }\n const sourceArray = Array.isArray(currentSource) ? currentSource : []\n const sourceIndex = findArrayIndex(sourceArray, segment)\n const placeholder = cloneValue(nextSource ?? (typeof segment === 'object' ? {_key: segment._key} : {}))\n index = insertionIndex(current, sourceArray, sourceIndex)\n current.splice(index, 0, placeholder)\n }\n if (isLast) {\n current[index] = value\n return\n }\n current = current[index]\n } else if (isPlainObject(current) && typeof segment === 'string') {\n if (isLast) {\n current[segment] = value\n return\n }\n if (current[segment] === undefined || current[segment] === null) {\n // Start missing fields empty: copying them from the source would bring along sibling\n // values in the source language, which would then look like existing translations.\n current[segment] = emptyContainer(nextSource, path[depth + 1])\n }\n current = current[segment]\n } else {\n throw new Error('Path does not match the document structure')\n }\n currentSource = nextSource\n }\n}\n\n/** An empty object (keeping only `_type`) or array, shaped like the source at that place. */\nfunction emptyContainer(source: unknown, next: PathSegment | undefined): unknown {\n if (Array.isArray(source) || typeof next !== 'string') return []\n return isPlainObject(source) && typeof source._type === 'string' ? {_type: source._type} : {}\n}\n\n/** Index in `target` right after the nearest preceding item that `source` also has. */\nfunction insertionIndex(target: unknown[], source: unknown[], sourceIndex: number): number {\n for (let i = sourceIndex - 1; i >= 0; i -= 1) {\n const previous = source[i]\n if (isPlainObject(previous) && typeof previous._key === 'string') {\n const found = findArrayIndex(target, {_key: previous._key})\n if (found !== -1) return found + 1\n }\n }\n return sourceIndex >= 0 ? 0 : target.length\n}\n","import {isPlainObject, type PlainObject} from './paths'\n\n/**\n * Helpers for sanity-plugin-internationalized-array fields: an array of\n * `{_key: '<language>', _type: 'internationalizedArray…Value', value}` items.\n */\nexport type IntlArrayItem = PlainObject & {_key: string; value?: unknown}\n\n/**\n * A language added in the Studio and not filled in yet has no `value` at all, only its key and\n * type; it still belongs to the field, so the type is enough to recognise an item.\n */\nexport function isIntlArray(value: unknown): value is IntlArrayItem[] {\n return (\n Array.isArray(value) &&\n value.length > 0 &&\n value.every(\n (item) =>\n isPlainObject(item) &&\n typeof item._key === 'string' &&\n (typeof item._type === 'string' ? item._type.startsWith('internationalizedArray') : 'value' in item),\n )\n )\n}\n\nexport function getIntlItem(array: unknown, language: string): IntlArrayItem | undefined {\n if (!Array.isArray(array)) return undefined\n return array.find(\n (item): item is IntlArrayItem => isPlainObject(item) && item._key === language,\n )\n}\n","import {cloneValue, isPlainObject, type PlainObject} from './paths'\n\n/**\n * Converts Portable Text blocks to TextUnited segment content and back.\n *\n * - A block with one unformatted span is sent as plain text.\n * - Otherwise every span is wrapped in `<span data-tu-id=\"KEY\">…</span>` so that its marks\n * (bold, links, …) can be restored on the translated text. TextUnited keeps these tags.\n * - Inline objects are not sent and stay as they are.\n * - Content longer than MAX_SEGMENT_LENGTH is split into several segments (chunks).\n */\n\nexport const MAX_SEGMENT_LENGTH = 2000\n\nexport type PortableTextBlock = PlainObject & {\n _type: 'block'\n children?: unknown[]\n markDefs?: unknown[]\n}\n\ntype Span = PlainObject & {_type: 'span'; text: string; marks?: unknown[]; _key?: string}\n\nconst ENTITIES: Record<string, string> = {amp: '&', apos: \"'\", gt: '>', lt: '<', nbsp: ' ', quot: '\"'}\n\nexport function isPortableTextBlock(value: unknown): value is PortableTextBlock {\n return isPlainObject(value) && value._type === 'block'\n}\n\nexport function isPortableTextArray(value: unknown): value is unknown[] {\n return Array.isArray(value) && value.some(isPortableTextBlock)\n}\n\nfunction isSpan(value: unknown): value is Span {\n return isPlainObject(value) && value._type === 'span' && typeof value.text === 'string'\n}\n\nfunction escapeHtml(value: string): string {\n return value\n .replace(/&/g, '&amp;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\"/g, '&quot;')\n}\n\nexport function decodeHtmlEntities(text: string): string {\n return text.replace(/&(#\\d+|#x[0-9a-f]+|[a-z]+);/gi, (entity, token: string) => {\n if (token[0] === '#') {\n const codePoint =\n token[1] === 'x' || token[1] === 'X'\n ? Number.parseInt(token.slice(2), 16)\n : Number.parseInt(token.slice(1), 10)\n return Number.isFinite(codePoint) ? String.fromCodePoint(codePoint) : entity\n }\n return ENTITIES[token.toLowerCase()] ?? entity\n })\n}\n\nfunction spanId(span: Span, index: number): string {\n return typeof span._key === 'string' ? span._key : `child-${index}`\n}\n\nfunction isPlainBlock(block: PortableTextBlock, spans: Span[]): boolean {\n return (\n spans.length === 1 &&\n (!Array.isArray(block.markDefs) || block.markDefs.length === 0) &&\n (!Array.isArray(spans[0]?.marks) || spans[0].marks.length === 0) &&\n (block.children?.length ?? 0) === 1\n )\n}\n\n/** Splits text into parts no longer than maxLength, preferring sentence and word boundaries. */\nexport function splitText(text: string, maxLength: number): string[] {\n const parts: string[] = []\n let remaining = text\n while (remaining.length > maxLength) {\n const slice = remaining.slice(0, maxLength)\n const boundary = Math.max(\n slice.lastIndexOf('. '),\n slice.lastIndexOf('! '),\n slice.lastIndexOf('? '),\n slice.lastIndexOf('; '),\n slice.lastIndexOf(', '),\n slice.lastIndexOf(' '),\n )\n const splitAt = boundary > maxLength * 0.5 ? boundary + 1 : maxLength\n parts.push(remaining.slice(0, splitAt))\n remaining = remaining.slice(splitAt)\n }\n if (remaining) parts.push(remaining)\n return parts\n}\n\n/** Joins translated plain-text chunks, restoring a space TextUnited may have trimmed. */\nexport function joinTextChunks(chunks: string[]): string {\n return chunks.reduce((joined, chunk) => {\n if (!joined) return chunk\n return /\\s$/.test(joined) || /^\\s/.test(chunk) ? joined + chunk : `${joined} ${chunk}`\n }, '')\n}\n\n/**\n * Returns the segment contents for one block, or an empty array when the block has no text.\n */\nexport function blockToSegmentContents(block: PortableTextBlock): string[] {\n const spans = (block.children ?? []).filter(isSpan)\n if (!spans.some((span) => span.text.trim() !== '')) return []\n\n if (isPlainBlock(block, spans)) {\n return splitText((spans[0] as Span).text, MAX_SEGMENT_LENGTH)\n }\n\n const chunks: string[] = []\n let current = ''\n spans.forEach((span, index) => {\n if (span.text === '') return\n const id = escapeHtml(spanId(span, index))\n const wrapperLength = `<span data-tu-id=\"${id}\"></span>`.length\n for (const part of splitText(span.text, Math.max(100, MAX_SEGMENT_LENGTH - wrapperLength))) {\n const wrapped = `<span data-tu-id=\"${id}\">${escapeHtml(part)}</span>`\n if (current && current.length + wrapped.length > MAX_SEGMENT_LENGTH) {\n chunks.push(current)\n current = ''\n }\n current += wrapped\n }\n })\n if (current) chunks.push(current)\n return chunks\n}\n\n/** Plain text of a block, used to tell whether a translated block is empty. */\nexport function blockText(block: unknown): string {\n if (!isPortableTextBlock(block)) return ''\n return (block.children ?? [])\n .filter(isSpan)\n .map((span) => span.text)\n .join('')\n}\n\n/**\n * Builds the translated block from the source block and the translated chunk contents.\n * Keys, styles, marks and inline objects come from the source block. A span missing from the\n * translation keeps its source text, so no content is ever dropped.\n */\nexport function applyBlockTranslation(\n sourceBlock: PortableTextBlock,\n translatedChunks: string[],\n): PortableTextBlock {\n const block = cloneValue(sourceBlock)\n const children = (block.children ?? []) as unknown[]\n const spans = children.filter(isSpan)\n\n if (isPlainBlock(sourceBlock, (sourceBlock.children ?? []).filter(isSpan))) {\n const span = spans[0] as Span\n span.text = decodeHtmlEntities(joinTextChunks(translatedChunks).replace(/<[^>]*>/g, ''))\n return block\n }\n\n const translatedById = new Map<string, string>()\n const pattern = /<span\\b([^>]*)>([\\s\\S]*?)<\\/span>/gi\n const html = translatedChunks.join('')\n let match: RegExpExecArray | null\n while ((match = pattern.exec(html))) {\n const idMatch = (match[1] ?? '').match(/\\bdata-tu-id\\s*=\\s*[\"']([^\"']+)[\"']/i)\n if (!idMatch?.[1]) continue\n const id = decodeHtmlEntities(idMatch[1])\n const text = decodeHtmlEntities((match[2] ?? '').replace(/<[^>]*>/g, ''))\n translatedById.set(id, (translatedById.get(id) ?? '') + text)\n }\n\n spans.forEach((span, index) => {\n const translated = translatedById.get(spanId(span, index))\n if (translated !== undefined) span.text = translated\n })\n return block\n}\n","import {stableHash} from '../hash'\nimport type {TranslationUnit} from './extract'\nimport {getIntlItem} from './intl'\nimport {getAtPath, type PlainObject} from './paths'\nimport {blockText} from './portableText'\n\n/**\n * Where the translations of one source document live.\n * - `fieldLevel`: in the source document itself (internationalized arrays).\n * - `documentLevel`: one document per target language; undefined when it does not exist yet.\n */\nexport type TranslationTargets =\n | {model: 'fieldLevel'; document: PlainObject}\n | {model: 'documentLevel'; documents: Record<string, PlainObject | undefined>}\n\n/** Current translated value of a unit in one language, or undefined. */\nexport function readTargetValue(\n unit: TranslationUnit,\n language: string,\n targets: TranslationTargets,\n): unknown {\n if (targets.model === 'fieldLevel') {\n const item = getIntlItem(getAtPath(targets.document, unit.fieldPath), language)\n return getAtPath(item?.value, unit.innerPath)\n }\n return getAtPath(targets.documents[language], [...unit.fieldPath, ...unit.innerPath])\n}\n\n/**\n * True when a unit has no usable translation: absent, empty, or still identical to the source\n * (a copy of the original, e.g. from duplicating the document, is not a translation).\n */\nexport function isMissingValue(unit: TranslationUnit, value: unknown): boolean {\n if (unit.kind === 'text') {\n return typeof value !== 'string' || value.trim() === '' || value.trim() === String(unit.source).trim()\n }\n return blockText(value).trim() === '' || blockText(value) === blockText(unit.source)\n}\n\n/**\n * True when a value still needs a translation. Like `isMissingValue`, except that a value the\n * plugin itself wrote from TextUnited counts as translated even when it equals the source: names,\n * codes and many short texts stay the same in other languages.\n */\nexport function needsTranslation(unit: TranslationUnit, value: unknown, appliedHash: string | undefined): boolean {\n if (!isMissingValue(unit, value)) return false\n const empty = unit.kind === 'text' ? typeof value !== 'string' || value.trim() === '' : blockText(value).trim() === ''\n return empty || appliedHash !== valueHash(value)\n}\n\n/** Hash of a translated value, used to tell whether someone edited it after the plugin wrote it. */\nexport function valueHash(value: unknown): string {\n return stableHash(JSON.stringify(value ?? null))\n}\n","import type {TranslationUnit} from './document/extract'\nimport {needsTranslation, readTargetValue, type TranslationTargets} from './document/target'\nimport type {ProjectSegment} from './textunited/types'\n\n/**\n * What a translation request covers. Replaces the old, misleading modes:\n * - `missing`: values with no translation in at least one selected language (absent or empty).\n * - `changed`: `missing` plus values whose source text changed since it was last sent.\n * - `all`: every value, and existing translations may be replaced.\n */\nexport type TranslationMode = 'missing' | 'changed' | 'all'\n\n/** What the plugin remembers per document, between requests and notifications. */\nexport type TranslationState = {\n units: Record<string, UnitState>\n}\n\nexport type UnitState = {\n /** Source hash at the time the unit was last sent to TextUnited */\n sourceHash: string\n /** When the unit was last sent; absent for a baseline of a value never sent */\n sentAt?: string\n /**\n * Legacy (single project): TextUnited task the unit was last sent in. Moved into `projects` by\n * `migrateLegacyState`.\n */\n taskId?: string\n /**\n * Per TextUnited project (custom id): what was last sent there. A document can have several\n * projects (languages added later get their own), and each holds its own version of the text.\n * `taskId` is the task holding the current copy, when updates add new tasks (append mode).\n */\n projects?: Record<string, SentRecord>\n /** Per Sanity language id: hash of the value the plugin last wrote, and its TextUnited status */\n languages: Record<string, {appliedHash: string; status?: string}>\n}\n\nexport type SentRecord = {sourceHash: string; sentAt: string; taskId?: string}\n\n/** What was last sent of a unit to one TextUnited project, if anything. */\nexport function sentRecord(record: UnitState | undefined, projectCustomId: string): SentRecord | undefined {\n return record?.projects?.[projectCustomId]\n}\n\n/**\n * States written before documents could have several projects keep the sent source and task on\n * the unit itself. They belong to the document's first project; move them there.\n */\nexport function migrateLegacyState(state: TranslationState, legacyProjectCustomId: string | undefined): TranslationState {\n if (!legacyProjectCustomId) return state\n let changed = false\n const units: Record<string, UnitState> = {}\n for (const [id, record] of Object.entries(state.units)) {\n if (record.sentAt && !record.projects) {\n const {taskId, ...rest} = record\n units[id] = {\n ...rest,\n projects: {\n [legacyProjectCustomId]: {sourceHash: record.sourceHash, sentAt: record.sentAt, ...(taskId ? {taskId} : {})},\n },\n }\n changed = true\n } else {\n units[id] = record\n }\n }\n return changed ? {units} : state\n}\n\nexport function emptyState(): TranslationState {\n return {units: {}}\n}\n\nexport type UnitSelectionReason = 'missing' | 'sourceChanged' | 'all'\n\nexport type TranslationPlan = {\n /** Units that need translation, with the reason */\n selected: Array<{unit: TranslationUnit; reason: UnitSelectionReason}>\n /**\n * Tasks to send when the API replaces whole tasks: each part of the document with a selected\n * unit goes out complete. In append mode only `selectedSegments` is sent.\n */\n tasks: Array<{taskId: string; segments: ProjectSegment[]}>\n}\n\n/** Segments of the selected units only, for an update that adds them as a new task. */\nexport function selectedSegments(plan: TranslationPlan): ProjectSegment[] {\n return plan.selected.flatMap(({unit}) => unit.segments.map((segment) => ({...segment})))\n}\n\nfunction selectionReason(\n unit: TranslationUnit,\n languages: string[],\n targets: TranslationTargets,\n state: TranslationState,\n mode: TranslationMode,\n projectCustomId?: string,\n): UnitSelectionReason | null {\n if (mode === 'all') return 'all'\n const record = state.units[unit.id]\n if (\n languages.some((language) =>\n needsTranslation(unit, readTargetValue(unit, language, targets), record?.languages[language]?.appliedHash),\n )\n ) {\n return 'missing'\n }\n // Without a record the unit was never sent by this plugin (e.g. translated by hand or by an\n // older mechanism), so there is nothing to compare: it is not treated as changed.\n // With a project, the text sent to that project counts; otherwise the last one sent anywhere.\n const sentHash = (projectCustomId ? sentRecord(record, projectCustomId)?.sourceHash : undefined) ?? record?.sourceHash\n if (mode === 'changed' && sentHash !== undefined && sentHash !== unit.sourceHash) return 'sourceChanged'\n return null\n}\n\n/**\n * Decides what to send to TextUnited. Returns no tasks when nothing needs translation, in which\n * case no project is created or updated.\n */\nexport function planTranslation(args: {\n units: TranslationUnit[]\n languages: string[]\n targets: TranslationTargets\n state: TranslationState\n mode: TranslationMode\n /** The TextUnited project the languages belong to; \"changed\" compares with what it was sent */\n projectCustomId?: string\n}): TranslationPlan {\n const selected: TranslationPlan['selected'] = []\n for (const unit of args.units) {\n const reason = selectionReason(unit, args.languages, args.targets, args.state, args.mode, args.projectCustomId)\n if (reason) selected.push({unit, reason})\n }\n\n const taskIds = new Set(selected.map(({unit}) => unit.taskId))\n const tasks = [...taskIds].map((taskId) => ({\n taskId,\n segments: args.units\n .filter((unit) => unit.taskId === taskId)\n .flatMap((unit) => unit.segments.map((segment) => ({...segment, taskId}))),\n }))\n\n return {selected, tasks}\n}\n\n/**\n * Remembers the current source of units the plugin has no record of yet (for example values\n * translated by hand before the plugin was installed). Without this baseline a later edit of\n * their source could not be noticed by the `changed` mode.\n */\nexport function recordBaseline(state: TranslationState, units: TranslationUnit[]): TranslationState {\n const next: TranslationState = {units: {...state.units}}\n for (const unit of units) {\n next.units[unit.id] ??= {sourceHash: unit.sourceHash, languages: {}}\n }\n return next\n}\n\n/**\n * Records the source of the units that were just sent. With a project, the record is kept per\n * project (with the task holding the copy, in append mode); the unit-level hash is the latest sent.\n */\nexport function recordSentUnits(\n state: TranslationState,\n units: TranslationUnit[],\n sentAt = new Date().toISOString(),\n taskId?: string,\n projectCustomId?: string,\n): TranslationState {\n const next: TranslationState = {units: {...state.units}}\n for (const unit of units) {\n const previous = next.units[unit.id]\n if (projectCustomId) {\n next.units[unit.id] = {\n sourceHash: unit.sourceHash,\n sentAt,\n projects: {\n ...previous?.projects,\n [projectCustomId]: {sourceHash: unit.sourceHash, sentAt, ...(taskId ? {taskId} : {})},\n },\n languages: previous?.languages ?? {},\n }\n } else {\n next.units[unit.id] = {\n sourceHash: unit.sourceHash,\n sentAt,\n ...(taskId ? {taskId} : {}),\n languages: previous?.languages ?? {},\n }\n }\n }\n return next\n}\n\n/** Copies the records of the given units from `changes` over `base`. */\nexport function mergeState(\n base: TranslationState,\n changes: TranslationState,\n unitIds: Iterable<string>,\n): TranslationState {\n const next: TranslationState = {units: {...base.units}}\n for (const id of unitIds) {\n const record = changes.units[id]\n if (record) next.units[id] = record\n }\n return next\n}\n\n/**\n * True while TextUnited may still change a sent translation: some unit sent to a project has, in\n * one of that project's languages, no translation yet or one that is not final.\n */\nexport function hasPendingTranslations(\n state: TranslationState,\n projects: Array<{customId: string; languages: string[]}>,\n isFinal: (status: string | undefined) => boolean,\n): boolean {\n return Object.values(state.units).some((record) =>\n projects.some(\n (project) =>\n sentRecord(record, project.customId) !== undefined &&\n project.languages.some((language) => !isFinal(record.languages[language]?.status)),\n ),\n )\n}\n","/**\n * Settings shared by the Studio plugin and the server handler. Both sides must agree on these,\n * so the recommended setup keeps them in one module that the Studio config and the server\n * route both import.\n */\nexport type TranslationLanguage = {\n /** Language id used in Sanity, e.g. `de` */\n id: string\n /** Label shown to editors, e.g. `German` */\n title: string\n /** TextUnited language code, e.g. `de-de` */\n textUnitedCode: string\n}\n\n/**\n * How a document type stores its translations in Sanity.\n * - `fieldLevel`: one document; each translatable field is an internationalized array\n * (sanity-plugin-internationalized-array) holding one value per language.\n * - `documentLevel`: one document per language, linked by translation metadata\n * (@sanity/document-internationalization).\n */\nexport type LocalizationModel = 'fieldLevel' | 'documentLevel'\n\nexport type DocumentTypeConfig = {\n type: string\n model: LocalizationModel\n /**\n * Top-level fields to translate. Recommended for `documentLevel`, where every string is\n * otherwise a candidate. When omitted, all fields are scanned.\n */\n fields?: string[]\n /** Field names never translated, at any depth, in addition to the built-in list */\n skipFields?: string[]\n /** `documentLevel` only: field holding the document's language. Defaults to `language`. */\n languageField?: string\n}\n\nexport type TranslationConfig = {\n sourceLanguage: TranslationLanguage\n targetLanguages: TranslationLanguage[]\n documentTypes: DocumentTypeConfig[]\n /** Portable Text block types copied as they are, never translated (e.g. code, tables) */\n skipBlockTypes?: string[]\n}\n\n/** Field names that never hold translatable text. */\nexport const BUILT_IN_SKIP_FIELDS: ReadonlySet<string> = new Set([\n 'language',\n 'slug',\n 'current',\n 'href',\n 'url',\n 'link',\n 'asset',\n 'crop',\n 'hotspot',\n 'markDefs',\n 'style',\n 'listItem',\n 'level',\n])\n\nexport function getDocumentTypeConfig(\n config: TranslationConfig,\n documentType: string,\n): DocumentTypeConfig | undefined {\n return config.documentTypes.find((entry) => entry.type === documentType)\n}\n","import {\n BUILT_IN_SKIP_FIELDS,\n type DocumentTypeConfig,\n type TranslationConfig,\n} from '../config'\nimport {stableHash} from '../hash'\nimport {\n createSegmentCustomId,\n createTaskId,\n FIELDS_TASK_ID,\n pathToString,\n type PathSegment,\n} from '../ids'\nimport {getIntlItem, isIntlArray} from './intl'\nimport {arrayItemSegment, isPlainObject, type PlainObject} from './paths'\nimport {\n blockToSegmentContents,\n isPortableTextArray,\n isPortableTextBlock,\n splitText,\n MAX_SEGMENT_LENGTH,\n type PortableTextBlock,\n} from './portableText'\n\n/**\n * One translatable value: a text field or one Portable Text block. It is sent to TextUnited\n * as one or more segments (long values are split into chunks).\n */\nexport type TranslationUnit = {\n /** Stable id, the path to the value written the Sanity way */\n id: string\n taskId: string\n /**\n * `fieldLevel`: path to the internationalized array. `documentLevel`: path to the text\n * field, or to the Portable Text array for blocks.\n */\n fieldPath: PathSegment[]\n /** Path inside the localized value: empty for text, `[{_key}]` for a block */\n innerPath: PathSegment[]\n kind: 'text' | 'block'\n source: string | PortableTextBlock\n segments: Array<{customId: string; content: string}>\n /** Hash of the source, used to notice later edits of the source text */\n sourceHash: string\n}\n\ntype WalkContext = {\n model: DocumentTypeConfig['model']\n sourceLanguage: string\n skipFields: ReadonlySet<string>\n skipBlockTypes: ReadonlySet<string>\n units: TranslationUnit[]\n}\n\nconst NON_TEXT_PATTERNS = [\n /^https?:\\/\\//i,\n /^mailto:/i,\n /^tel:/i,\n /^#[0-9a-f]{3,8}$/i, // colors\n /^[\\d\\s.,:%+-]+$/, // numbers, dates, percentages\n /^\\d{4}-\\d{2}-\\d{2}/, // ISO dates\n]\n\nfunction isTranslatableString(value: string): boolean {\n const trimmed = value.trim()\n return trimmed !== '' && !NON_TEXT_PATTERNS.some((pattern) => pattern.test(trimmed))\n}\n\nfunction shouldSkipField(name: string, context: WalkContext): boolean {\n return name.startsWith('_') || context.skipFields.has(name)\n}\n\nfunction addTextUnit(\n context: WalkContext,\n taskId: string,\n fieldPath: PathSegment[],\n text: string,\n): void {\n const id = pathToString(fieldPath)\n const parts = splitText(text, MAX_SEGMENT_LENGTH)\n context.units.push({\n id,\n taskId,\n fieldPath,\n innerPath: [],\n kind: 'text',\n source: text,\n segments: parts.map((content, chunk) => ({\n customId: createSegmentCustomId(fieldPath, chunk),\n content,\n })),\n sourceHash: stableHash(text),\n })\n}\n\nfunction addBlockUnits(\n context: WalkContext,\n taskId: string,\n fieldPath: PathSegment[],\n blocks: unknown[],\n /** Walks non-block items (images, custom objects) for documentLevel text */\n walkObjects: boolean,\n): void {\n blocks.forEach((block, index) => {\n const segment = arrayItemSegment(block, index)\n if (isPortableTextBlock(block)) {\n const contents = blockToSegmentContents(block)\n if (contents.length === 0) return\n const innerPath = [segment]\n const fullPath = [...fieldPath, ...innerPath]\n context.units.push({\n id: pathToString(fullPath),\n taskId,\n fieldPath,\n innerPath,\n kind: 'block',\n source: block,\n segments: contents.map((content, chunk) => ({\n customId: createSegmentCustomId(fullPath, chunk),\n content,\n })),\n sourceHash: stableHash(JSON.stringify(contents)),\n })\n return\n }\n if (!walkObjects || !isPlainObject(block)) return\n if (typeof block._type === 'string' && context.skipBlockTypes.has(block._type)) return\n walk(block, [...fieldPath, segment], taskId, context)\n })\n}\n\nfunction walk(value: unknown, path: PathSegment[], taskId: string, context: WalkContext): void {\n if (context.model === 'fieldLevel' && isIntlArray(value)) {\n const sourceValue = getIntlItem(value, context.sourceLanguage)?.value\n if (typeof sourceValue === 'string') {\n if (sourceValue.trim() !== '') addTextUnit(context, taskId, path, sourceValue)\n } else if (isPortableTextArray(sourceValue)) {\n addBlockUnits(context, taskId, path, sourceValue, false)\n }\n return\n }\n\n if (typeof value === 'string') {\n if (context.model === 'documentLevel' && isTranslatableString(value)) {\n addTextUnit(context, taskId, path, value)\n }\n return\n }\n\n if (Array.isArray(value)) {\n if (context.model === 'documentLevel' && isPortableTextArray(value)) {\n addBlockUnits(context, taskId, path, value, true)\n return\n }\n value.forEach((item, index) => {\n if (isPlainObject(item) && typeof item._type === 'string' && context.skipBlockTypes.has(item._type)) {\n return\n }\n walk(item, [...path, arrayItemSegment(item, index)], taskId, context)\n })\n return\n }\n\n if (isPlainObject(value)) {\n // References point at other documents; their text is translated there.\n if (typeof value._ref === 'string') return\n for (const [name, child] of Object.entries(value)) {\n if (shouldSkipField(name, context)) continue\n walk(child, [...path, name], taskId, context)\n }\n }\n}\n\nfunction isPageBuilderArray(value: unknown, context: WalkContext): value is unknown[] {\n if (!Array.isArray(value) || value.length === 0) return false\n if (isPortableTextArray(value)) return false\n if (context.model === 'fieldLevel' && isIntlArray(value)) return false\n return value.every((item) => isPlainObject(item) && typeof item._key === 'string')\n}\n\n/**\n * Lists the translatable values of a source document, in document order.\n *\n * Tasks: each item of a page-builder array becomes its own task (`sections.a1`), a rich-text\n * field is one task (`body`), and every other field goes to the shared `fields` task.\n */\nexport function extractTranslationUnits(\n document: PlainObject,\n typeConfig: DocumentTypeConfig,\n config: TranslationConfig,\n): TranslationUnit[] {\n const context: WalkContext = {\n model: typeConfig.model,\n sourceLanguage: config.sourceLanguage.id,\n skipFields: new Set([...BUILT_IN_SKIP_FIELDS, ...(typeConfig.skipFields ?? [])]),\n skipBlockTypes: new Set(config.skipBlockTypes ?? []),\n units: [],\n }\n const allowed = typeConfig.fields ? new Set(typeConfig.fields) : undefined\n\n for (const [field, value] of Object.entries(document)) {\n if (shouldSkipField(field, context)) continue\n if (allowed && !allowed.has(field)) continue\n\n if (isPageBuilderArray(value, context)) {\n value.forEach((item, index) => {\n const segment = arrayItemSegment(item, index)\n walk(item, [field, segment], createTaskId(field, segment), context)\n })\n continue\n }\n\n const isRichText =\n isPortableTextArray(value) ||\n (context.model === 'fieldLevel' &&\n isIntlArray(value) &&\n isPortableTextArray(getIntlItem(value, context.sourceLanguage)?.value))\n\n walk(value, [field], isRichText ? createTaskId(field) : FIELDS_TASK_ID, context)\n }\n\n return context.units\n}\n","/** URL slug from a title: lowercase ASCII words joined by hyphens, at most 96 characters. */\nexport function slugify(title: string): string {\n return title\n .normalize('NFKD')\n .replace(/[̀-ͯ]/g, '')\n .replace(/ß/g, 'ss')\n .replace(/[łŁ]/g, 'l')\n .toLowerCase()\n .replace(/[^a-z0-9]+/g, '-')\n .replace(/^-+|-+$/g, '')\n .slice(0, 96)\n .replace(/-+$/, '')\n}\n","import type {DocumentTypeConfig} from '../core/config'\nimport {cloneValue, isPlainObject, type PlainObject} from '../core/document/paths'\nimport {slugify} from '../core/document/slug'\nimport type {TranslationTargets} from '../core/document/target'\nimport {getBaseDocumentId} from '../core/ids'\nimport {emptyState, migrateLegacyState, type TranslationState} from '../core/plan'\nimport {activeProjects, projectLanguages, readProjects, type ProjectRecord} from '../core/projects'\nimport {getPreferredDocument, type Mutation, type SanityStore} from './sanityStore'\n\n/** Types of the documents this package keeps in Sanity. Their ids contain a dot, so they are private. */\nexport const REQUEST_TYPE = 'textunited.translationRequest'\nexport const STATE_TYPE = 'textunited.translationState'\n\nexport function stateDocumentId(baseDocumentId: string): string {\n return `textunited.state.${baseDocumentId}`\n}\n\nconst SYSTEM_FIELDS = ['_id', '_rev', '_createdAt', '_updatedAt']\n\nfunction withoutSystemFields(document: PlainObject): PlainObject {\n const copy = cloneValue(document)\n for (const field of SYSTEM_FIELDS) delete copy[field]\n return copy\n}\n\nexport type StoredState = {\n state: TranslationState\n /** The document's TextUnited projects; each language belongs to one of them */\n projects: ProjectRecord[]\n /** Projects replaced by a reset; kept for reference */\n archived: ProjectRecord[]\n /** Languages stopped by an editor for this document */\n stopped: string[]\n /** Revision of the state document when it was read; absent when it does not exist yet */\n revision?: string\n}\n\nexport async function loadState(store: SanityStore, baseDocumentId: string): Promise<StoredState> {\n const document = await store.getDocument(stateDocumentId(baseDocumentId))\n if (!document) return {state: emptyState(), projects: [], archived: [], stopped: []}\n const revision = typeof document._rev === 'string' ? document._rev : undefined\n let state = emptyState()\n try {\n if (typeof document.stateJson === 'string') state = JSON.parse(document.stateJson) as TranslationState\n } catch {\n // A damaged state only means translations are treated as not written by the plugin.\n }\n const {projects, archived, stopped} = readProjects(document)\n // States from before several projects keep what was sent on the unit: it belongs to the first.\n if (typeof document.projectsJson !== 'string') state = migrateLegacyState(state, projects[0]?.customId)\n return {state, revision, projects, archived, stopped}\n}\n\n/**\n * Saves the state, but only if nobody saved it since it was read (TextUnited may send several\n * notifications at once). A conflict surfaces as SanityConflictError; the caller re-reads and\n * retries. The single-project fields are kept too, for readers of the older format.\n */\nexport function saveStateMutation(\n baseDocumentId: string,\n stored: StoredState,\n pending: boolean,\n): Mutation {\n const first = stored.projects[0]\n const fields = {\n documentId: baseDocumentId,\n projectsJson: JSON.stringify({projects: stored.projects, archived: stored.archived, stopped: stored.stopped}),\n projectCustomId: first?.customId,\n projectLanguages: projectLanguages(activeProjects(stored.projects, stored.stopped)),\n projectType: first?.projectType,\n projectId: first?.projectId,\n stateJson: JSON.stringify(stored.state),\n pending,\n updatedAt: new Date().toISOString(),\n }\n const id = stateDocumentId(baseDocumentId)\n if (stored.revision) return {patch: {id, ifRevisionID: stored.revision, set: fields}}\n return {create: {_id: id, _type: STATE_TYPE, ...fields}}\n}\n\n/** Ids of the existing translations of a documentLevel document, per language. */\nasync function translationDocumentIds(\n store: SanityStore,\n baseDocumentId: string,\n): Promise<{metadata: PlainObject | null; ids: Record<string, string>}> {\n const metadata = await store.findTranslationMetadata(baseDocumentId)\n const ids: Record<string, string> = {}\n const translations = Array.isArray(metadata?.translations) ? metadata.translations : []\n for (const entry of translations) {\n if (!isPlainObject(entry) || typeof entry._key !== 'string') continue\n const value = entry.value\n if (isPlainObject(value) && typeof value._ref === 'string') ids[entry._key] = value._ref\n }\n return {metadata, ids}\n}\n\nexport type LoadedTargets = {\n targets: TranslationTargets\n /** documentLevel: translation metadata, to be updated when new documents are created */\n metadata: PlainObject | null\n}\n\nexport async function loadTargets(args: {\n store: SanityStore\n source: PlainObject\n typeConfig: DocumentTypeConfig\n languages: string[]\n}): Promise<LoadedTargets> {\n if (args.typeConfig.model === 'fieldLevel') {\n return {targets: {model: 'fieldLevel', document: cloneValue(args.source)}, metadata: null}\n }\n const baseId = getBaseDocumentId(String(args.source._id))\n const {metadata, ids} = await translationDocumentIds(args.store, baseId)\n const documents: Record<string, PlainObject | undefined> = {}\n for (const language of args.languages) {\n const id = ids[language]\n documents[language] = id ? ((await getPreferredDocument(args.store, id)) ?? undefined) : undefined\n }\n return {targets: {model: 'documentLevel', documents}, metadata}\n}\n\n/**\n * Creates in-memory documentLevel translations for languages that have none yet: a copy of the\n * source without the translated fields, with a new id and the target language. Returns the\n * languages that got a new document.\n */\nexport function createMissingTranslationDocuments(args: {\n targets: TranslationTargets\n source: PlainObject\n typeConfig: DocumentTypeConfig\n languages: string[]\n newId: () => string\n}): string[] {\n if (args.targets.model !== 'documentLevel') return []\n const created: string[] = []\n const languageField = args.typeConfig.languageField ?? 'language'\n for (const language of args.languages) {\n if (args.targets.documents[language]) continue\n const copy = withoutSystemFields(args.source)\n for (const field of args.typeConfig.fields ?? []) delete copy[field]\n delete copy.slug\n copy._id = `drafts.${args.newId()}`\n copy[languageField] = language\n args.targets.documents[language] = copy\n created.push(language)\n }\n return created\n}\n\nfunction translationReference(language: string, documentId: string, type: string): PlainObject {\n return {\n _key: language,\n _type: 'internationalizedArrayReferenceValue',\n value: {\n _type: 'reference',\n _ref: getBaseDocumentId(documentId),\n _weak: true,\n _strengthenOnPublish: {type},\n },\n }\n}\n\n/** Mutations that save the changed translations as drafts. */\nexport function writeTargetsMutations(args: {\n loaded: LoadedTargets\n targets: TranslationTargets\n source: PlainObject\n typeConfig: DocumentTypeConfig\n sourceLanguage: string\n changedFields: Map<string, Set<string>>\n createdLanguages: string[]\n newId: () => string\n}): Mutation[] {\n const mutations: Mutation[] = []\n\n const saveDraft = (document: PlainObject, fields: Set<string>, isNew: boolean) => {\n const id = String(document._id)\n const draftId = id.startsWith('drafts.') ? id : `drafts.${id}`\n if (isNew || !id.startsWith('drafts.')) {\n // No draft yet: the draft starts as the full current document.\n mutations.push({createOrReplace: {...withoutSystemFields(document), _id: draftId}})\n return\n }\n const set: PlainObject = {}\n for (const field of fields) set[field] = document[field]\n mutations.push({patch: {id: draftId, set}})\n }\n\n if (args.targets.model === 'fieldLevel') {\n const fields = args.changedFields.get('')\n if (fields?.size) saveDraft(args.targets.document, fields, false)\n return mutations\n }\n\n for (const [language, changed] of args.changedFields) {\n let fields = changed\n const document = args.targets.documents[language]\n if (!document) continue\n const isNew = args.createdLanguages.includes(language)\n // A new translation, or one created empty in the Studio (e.g. from the Translations menu),\n // gets a slug from its translated title.\n const slug = document.slug as {current?: unknown} | null | undefined\n if (isNew || !slug || typeof slug.current !== 'string' || slug.current === '') {\n const titleField = (args.typeConfig.fields ?? ['title']).find((field) => typeof document[field] === 'string')\n const title = titleField ? String(document[titleField]) : ''\n if (title) {\n document.slug = {_type: 'slug', current: slugify(title)}\n fields = new Set([...fields, 'slug'])\n }\n }\n saveDraft(document, fields, isNew)\n }\n\n const createdIds = args.createdLanguages\n .filter((language) => args.changedFields.has(language))\n .map((language) => [language, String(args.targets.model === 'documentLevel' ? args.targets.documents[language]?._id : '')] as const)\n if (createdIds.length === 0) return mutations\n\n const type = String(args.source._type)\n const sourceRef = translationReference(args.sourceLanguage, String(args.source._id), type)\n const newRefs = createdIds.map(([language, id]) => translationReference(language, id, type))\n const existing = args.loaded.metadata\n if (!existing) {\n mutations.push({\n create: {\n _id: `translation.metadata.${args.newId()}`,\n _type: 'translation.metadata',\n schemaTypes: [type],\n translations: [sourceRef, ...newRefs],\n },\n })\n } else {\n // A language whose translation was deleted still has its entry, pointing to the deleted\n // document; the new document takes its place.\n const replaced = new Set(newRefs.map((ref) => ref._key))\n const kept = (Array.isArray(existing.translations) ? existing.translations : []).filter(\n (entry) => !(isPlainObject(entry) && replaced.has(String(entry._key))),\n )\n const keys = new Set(kept.map((entry) => (isPlainObject(entry) ? entry._key : undefined)))\n const additions = [sourceRef, ...newRefs].filter((ref) => !keys.has(ref._key))\n mutations.push({patch: {id: String(existing._id), set: {translations: [...kept, ...additions]}}})\n }\n return mutations\n}\n"]}