@textunited/sanity-plugin 0.1.2 → 0.1.4
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.
- package/CHANGELOG.md +11 -0
- package/dist/{chunk-H7FXEDXW.cjs → chunk-5DQ7NDBQ.cjs} +56 -4
- package/dist/chunk-5DQ7NDBQ.cjs.map +1 -0
- package/dist/{chunk-VCPPHQK2.js → chunk-GK4JJHRR.js} +3 -3
- package/dist/{chunk-VCPPHQK2.js.map → chunk-GK4JJHRR.js.map} +1 -1
- package/dist/{chunk-QVQAWQEI.js → chunk-H7WDVCKS.js} +56 -4
- package/dist/chunk-H7WDVCKS.js.map +1 -0
- package/dist/{chunk-4AVTK3TI.cjs → chunk-S2E3ALGC.cjs} +58 -58
- package/dist/{chunk-4AVTK3TI.cjs.map → chunk-S2E3ALGC.cjs.map} +1 -1
- package/dist/next/index.cjs +3 -3
- package/dist/next/index.js +2 -2
- package/dist/server/index.cjs +8 -8
- package/dist/server/index.js +2 -2
- package/dist/studio/index.cjs +23 -23
- package/dist/studio/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-H7FXEDXW.cjs.map +0 -1
- package/dist/chunk-QVQAWQEI.js.map +0 -1
|
@@ -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/core/document/slug.ts","../src/server/documents.ts"],"names":[],"mappings":";AA+BO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AACF;AAUO,IAAM,kBAAN,MAA6C;AAAA,EACjC,IAAA;A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.js","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'\r\n\r\nexport type PlainObject = Record<string, unknown>\r\n\r\nexport function isPlainObject(value: unknown): value is PlainObject {\r\n return typeof value === 'object' && value !== null && !Array.isArray(value)\r\n}\r\n\r\nexport function cloneValue<T>(value: T): T {\r\n return structuredClone(value)\r\n}\r\n\r\n/**\r\n * A copy of a source value for a translation: everything is kept (images, files, references,\r\n * blocks without text) except canonical URLs, which name the source-language page and would\r\n * tell search engines that the translation is a duplicate of it.\r\n */\r\nexport function cloneForTranslation<T>(value: T): T {\r\n const copy = structuredClone(value)\r\n const strip = (node: unknown): void => {\r\n if (Array.isArray(node)) {\r\n node.forEach(strip)\r\n } else if (isPlainObject(node)) {\r\n for (const key of Object.keys(node)) {\r\n if (/canonical/i.test(key)) delete node[key]\r\n else strip(node[key])\r\n }\r\n }\r\n }\r\n strip(copy)\r\n return copy\r\n}\r\n\r\n/** Builds the path step for one array item: its `_key` when present, else its index. */\r\nexport function arrayItemSegment(item: unknown, index: number): PathSegment {\r\n return isPlainObject(item) && typeof item._key === 'string' ? {_key: item._key} : index\r\n}\r\n\r\nfunction findArrayIndex(array: unknown[], segment: PathSegment): number {\r\n if (typeof segment === 'number') return segment < array.length ? segment : -1\r\n if (typeof segment === 'object') {\r\n return array.findIndex((item) => isPlainObject(item) && item._key === segment._key)\r\n }\r\n return -1\r\n}\r\n\r\n/** Reads the value at a path, or undefined when any step is missing. */\r\nexport function getAtPath(root: unknown, path: readonly PathSegment[]): unknown {\r\n let current: unknown = root\r\n for (const segment of path) {\r\n if (Array.isArray(current)) {\r\n const index = findArrayIndex(current, segment)\r\n if (index === -1) return undefined\r\n current = current[index]\r\n } else if (isPlainObject(current) && typeof segment === 'string') {\r\n current = current[segment]\r\n } else {\r\n return undefined\r\n }\r\n }\r\n return current\r\n}\r\n\r\n/**\r\n * Writes a value at a path inside `target`, creating missing parents by copying them from\r\n * `source` at the same path. Missing array items are inserted at the position they have in\r\n * `source`, so a translated document keeps the structure of the original.\r\n */\r\nexport function setAtPath(\r\n target: PlainObject,\r\n source: unknown,\r\n path: readonly PathSegment[],\r\n value: unknown,\r\n): void {\r\n if (path.length === 0) throw new Error('Cannot set a value at an empty path')\r\n\r\n let current: unknown = target\r\n let currentSource: unknown = source\r\n\r\n for (let depth = 0; depth < path.length; depth += 1) {\r\n const segment = path[depth] as PathSegment\r\n const isLast = depth === path.length - 1\r\n const nextSource = getAtPath(currentSource, [segment])\r\n\r\n if (Array.isArray(current)) {\r\n let index = findArrayIndex(current, segment)\r\n if (index === -1) {\r\n if (isLast) {\r\n current.push(value)\r\n return\r\n }\r\n const sourceArray = Array.isArray(currentSource) ? currentSource : []\r\n const sourceIndex = findArrayIndex(sourceArray, segment)\r\n const placeholder = cloneValue(nextSource ?? (typeof segment === 'object' ? {_key: segment._key} : {}))\r\n index = insertionIndex(current, sourceArray, sourceIndex)\r\n current.splice(index, 0, placeholder)\r\n }\r\n if (isLast) {\r\n current[index] = value\r\n return\r\n }\r\n current = current[index]\r\n } else if (isPlainObject(current) && typeof segment === 'string') {\r\n if (isLast) {\r\n current[segment] = value\r\n return\r\n }\r\n if (current[segment] === undefined || current[segment] === null) {\r\n // Copy a missing field from the source, so its parts that are not text (an image's\r\n // asset, a file, blocks without text) are kept. Texts copied along stay equal to the\r\n // source, which counts as not translated, and are replaced by their translations.\r\n current[segment] =\r\n nextSource !== undefined && nextSource !== null\r\n ? cloneForTranslation(nextSource)\r\n : emptyContainer(nextSource, path[depth + 1])\r\n }\r\n current = current[segment]\r\n } else {\r\n throw new Error('Path does not match the document structure')\r\n }\r\n currentSource = nextSource\r\n }\r\n}\r\n\r\n/** An empty object (keeping only `_type`) or array, shaped like the source at that place. */\r\nfunction emptyContainer(source: unknown, next: PathSegment | undefined): unknown {\r\n if (Array.isArray(source) || typeof next !== 'string') return []\r\n return isPlainObject(source) && typeof source._type === 'string' ? {_type: source._type} : {}\r\n}\r\n\r\n/** Index in `target` right after the nearest preceding item that `source` also has. */\r\nfunction insertionIndex(target: unknown[], source: unknown[], sourceIndex: number): number {\r\n for (let i = sourceIndex - 1; i >= 0; i -= 1) {\r\n const previous = source[i]\r\n if (isPlainObject(previous) && typeof previous._key === 'string') {\r\n const found = findArrayIndex(target, {_key: previous._key})\r\n if (found !== -1) return found + 1\r\n }\r\n }\r\n return sourceIndex >= 0 ? 0 : target.length\r\n}\r\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, '&')\n .replace(/</g, '<')\n .replace(/>/g, '>')\n .replace(/\"/g, '"')\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'\r\nimport {cloneForTranslation, cloneValue, isPlainObject, type PlainObject} from '../core/document/paths'\r\nimport {slugify} from '../core/document/slug'\r\nimport type {TranslationTargets} from '../core/document/target'\r\nimport {getBaseDocumentId} from '../core/ids'\r\nimport {emptyState, migrateLegacyState, type TranslationState} from '../core/plan'\r\nimport {activeProjects, projectLanguages, readProjects, type ProjectRecord} from '../core/projects'\r\nimport {getPreferredDocument, type Mutation, type SanityStore} from './sanityStore'\r\n\r\n/** Types of the documents this package keeps in Sanity. Their ids contain a dot, so they are private. */\r\nexport const REQUEST_TYPE = 'textunited.translationRequest'\r\nexport const STATE_TYPE = 'textunited.translationState'\r\n\r\nexport function stateDocumentId(baseDocumentId: string): string {\r\n return `textunited.state.${baseDocumentId}`\r\n}\r\n\r\nconst SYSTEM_FIELDS = ['_id', '_rev', '_createdAt', '_updatedAt']\r\n\r\nfunction withoutSystemFields(document: PlainObject): PlainObject {\r\n const copy = cloneValue(document)\r\n for (const field of SYSTEM_FIELDS) delete copy[field]\r\n return copy\r\n}\r\n\r\nexport type StoredState = {\r\n state: TranslationState\r\n /** The document's TextUnited projects; each language belongs to one of them */\r\n projects: ProjectRecord[]\r\n /** Projects replaced by a reset; kept for reference */\r\n archived: ProjectRecord[]\r\n /** Languages stopped by an editor for this document */\r\n stopped: string[]\r\n /** Revision of the state document when it was read; absent when it does not exist yet */\r\n revision?: string\r\n}\r\n\r\nexport async function loadState(store: SanityStore, baseDocumentId: string): Promise<StoredState> {\r\n const document = await store.getDocument(stateDocumentId(baseDocumentId))\r\n if (!document) return {state: emptyState(), projects: [], archived: [], stopped: []}\r\n const revision = typeof document._rev === 'string' ? document._rev : undefined\r\n let state = emptyState()\r\n try {\r\n if (typeof document.stateJson === 'string') state = JSON.parse(document.stateJson) as TranslationState\r\n } catch {\r\n // A damaged state only means translations are treated as not written by the plugin.\r\n }\r\n const {projects, archived, stopped} = readProjects(document)\r\n // States from before several projects keep what was sent on the unit: it belongs to the first.\r\n if (typeof document.projectsJson !== 'string') state = migrateLegacyState(state, projects[0]?.customId)\r\n return {state, revision, projects, archived, stopped}\r\n}\r\n\r\n/**\r\n * Saves the state, but only if nobody saved it since it was read (TextUnited may send several\r\n * notifications at once). A conflict surfaces as SanityConflictError; the caller re-reads and\r\n * retries. The single-project fields are kept too, for readers of the older format.\r\n */\r\nexport function saveStateMutation(\r\n baseDocumentId: string,\r\n stored: StoredState,\r\n pending: boolean,\r\n): Mutation {\r\n const first = stored.projects[0]\r\n const fields = {\r\n documentId: baseDocumentId,\r\n projectsJson: JSON.stringify({projects: stored.projects, archived: stored.archived, stopped: stored.stopped}),\r\n projectCustomId: first?.customId,\r\n projectLanguages: projectLanguages(activeProjects(stored.projects, stored.stopped)),\r\n projectType: first?.projectType,\r\n projectId: first?.projectId,\r\n stateJson: JSON.stringify(stored.state),\r\n pending,\r\n updatedAt: new Date().toISOString(),\r\n }\r\n const id = stateDocumentId(baseDocumentId)\r\n if (stored.revision) return {patch: {id, ifRevisionID: stored.revision, set: fields}}\r\n return {create: {_id: id, _type: STATE_TYPE, ...fields}}\r\n}\r\n\r\n/** Ids of the existing translations of a documentLevel document, per language. */\r\nasync function translationDocumentIds(\r\n store: SanityStore,\r\n baseDocumentId: string,\r\n): Promise<{metadata: PlainObject | null; ids: Record<string, string>}> {\r\n const metadata = await store.findTranslationMetadata(baseDocumentId)\r\n const ids: Record<string, string> = {}\r\n const translations = Array.isArray(metadata?.translations) ? metadata.translations : []\r\n for (const entry of translations) {\r\n if (!isPlainObject(entry) || typeof entry._key !== 'string') continue\r\n const value = entry.value\r\n if (isPlainObject(value) && typeof value._ref === 'string') ids[entry._key] = value._ref\r\n }\r\n return {metadata, ids}\r\n}\r\n\r\nexport type LoadedTargets = {\r\n targets: TranslationTargets\r\n /** documentLevel: translation metadata, to be updated when new documents are created */\r\n metadata: PlainObject | null\r\n}\r\n\r\nexport async function loadTargets(args: {\r\n store: SanityStore\r\n source: PlainObject\r\n typeConfig: DocumentTypeConfig\r\n languages: string[]\r\n}): Promise<LoadedTargets> {\r\n if (args.typeConfig.model === 'fieldLevel') {\r\n return {targets: {model: 'fieldLevel', document: cloneValue(args.source)}, metadata: null}\r\n }\r\n const baseId = getBaseDocumentId(String(args.source._id))\r\n const {metadata, ids} = await translationDocumentIds(args.store, baseId)\r\n const documents: Record<string, PlainObject | undefined> = {}\r\n for (const language of args.languages) {\r\n const id = ids[language]\r\n documents[language] = id ? ((await getPreferredDocument(args.store, id)) ?? undefined) : undefined\r\n }\r\n return {targets: {model: 'documentLevel', documents}, metadata}\r\n}\r\n\r\n/**\r\n * Creates in-memory documentLevel translations for languages that have none yet: a copy of the\r\n * source without the translated fields, with a new id and the target language. Returns the\r\n * languages that got a new document.\r\n */\r\nexport function createMissingTranslationDocuments(args: {\r\n targets: TranslationTargets\r\n source: PlainObject\r\n typeConfig: DocumentTypeConfig\r\n languages: string[]\r\n newId: () => string\r\n}): string[] {\r\n if (args.targets.model !== 'documentLevel') return []\r\n const created: string[] = []\r\n const languageField = args.typeConfig.languageField ?? 'language'\r\n for (const language of args.languages) {\r\n if (args.targets.documents[language]) continue\r\n // A full copy of the source: images, files, references and blocks without text stay as they\r\n // are, and the translations replace the texts. A text still equal to the source counts as\r\n // not translated, so nothing in the source language passes for a translation.\r\n const copy = cloneForTranslation(withoutSystemFields(args.source))\r\n delete copy.slug\r\n copy._id = `drafts.${args.newId()}`\r\n copy[languageField] = language\r\n args.targets.documents[language] = copy\r\n created.push(language)\r\n }\r\n return created\r\n}\r\n\r\nfunction translationReference(language: string, documentId: string, type: string): PlainObject {\r\n return {\r\n _key: language,\r\n _type: 'internationalizedArrayReferenceValue',\r\n value: {\r\n _type: 'reference',\r\n _ref: getBaseDocumentId(documentId),\r\n _weak: true,\r\n _strengthenOnPublish: {type},\r\n },\r\n }\r\n}\r\n\r\n/** Mutations that save the changed translations as drafts. */\r\nexport function writeTargetsMutations(args: {\r\n loaded: LoadedTargets\r\n targets: TranslationTargets\r\n source: PlainObject\r\n typeConfig: DocumentTypeConfig\r\n sourceLanguage: string\r\n changedFields: Map<string, Set<string>>\r\n createdLanguages: string[]\r\n newId: () => string\r\n}): Mutation[] {\r\n const mutations: Mutation[] = []\r\n\r\n const saveDraft = (document: PlainObject, fields: Set<string>, isNew: boolean) => {\r\n const id = String(document._id)\r\n const draftId = id.startsWith('drafts.') ? id : `drafts.${id}`\r\n if (isNew || !id.startsWith('drafts.')) {\r\n // No draft yet: the draft starts as the full current document.\r\n mutations.push({createOrReplace: {...withoutSystemFields(document), _id: draftId}})\r\n return\r\n }\r\n const set: PlainObject = {}\r\n for (const field of fields) set[field] = document[field]\r\n mutations.push({patch: {id: draftId, set}})\r\n }\r\n\r\n if (args.targets.model === 'fieldLevel') {\r\n const fields = args.changedFields.get('')\r\n if (fields?.size) saveDraft(args.targets.document, fields, false)\r\n return mutations\r\n }\r\n\r\n for (const [language, changed] of args.changedFields) {\r\n let fields = changed\r\n const document = args.targets.documents[language]\r\n if (!document) continue\r\n const isNew = args.createdLanguages.includes(language)\r\n // A new translation, or one created empty in the Studio (e.g. from the Translations menu),\r\n // gets a slug from its translated title.\r\n const slug = document.slug as {current?: unknown} | null | undefined\r\n if (isNew || !slug || typeof slug.current !== 'string' || slug.current === '') {\r\n const titleField = (args.typeConfig.fields ?? ['title']).find((field) => typeof document[field] === 'string')\r\n const title = titleField ? String(document[titleField]) : ''\r\n if (title) {\r\n document.slug = {_type: 'slug', current: slugify(title)}\r\n fields = new Set([...fields, 'slug'])\r\n }\r\n }\r\n saveDraft(document, fields, isNew)\r\n }\r\n\r\n const createdIds = args.createdLanguages\r\n .filter((language) => args.changedFields.has(language))\r\n .map((language) => [language, String(args.targets.model === 'documentLevel' ? args.targets.documents[language]?._id : '')] as const)\r\n if (createdIds.length === 0) return mutations\r\n\r\n const type = String(args.source._type)\r\n const sourceRef = translationReference(args.sourceLanguage, String(args.source._id), type)\r\n const newRefs = createdIds.map(([language, id]) => translationReference(language, id, type))\r\n const existing = args.loaded.metadata\r\n if (!existing) {\r\n mutations.push({\r\n create: {\r\n // A plain id, like the Studio uses: an id with a dot is private, so a website reading\r\n // without a token would not see the link and its language switcher would break.\r\n _id: args.newId(),\r\n _type: 'translation.metadata',\r\n schemaTypes: [type],\r\n translations: [sourceRef, ...newRefs],\r\n },\r\n })\r\n } else {\r\n // A language whose translation was deleted still has its entry, pointing to the deleted\r\n // document; the new document takes its place.\r\n const replaced = new Set(newRefs.map((ref) => ref._key))\r\n const kept = (Array.isArray(existing.translations) ? existing.translations : []).filter(\r\n (entry) => !(isPlainObject(entry) && replaced.has(String(entry._key))),\r\n )\r\n const keys = new Set(kept.map((entry) => (isPlainObject(entry) ? entry._key : undefined)))\r\n const additions = [sourceRef, ...newRefs].filter((ref) => !keys.has(ref._key))\r\n mutations.push({patch: {id: String(existing._id), set: {translations: [...kept, ...additions]}}})\r\n }\r\n return mutations\r\n}\r\n"]}
|