gt 2.28.0 → 2.28.2

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 CHANGED
@@ -1,5 +1,22 @@
1
1
  # gtx-cli
2
2
 
3
+ ## 2.28.2
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [[`7aae545`](https://github.com/generaltranslation/gt/commit/7aae545bd9e65148b8cbf98a4df3ce750ab1cdbf)]:
8
+ - @generaltranslation/format@0.1.10
9
+ - generaltranslation@9.5.12
10
+ - @generaltranslation/vue-extractor@0.1.26
11
+ - @generaltranslation/python-extractor@0.2.67
12
+ - @generaltranslation/supported-locales@2.1.48
13
+
14
+ ## 2.28.1
15
+
16
+ ### Patch Changes
17
+
18
+ - [#2707](https://github.com/generaltranslation/gt/pull/2707) [`691493b`](https://github.com/generaltranslation/gt/commit/691493b9f75b10bcafc2fe50e0361a68b76ebd45) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - fix(cli): stop `--save-local` from replacing a Mintlify `docs.json` translation with an empty one when its languages are split into `$ref` files
19
+
3
20
  ## 2.28.0
4
21
 
5
22
  ### Minor Changes
@@ -3,19 +3,81 @@ import { hashStringSync } from "../utils/hash.js";
3
3
  import { getRelative } from "../fs/findFilepath.js";
4
4
  import { api } from "../utils/api.js";
5
5
  import { readFileContent } from "../fs/fileContent.js";
6
+ import { getJSONPathMatches } from "../formats/json/jsonPath.js";
7
+ import { findMatchingItemArray, findMatchingItemObject, generateSourceObjectPointers, validateJsonSchema } from "../formats/json/utils.js";
6
8
  import { extractJson } from "../formats/json/extractJson.js";
7
9
  import { recordWarning } from "../state/translateWarnings.js";
8
10
  import { readLockfile } from "../fs/config/downloadedVersions.js";
9
11
  import { createFileMapping } from "../formats/files/fileMapping.js";
12
+ import { resolveMintlifyRefs, shouldResolveRefs } from "../utils/resolveMintlifyRefs.js";
10
13
  import { getGitUnifiedDiff } from "../utils/gitDiff.js";
11
14
  import { emptyLocaleContent, localeContent } from "../formats/files/localeContent.js";
12
15
  import { extractYaml } from "../formats/yaml/extractYaml.js";
13
16
  import { randomUUID } from "node:crypto";
17
+ import { isDeepStrictEqual } from "node:util";
14
18
  import * as path$1 from "node:path";
15
19
  import * as fs$1 from "node:fs";
20
+ import { createDiagnosticMessage } from "generaltranslation/diagnostics";
16
21
  import os from "node:os";
17
22
  import { isBinaryFileFormat } from "generaltranslation/types";
18
23
  //#region src/api/collectUserEditDiffs.ts
24
+ const unsavedJsonEditsWarning = (relativePath, locale, reason) => createDiagnosticMessage({
25
+ source: "gt",
26
+ severity: "Warning",
27
+ whatHappened: `Local edits to ${relativePath} were not saved for ${locale}`,
28
+ why: reason,
29
+ reassurance: "The stored translation was left unchanged"
30
+ });
31
+ const resolveLocalRefs = (content, outputPath, settings) => {
32
+ if (!shouldResolveRefs(outputPath, settings.options)) return {
33
+ content,
34
+ unreadableRefs: []
35
+ };
36
+ try {
37
+ const { resolved, unreadableRefs } = resolveMintlifyRefs(JSON.parse(content), outputPath);
38
+ return {
39
+ content: JSON.stringify(resolved, null, 2),
40
+ unreadableRefs
41
+ };
42
+ } catch {
43
+ return {
44
+ content,
45
+ unreadableRefs: []
46
+ };
47
+ }
48
+ };
49
+ /**
50
+ * The unreadable refs that could hold values of the locale: all of them,
51
+ * except those inside an entry of a composite file known to belong to another
52
+ * locale.
53
+ */
54
+ const unreadableRefsForLocale = (unreadableRefs, resolvedContent, fileName, locale, settings) => {
55
+ if (unreadableRefs.length === 0) return [];
56
+ const composite = validateJsonSchema(settings.options ?? {}, fileName)?.composite;
57
+ const json = parseJson(resolvedContent);
58
+ if (!composite || json === void 0) return unreadableRefs;
59
+ const localeKey = settings.options?.experimentalCanonicalLocaleKeys ? api.resolveCanonicalLocale(locale) : locale;
60
+ const otherLocalePointers = [];
61
+ for (const [pointer, { sourceObjectValue, sourceObjectOptions }] of Object.entries(generateSourceObjectPointers(composite, json))) if (sourceObjectOptions.type === "array") {
62
+ if (!Array.isArray(sourceObjectValue)) continue;
63
+ const ownItems = findMatchingItemArray(localeKey, sourceObjectOptions, pointer, sourceObjectValue);
64
+ sourceObjectValue.forEach((item, index) => {
65
+ if (!!sourceObjectOptions.key && (getJSONPathMatches(item, sourceObjectOptions.key)?.length ?? 0) > 0 && !(`/${index}` in ownItems)) otherLocalePointers.push(`${pointer}/${index}`);
66
+ });
67
+ } else if (sourceObjectValue && typeof sourceObjectValue === "object") {
68
+ const { keyParentProperty } = findMatchingItemObject(localeKey, pointer, sourceObjectOptions, sourceObjectValue);
69
+ for (const key of Object.keys(sourceObjectValue)) if (key !== keyParentProperty) otherLocalePointers.push(`${pointer}/${key}`);
70
+ }
71
+ return unreadableRefs.filter((ref) => !otherLocalePointers.some((pointer) => ref.pointer === pointer || ref.pointer.startsWith(`${pointer}/`)));
72
+ };
73
+ const hasLeafValue = (value) => value !== null && typeof value === "object" ? Object.values(value).some(hasLeafValue) : value !== void 0;
74
+ const parseJson = (content) => {
75
+ try {
76
+ return JSON.parse(content);
77
+ } catch {
78
+ return;
79
+ }
80
+ };
19
81
  /**
20
82
  * The bytes a file's pipeline content stands for: binary formats carry base64,
21
83
  * everything else carries UTF-8 text. Applied to both sides of the comparison
@@ -134,8 +196,21 @@ async function collectAndSendUserEditDiffs(files, settings) {
134
196
  const rawLocalContent = localBytes.toString("utf8");
135
197
  let localContent = rawLocalContent;
136
198
  if (c.fileName.endsWith(".json") && settings.options?.jsonSchema && c.locale !== settings.defaultLocale) {
137
- const extractedContent = extractJson(rawLocalContent, c.fileName, settings.options, c.locale, settings.defaultLocale);
138
- if (extractedContent) localContent = extractedContent;
199
+ const resolvedLocal = resolveLocalRefs(rawLocalContent, c.outputPath, settings);
200
+ const extractedContent = extractJson(resolvedLocal.content, c.fileName, settings.options, c.locale, settings.defaultLocale);
201
+ if (extractedContent) {
202
+ const extracted = parseJson(extractedContent);
203
+ const unreadableRefs = unreadableRefsForLocale(resolvedLocal.unreadableRefs, resolvedLocal.content, c.fileName, c.locale, settings);
204
+ 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" : void 0;
205
+ if (reason) {
206
+ const relativePath = getRelative(c.outputPath);
207
+ logger.warn(unsavedJsonEditsWarning(relativePath, c.locale, reason));
208
+ recordWarning("skipped_file", relativePath, reason);
209
+ continue;
210
+ }
211
+ if (isDeepStrictEqual(extracted, parseJson(serverContent))) continue;
212
+ localContent = extractedContent;
213
+ }
139
214
  } else if ((c.fileName.endsWith(".yaml") || c.fileName.endsWith(".yml")) && settings.options?.yamlSchema && c.locale !== settings.defaultLocale) {
140
215
  const extractedContent = extractYaml(rawLocalContent, c.fileName, settings.options);
141
216
  if (extractedContent) localContent = extractedContent;
@@ -1 +1 @@
1
- {"version":3,"file":"collectUserEditDiffs.js","names":["path","fs"],"sources":["../../src/api/collectUserEditDiffs.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport {\n readLockfile,\n EntryMap,\n DownloadedTranslation,\n} from '../fs/config/downloadedVersions.js';\nimport { Settings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport { getGitUnifiedDiff } from '../utils/gitDiff.js';\nimport { api } from '../utils/api.js';\nimport {\n FileReference,\n isBinaryFileFormat,\n SubmitUserEditDiff,\n type FileFormat,\n} from 'generaltranslation/types';\nimport { readFileContent } from '../fs/fileContent.js';\nimport os from 'node:os';\nimport { randomUUID } from 'node:crypto';\nimport { hashStringSync } from '../utils/hash.js';\nimport { extractJson } from '../formats/json/extractJson.js';\nimport {\n emptyLocaleContent,\n localeContent,\n} from '../formats/files/localeContent.js';\nimport { extractYaml } from '../formats/yaml/extractYaml.js';\nimport { logger } from '../console/logger.js';\nimport { recordWarning } from '../state/translateWarnings.js';\nimport { getRelative } from '../fs/findFilepath.js';\n\ntype LatestDownloadedVersion = {\n versionId: string;\n entry: DownloadedTranslation;\n};\n\n/**\n * The bytes a file's pipeline content stands for: binary formats carry base64,\n * everything else carries UTF-8 text. Applied to both sides of the comparison\n * so they are measured the same way.\n */\nconst contentBytes = (content: string, fileFormat: FileFormat): Buffer =>\n isBinaryFileFormat(fileFormat)\n ? Buffer.from(content, 'base64')\n : Buffer.from(content, 'utf8');\n\nconst findLatestDownloadedVersion = (\n entryMap: EntryMap,\n fileId: string,\n locale: string\n): LatestDownloadedVersion | null => {\n const entry = entryMap.get(fileId);\n if (!entry) return null;\n\n const translation = entry.translations[locale];\n if (!translation) return null;\n\n return { versionId: entry.versionId, entry: translation };\n};\n\n/**\n * Collects local user edits by diffing the latest downloaded server translation version\n * against the current local translation file, and submits the diffs upstream.\n * A file that holds every locale is compared one locale slice at a time, so an\n * edit to one locale is submitted under that locale alone.\n *\n * Must run before enqueueing new translations so rules are available to the generator.\n */\nexport async function collectAndSendUserEditDiffs(\n files: FileReference[],\n settings: Settings\n): Promise<boolean> {\n if (!settings.files) return false;\n\n const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } =\n settings.files;\n const fileMapping = createFileMapping(\n resolvedPaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n const { entryMap } = readLockfile(settings);\n\n const tempDir = path.join(os.tmpdir(), randomUUID());\n if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });\n\n // Build candidates for diff and batch-fetch server contents\n type DiffCandidate = {\n branchId: string;\n fileName: string;\n fileId: string;\n versionId: string;\n locale: string; // resolved\n outputPath: string;\n fileFormat: FileFormat;\n };\n const candidates: DiffCandidate[] = [];\n\n for (const uploadedFile of files) {\n for (const locale of settings.locales) {\n const outputPath = fileMapping[locale]?.[uploadedFile.fileName] ?? null;\n if (!outputPath) continue;\n if (!fs.existsSync(outputPath)) continue;\n\n const latestDownloaded = findLatestDownloadedVersion(\n entryMap,\n uploadedFile.fileId,\n locale\n );\n\n if (!latestDownloaded) continue;\n const downloadedVersion = latestDownloaded.entry;\n\n // Skip if the locale's local content matches the last recorded hash\n if (downloadedVersion.postProcessHash) {\n try {\n // Hashed from the locale's share of the pipeline content, which is\n // what was recorded, so an untouched locale matches regardless of\n // the file's encoding or of edits to its other locales.\n const localFile = readFileContent(\n outputPath,\n uploadedFile.fileFormat\n );\n const localHash = hashStringSync(\n localeContent(localFile, uploadedFile.fileFormat, locale) ??\n emptyLocaleContent(localFile, uploadedFile.fileFormat)\n );\n if (localHash === downloadedVersion.postProcessHash) {\n continue;\n }\n } catch {\n // If hash check fails, fall through to diff\n }\n }\n\n candidates.push({\n branchId: uploadedFile.branchId,\n fileName: uploadedFile.fileName,\n fileId: uploadedFile.fileId,\n versionId: latestDownloaded.versionId,\n locale: locale,\n outputPath,\n fileFormat: uploadedFile.fileFormat,\n });\n }\n }\n\n const collectedDiffs: SubmitUserEditDiff[] = [];\n\n if (candidates.length > 0) {\n const fileQueryData = candidates.map((c) => ({\n versionId: c.versionId,\n locale: c.locale,\n fileId: c.fileId,\n branchId: c.branchId,\n }));\n\n // Single batched check to obtain translation IDs\n const checkResponse = await api.queryFileData({\n translatedFiles: fileQueryData,\n });\n const translatedFiles =\n checkResponse.translatedFiles?.filter((t) => t.completedAt) ?? [];\n\n // The server's copy of each candidate, keyed like the candidates\n type ServerPayload = { data: string; fileFormat: FileFormat };\n const serverPayloadByKey = new Map<string, ServerPayload>();\n try {\n const resp = await api.downloadFileBatch(\n translatedFiles.map((file) => ({\n branchId: file.branchId,\n fileId: file.fileId,\n locale: file.locale,\n versionId: file.versionId,\n }))\n );\n for (const f of resp?.files || []) {\n if (!f.locale) continue;\n serverPayloadByKey.set(\n `${f.branchId}:${f.fileId}:${f.versionId}:${f.locale}`,\n { data: f.data, fileFormat: f.fileFormat }\n );\n }\n } catch {\n // Ignore chunk failures; proceed with what we have\n }\n\n // Compute diffs using fetched server contents\n for (const c of candidates) {\n const key = `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`;\n const payload = serverPayloadByKey.get(key);\n // Absent means the batch did not return this file, so there is no\n // baseline. An empty payload is a baseline of nothing, which the user\n // may well have written against.\n if (!payload) continue;\n\n // The locale's share of the payload, read on its own so a payload the\n // server sent malformed costs only its own locale. A catalog payload\n // that carries nothing for the locale is that file's empty payload, and\n // a baseline of nothing like any other.\n let serverContent: string;\n try {\n serverContent =\n localeContent(payload.data, payload.fileFormat, c.locale) ??\n emptyLocaleContent(payload.data, payload.fileFormat);\n } catch (error) {\n const relativePath = getRelative(c.outputPath);\n const reason = `The downloaded ${c.locale} translation could not be read (${\n error instanceof Error ? error.message : String(error)\n })`;\n logger.warn(`Skipping local edits to ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n const serverBytes = contentBytes(serverContent, payload.fileFormat);\n\n try {\n // Read the local file the same way the pipeline read it originally, so\n // a file stored differently on disk than the server's copy is compared\n // as content rather than as bytes. Otherwise every such file would read\n // as edited on every run. Then cut to this locale's share, so a file\n // that holds every locale is compared slice to slice.\n const local = localeContent(\n readFileContent(c.outputPath, c.fileFormat),\n c.fileFormat,\n c.locale\n );\n // A catalog that no longer carries the locale has nothing to submit\n if (local === undefined) continue;\n const localBytes = contentBytes(local, c.fileFormat);\n\n // Nothing was edited, so there is no diff to compute or report.\n if (localBytes.equals(serverBytes)) continue;\n\n // A unified diff and localContent are both UTF-8 text, and every text\n // format's content is UTF-8 by the time it reaches here. Only a binary\n // format's bytes — a Lottie zip — have no text form at all. Say so:\n // the edit is real and will be lost on the next download.\n if (isBinaryFileFormat(c.fileFormat)) {\n const relativePath = getRelative(c.outputPath);\n const reason =\n 'Edited file is a binary format, so its changes cannot be submitted';\n logger.warn(`Skipping local edits to ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n\n const safeName = Buffer.from(\n `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`\n )\n .toString('base64')\n .replace(/=+$/g, '');\n const tempServerFile = path.join(tempDir, `${safeName}.server`);\n await fs.promises.writeFile(tempServerFile, serverBytes);\n\n // git diff reads bytes, so both sides are written from the content\n // they represent rather than diffing the file as it sits on disk.\n const tempLocalFile = path.join(tempDir, `${safeName}.local`);\n await fs.promises.writeFile(tempLocalFile, localBytes);\n\n const diff = await getGitUnifiedDiff(tempServerFile, tempLocalFile);\n for (const tempFile of [tempServerFile, tempLocalFile]) {\n try {\n await fs.promises.unlink(tempFile);\n } catch {\n // Ignore cleanup errors for temporary comparison files.\n }\n }\n\n if (diff && diff.trim().length > 0) {\n const rawLocalContent = localBytes.toString('utf8');\n\n // For JSON files with jsonSchema config, extract to composite format\n let localContent = rawLocalContent;\n if (\n c.fileName.endsWith('.json') &&\n settings.options?.jsonSchema &&\n c.locale !== settings.defaultLocale\n ) {\n const extractedContent = extractJson(\n rawLocalContent,\n c.fileName,\n settings.options,\n c.locale,\n settings.defaultLocale\n );\n if (extractedContent) {\n localContent = extractedContent;\n }\n } else if (\n (c.fileName.endsWith('.yaml') || c.fileName.endsWith('.yml')) &&\n settings.options?.yamlSchema &&\n c.locale !== settings.defaultLocale\n ) {\n const extractedContent = extractYaml(\n rawLocalContent,\n c.fileName,\n settings.options\n );\n if (extractedContent) {\n localContent = extractedContent;\n }\n }\n\n collectedDiffs.push({\n fileName: c.fileName,\n locale: c.locale,\n diff,\n branchId: c.branchId,\n versionId: c.versionId,\n fileId: c.fileId,\n localContent,\n } satisfies SubmitUserEditDiff);\n }\n } catch {\n // Ignore failures for this file\n }\n }\n }\n\n if (collectedDiffs.length > 0) {\n await api.submitUserEditDiffs({ diffs: collectedDiffs });\n }\n\n return collectedDiffs.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAyCA,MAAM,gBAAgB,SAAiB,eACrC,mBAAmB,WAAW,GAC1B,OAAO,KAAK,SAAS,SAAS,GAC9B,OAAO,KAAK,SAAS,OAAO;AAElC,MAAM,+BACJ,UACA,QACA,WACmC;CACnC,MAAM,QAAQ,SAAS,IAAI,OAAO;AAClC,KAAI,CAAC,MAAO,Q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E,WAAW,SAAS,eACtB;MACA,MAAM,mBAAmB,YACvB,iBACA,EAAE,UACF,SAAS,QACV;AACD,UAAI,iBACF,gBAAe;;AAInB,oBAAe,KAAK;MAClB,UAAU,EAAE;MACZ,QAAQ,EAAE;MACV;MACA,UAAU,EAAE;MACZ,WAAW,EAAE;MACb,QAAQ,EAAE;MACV;MACD,CAA8B;;WAE3B;;;AAMZ,KAAI,eAAe,SAAS,EAC1B,OAAM,IAAI,oBAAoB,EAAE,OAAO,gBAAgB,CAAC;AAG1D,QAAO,eAAe,SAAS"}
1
+ {"version":3,"file":"collectUserEditDiffs.js","names":["path","fs"],"sources":["../../src/api/collectUserEditDiffs.ts"],"sourcesContent":["import * as fs from 'node:fs';\nimport * as path from 'node:path';\nimport {\n readLockfile,\n EntryMap,\n DownloadedTranslation,\n} from '../fs/config/downloadedVersions.js';\nimport { Settings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport { getGitUnifiedDiff } from '../utils/gitDiff.js';\nimport { api } from '../utils/api.js';\nimport {\n FileReference,\n isBinaryFileFormat,\n SubmitUserEditDiff,\n type FileFormat,\n} from 'generaltranslation/types';\nimport { readFileContent } from '../fs/fileContent.js';\nimport os from 'node:os';\nimport { randomUUID } from 'node:crypto';\nimport { hashStringSync } from '../utils/hash.js';\nimport { extractJson } from '../formats/json/extractJson.js';\nimport {\n emptyLocaleContent,\n localeContent,\n} from '../formats/files/localeContent.js';\nimport { extractYaml } from '../formats/yaml/extractYaml.js';\nimport { logger } from '../console/logger.js';\nimport { recordWarning } from '../state/translateWarnings.js';\nimport { getRelative } from '../fs/findFilepath.js';\nimport {\n resolveMintlifyRefs,\n shouldResolveRefs,\n type UnreadableRef,\n} from '../utils/resolveMintlifyRefs.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n validateJsonSchema,\n} from '../formats/json/utils.js';\nimport type { JSONObject, JSONValue } from '../types/data/json.js';\nimport { getJSONPathMatches } from '../formats/json/jsonPath.js';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { isDeepStrictEqual } from 'node:util';\n\nconst unsavedJsonEditsWarning = (\n relativePath: string,\n locale: string,\n reason: string\n) =>\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `Local edits to ${relativePath} were not saved for ${locale}`,\n why: reason,\n reassurance: 'The stored translation was left unchanged',\n });\n\nconst resolveLocalRefs = (\n content: string,\n outputPath: string,\n settings: Settings\n): { content: string; unreadableRefs: UnreadableRef[] } => {\n if (!shouldResolveRefs(outputPath, settings.options)) {\n return { content, unreadableRefs: [] };\n }\n try {\n const { resolved, unreadableRefs } = resolveMintlifyRefs(\n JSON.parse(content),\n outputPath\n );\n return { content: JSON.stringify(resolved, null, 2), unreadableRefs };\n } catch {\n return { content, unreadableRefs: [] };\n }\n};\n\n/**\n * The unreadable refs that could hold values of the locale: all of them,\n * except those inside an entry of a composite file known to belong to another\n * locale.\n */\nconst unreadableRefsForLocale = (\n unreadableRefs: UnreadableRef[],\n resolvedContent: string,\n fileName: string,\n locale: string,\n settings: Settings\n): UnreadableRef[] => {\n if (unreadableRefs.length === 0) return [];\n const composite = validateJsonSchema(\n settings.options ?? {},\n fileName\n )?.composite;\n const json = parseJson(resolvedContent) as JSONValue | undefined;\n if (!composite || json === undefined) return unreadableRefs;\n\n const localeKey = settings.options?.experimentalCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(locale)\n : locale;\n const otherLocalePointers: string[] = [];\n for (const [\n pointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(generateSourceObjectPointers(composite, json))) {\n if (sourceObjectOptions.type === 'array') {\n if (!Array.isArray(sourceObjectValue)) continue;\n const ownItems = findMatchingItemArray(\n localeKey,\n sourceObjectOptions,\n pointer,\n sourceObjectValue\n );\n sourceObjectValue.forEach((item, index) => {\n // An entry whose locale key sat in the unreadable file has no key\n // left, so it may be the locale's own.\n const hasLocaleKey =\n !!sourceObjectOptions.key &&\n (getJSONPathMatches(item, sourceObjectOptions.key)?.length ?? 0) > 0;\n if (hasLocaleKey && !(`/${index}` in ownItems)) {\n otherLocalePointers.push(`${pointer}/${index}`);\n }\n });\n } else if (sourceObjectValue && typeof sourceObjectValue === 'object') {\n const { keyParentProperty } = findMatchingItemObject(\n localeKey,\n pointer,\n sourceObjectOptions,\n sourceObjectValue as JSONObject\n );\n for (const key of Object.keys(sourceObjectValue)) {\n if (key !== keyParentProperty) {\n otherLocalePointers.push(`${pointer}/${key}`);\n }\n }\n }\n }\n return unreadableRefs.filter(\n (ref) =>\n !otherLocalePointers.some(\n (pointer) =>\n ref.pointer === pointer || ref.pointer.startsWith(`${pointer}/`)\n )\n );\n};\n\nconst hasLeafValue = (value: unknown): boolean =>\n value !== null && typeof value === 'object'\n ? Object.values(value).some(hasLeafValue)\n : value !== undefined;\n\nconst parseJson = (content: string): unknown => {\n try {\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n};\n\ntype LatestDownloadedVersion = {\n versionId: string;\n entry: DownloadedTranslation;\n};\n\n/**\n * The bytes a file's pipeline content stands for: binary formats carry base64,\n * everything else carries UTF-8 text. Applied to both sides of the comparison\n * so they are measured the same way.\n */\nconst contentBytes = (content: string, fileFormat: FileFormat): Buffer =>\n isBinaryFileFormat(fileFormat)\n ? Buffer.from(content, 'base64')\n : Buffer.from(content, 'utf8');\n\nconst findLatestDownloadedVersion = (\n entryMap: EntryMap,\n fileId: string,\n locale: string\n): LatestDownloadedVersion | null => {\n const entry = entryMap.get(fileId);\n if (!entry) return null;\n\n const translation = entry.translations[locale];\n if (!translation) return null;\n\n return { versionId: entry.versionId, entry: translation };\n};\n\n/**\n * Collects local user edits by diffing the latest downloaded server translation version\n * against the current local translation file, and submits the diffs upstream.\n * A file that holds every locale is compared one locale slice at a time, so an\n * edit to one locale is submitted under that locale alone.\n *\n * Must run before enqueueing new translations so rules are available to the generator.\n */\nexport async function collectAndSendUserEditDiffs(\n files: FileReference[],\n settings: Settings\n): Promise<boolean> {\n if (!settings.files) return false;\n\n const { resolvedPaths, placeholderPaths, transformPaths, transformFormats } =\n settings.files;\n const fileMapping = createFileMapping(\n resolvedPaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n const { entryMap } = readLockfile(settings);\n\n const tempDir = path.join(os.tmpdir(), randomUUID());\n if (!fs.existsSync(tempDir)) fs.mkdirSync(tempDir, { recursive: true });\n\n // Build candidates for diff and batch-fetch server contents\n type DiffCandidate = {\n branchId: string;\n fileName: string;\n fileId: string;\n versionId: string;\n locale: string; // resolved\n outputPath: string;\n fileFormat: FileFormat;\n };\n const candidates: DiffCandidate[] = [];\n\n for (const uploadedFile of files) {\n for (const locale of settings.locales) {\n const outputPath = fileMapping[locale]?.[uploadedFile.fileName] ?? null;\n if (!outputPath) continue;\n if (!fs.existsSync(outputPath)) continue;\n\n const latestDownloaded = findLatestDownloadedVersion(\n entryMap,\n uploadedFile.fileId,\n locale\n );\n\n if (!latestDownloaded) continue;\n const downloadedVersion = latestDownloaded.entry;\n\n // Skip if the locale's local content matches the last recorded hash\n if (downloadedVersion.postProcessHash) {\n try {\n // Hashed from the locale's share of the pipeline content, which is\n // what was recorded, so an untouched locale matches regardless of\n // the file's encoding or of edits to its other locales.\n const localFile = readFileContent(\n outputPath,\n uploadedFile.fileFormat\n );\n const localHash = hashStringSync(\n localeContent(localFile, uploadedFile.fileFormat, locale) ??\n emptyLocaleContent(localFile, uploadedFile.fileFormat)\n );\n if (localHash === downloadedVersion.postProcessHash) {\n continue;\n }\n } catch {\n // If hash check fails, fall through to diff\n }\n }\n\n candidates.push({\n branchId: uploadedFile.branchId,\n fileName: uploadedFile.fileName,\n fileId: uploadedFile.fileId,\n versionId: latestDownloaded.versionId,\n locale: locale,\n outputPath,\n fileFormat: uploadedFile.fileFormat,\n });\n }\n }\n\n const collectedDiffs: SubmitUserEditDiff[] = [];\n\n if (candidates.length > 0) {\n const fileQueryData = candidates.map((c) => ({\n versionId: c.versionId,\n locale: c.locale,\n fileId: c.fileId,\n branchId: c.branchId,\n }));\n\n // Single batched check to obtain translation IDs\n const checkResponse = await api.queryFileData({\n translatedFiles: fileQueryData,\n });\n const translatedFiles =\n checkResponse.translatedFiles?.filter((t) => t.completedAt) ?? [];\n\n // The server's copy of each candidate, keyed like the candidates\n type ServerPayload = { data: string; fileFormat: FileFormat };\n const serverPayloadByKey = new Map<string, ServerPayload>();\n try {\n const resp = await api.downloadFileBatch(\n translatedFiles.map((file) => ({\n branchId: file.branchId,\n fileId: file.fileId,\n locale: file.locale,\n versionId: file.versionId,\n }))\n );\n for (const f of resp?.files || []) {\n if (!f.locale) continue;\n serverPayloadByKey.set(\n `${f.branchId}:${f.fileId}:${f.versionId}:${f.locale}`,\n { data: f.data, fileFormat: f.fileFormat }\n );\n }\n } catch {\n // Ignore chunk failures; proceed with what we have\n }\n\n // Compute diffs using fetched server contents\n for (const c of candidates) {\n const key = `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`;\n const payload = serverPayloadByKey.get(key);\n // Absent means the batch did not return this file, so there is no\n // baseline. An empty payload is a baseline of nothing, which the user\n // may well have written against.\n if (!payload) continue;\n\n // The locale's share of the payload, read on its own so a payload the\n // server sent malformed costs only its own locale. A catalog payload\n // that carries nothing for the locale is that file's empty payload, and\n // a baseline of nothing like any other.\n let serverContent: string;\n try {\n serverContent =\n localeContent(payload.data, payload.fileFormat, c.locale) ??\n emptyLocaleContent(payload.data, payload.fileFormat);\n } catch (error) {\n const relativePath = getRelative(c.outputPath);\n const reason = `The downloaded ${c.locale} translation could not be read (${\n error instanceof Error ? error.message : String(error)\n })`;\n logger.warn(`Skipping local edits to ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n const serverBytes = contentBytes(serverContent, payload.fileFormat);\n\n try {\n // Read the local file the same way the pipeline read it originally, so\n // a file stored differently on disk than the server's copy is compared\n // as content rather than as bytes. Otherwise every such file would read\n // as edited on every run. Then cut to this locale's share, so a file\n // that holds every locale is compared slice to slice.\n const local = localeContent(\n readFileContent(c.outputPath, c.fileFormat),\n c.fileFormat,\n c.locale\n );\n // A catalog that no longer carries the locale has nothing to submit\n if (local === undefined) continue;\n const localBytes = contentBytes(local, c.fileFormat);\n\n // Nothing was edited, so there is no diff to compute or report.\n if (localBytes.equals(serverBytes)) continue;\n\n // A unified diff and localContent are both UTF-8 text, and every text\n // format's content is UTF-8 by the time it reaches here. Only a binary\n // format's bytes — a Lottie zip — have no text form at all. Say so:\n // the edit is real and will be lost on the next download.\n if (isBinaryFileFormat(c.fileFormat)) {\n const relativePath = getRelative(c.outputPath);\n const reason =\n 'Edited file is a binary format, so its changes cannot be submitted';\n logger.warn(`Skipping local edits to ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n\n const safeName = Buffer.from(\n `${c.branchId}:${c.fileId}:${c.versionId}:${c.locale}`\n )\n .toString('base64')\n .replace(/=+$/g, '');\n const tempServerFile = path.join(tempDir, `${safeName}.server`);\n await fs.promises.writeFile(tempServerFile, serverBytes);\n\n // git diff reads bytes, so both sides are written from the content\n // they represent rather than diffing the file as it sits on disk.\n const tempLocalFile = path.join(tempDir, `${safeName}.local`);\n await fs.promises.writeFile(tempLocalFile, localBytes);\n\n const diff = await getGitUnifiedDiff(tempServerFile, tempLocalFile);\n for (const tempFile of [tempServerFile, tempLocalFile]) {\n try {\n await fs.promises.unlink(tempFile);\n } catch {\n // Ignore cleanup errors for temporary comparison files.\n }\n }\n\n if (diff && diff.trim().length > 0) {\n const rawLocalContent = localBytes.toString('utf8');\n\n // For JSON files with jsonSchema config, extract to composite format\n let localContent = rawLocalContent;\n if (\n c.fileName.endsWith('.json') &&\n settings.options?.jsonSchema &&\n c.locale !== settings.defaultLocale\n ) {\n const resolvedLocal = resolveLocalRefs(\n rawLocalContent,\n c.outputPath,\n settings\n );\n const extractedContent = extractJson(\n resolvedLocal.content,\n c.fileName,\n settings.options,\n c.locale,\n settings.defaultLocale\n );\n if (extractedContent) {\n const extracted = parseJson(extractedContent);\n // The submitted content replaces the stored translation, so\n // values missing from it would be erased.\n const unreadableRefs = unreadableRefsForLocale(\n resolvedLocal.unreadableRefs,\n resolvedLocal.content,\n c.fileName,\n c.locale,\n settings\n );\n const reason =\n unreadableRefs.length > 0\n ? `these $ref files could not be read: ${unreadableRefs.map((ref) => ref.refPath).join(', ')}`\n : !hasLeafValue(extracted)\n ? 'no translated values for that locale could be read from the file'\n : undefined;\n if (reason) {\n const relativePath = getRelative(c.outputPath);\n logger.warn(\n unsavedJsonEditsWarning(relativePath, c.locale, reason)\n );\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n if (isDeepStrictEqual(extracted, parseJson(serverContent))) {\n continue;\n }\n localContent = extractedContent;\n }\n } else if (\n (c.fileName.endsWith('.yaml') || c.fileName.endsWith('.yml')) &&\n settings.options?.yamlSchema &&\n c.locale !== settings.defaultLocale\n ) {\n const extractedContent = extractYaml(\n rawLocalContent,\n c.fileName,\n settings.options\n );\n if (extractedContent) {\n localContent = extractedContent;\n }\n }\n\n collectedDiffs.push({\n fileName: c.fileName,\n locale: c.locale,\n diff,\n branchId: c.branchId,\n versionId: c.versionId,\n fileId: c.fileId,\n localContent,\n } satisfies SubmitUserEditDiff);\n }\n } catch {\n // Ignore failures for this file\n }\n }\n }\n\n if (collectedDiffs.length > 0) {\n await api.submitUserEditDiffs({ diffs: collectedDiffs });\n }\n\n return collectedDiffs.length > 0;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,2BACJ,cACA,QACA,WAEA,wBAAwB;CACtB,QAAQ;CACR,UAAU;CACV,cAAc,kBAAkB,aAAa,sBAAsB;CACnE,KAAK;CACL,aAAa;CACd,CAAC;AAEJ,MAAM,oBACJ,SACA,YACA,aACyD;AACzD,KAAI,CAAC,kBAAkB,YAAY,SAAS,QAAQ,CAClD,QAAO;EAAE;EAAS,gBAAgB,EAAE;EAAE;AAExC,KAAI;EACF,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AAE,OAAO,gBAAgB,CAAC;AAG1D,QAAO,eAAe,SAAS"}
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.28.0";
1
+ export declare const PACKAGE_VERSION = "2.28.2";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.28.0";
2
+ const PACKAGE_VERSION = "2.28.2";
3
3
  //#endregion
4
4
  export { PACKAGE_VERSION };
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.28.0';\n"],"mappings":";AACA,MAAa,kBAAkB"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.28.2';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -6,9 +6,14 @@ export type RefMapEntry = {
6
6
  siblings?: Record<string, unknown>;
7
7
  };
8
8
  export type RefMap = Map<string, RefMapEntry>;
9
+ export type UnreadableRef = {
10
+ refPath: string;
11
+ pointer: string;
12
+ };
9
13
  export type ResolvedRefs = {
10
14
  resolved: unknown;
11
15
  refMap: RefMap;
16
+ unreadableRefs: UnreadableRef[];
12
17
  };
13
18
  /**
14
19
  * Resolve all Mintlify $ref references in a parsed JSON object.
@@ -13,21 +13,23 @@ import micromatch from "micromatch";
13
13
  */
14
14
  function resolveMintlifyRefs(json, filePath) {
15
15
  const refMap = /* @__PURE__ */ new Map();
16
+ const unreadableRefs = [];
16
17
  return {
17
- resolved: resolveNode(json, path.dirname(path.resolve(filePath)), "", /* @__PURE__ */ new Set(), refMap),
18
- refMap
18
+ resolved: resolveNode(json, path.dirname(path.resolve(filePath)), "", /* @__PURE__ */ new Set(), refMap, unreadableRefs),
19
+ refMap,
20
+ unreadableRefs
19
21
  };
20
22
  }
21
- function resolveNode(node, baseDir, pointer, visiting, refMap) {
23
+ function resolveNode(node, baseDir, pointer, visiting, refMap, unreadableRefs) {
22
24
  if (node === null || typeof node !== "object") return node;
23
- if (Array.isArray(node)) return node.map((item, i) => resolveNode(item, baseDir, `${pointer}/${i}`, visiting, refMap));
25
+ if (Array.isArray(node)) return node.map((item, i) => resolveNode(item, baseDir, `${pointer}/${i}`, visiting, refMap, unreadableRefs));
24
26
  const obj = node;
25
- if (typeof obj["$ref"] === "string") return resolveRef(obj, baseDir, pointer, visiting, refMap);
27
+ if (typeof obj["$ref"] === "string") return resolveRef(obj, baseDir, pointer, visiting, refMap, unreadableRefs);
26
28
  const result = {};
27
- for (const [key, value] of Object.entries(obj)) result[key] = resolveNode(value, baseDir, `${pointer}/${key}`, visiting, refMap);
29
+ for (const [key, value] of Object.entries(obj)) result[key] = resolveNode(value, baseDir, `${pointer}/${key}`, visiting, refMap, unreadableRefs);
28
30
  return result;
29
31
  }
30
- function resolveRef(obj, baseDir, pointer, visiting, refMap) {
32
+ function resolveRef(obj, baseDir, pointer, visiting, refMap, unreadableRefs) {
31
33
  const refPath = obj["$ref"];
32
34
  if (!isRelativePath(refPath)) {
33
35
  logger.warn(chalk.yellow(`Skipping non-relative $ref at ${pointer || "/"}: ${refPath}`));
@@ -37,11 +39,19 @@ function resolveRef(obj, baseDir, pointer, visiting, refMap) {
37
39
  const resolvedFilePath = path.resolve(baseDir, refPath);
38
40
  if (visiting.has(resolvedFilePath)) {
39
41
  logger.warn(chalk.yellow(`Circular $ref detected at ${pointer || "/"}: ${refPath}`));
42
+ unreadableRefs.push({
43
+ refPath,
44
+ pointer
45
+ });
40
46
  const { $ref: _, ...rest } = obj;
41
47
  return rest;
42
48
  }
43
49
  if (!fs.existsSync(resolvedFilePath)) {
44
50
  logger.warn(chalk.yellow(`$ref file not found at ${pointer || "/"}: ${refPath} (resolved to ${resolvedFilePath})`));
51
+ unreadableRefs.push({
52
+ refPath,
53
+ pointer
54
+ });
45
55
  const { $ref: _, ...rest } = obj;
46
56
  return rest;
47
57
  }
@@ -50,6 +60,10 @@ function resolveRef(obj, baseDir, pointer, visiting, refMap) {
50
60
  fileContent = fs.readFileSync(resolvedFilePath, "utf-8");
51
61
  } catch {
52
62
  logger.warn(chalk.yellow(`Failed to read $ref file: ${resolvedFilePath}`));
63
+ unreadableRefs.push({
64
+ refPath,
65
+ pointer
66
+ });
53
67
  const { $ref: _, ...rest } = obj;
54
68
  return rest;
55
69
  }
@@ -58,6 +72,10 @@ function resolveRef(obj, baseDir, pointer, visiting, refMap) {
58
72
  parsed = JSON.parse(fileContent);
59
73
  } catch {
60
74
  logger.warn(chalk.yellow(`$ref file is not valid JSON: ${resolvedFilePath}`));
75
+ unreadableRefs.push({
76
+ refPath,
77
+ pointer
78
+ });
61
79
  const { $ref: _, ...rest } = obj;
62
80
  return rest;
63
81
  }
@@ -72,7 +90,7 @@ function resolveRef(obj, baseDir, pointer, visiting, refMap) {
72
90
  const refFileDir = path.dirname(resolvedFilePath);
73
91
  const nextVisiting = new Set(visiting);
74
92
  nextVisiting.add(resolvedFilePath);
75
- const resolvedContent = resolveNode(parsed, refFileDir, pointer, nextVisiting, refMap);
93
+ const resolvedContent = resolveNode(parsed, refFileDir, pointer, nextVisiting, refMap, unreadableRefs);
76
94
  if (resolvedContent !== null && typeof resolvedContent === "object" && !Array.isArray(resolvedContent)) return {
77
95
  ...resolvedContent,
78
96
  ...siblings
@@ -1 +1 @@
1
- {"version":3,"file":"resolveMintlifyRefs.js","names":["jsonSchema"],"sources":["../../src/utils/resolveMintlifyRefs.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport chalk from 'chalk';\nimport micromatch from 'micromatch';\n\nexport type RefMapEntry = {\n sourceFile: string;\n refPath: string;\n containingDir: string;\n originalContent: unknown;\n siblings?: Record<string, unknown>;\n};\n\nexport type RefMap = Map<string, RefMapEntry>;\n\nexport type ResolvedRefs = {\n resolved: unknown;\n refMap: RefMap;\n};\n\n/**\n * Resolve all Mintlify $ref references in a parsed JSON object.\n *\n * Returns the fully-expanded JSON and a refMap that tracks which subtrees\n * came from which files (used later to split translated output back into\n * the same file topology).\n */\nexport function resolveMintlifyRefs(\n json: unknown,\n filePath: string\n): ResolvedRefs {\n const refMap: RefMap = new Map();\n const resolved = resolveNode(\n json,\n path.dirname(path.resolve(filePath)),\n '',\n new Set<string>(),\n refMap\n );\n return { resolved, refMap };\n}\n\nfunction resolveNode(\n node: unknown,\n baseDir: string,\n pointer: string,\n visiting: Set<string>,\n refMap: RefMap\n): unknown {\n if (node === null || typeof node !== 'object') return node;\n\n if (Array.isArray(node)) {\n return node.map((item, i) =>\n resolveNode(item, baseDir, `${pointer}/${i}`, visiting, refMap)\n );\n }\n\n const obj = node as Record<string, unknown>;\n\n if (typeof obj['$ref'] === 'string') {\n return resolveRef(obj, baseDir, pointer, visiting, refMap);\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = resolveNode(\n value,\n baseDir,\n `${pointer}/${key}`,\n visiting,\n refMap\n );\n }\n return result;\n}\n\nfunction resolveRef(\n obj: Record<string, unknown>,\n baseDir: string,\n pointer: string,\n visiting: Set<string>,\n refMap: RefMap\n): unknown {\n const refPath = obj['$ref'] as string;\n\n if (!isRelativePath(refPath)) {\n logger.warn(\n chalk.yellow(\n `Skipping non-relative $ref at ${pointer || '/'}: ${refPath}`\n )\n );\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n const resolvedFilePath = path.resolve(baseDir, refPath);\n\n if (visiting.has(resolvedFilePath)) {\n logger.warn(\n chalk.yellow(`Circular $ref detected at ${pointer || '/'}: ${refPath}`)\n );\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n if (!fs.existsSync(resolvedFilePath)) {\n logger.warn(\n chalk.yellow(\n `$ref file not found at ${pointer || '/'}: ${refPath} (resolved to ${resolvedFilePath})`\n )\n );\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n let fileContent: string;\n try {\n fileContent = fs.readFileSync(resolvedFilePath, 'utf-8');\n } catch {\n logger.warn(chalk.yellow(`Failed to read $ref file: ${resolvedFilePath}`));\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fileContent);\n } catch {\n logger.warn(\n chalk.yellow(`$ref file is not valid JSON: ${resolvedFilePath}`)\n );\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n const { $ref: _, ...siblings } = obj;\n\n // Record provenance before recursive resolution\n refMap.set(pointer, {\n sourceFile: resolvedFilePath,\n refPath,\n containingDir: baseDir,\n originalContent: parsed,\n siblings,\n });\n\n // Recursively resolve nested $ref in the referenced file\n const refFileDir = path.dirname(resolvedFilePath);\n const nextVisiting = new Set(visiting);\n nextVisiting.add(resolvedFilePath);\n\n const resolvedContent = resolveNode(\n parsed,\n refFileDir,\n pointer,\n nextVisiting,\n refMap\n );\n\n // Apply Mintlify merge rules\n if (\n resolvedContent !== null &&\n typeof resolvedContent === 'object' &&\n !Array.isArray(resolvedContent)\n ) {\n // Object: merge siblings on top (siblings take precedence)\n return { ...(resolvedContent as Record<string, unknown>), ...siblings };\n }\n\n // Non-object (array, string, number, etc.): replace entirely, drop siblings\n return resolvedContent;\n}\n\n/**\n * Check if a file should have $ref resolution applied based on the settings.\n * Returns true if the file matches a jsonSchema entry with resolveRefs: true.\n */\nexport function shouldResolveRefs(\n filePath: string,\n options?: { jsonSchema?: Record<string, unknown> }\n): boolean {\n if (!options?.jsonSchema) return false;\n\n const relative = path.relative(process.cwd(), filePath);\n for (const [glob, schema] of Object.entries(options.jsonSchema)) {\n const jsonSchema = schema as { resolveRefs?: boolean };\n if (jsonSchema.resolveRefs && micromatch.isMatch(relative, glob)) {\n return true;\n }\n }\n return false;\n}\n\nfunction isRelativePath(refPath: string): boolean {\n if (path.isAbsolute(refPath)) return false;\n if (/^[a-z]+:\\/\\//i.test(refPath)) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AA4BA,SAAgB,o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","names":["jsonSchema"],"sources":["../../src/utils/resolveMintlifyRefs.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport chalk from 'chalk';\nimport micromatch from 'micromatch';\n\nexport type RefMapEntry = {\n sourceFile: string;\n refPath: string;\n containingDir: string;\n originalContent: unknown;\n siblings?: Record<string, unknown>;\n};\n\nexport type RefMap = Map<string, RefMapEntry>;\n\nexport type UnreadableRef = { refPath: string; pointer: string };\n\nexport type ResolvedRefs = {\n resolved: unknown;\n refMap: RefMap;\n unreadableRefs: UnreadableRef[];\n};\n\n/**\n * Resolve all Mintlify $ref references in a parsed JSON object.\n *\n * Returns the fully-expanded JSON and a refMap that tracks which subtrees\n * came from which files (used later to split translated output back into\n * the same file topology).\n */\nexport function resolveMintlifyRefs(\n json: unknown,\n filePath: string\n): ResolvedRefs {\n const refMap: RefMap = new Map();\n const unreadableRefs: UnreadableRef[] = [];\n const resolved = resolveNode(\n json,\n path.dirname(path.resolve(filePath)),\n '',\n new Set<string>(),\n refMap,\n unreadableRefs\n );\n return { resolved, refMap, unreadableRefs };\n}\n\nfunction resolveNode(\n node: unknown,\n baseDir: string,\n pointer: string,\n visiting: Set<string>,\n refMap: RefMap,\n unreadableRefs: UnreadableRef[]\n): unknown {\n if (node === null || typeof node !== 'object') return node;\n\n if (Array.isArray(node)) {\n return node.map((item, i) =>\n resolveNode(\n item,\n baseDir,\n `${pointer}/${i}`,\n visiting,\n refMap,\n unreadableRefs\n )\n );\n }\n\n const obj = node as Record<string, unknown>;\n\n if (typeof obj['$ref'] === 'string') {\n return resolveRef(obj, baseDir, pointer, visiting, refMap, unreadableRefs);\n }\n\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n result[key] = resolveNode(\n value,\n baseDir,\n `${pointer}/${key}`,\n visiting,\n refMap,\n unreadableRefs\n );\n }\n return result;\n}\n\nfunction resolveRef(\n obj: Record<string, unknown>,\n baseDir: string,\n pointer: string,\n visiting: Set<string>,\n refMap: RefMap,\n unreadableRefs: UnreadableRef[]\n): unknown {\n const refPath = obj['$ref'] as string;\n\n if (!isRelativePath(refPath)) {\n logger.warn(\n chalk.yellow(\n `Skipping non-relative $ref at ${pointer || '/'}: ${refPath}`\n )\n );\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n const resolvedFilePath = path.resolve(baseDir, refPath);\n\n if (visiting.has(resolvedFilePath)) {\n logger.warn(\n chalk.yellow(`Circular $ref detected at ${pointer || '/'}: ${refPath}`)\n );\n unreadableRefs.push({ refPath, pointer });\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n if (!fs.existsSync(resolvedFilePath)) {\n logger.warn(\n chalk.yellow(\n `$ref file not found at ${pointer || '/'}: ${refPath} (resolved to ${resolvedFilePath})`\n )\n );\n unreadableRefs.push({ refPath, pointer });\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n let fileContent: string;\n try {\n fileContent = fs.readFileSync(resolvedFilePath, 'utf-8');\n } catch {\n logger.warn(chalk.yellow(`Failed to read $ref file: ${resolvedFilePath}`));\n unreadableRefs.push({ refPath, pointer });\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(fileContent);\n } catch {\n logger.warn(\n chalk.yellow(`$ref file is not valid JSON: ${resolvedFilePath}`)\n );\n unreadableRefs.push({ refPath, pointer });\n const { $ref: _, ...rest } = obj;\n return rest;\n }\n\n const { $ref: _, ...siblings } = obj;\n\n // Record provenance before recursive resolution\n refMap.set(pointer, {\n sourceFile: resolvedFilePath,\n refPath,\n containingDir: baseDir,\n originalContent: parsed,\n siblings,\n });\n\n // Recursively resolve nested $ref in the referenced file\n const refFileDir = path.dirname(resolvedFilePath);\n const nextVisiting = new Set(visiting);\n nextVisiting.add(resolvedFilePath);\n\n const resolvedContent = resolveNode(\n parsed,\n refFileDir,\n pointer,\n nextVisiting,\n refMap,\n unreadableRefs\n );\n\n // Apply Mintlify merge rules\n if (\n resolvedContent !== null &&\n typeof resolvedContent === 'object' &&\n !Array.isArray(resolvedContent)\n ) {\n // Object: merge siblings on top (siblings take precedence)\n return { ...(resolvedContent as Record<string, unknown>), ...siblings };\n }\n\n // Non-object (array, string, number, etc.): replace entirely, drop siblings\n return resolvedContent;\n}\n\n/**\n * Check if a file should have $ref resolution applied based on the settings.\n * Returns true if the file matches a jsonSchema entry with resolveRefs: true.\n */\nexport function shouldResolveRefs(\n filePath: string,\n options?: { jsonSchema?: Record<string, unknown> }\n): boolean {\n if (!options?.jsonSchema) return false;\n\n const relative = path.relative(process.cwd(), filePath);\n for (const [glob, schema] of Object.entries(options.jsonSchema)) {\n const jsonSchema = schema as { resolveRefs?: boolean };\n if (jsonSchema.resolveRefs && micromatch.isMatch(relative, glob)) {\n return true;\n }\n }\n return false;\n}\n\nfunction isRelativePath(refPath: string): boolean {\n if (path.isAbsolute(refPath)) return false;\n if (/^[a-z]+:\\/\\//i.test(refPath)) return false;\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AA+BA,SAAgB,oBACd,MACA,UACc;CACd,MAAM,yBAAiB,IAAI,KAAK;CAChC,MAAM,iBAAkC,EAAE;AAS1C,QAAO;EAAE,UARQ,YACf,MACA,KAAK,QAAQ,KAAK,QAAQ,SAAS,CAAC,EACpC,oBACA,IAAI,KAAa,EACjB,QACA,eAEe;EAAE;EAAQ;EAAgB;;AAG7C,SAAS,YACP,MACA,SACA,SACA,UACA,QACA,gBACS;AACT,KAAI,SAAS,QAAQ,OAAO,SAAS,SAAU,QAAO;AAEtD,KAAI,MAAM,QAAQ,KAAK,CACrB,QAAO,KAAK,KAAK,MAAM,MACrB,YACE,MACA,SACA,GAAG,QAAQ,GAAG,KACd,UACA,QACA,eACD,CACF;CAGH,MAAM,MAAM;AAEZ,KAAI,OAAO,IAAI,YAAY,SACzB,QAAO,WAAW,KAAK,SAAS,SAAS,UAAU,QAAQ,eAAe;CAG5E,MAAM,SAAkC,EAAE;AAC1C,MAAK,MAAM,CAA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AAM,GAAG,GAAG,SAAS;AAC7B,SAAO;;CAGT,MAAM,EAAE,MAAM,GAAG,GAAG,aAAa;AAGjC,QAAO,IAAI,SAAS;EAClB,YAAY;EACZ;EACA,eAAe;EACf,iBAAiB;EACjB;EACD,CAAC;CAGF,MAAM,aAAa,KAAK,QAAQ,iBAAiB;CACjD,MAAM,eAAe,IAAI,IAAI,SAAS;AACtC,cAAa,IAAI,iBAAiB;CAElC,MAAM,kBAAkB,YACtB,QACA,YACA,SACA,cACA,QACA,eACD;AAGD,KACE,oBAAoB,QACpB,OAAO,oBAAoB,YAC3B,CAAC,MAAM,QAAQ,gBAAgB,CAG/B,QAAO;EAAE,GAAI;EAA6C,GAAG;EAAU;AAIzE,QAAO;;;;;;AAOT,SAAgB,kBACd,UACA,SACS;AACT,KAAI,CAAC,SAAS,WAAY,QAAO;CAEjC,MAAM,WAAW,KAAK,SAAS,QAAQ,KAAK,EAAE,SAAS;AACvD,MAAK,MAAM,CAAC,MAAM,WAAW,OAAO,QAAQ,QAAQ,WAAW,CAE7D,KAAIA,OAAW,eAAe,WAAW,QAAQ,UAAU,KAAK,CAC9D,QAAO;AAGX,QAAO;;AAGT,SAAS,eAAe,SAA0B;AAChD,KAAI,KAAK,WAAW,QAAQ,CAAE,QAAO;AACrC,KAAI,gBAAgB,KAAK,QAAQ,CAAE,QAAO;AAC1C,QAAO"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gt",
3
- "version": "2.28.0",
3
+ "version": "2.28.2",
4
4
  "main": "dist/index.js",
5
5
  "bin": "bin/main.js",
6
6
  "files": [
@@ -116,12 +116,12 @@
116
116
  "unified": "^11.0.5",
117
117
  "unist-util-visit": "^5.0.0",
118
118
  "yaml": "^2.8.0",
119
- "@generaltranslation/format": "0.1.9",
119
+ "@generaltranslation/format": "0.1.10",
120
120
  "@generaltranslation/icu": "0.1.2",
121
- "@generaltranslation/python-extractor": "0.2.66",
122
- "@generaltranslation/supported-locales": "2.1.47",
123
- "@generaltranslation/vue-extractor": "0.1.25",
124
- "generaltranslation": "9.5.11",
121
+ "@generaltranslation/python-extractor": "0.2.67",
122
+ "@generaltranslation/supported-locales": "2.1.48",
123
+ "@generaltranslation/vue-extractor": "0.1.26",
124
+ "generaltranslation": "9.5.12",
125
125
  "gt-remark": "1.0.12"
126
126
  },
127
127
  "devDependencies": {