import * as fs from 'node:fs'; import * as path from 'node:path'; import { readLockfile, EntryMap, DownloadedTranslation, } from '../fs/config/downloadedVersions.js'; import { Settings } from '../types/index.js'; import { createFileMapping } from '../formats/files/fileMapping.js'; import { getGitUnifiedDiff } from '../utils/gitDiff.js'; import { api } from '../utils/api.js'; import { FileReference, isBinaryFileFormat, SubmitUserEditDiff, type FileFormat, } from 'generaltranslation/types'; import { readFileContent } from '../fs/fileContent.js'; import os from 'node:os'; import { randomUUID } from 'node:crypto'; import { hashStringSync } from '../utils/hash.js'; import { extractJson } from '../formats/json/extractJson.js'; import { emptyLocaleContent, localeContent, } from '../formats/files/localeContent.js'; import { extractYaml } from '../formats/yaml/extractYaml.js'; import { logger } from '../console/logger.js'; import { recordWarning } from '../state/translateWarnings.js'; import { getRelative } from '../fs/findFilepath.js'; import { resolveMintlifyRefs, shouldResolveRefs, type UnreadableRef, } from '../utils/resolveMintlifyRefs.js'; import { findMatchingItemArray, findMatchingItemObject, generateSourceObjectPointers, validateJsonSchema, } from '../formats/json/utils.js'; import type { JSONObject, JSONValue } from '../types/data/json.js'; import { getJSONPathMatches } from '../formats/json/jsonPath.js'; import { createDiagnosticMessage } from 'generaltranslation/diagnostics'; import { isDeepStrictEqual } from 'node:util'; const unsavedJsonEditsWarning = ( relativePath: string, locale: string, reason: string ) => createDiagnosticMessage({ source: 'gt', severity: 'Warning', whatHappened: `Local edits to ${relativePath} were not saved for ${locale}`, why: reason, reassurance: 'The stored translation was left unchanged', }); const resolveLocalRefs = ( content: string, outputPath: string, settings: Settings ): { content: string; unreadableRefs: UnreadableRef[] } => { if (!shouldResolveRefs(outputPath, settings.options)) { return { content, unreadableRefs: [] }; } try { const { resolved, unreadableRefs } = resolveMintlifyRefs( JSON.parse(content), outputPath ); return { content: JSON.stringify(resolved, null, 2), unreadableRefs }; } catch { return { content, unreadableRefs: [] }; } }; /** * The unreadable refs that could hold values of the locale: all of them, * except those inside an entry of a composite file known to belong to another * locale. */ const unreadableRefsForLocale = ( unreadableRefs: UnreadableRef[], resolvedContent: string, fileName: string, locale: string, settings: Settings ): UnreadableRef[] => { if (unreadableRefs.length === 0) return []; const composite = validateJsonSchema( settings.options ?? {}, fileName )?.composite; const json = parseJson(resolvedContent) as JSONValue | undefined; if (!composite || json === undefined) return unreadableRefs; const localeKey = settings.options?.experimentalCanonicalLocaleKeys ? api.resolveCanonicalLocale(locale) : locale; const otherLocalePointers: string[] = []; for (const [ pointer, { sourceObjectValue, sourceObjectOptions }, ] of Object.entries(generateSourceObjectPointers(composite, json))) { if (sourceObjectOptions.type === 'array') { if (!Array.isArray(sourceObjectValue)) continue; const ownItems = findMatchingItemArray( localeKey, sourceObjectOptions, pointer, sourceObjectValue ); sourceObjectValue.forEach((item, index) => { // An entry whose locale key sat in the unreadable file has no key // left, so it may be the locale's own. const hasLocaleKey = !!sourceObjectOptions.key && (getJSONPathMatches(item, sourceObjectOptions.key)?.length ?? 0) > 0; if (hasLocaleKey && !(`/${index}` in ownItems)) { otherLocalePointers.push(`${pointer}/${index}`); } }); } else if (sourceObjectValue && typeof sourceObjectValue === 'object') { const { keyParentProperty } = findMatchingItemObject( localeKey, pointer, sourceObjectOptions, sourceObjectValue as JSONObject ); for (const key of Object.keys(sourceObjectValue)) { if (key !== keyParentProperty) { otherLocalePointers.push(`${pointer}/${key}`); } } } } return unreadableRefs.filter( (ref) => !otherLocalePointers.some( (pointer) => ref.pointer === pointer || ref.pointer.startsWith(`${pointer}/`) ) ); }; const hasLeafValue = (value: unknown): boolean => value !== null && typeof value === 'object' ? Object.values(value).some(hasLeafValue) : value !== undefined; const parseJson = (content: string): unknown => { try { return JSON.parse(content); } catch { return undefined; } }; type LatestDownloadedVersion = { versionId: string; entry: DownloadedTranslation; }; /** * The bytes a file's pipeline content stands for: binary formats carry base64, * everything else carries UTF-8 text. Applied to both sides of the comparison * so they are measured the same way. */ const contentBytes = (content: string, fileFormat: FileFormat): Buffer => isBinaryFileFormat(fileFormat) ? Buffer.from(content, 'base64') : Buffer.from(content, 'utf8'); /** * The branch these files were uploaded under. `readLockfile` needs it to pick * the matching entries out of a v1 lockfile, which keeps every branch it has * seen; without it the file's entries are read from whichever branch is listed * first. The files carry the branch resolved for this invocation, while * `settings._branchId` can still hold the value persisted by an earlier run. */ const lockfileBranchId = ( files: FileReference[], settings: Settings ): string | undefined => files.find((file) => file.branchId)?.branchId ?? settings._branchId; const findLatestDownloadedVersion = ( entryMap: EntryMap, fileId: string, locale: string ): LatestDownloadedVersion | null => { const entry = entryMap.get(fileId); if (!entry) return null; const translation = entry.translations[locale]; if (!translation) return null; return { versionId: entry.versionId, entry: translation }; }; /** * Collects local user edits by diffing the latest downloaded server translation version * against the current local translation file, and submits the diffs upstream. * A file that holds every locale is compared one locale slice at a time, so an * edit to one locale is submitted under that locale alone. * * Must run before enqueueing new translations so rules are available to the generator. */ export async function collectAndSendUserEditDiffs( files: FileReference[], settings: Settings ): Promise { if (!settings.files) return false; const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } = settings.files; const fileMapping = createFileMapping( resolvedPaths, placeholderPaths, transformPaths, transformFormats, settings.locales, settings.defaultLocale ); // readLockfile uses _branchId to select branch-specific entries. Keep it on a // scoped copy so the caller's settings object is not mutated. const branchId = lockfileBranchId(files, settings); const { entryMap } = readLockfile( branchId ? { ...settings, _branchId: branchId } : settings ); const tempDir = path.join(os.tmpdir(), randomUUID()); if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true }); // Build candidates for diff and batch-fetch server contents type DiffCandidate = { branchId: string; fileName: string; fileId: string; versionId: string; locale: string; // resolved outputPath: string; fileFormat: FileFormat; /** The recorded hash did not match, so this locale is known to be edited. */ knownEdited: boolean; }; const candidates: DiffCandidate[] = []; for (const uploadedFile of files) { for (const locale of settings.locales) { const outputPath = fileMapping[locale]?.[uploadedFile.fileName] ?? null; if (!outputPath) continue; if (!fs.existsSync(outputPath)) continue; const latestDownloaded = findLatestDownloadedVersion( entryMap, uploadedFile.fileId, locale ); if (!latestDownloaded) continue; const downloadedVersion = latestDownloaded.entry; // Skip if the locale's local content matches the last recorded hash let knownEdited = false; if (downloadedVersion.postProcessHash) { try { // Hashed from the locale's share of the pipeline content, which is // what was recorded, so an untouched locale matches regardless of // the file's encoding or of edits to its other locales. const localFile = readFileContent( outputPath, uploadedFile.fileFormat ); const localHash = hashStringSync( localeContent(localFile, uploadedFile.fileFormat, locale) ?? emptyLocaleContent(localFile, uploadedFile.fileFormat) ); if (localHash === downloadedVersion.postProcessHash) { continue; } knownEdited = true; } catch { // If hash check fails, fall through to diff } } candidates.push({ branchId: uploadedFile.branchId, fileName: uploadedFile.fileName, fileId: uploadedFile.fileId, versionId: latestDownloaded.versionId, locale: locale, outputPath, fileFormat: uploadedFile.fileFormat, knownEdited, }); } } const collectedDiffs: SubmitUserEditDiff[] = []; if (candidates.length > 0) { const fileQueryData = candidates.map((c) => ({ versionId: c.versionId, locale: c.locale, fileId: c.fileId, branchId: c.branchId, })); // Single batched check to obtain translation IDs const checkResponse = await api.queryFileData({ translatedFiles: fileQueryData, }); const translatedFiles = checkResponse.translatedFiles?.filter((t) => t.completedAt) ?? []; // The server's copy of each candidate, keyed like the candidates type ServerPayload = { data: string; fileFormat: FileFormat }; const serverPayloadByKey = new Map(); try { const resp = await api.downloadFileBatch( translatedFiles.map((file) => ({ branchId: file.branchId, fileId: file.fileId, locale: file.locale, versionId: file.versionId, })) ); for (const f of resp?.files || []) { if (!f.locale) continue; serverPayloadByKey.set( `${f.branchId}:${f.fileId}:${f.versionId}:${f.locale}`, { data: f.data, fileFormat: f.fileFormat } ); } } catch { // Ignore chunk failures; proceed with what we have } // Compute diffs using fetched server contents for (const c of candidates) { const key = `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`; const payload = serverPayloadByKey.get(key); // Absent means the batch did not return this file, so there is no // baseline. An empty payload is a baseline of nothing, which the user // may well have written against. When the recorded hash already showed // an edit, say so rather than leaving the run looking clean. An empty // map cannot tell a version the server does not have from a batch that // failed to return it, so the message covers both. if (!payload) { if (c.knownEdited) { const relativePath = getRelative(c.outputPath); const reason = `the ${c.locale} baseline recorded in the lockfile could not be retrieved, so the edit could not be compared`; logger.warn(unsavedJsonEditsWarning(relativePath, c.locale, reason)); recordWarning('skipped_file', relativePath, reason); } continue; } // The locale's share of the payload, read on its own so a payload the // server sent malformed costs only its own locale. A catalog payload // that carries nothing for the locale is that file's empty payload, and // a baseline of nothing like any other. let serverContent: string; try { serverContent = localeContent(payload.data, payload.fileFormat, c.locale) ?? emptyLocaleContent(payload.data, payload.fileFormat); } catch (error) { const relativePath = getRelative(c.outputPath); const reason = `The downloaded ${c.locale} translation could not be read (${ error instanceof Error ? error.message : String(error) })`; logger.warn(`Skipping local edits to ${relativePath}: ${reason}`); recordWarning('skipped_file', relativePath, reason); continue; } const serverBytes = contentBytes(serverContent, payload.fileFormat); try { // Read the local file the same way the pipeline read it originally, so // a file stored differently on disk than the server's copy is compared // as content rather than as bytes. Otherwise every such file would read // as edited on every run. Then cut to this locale's share, so a file // that holds every locale is compared slice to slice. const local = localeContent( readFileContent(c.outputPath, c.fileFormat), c.fileFormat, c.locale ); // A catalog that no longer carries the locale has nothing to submit if (local === undefined) continue; const localBytes = contentBytes(local, c.fileFormat); // Nothing was edited, so there is no diff to compute or report. if (localBytes.equals(serverBytes)) continue; // A unified diff and localContent are both UTF-8 text, and every text // format's content is UTF-8 by the time it reaches here. Only a binary // format's bytes — a Lottie zip — have no text form at all. Say so: // the edit is real and will be lost on the next download. if (isBinaryFileFormat(c.fileFormat)) { const relativePath = getRelative(c.outputPath); const reason = 'Edited file is a binary format, so its changes cannot be submitted'; logger.warn(`Skipping local edits to ${relativePath}: ${reason}`); recordWarning('skipped_file', relativePath, reason); continue; } const safeName = Buffer.from( `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}` ) .toString('base64') .replace(/=+$/g, ''); const tempServerFile = path.join(tempDir, `${safeName}.server`); await fs.promises.writeFile(tempServerFile, serverBytes); // git diff reads bytes, so both sides are written from the content // they represent rather than diffing the file as it sits on disk. const tempLocalFile = path.join(tempDir, `${safeName}.local`); await fs.promises.writeFile(tempLocalFile, localBytes); const diff = await getGitUnifiedDiff(tempServerFile, tempLocalFile); for (const tempFile of [tempServerFile, tempLocalFile]) { try { await fs.promises.unlink(tempFile); } catch { // Ignore cleanup errors for temporary comparison files. } } if (diff && diff.trim().length > 0) { const rawLocalContent = localBytes.toString('utf8'); // For JSON files with jsonSchema config, extract to composite format let localContent = rawLocalContent; if ( c.fileName.endsWith('.json') && settings.options?.jsonSchema && c.locale !== settings.defaultLocale ) { const resolvedLocal = resolveLocalRefs( rawLocalContent, c.outputPath, settings ); const extractedContent = extractJson( resolvedLocal.content, c.fileName, settings.options, c.locale, settings.defaultLocale ); if (extractedContent) { const extracted = parseJson(extractedContent); // The submitted content replaces the stored translation, so // values missing from it would be erased. const unreadableRefs = unreadableRefsForLocale( resolvedLocal.unreadableRefs, resolvedLocal.content, c.fileName, c.locale, settings ); const reason = unreadableRefs.length > 0 ? `these $ref files could not be read: ${unreadableRefs.map((ref) => ref.refPath).join(', ')}` : !hasLeafValue(extracted) ? 'no translated values for that locale could be read from the file' : undefined; if (reason) { const relativePath = getRelative(c.outputPath); logger.warn( unsavedJsonEditsWarning(relativePath, c.locale, reason) ); recordWarning('skipped_file', relativePath, reason); continue; } if (isDeepStrictEqual(extracted, parseJson(serverContent))) { continue; } localContent = extractedContent; } } else if ( (c.fileName.endsWith('.yaml') || c.fileName.endsWith('.yml')) && settings.options?.yamlSchema && c.locale !== settings.defaultLocale ) { const extractedContent = extractYaml( rawLocalContent, c.fileName, settings.options ); if (extractedContent) { localContent = extractedContent; } } collectedDiffs.push({ fileName: c.fileName, locale: c.locale, diff, branchId: c.branchId, versionId: c.versionId, fileId: c.fileId, localContent, } satisfies SubmitUserEditDiff); } } catch { // Ignore failures for this file } } } if (collectedDiffs.length > 0) { await api.submitUserEditDiffs({ diffs: collectedDiffs }); } return collectedDiffs.length > 0; }