gt 2.26.10 → 2.26.11

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,11 @@
1
1
  # gtx-cli
2
2
 
3
+ ## 2.26.11
4
+
5
+ ### Patch Changes
6
+
7
+ - [#2532](https://github.com/generaltranslation/gt/pull/2532) [`de29049`](https://github.com/generaltranslation/gt/commit/de29049fa16e7c4f60c4cf2baf1a83def5168479) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Keep the trailing newline of JSON files the CLI rewrites in place, such as `redirects.json`, `docs.json`, `gt.config.json`, and `package.json`, and end JSON files the CLI generates, such as `gt-lock.json`, with a newline
8
+
3
9
  ## 2.26.10
4
10
 
5
11
  ### Patch Changes
@@ -1,3 +1,4 @@
1
+ import { stringifyJson } from "../../../fs/stringifyJson.js";
1
2
  import { getRelative } from "../../../fs/findFilepath.js";
2
3
  import { api } from "../../../utils/api.js";
3
4
  import { getConfiguredLocaleProperties } from "../../utils.js";
@@ -31,7 +32,8 @@ function keepUntranslatedPagePaths(settings, includeFiles) {
31
32
  for (const filePath of settings.files.resolvedPaths.json ?? []) {
32
33
  const schema = validateJsonSchema(options, filePath);
33
34
  if (!schema?.composite || !isIncluded(filePath)) continue;
34
- const json = JSON.parse(fs.readFileSync(filePath, "utf8"));
35
+ const content = fs.readFileSync(filePath, "utf8");
36
+ const json = JSON.parse(content);
35
37
  const dir = path.dirname(filePath);
36
38
  if (schema.structuralTransform) applyStructuralTransforms(json, schema.structuralTransform, schema.composite);
37
39
  const localeKey = (locale) => options.experimentalCanonicalLocaleKeys ? api.resolveCanonicalLocale(locale) : locale;
@@ -52,7 +54,7 @@ function keepUntranslatedPagePaths(settings, includeFiles) {
52
54
  }
53
55
  if (changed) {
54
56
  if (schema.structuralTransform) unapplyStructuralTransforms(json, schema.structuralTransform, schema.composite);
55
- fs.writeFileSync(filePath, JSON.stringify(json, null, 2));
57
+ fs.writeFileSync(filePath, stringifyJson(json, content));
56
58
  }
57
59
  }
58
60
  const yamlSources = settings.files.resolvedPaths.yaml ?? [];
@@ -1 +1 @@
1
- {"version":3,"file":"keepUntranslatedPagePaths.js","names":[],"sources":["../../../../src/formats/files/postprocess/keepUntranslatedPagePaths.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport type { Settings, TransformOptions } from '../../../types/index.js';\nimport type { JSONValue } from '../../../types/data/json.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n} from '../../../utils/localizeStaticUrls.js';\nimport { getConfiguredLocaleProperties } from '../../utils.js';\nimport { getJSONPathMatches } from '../../json/jsonPath.js';\nimport {\n getJSONPointerValue,\n setJSONPointerValue,\n} from '../../json/jsonPointer.js';\nimport { transformValue } from '../../json/mergeJson.js';\nimport {\n applyStructuralTransforms,\n unapplyStructuralTransforms,\n} from '../../json/transformJson.js';\nimport { api } from '../../../utils/api.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n validateJsonSchema,\n} from '../../json/utils.js';\nimport { validateYamlSchema } from '../../yaml/utils.js';\nimport { createFileMapping } from '../fileMapping.js';\n\n/**\n * With `skipUntranslatedPages`, undo `transform` rewrites that point a\n * localized JSON or YAML file (such as a docs navigation file) at a page that\n * was not translated. A value is restored to its source form when the source\n * value names an existing .md/.mdx page and the transformed value does not.\n * Values that are not page paths are left alone. Runs after all downloads, so\n * every translated page from this run is on disk.\n */\nexport function keepUntranslatedPagePaths(\n settings: Settings,\n includeFiles?: Set<string>\n): void {\n const options = settings.options;\n const localizeOptions = options?.experimentalLocalizeStaticUrls;\n if (\n !options ||\n typeof localizeOptions !== 'object' ||\n localizeOptions.skipUntranslatedPages !== true ||\n !settings.files\n ) {\n return;\n }\n const { defaultLocale } = settings;\n const targetLocales = settings.locales.filter((l) => l !== defaultLocale);\n const isIncluded = (filePath: string) =>\n !includeFiles ||\n includeFiles.has(filePath) ||\n includeFiles.has(getRelative(filePath));\n\n // Composite JSON: every locale's entry lives in the source file itself.\n for (const filePath of settings.files.resolvedPaths.json ?? []) {\n const schema = validateJsonSchema(options, filePath);\n if (!schema?.composite || !isIncluded(filePath)) continue;\n const json = JSON.parse(fs.readFileSync(filePath, 'utf8')) as JSONValue;\n const dir = path.dirname(filePath);\n // Match entries the way mergeJson wrote them: same structural transforms\n // and the same locale keys.\n if (schema.structuralTransform) {\n applyStructuralTransforms(\n json,\n schema.structuralTransform,\n schema.composite\n );\n }\n const localeKey = (locale: string) =>\n options.experimentalCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(locale)\n : locale;\n let changed = false;\n const sourceObjects = generateSourceObjectPointers(schema.composite, json);\n for (const [\n pointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(sourceObjects)) {\n if (!sourceObjectOptions.transform) continue;\n // Every entry for a locale, in order. mergeJson builds one target entry\n // per default-locale entry in the same order, so they pair by position.\n const entriesFor = (locale: string): JSONValue[] => {\n if (Array.isArray(sourceObjectValue)) {\n return Object.values(\n findMatchingItemArray(\n localeKey(locale),\n sourceObjectOptions,\n pointer,\n sourceObjectValue\n )\n )\n .sort((a, b) => a.index - b.index)\n .map(({ sourceItem }) => sourceItem);\n }\n const { sourceItem } = findMatchingItemObject(\n localeKey(locale),\n pointer,\n sourceObjectOptions,\n sourceObjectValue as Record<string, JSONValue>\n );\n return sourceItem === undefined ? [] : [sourceItem];\n };\n const sources = entriesFor(defaultLocale);\n for (const locale of targetLocales) {\n entriesFor(locale).forEach((target, i) => {\n if (sources[i] === undefined) return;\n changed =\n restorePagePaths(\n sources[i],\n target,\n sourceObjectOptions.transform!,\n locale,\n defaultLocale,\n dir,\n dir\n ) || changed;\n });\n }\n }\n if (changed) {\n if (schema.structuralTransform) {\n unapplyStructuralTransforms(\n json,\n schema.structuralTransform,\n schema.composite\n );\n }\n fs.writeFileSync(filePath, JSON.stringify(json, null, 2));\n }\n }\n\n // YAML: each locale has its own output file, mapped from the source file.\n const yamlSources = settings.files.resolvedPaths.yaml ?? [];\n if (!yamlSources.length) return;\n const fileMapping = createFileMapping(\n settings.files.resolvedPaths,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n defaultLocale\n );\n for (const filePath of yamlSources) {\n const schema = validateYamlSchema(options, filePath);\n if (!schema?.transform) continue;\n const source = YAML.parse(fs.readFileSync(filePath, 'utf8')) as JSONValue;\n for (const locale of targetLocales) {\n const outputPath = fileMapping[locale]?.[getRelative(filePath)];\n if (!outputPath || !fs.existsSync(outputPath) || !isIncluded(outputPath))\n continue;\n const target = YAML.parse(\n fs.readFileSync(outputPath, 'utf8')\n ) as JSONValue;\n const restored = restorePagePaths(\n source,\n target,\n schema.transform,\n locale,\n defaultLocale,\n path.dirname(filePath),\n path.dirname(outputPath)\n );\n if (restored) fs.writeFileSync(outputPath, YAML.stringify(target));\n }\n }\n}\n\n/**\n * For each value a transform produced in `target` from the value at the same\n * position in `source`, restore the source page path when the transformed\n * page does not exist. Returns whether anything changed.\n */\nfunction restorePagePaths(\n source: JSONValue,\n target: JSONValue,\n transform: TransformOptions,\n locale: string,\n defaultLocale: string,\n sourceDir: string,\n targetDir: string\n): boolean {\n const targetLocaleProperties = getConfiguredLocaleProperties(locale);\n const defaultLocaleProperties = getConfiguredLocaleProperties(defaultLocale);\n let changed = false;\n for (const [transformPath, transformOption] of Object.entries(transform)) {\n for (const match of getJSONPathMatches(source, transformPath) ?? []) {\n if (typeof match.value !== 'string') continue;\n const transformed = transformValue(\n match.value,\n transformOption,\n targetLocaleProperties,\n defaultLocaleProperties\n );\n if (\n transformed === match.value ||\n getJSONPointerValue(target, match.pointer) !== transformed ||\n pageExists(transformed, targetDir) ||\n !pageExists(match.value, sourceDir)\n ) {\n continue;\n }\n const restored =\n sourceDir === targetDir\n ? match.value\n : path\n .relative(targetDir, path.join(sourceDir, match.value))\n .split(path.sep)\n .join('/');\n setJSONPointerValue(target, match.pointer, restored);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Whether a path value names an .md/.mdx page, with or without extension. An\n * empty value or one ending in `/` names a folder's index page\n */\nfunction pageExists(value: string, dir: string): boolean {\n const filePath = path.join(dir, value);\n if (value === '' || value.endsWith('/')) {\n return PAGE_EXTENSIONS.some((ext) =>\n fs.existsSync(path.join(filePath, `${INDEX_PAGE}${ext}`))\n );\n }\n if (PAGE_EXTENSIONS.includes(path.extname(filePath))) {\n return fs.existsSync(filePath);\n }\n return PAGE_EXTENSIONS.some((ext) => fs.existsSync(`${filePath}${ext}`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAgB,0BACd,UACA,cACM;CACN,MAAM,UAAU,SAAS;CACzB,MAAM,kBAAkB,SAAS;AACjC,KACE,CAAC,WACD,OAAO,oBAAoB,YAC3B,gBAAgB,0BAA0B,QAC1C,CAAC,SAAS,MAEV;CAEF,MAAM,EAAE,kBAAkB;CAC1B,MAAM,gBAAgB,SAAS,QAAQ,QAAQ,MAAM,MAAM,cAAc;CACzE,MAAM,cAAc,aAClB,CAAC,gBACD,aAAa,IAAI,SAAS,IAC1B,aAAa,IAAI,YAAY,SAAS,CAAC;AAGzC,MAAK,MAAM,YAAY,SAAS,MAAM,cAAc,QAAQ,EAAE,EAAE;EAC9D,MAAM,SAAS,mBAAmB,SAAS,SAAS;AACpD,MAAI,CAAC,QAAQ,aAAa,CAAC,WAAW,SAAS,CAAE;EACjD,MAAM,OAAO,KAAK,MAAM,GAAG,aAAa,UAAU,OAAO,CAAC;EAC1D,MAAM,MAAM,KAAK,QAAQ,SAAS;AAGlC,MAAI,OAAO,oBACT,2BACE,MACA,OAAO,qBACP,OAAO,UACR;EAEH,MAAM,aAAa,WACjB,QAAQ,kCACJ,IAAI,uBAAuB,OAAO,GAClC;EACN,IAAI,UAAU;EACd,MAAM,gBAAgB,6BAA6B,OAAO,WAAW,KAAK;AAC1E,OAAK,M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AG,WAAW,SAAS;AAEhC,QAAO,gBAAgB,MAAM,QAAQ,GAAG,WAAW,GAAG,WAAW,MAAM,CAAC"}
1
+ {"version":3,"file":"keepUntranslatedPagePaths.js","names":[],"sources":["../../../../src/formats/files/postprocess/keepUntranslatedPagePaths.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport YAML from 'yaml';\nimport type { Settings, TransformOptions } from '../../../types/index.js';\nimport type { JSONValue } from '../../../types/data/json.js';\nimport { stringifyJson } from '../../../fs/stringifyJson.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n} from '../../../utils/localizeStaticUrls.js';\nimport { getConfiguredLocaleProperties } from '../../utils.js';\nimport { getJSONPathMatches } from '../../json/jsonPath.js';\nimport {\n getJSONPointerValue,\n setJSONPointerValue,\n} from '../../json/jsonPointer.js';\nimport { transformValue } from '../../json/mergeJson.js';\nimport {\n applyStructuralTransforms,\n unapplyStructuralTransforms,\n} from '../../json/transformJson.js';\nimport { api } from '../../../utils/api.js';\nimport {\n findMatchingItemArray,\n findMatchingItemObject,\n generateSourceObjectPointers,\n validateJsonSchema,\n} from '../../json/utils.js';\nimport { validateYamlSchema } from '../../yaml/utils.js';\nimport { createFileMapping } from '../fileMapping.js';\n\n/**\n * With `skipUntranslatedPages`, undo `transform` rewrites that point a\n * localized JSON or YAML file (such as a docs navigation file) at a page that\n * was not translated. A value is restored to its source form when the source\n * value names an existing .md/.mdx page and the transformed value does not.\n * Values that are not page paths are left alone. Runs after all downloads, so\n * every translated page from this run is on disk.\n */\nexport function keepUntranslatedPagePaths(\n settings: Settings,\n includeFiles?: Set<string>\n): void {\n const options = settings.options;\n const localizeOptions = options?.experimentalLocalizeStaticUrls;\n if (\n !options ||\n typeof localizeOptions !== 'object' ||\n localizeOptions.skipUntranslatedPages !== true ||\n !settings.files\n ) {\n return;\n }\n const { defaultLocale } = settings;\n const targetLocales = settings.locales.filter((l) => l !== defaultLocale);\n const isIncluded = (filePath: string) =>\n !includeFiles ||\n includeFiles.has(filePath) ||\n includeFiles.has(getRelative(filePath));\n\n // Composite JSON: every locale's entry lives in the source file itself.\n for (const filePath of settings.files.resolvedPaths.json ?? []) {\n const schema = validateJsonSchema(options, filePath);\n if (!schema?.composite || !isIncluded(filePath)) continue;\n const content = fs.readFileSync(filePath, 'utf8');\n const json = JSON.parse(content) as JSONValue;\n const dir = path.dirname(filePath);\n // Match entries the way mergeJson wrote them: same structural transforms\n // and the same locale keys.\n if (schema.structuralTransform) {\n applyStructuralTransforms(\n json,\n schema.structuralTransform,\n schema.composite\n );\n }\n const localeKey = (locale: string) =>\n options.experimentalCanonicalLocaleKeys\n ? api.resolveCanonicalLocale(locale)\n : locale;\n let changed = false;\n const sourceObjects = generateSourceObjectPointers(schema.composite, json);\n for (const [\n pointer,\n { sourceObjectValue, sourceObjectOptions },\n ] of Object.entries(sourceObjects)) {\n if (!sourceObjectOptions.transform) continue;\n // Every entry for a locale, in order. mergeJson builds one target entry\n // per default-locale entry in the same order, so they pair by position.\n const entriesFor = (locale: string): JSONValue[] => {\n if (Array.isArray(sourceObjectValue)) {\n return Object.values(\n findMatchingItemArray(\n localeKey(locale),\n sourceObjectOptions,\n pointer,\n sourceObjectValue\n )\n )\n .sort((a, b) => a.index - b.index)\n .map(({ sourceItem }) => sourceItem);\n }\n const { sourceItem } = findMatchingItemObject(\n localeKey(locale),\n pointer,\n sourceObjectOptions,\n sourceObjectValue as Record<string, JSONValue>\n );\n return sourceItem === undefined ? [] : [sourceItem];\n };\n const sources = entriesFor(defaultLocale);\n for (const locale of targetLocales) {\n entriesFor(locale).forEach((target, i) => {\n if (sources[i] === undefined) return;\n changed =\n restorePagePaths(\n sources[i],\n target,\n sourceObjectOptions.transform!,\n locale,\n defaultLocale,\n dir,\n dir\n ) || changed;\n });\n }\n }\n if (changed) {\n if (schema.structuralTransform) {\n unapplyStructuralTransforms(\n json,\n schema.structuralTransform,\n schema.composite\n );\n }\n fs.writeFileSync(filePath, stringifyJson(json, content));\n }\n }\n\n // YAML: each locale has its own output file, mapped from the source file.\n const yamlSources = settings.files.resolvedPaths.yaml ?? [];\n if (!yamlSources.length) return;\n const fileMapping = createFileMapping(\n settings.files.resolvedPaths,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n defaultLocale\n );\n for (const filePath of yamlSources) {\n const schema = validateYamlSchema(options, filePath);\n if (!schema?.transform) continue;\n const source = YAML.parse(fs.readFileSync(filePath, 'utf8')) as JSONValue;\n for (const locale of targetLocales) {\n const outputPath = fileMapping[locale]?.[getRelative(filePath)];\n if (!outputPath || !fs.existsSync(outputPath) || !isIncluded(outputPath))\n continue;\n const target = YAML.parse(\n fs.readFileSync(outputPath, 'utf8')\n ) as JSONValue;\n const restored = restorePagePaths(\n source,\n target,\n schema.transform,\n locale,\n defaultLocale,\n path.dirname(filePath),\n path.dirname(outputPath)\n );\n if (restored) fs.writeFileSync(outputPath, YAML.stringify(target));\n }\n }\n}\n\n/**\n * For each value a transform produced in `target` from the value at the same\n * position in `source`, restore the source page path when the transformed\n * page does not exist. Returns whether anything changed.\n */\nfunction restorePagePaths(\n source: JSONValue,\n target: JSONValue,\n transform: TransformOptions,\n locale: string,\n defaultLocale: string,\n sourceDir: string,\n targetDir: string\n): boolean {\n const targetLocaleProperties = getConfiguredLocaleProperties(locale);\n const defaultLocaleProperties = getConfiguredLocaleProperties(defaultLocale);\n let changed = false;\n for (const [transformPath, transformOption] of Object.entries(transform)) {\n for (const match of getJSONPathMatches(source, transformPath) ?? []) {\n if (typeof match.value !== 'string') continue;\n const transformed = transformValue(\n match.value,\n transformOption,\n targetLocaleProperties,\n defaultLocaleProperties\n );\n if (\n transformed === match.value ||\n getJSONPointerValue(target, match.pointer) !== transformed ||\n pageExists(transformed, targetDir) ||\n !pageExists(match.value, sourceDir)\n ) {\n continue;\n }\n const restored =\n sourceDir === targetDir\n ? match.value\n : path\n .relative(targetDir, path.join(sourceDir, match.value))\n .split(path.sep)\n .join('/');\n setJSONPointerValue(target, match.pointer, restored);\n changed = true;\n }\n }\n return changed;\n}\n\n/**\n * Whether a path value names an .md/.mdx page, with or without extension. An\n * empty value or one ending in `/` names a folder's index page\n */\nfunction pageExists(value: string, dir: string): boolean {\n const filePath = path.join(dir, value);\n if (value === '' || value.endsWith('/')) {\n return PAGE_EXTENSIONS.some((ext) =>\n fs.existsSync(path.join(filePath, `${INDEX_PAGE}${ext}`))\n );\n }\n if (PAGE_EXTENSIONS.includes(path.extname(filePath))) {\n return fs.existsSync(filePath);\n }\n return PAGE_EXTENSIONS.some((ext) => fs.existsSync(`${filePath}${ext}`));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAgB,0BACd,UACA,cACM;CACN,MAAM,UAAU,SAAS;CACzB,MAAM,kBAAkB,SAAS;AACjC,KACE,CAAC,WACD,OAAO,oBAAoB,YAC3B,gBAAgB,0BAA0B,QAC1C,CAAC,SAAS,MAEV;CAEF,MAAM,EAAE,kBAAkB;CAC1B,MAAM,gBAAgB,SAAS,QAAQ,QAAQ,MAAM,MAAM,cAAc;CACzE,MAAM,cAAc,aAClB,CAAC,gBACD,aAAa,IAAI,SAAS,IAC1B,aAAa,IAAI,YAAY,SAAS,CAAC;AAGzC,MAAK,MAAM,YAAY,SAAS,MAAM,cAAc,QAAQ,EAAE,EAAE;EAC9D,MAAM,SAAS,mBAAmB,SAAS,SAAS;AACpD,MAAI,CAAC,QAAQ,aAAa,CAAC,WAAW,SAAS,CAAE;EACjD,MAAM,UAAU,GAAG,aAAa,UAAU,OAAO;EACjD,MAAM,OAAO,KAAK,MAAM,QAAQ;EAChC,MAAM,MAAM,KAAK,QAAQ,SAAS;AAGlC,MAAI,OAAO,oBACT,2BACE,MACA,OAAO,qBACP,OAAO,UACR;EAEH,MAAM,aAAa,WACjB,QAAQ,kCACJ,IAAI,uBAAuB,OAAO,GAClC;EACN,IAAI,UAAU;EACd,MAAM,gB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K,QAAQ,SAAS,CAAC,CAClD,QAAO,GAAG,WAAW,SAAS;AAEhC,QAAO,gBAAgB,MAAM,QAAQ,GAAG,WAAW,GAAG,WAAW,MAAM,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { logger } from "../../../console/logger.js";
2
+ import { stringifyJson } from "../../../fs/stringifyJson.js";
2
3
  import { getRelative } from "../../../fs/findFilepath.js";
3
4
  import loadJSON from "../../../fs/loadJSON.js";
4
5
  import { createFileMapping } from "../fileMapping.js";
@@ -118,10 +119,10 @@ function readRedirects(docsJsonPath) {
118
119
  const redirectsFile = holder;
119
120
  return {
120
121
  redirects: value,
121
- write: (updated) => fs.writeFileSync(redirectsFile, JSON.stringify(redirectsFile === docsJsonPath ? {
122
+ write: (updated) => fs.writeFileSync(redirectsFile, stringifyJson(redirectsFile === docsJsonPath ? {
122
123
  ...docsJson,
123
124
  redirects: updated
124
- } : updated, null, 2))
125
+ } : updated, fs.readFileSync(redirectsFile, "utf-8")))
125
126
  };
126
127
  }
127
128
  //#endregion
@@ -1 +1 @@
1
- {"version":3,"file":"localizeMintlifyRedirects.js","names":[],"sources":["../../../../src/formats/files/postprocess/localizeMintlifyRedirects.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { logger } from '../../../console/logger.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport loadJSON from '../../../fs/loadJSON.js';\nimport type { Settings } from '../../../types/index.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n findPatternHead,\n getPatternHeads,\n transformUrlPath,\n translationMissing,\n} from '../../../utils/localizeStaticUrls.js';\nimport { createFileMapping } from '../fileMapping.js';\n\ntype Redirect = { source: string; destination: string; permanent?: unknown };\n\nconst missingDocsUrlPatternWarning = createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: 'Localized redirects were not added',\n why: 'options.mintlify.localizeRedirects uses options.docsUrlPattern to place the locale in redirect URLs',\n fix: 'Set options.docsUrlPattern in gt.config.json, such as \"/docs/[locale]\"',\n});\n\n/**\n * Adds localized copies of the English redirects whose source is a renamed or\n * removed page, and returns the redirects it added. Orphaned file names come\n * from the upload step, so redirects for pages GT never translated are never\n * localized. URLs are localized like links inside\n * pages: with docsUrlPattern, and not for locales missing the destination's\n * translation.\n */\nexport function localizeMintlifyRedirects(\n settings: Settings,\n orphanedFileNames: string[]\n): Redirect[] {\n if (\n settings.options?.mintlify?.localizeRedirects !== true ||\n !settings.files\n ) {\n return [];\n }\n const urlPattern = settings.options.docsUrlPattern;\n if (!urlPattern || urlPattern.length === 0) {\n logger.warn(missingDocsUrlPatternWarning);\n return [];\n }\n const location = readRedirects(path.resolve('docs.json'));\n if (!location) return [];\n\n const oldPageUrls = new Set(\n orphanedFileNames\n .filter((fileName) => PAGE_EXTENSIONS.includes(path.extname(fileName)))\n .map(pageUrl)\n );\n\n const targetLocales = settings.locales.filter(\n (locale) => locale !== settings.defaultLocale\n );\n const { files } = settings;\n const fileMapping = createFileMapping(\n files.resolvedPaths,\n files.placeholderPaths,\n files.transformPaths,\n files.transformFormats,\n targetLocales,\n settings.defaultLocale\n );\n // Localize URLs the way links inside pages are localized\n const urlPatternHeads = getPatternHeads(urlPattern);\n const localizeUrl = (url: string, locale: string) => {\n const urlPatternHead = findPatternHead(url, urlPatternHeads);\n if (urlPatternHead === undefined) return null;\n const localized = transformUrlPath(\n url,\n urlPatternHead,\n locale,\n settings.defaultLocale,\n settings.options?.experimentalHideDefaultLocale ?? false\n );\n return localized === null ? null : normalizeUrl(localized);\n };\n // Translated pages can be orphaned too, so their redirects are already\n // localized. Localizing them again would nest locales (/docs/ja-jp/fr-ca/...)\n const isLocalized = (url: string) => {\n const urlPatternHead = findPatternHead(url, urlPatternHeads);\n if (urlPatternHead === undefined) return false;\n const localeSegmentIndex = urlPatternHead.split('/').filter(Boolean).length;\n return targetLocales.includes(\n url.split('/').filter(Boolean)[localeSegmentIndex]\n );\n };\n const takenSources = new Set(\n location.redirects.filter(isRedirect).map((r) => normalizeUrl(r.source))\n );\n\n const added: Redirect[] = [];\n const updated = location.redirects.flatMap((entry) => {\n if (!isRedirect(entry)) return [entry];\n const [destinationPath, anchor] = splitAnchor(entry.destination);\n const sourceUrl = normalizeUrl(entry.source);\n const destinationUrl = normalizeUrl(destinationPath);\n if (\n !oldPageUrls.has(sourceUrl) ||\n isLocalized(sourceUrl) ||\n isLocalized(destinationUrl)\n ) {\n return [entry];\n }\n\n const localized: Redirect[] = [];\n for (const locale of targetLocales) {\n const localizedSource = localizeUrl(sourceUrl, locale);\n const localizedDestination = localizeUrl(destinationUrl, locale);\n if (\n !localizedSource ||\n !localizedDestination ||\n localizedSource === localizedDestination ||\n takenSources.has(localizedSource) ||\n translationMissing(\n destinationUrl,\n localizedDestination,\n fileMapping[locale] ?? {}\n )\n ) {\n continue;\n }\n takenSources.add(localizedSource);\n localized.push({\n source: localizedSource,\n destination: `${localizedDestination}${anchor}`,\n ...('permanent' in entry && { permanent: entry.permanent }),\n });\n }\n added.push(...localized);\n return [entry, ...localized];\n });\n\n if (added.length > 0) location.write(updated);\n return added;\n}\n\nfunction isRedirect(entry: unknown): entry is Redirect {\n return (\n typeof (entry as Redirect)?.source === 'string' &&\n typeof (entry as Redirect)?.destination === 'string'\n );\n}\n\n/** Splits `/docs/page#section` into `/docs/page` and `#section`. */\nfunction splitAnchor(url: string): [string, string] {\n const anchorStart = url.indexOf('#');\n return anchorStart === -1\n ? [url, '']\n : [url.slice(0, anchorStart), url.slice(anchorStart)];\n}\n\n/**\n * The URL of a page file: its path without the extension. Like static URL\n * localization, URLs are relative to the working directory.\n */\nfunction pageUrl(fileName: string): string {\n const relative = getRelative(fileName);\n return normalizeUrl(\n relative\n .slice(0, relative.length - path.extname(relative).length)\n .split(path.sep)\n .join('/')\n );\n}\n\n/**\n * Leading slash, no trailing slash, and index pages named by their folder, so\n * equivalent spellings compare equal.\n */\nfunction normalizeUrl(url: string): string {\n const segments = url.split('/').filter(Boolean);\n if (segments.at(-1) === INDEX_PAGE) segments.pop();\n return `/${segments.join('/')}`;\n}\n\n/**\n * Finds the redirects array in docs.json, either inline or at the end of its\n * `$ref` chain, and returns a writer for the file that holds it.\n */\nfunction readRedirects(\n docsJsonPath: string\n): { redirects: unknown[]; write: (redirects: unknown[]) => void } | null {\n const docsJson = loadJSON(docsJsonPath);\n let holder = docsJsonPath;\n let value: unknown = docsJson?.redirects;\n const visited = new Set([holder]);\n while (typeof (value as { $ref?: unknown })?.$ref === 'string') {\n holder = path.resolve(\n path.dirname(holder),\n (value as { $ref: string }).$ref\n );\n if (visited.has(holder)) return null;\n visited.add(holder);\n value = loadJSON(holder);\n }\n if (!Array.isArray(value)) return null;\n\n const redirectsFile = holder;\n return {\n redirects: value,\n write: (updated) =>\n fs.writeFileSync(\n redirectsFile,\n JSON.stringify(\n redirectsFile === docsJsonPath\n ? { ...docsJson, redirects: updated }\n : updated,\n null,\n 2\n )\n ),\n };\n}\n"],"mappings":";;;;;;;;;AAmBA,MAAM,+BAA+B,wBAAwB;CAC3D,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,KAAK;CACN,CAAC;;;;;;;;;AAUF,SAAgB,0BACd,UACA,mBACY;AACZ,KACE,SAAS,SAAS,UAAU,sBAAsB,QAClD,CAAC,SAAS,MAEV,QAAO,EAAE;CAEX,MAAM,aAAa,SAAS,QAAQ;AACpC,KAAI,CAAC,cAAc,WAAW,WAAW,GAAG;AAC1C,SAAO,KAAK,6BAA6B;AACzC,SAAO,EAAE;;CAEX,MAAM,WAAW,cAAc,KAAK,QAAQ,YAAY,CAAC;AACzD,KAAI,CAAC,SAAU,QAAO,EAAE;CAExB,MAAM,cAAc,IAAI,IACtB,kBACG,QAAQ,aAAa,gBAAgB,SAAS,KAAK,QAAQ,SAAS,CAAC,CAAC,CACtE,IAAI,QAAQ,CAChB;CAED,MAAM,gBAAgB,SAAS,QAAQ,QACpC,WAAW,WAAW,SAAS,cACj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AK,QAAQ,OAAO,EACnB,MAA2B,KAC7B;AACD,MAAI,QAAQ,IAAI,OAAO,CAAE,QAAO;AAChC,UAAQ,IAAI,OAAO;AACnB,UAAQ,SAAS,OAAO;;AAE1B,KAAI,CAAC,MAAM,QAAQ,MAAM,CAAE,QAAO;CAElC,MAAM,gBAAgB;AACtB,QAAO;EACL,WAAW;EACX,QAAQ,YACN,GAAG,cACD,eACA,KAAK,UACH,kBAAkB,eACd;GAAE,GAAG;GAAU,WAAW;GAAS,GACnC,SACJ,MACA,EACD,CACF;EACJ"}
1
+ {"version":3,"file":"localizeMintlifyRedirects.js","names":[],"sources":["../../../../src/formats/files/postprocess/localizeMintlifyRedirects.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport { logger } from '../../../console/logger.js';\nimport { getRelative } from '../../../fs/findFilepath.js';\nimport loadJSON from '../../../fs/loadJSON.js';\nimport { stringifyJson } from '../../../fs/stringifyJson.js';\nimport type { Settings } from '../../../types/index.js';\nimport {\n INDEX_PAGE,\n PAGE_EXTENSIONS,\n findPatternHead,\n getPatternHeads,\n transformUrlPath,\n translationMissing,\n} from '../../../utils/localizeStaticUrls.js';\nimport { createFileMapping } from '../fileMapping.js';\n\ntype Redirect = { source: string; destination: string; permanent?: unknown };\n\nconst missingDocsUrlPatternWarning = createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: 'Localized redirects were not added',\n why: 'options.mintlify.localizeRedirects uses options.docsUrlPattern to place the locale in redirect URLs',\n fix: 'Set options.docsUrlPattern in gt.config.json, such as \"/docs/[locale]\"',\n});\n\n/**\n * Adds localized copies of the English redirects whose source is a renamed or\n * removed page, and returns the redirects it added. Orphaned file names come\n * from the upload step, so redirects for pages GT never translated are never\n * localized. URLs are localized like links inside\n * pages: with docsUrlPattern, and not for locales missing the destination's\n * translation.\n */\nexport function localizeMintlifyRedirects(\n settings: Settings,\n orphanedFileNames: string[]\n): Redirect[] {\n if (\n settings.options?.mintlify?.localizeRedirects !== true ||\n !settings.files\n ) {\n return [];\n }\n const urlPattern = settings.options.docsUrlPattern;\n if (!urlPattern || urlPattern.length === 0) {\n logger.warn(missingDocsUrlPatternWarning);\n return [];\n }\n const location = readRedirects(path.resolve('docs.json'));\n if (!location) return [];\n\n const oldPageUrls = new Set(\n orphanedFileNames\n .filter((fileName) => PAGE_EXTENSIONS.includes(path.extname(fileName)))\n .map(pageUrl)\n );\n\n const targetLocales = settings.locales.filter(\n (locale) => locale !== settings.defaultLocale\n );\n const { files } = settings;\n const fileMapping = createFileMapping(\n files.resolvedPaths,\n files.placeholderPaths,\n files.transformPaths,\n files.transformFormats,\n targetLocales,\n settings.defaultLocale\n );\n // Localize URLs the way links inside pages are localized\n const urlPatternHeads = getPatternHeads(urlPattern);\n const localizeUrl = (url: string, locale: string) => {\n const urlPatternHead = findPatternHead(url, urlPatternHeads);\n if (urlPatternHead === undefined) return null;\n const localized = transformUrlPath(\n url,\n urlPatternHead,\n locale,\n settings.defaultLocale,\n settings.options?.experimentalHideDefaultLocale ?? false\n );\n return localized === null ? null : normalizeUrl(localized);\n };\n // Translated pages can be orphaned too, so their redirects are already\n // localized. Localizing them again would nest locales (/docs/ja-jp/fr-ca/...)\n const isLocalized = (url: string) => {\n const urlPatternHead = findPatternHead(url, urlPatternHeads);\n if (urlPatternHead === undefined) return false;\n const localeSegmentIndex = urlPatternHead.split('/').filter(Boolean).length;\n return targetLocales.includes(\n url.split('/').filter(Boolean)[localeSegmentIndex]\n );\n };\n const takenSources = new Set(\n location.redirects.filter(isRedirect).map((r) => normalizeUrl(r.source))\n );\n\n const added: Redirect[] = [];\n const updated = location.redirects.flatMap((entry) => {\n if (!isRedirect(entry)) return [entry];\n const [destinationPath, anchor] = splitAnchor(entry.destination);\n const sourceUrl = normalizeUrl(entry.source);\n const destinationUrl = normalizeUrl(destinationPath);\n if (\n !oldPageUrls.has(sourceUrl) ||\n isLocalized(sourceUrl) ||\n isLocalized(destinationUrl)\n ) {\n return [entry];\n }\n\n const localized: Redirect[] = [];\n for (const locale of targetLocales) {\n const localizedSource = localizeUrl(sourceUrl, locale);\n const localizedDestination = localizeUrl(destinationUrl, locale);\n if (\n !localizedSource ||\n !localizedDestination ||\n localizedSource === localizedDestination ||\n takenSources.has(localizedSource) ||\n translationMissing(\n destinationUrl,\n localizedDestination,\n fileMapping[locale] ?? {}\n )\n ) {\n continue;\n }\n takenSources.add(localizedSource);\n localized.push({\n source: localizedSource,\n destination: `${localizedDestination}${anchor}`,\n ...('permanent' in entry && { permanent: entry.permanent }),\n });\n }\n added.push(...localized);\n return [entry, ...localized];\n });\n\n if (added.length > 0) location.write(updated);\n return added;\n}\n\nfunction isRedirect(entry: unknown): entry is Redirect {\n return (\n typeof (entry as Redirect)?.source === 'string' &&\n typeof (entry as Redirect)?.destination === 'string'\n );\n}\n\n/** Splits `/docs/page#section` into `/docs/page` and `#section`. */\nfunction splitAnchor(url: string): [string, string] {\n const anchorStart = url.indexOf('#');\n return anchorStart === -1\n ? [url, '']\n : [url.slice(0, anchorStart), url.slice(anchorStart)];\n}\n\n/**\n * The URL of a page file: its path without the extension. Like static URL\n * localization, URLs are relative to the working directory.\n */\nfunction pageUrl(fileName: string): string {\n const relative = getRelative(fileName);\n return normalizeUrl(\n relative\n .slice(0, relative.length - path.extname(relative).length)\n .split(path.sep)\n .join('/')\n );\n}\n\n/**\n * Leading slash, no trailing slash, and index pages named by their folder, so\n * equivalent spellings compare equal.\n */\nfunction normalizeUrl(url: string): string {\n const segments = url.split('/').filter(Boolean);\n if (segments.at(-1) === INDEX_PAGE) segments.pop();\n return `/${segments.join('/')}`;\n}\n\n/**\n * Finds the redirects array in docs.json, either inline or at the end of its\n * `$ref` chain, and returns a writer for the file that holds it.\n */\nfunction readRedirects(\n docsJsonPath: string\n): { redirects: unknown[]; write: (redirects: unknown[]) => void } | null {\n const docsJson = loadJSON(docsJsonPath);\n let holder = docsJsonPath;\n let value: unknown = docsJson?.redirects;\n const visited = new Set([holder]);\n while (typeof (value as { $ref?: unknown })?.$ref === 'string') {\n holder = path.resolve(\n path.dirname(holder),\n (value as { $ref: string }).$ref\n );\n if (visited.has(holder)) return null;\n visited.add(holder);\n value = loadJSON(holder);\n }\n if (!Array.isArray(value)) return null;\n\n const redirectsFile = holder;\n return {\n redirects: value,\n write: (updated) =>\n fs.writeFileSync(\n redirectsFile,\n stringifyJson(\n redirectsFile === docsJsonPath\n ? { ...docsJson, redirects: updated }\n : updated,\n fs.readFileSync(redirectsFile, 'utf-8')\n )\n ),\n };\n}\n"],"mappings":";;;;;;;;;;AAoBA,MAAM,+BAA+B,wBAAwB;CAC3D,QAAQ;CACR,UAAU;CACV,cAAc;CACd,KAAK;CACL,KAAK;CACN,CAAC;;;;;;;;;AAUF,SAAgB,0BACd,UACA,mBACY;AACZ,KACE,SAAS,SAAS,UAAU,sBAAsB,QAClD,CAAC,SAAS,MAEV,QAAO,EAAE;CAEX,MAAM,aAAa,SAAS,QAAQ;AACpC,KAAI,CAAC,cAAc,WAAW,WAAW,GAAG;AAC1C,SAAO,KAAK,6BAA6B;AACzC,SAAO,EAAE;;CAEX,MAAM,WAAW,cAAc,KAAK,QAAQ,YAAY,CAAC;AACzD,KAAI,CAAC,SAAU,QAAO,EAAE;CAExB,MAAM,cAAc,IAAI,IACtB,kBACG,QAAQ,aAAa,gBAAgB,SAAS,KAAK,QAAQ,SAAS,CAAC,CAAC,CACtE,IAAI,QAAQ,CAChB;CAED,MAAM,gBAAgB,SAAS,QAAQ,QACpC,WAAW,WAAW,SAAS,cACjC;CACD,MAAM,EAAE,UAAU;CAClB,MAAM,cAAc,kBAClB,MAAM,eACN,MAAM,kBACN,MAAM,gBACN,MAAM,kBACN,eACA,SAAS,cACV;CAED,MAAM,kBAAkB,gBAAgB,WAAW;CACnD,MAAM,eAAe,KAAa,WAAmB;EACnD,MAAM,iBAAiB,gBAAgB,KAAK,gBAAgB;AAC5D,MAAI,mBAAmB,KAAA,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ACD,eACA,cACE,kBAAkB,eACd;GAAE,GAAG;GAAU,WAAW;GAAS,GACnC,SACJ,GAAG,aAAa,eAAe,QAAQ,CACxC,CACF;EACJ"}
@@ -1,4 +1,5 @@
1
1
  import { logger } from "../../console/logger.js";
2
+ import { stringifyJson } from "../stringifyJson.js";
2
3
  import path from "node:path";
3
4
  import fs from "node:fs";
4
5
  //#region src/fs/config/downloadedVersions.ts
@@ -119,8 +120,8 @@ function writeLockfile(data, originalV1) {
119
120
  [data.branchId]: convertV2ToV1Branch(data)
120
121
  }
121
122
  };
122
- fs.writeFileSync(filepath, JSON.stringify(mergedV1, null, 2));
123
- } else fs.writeFileSync(filepath, JSON.stringify(data, null, 2));
123
+ fs.writeFileSync(filepath, stringifyJson(mergedV1));
124
+ } else fs.writeFileSync(filepath, stringifyJson(data));
124
125
  } catch (error) {
125
126
  logger.error(`An error occurred while updating ${GT_LOCK_FILE}: ${error}`);
126
127
  }
@@ -1 +1 @@
1
- {"version":3,"file":"downloadedVersions.js","names":[],"sources":["../../../src/fs/config/downloadedVersions.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../../console/logger.js';\nimport type { Settings } from '../../types/index.js';\n\nconst GT_LOCK_FILE = 'gt-lock.json';\n\n// ── V2 types (internal working format) ──────────────────────────────\n\nexport type DownloadedTranslation = {\n updatedAt?: string;\n postProcessHash?: string;\n fileName?: string; // output path for this locale, e.g. \"es-US/my/file/path.mdx\"\n};\n\nexport type DownloadedVersionEntry = {\n fileId: string;\n versionId: string;\n fileName?: string; // source file path\n staged?: boolean; // true if this entry was staged but not yet downloaded\n translations: {\n [locale: string]: DownloadedTranslation;\n };\n};\n\nexport type DownloadedVersions = {\n version: 2;\n branchId: string;\n entries: DownloadedVersionEntry[];\n};\n\n// ── V1 types (backwards compatibility) ──────────────────────────────\n\nexport type DownloadedVersionEntryV1 = {\n fileName?: string;\n updatedAt?: string;\n postProcessHash?: string;\n sourceHash?: string;\n};\n\nexport type DownloadedVersionsV1 = {\n version: number;\n entries: {\n [branchId: string]: {\n [fileId: string]: {\n [versionId: string]: { [locale: string]: DownloadedVersionEntryV1 };\n };\n };\n };\n};\n\n// ── Conversion helpers ──────────────────────────────────────────────\n\nfunction convertV1ToV2(\n v1: DownloadedVersionsV1,\n branchId: string\n): DownloadedVersions {\n const branchEntries = v1.entries?.[branchId];\n if (!branchEntries) {\n return { version: 2, branchId, entries: [] };\n }\n\n const entries: DownloadedVersionEntry[] = [];\n\n for (const [fileId, versions] of Object.entries(branchEntries)) {\n const versionIds = Object.keys(versions);\n if (versionIds.length === 0) continue;\n\n // Pick the versionId with the most recent updatedAt, defaulting to the first\n let latestVersionId = versionIds[0];\n let latestTime = 0;\n\n for (const [versionId, locales] of Object.entries(versions)) {\n for (const entry of Object.values(locales)) {\n const t = entry.updatedAt ? Date.parse(entry.updatedAt) : 0;\n if (t > latestTime) {\n latestTime = t;\n latestVersionId = versionId;\n }\n }\n }\n\n const localeEntries = versions[latestVersionId];\n const translations: { [locale: string]: DownloadedTranslation } = {};\n\n for (const [locale, entry] of Object.entries(localeEntries)) {\n translations[locale] = {\n ...(entry.updatedAt ? { updatedAt: entry.updatedAt } : {}),\n ...(entry.postProcessHash\n ? { postProcessHash: entry.postProcessHash }\n : {}),\n };\n }\n\n entries.push({\n fileId,\n versionId: latestVersionId,\n translations,\n });\n }\n\n return { version: 2, branchId, entries };\n}\n\nfunction convertV2ToV1Branch(\n v2: DownloadedVersions\n): DownloadedVersionsV1['entries'][string] {\n const branch: DownloadedVersionsV1['entries'][string] = {};\n\n for (const entry of v2.entries) {\n if (!branch[entry.fileId]) {\n branch[entry.fileId] = {};\n }\n if (!branch[entry.fileId][entry.versionId]) {\n branch[entry.fileId][entry.versionId] = {};\n }\n\n for (const [locale, translation] of Object.entries(entry.translations)) {\n branch[entry.fileId][entry.versionId][locale] = {\n ...(translation.updatedAt ? { updatedAt: translation.updatedAt } : {}),\n ...(translation.postProcessHash\n ? { postProcessHash: translation.postProcessHash }\n : {}),\n };\n }\n }\n\n return branch;\n}\n\n// ── Public API ──────────────────────────────────────────────────────\n\n/**\n * Reads the lockfile and returns v2 data regardless of the on-disk format.\n * If the file is v1, `originalV1` contains the full v1 data so that\n * `writeLockfile` can merge changes back without losing other branches.\n */\nexport function readLockfile(settings: Settings): {\n data: DownloadedVersions;\n entryMap: EntryMap;\n originalV1: DownloadedVersionsV1 | null;\n} {\n let branchId = settings._branchId ?? '';\n\n let data: DownloadedVersions;\n let originalV1: DownloadedVersionsV1 | null = null;\n\n try {\n const rootPath = path.join(process.cwd(), GT_LOCK_FILE);\n if (!fs.existsSync(rootPath)) {\n data = { version: 2, branchId, entries: [] };\n } else {\n const raw = JSON.parse(fs.readFileSync(rootPath, 'utf8'));\n if (!raw || typeof raw !== 'object' || !raw.entries) {\n data = { version: 2, branchId, entries: [] };\n } else if (raw.version === 2 && Array.isArray(raw.entries)) {\n data = raw as DownloadedVersions;\n if (branchId) data.branchId = branchId;\n } else {\n originalV1 = raw as DownloadedVersionsV1;\n if (!branchId) {\n const branches = Object.keys(originalV1.entries);\n if (branches.length > 0) branchId = branches[0];\n }\n data = convertV1ToV2(originalV1, branchId);\n }\n }\n } catch (error) {\n logger.error(`An error occurred while reading ${GT_LOCK_FILE}: ${error}`);\n data = { version: 2, branchId, entries: [] };\n }\n\n return { data, entryMap: buildEntryMap(data.entries), originalV1 };\n}\n\n/**\n * Writes the lockfile. If `originalV1` is provided, merges the current\n * branch's data back into the v1 structure (preserving other branches)\n * and writes v1 format. Otherwise writes v2.\n */\nexport function writeLockfile(\n data: DownloadedVersions,\n originalV1: DownloadedVersionsV1 | null\n): void {\n try {\n const filepath = path.join(process.cwd(), GT_LOCK_FILE);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // V1 format can't represent the staged flag — upgrade to V2 if any entries are staged\n if (originalV1 && !data.entries.some((e) => e.staged)) {\n const mergedV1: DownloadedVersionsV1 = {\n ...originalV1,\n entries: {\n ...originalV1.entries,\n [data.branchId]: convertV2ToV1Branch(data),\n },\n };\n fs.writeFileSync(filepath, JSON.stringify(mergedV1, null, 2));\n } else {\n fs.writeFileSync(filepath, JSON.stringify(data, null, 2));\n }\n } catch (error) {\n logger.error(`An error occurred while updating ${GT_LOCK_FILE}: ${error}`);\n }\n}\n\n// ── Lookup helpers ──────────────────────────────────────────────────\n\nexport type EntryMap = Map<string, DownloadedVersionEntry>;\n\nexport function buildEntryMap(entries: DownloadedVersionEntry[]): EntryMap {\n return new Map(entries.map((e) => [e.fileId, e]));\n}\n\n/**\n * Finds or creates an entry, keeping the map and backing array in sync.\n * If the fileId exists but versionId changed, replaces it in-place.\n */\nexport function findOrCreateEntry(\n entryMap: EntryMap,\n entries: DownloadedVersionEntry[],\n fileId: string,\n versionId: string\n): DownloadedVersionEntry {\n const existing = entryMap.get(fileId);\n if (existing) {\n if (existing.versionId === versionId) return existing;\n // Version changed — replace in array and map\n const updated: DownloadedVersionEntry = {\n fileId,\n versionId,\n translations: {},\n };\n const idx = entries.indexOf(existing);\n if (idx !== -1) entries[idx] = updated;\n entryMap.set(fileId, updated);\n return updated;\n }\n const entry: DownloadedVersionEntry = {\n fileId,\n versionId,\n translations: {},\n };\n entries.push(entry);\n entryMap.set(fileId, entry);\n return entry;\n}\n\n// ── Staging helpers ─────────────────────────────────────────────────\n\n/**\n * Writes staged file entries into the lockfile.\n * Each entry is marked with `staged: true` and empty translations.\n */\nexport function writeStagedEntries(\n settings: Settings,\n stagedFiles: { fileId: string; versionId: string; fileName: string }[],\n branchId?: string\n): void {\n const { data, entryMap, originalV1 } = readLockfile(settings);\n\n if (branchId) {\n data.branchId = branchId;\n }\n\n for (const file of stagedFiles) {\n const entry = findOrCreateEntry(\n entryMap,\n data.entries,\n file.fileId,\n file.versionId\n );\n entry.fileName = file.fileName;\n entry.staged = true;\n }\n\n writeLockfile(data, originalV1);\n}\n\n/**\n * Reads staged entries from the lockfile.\n * Returns the same shape as FileTranslationData for compatibility\n * with the download workflow.\n */\nexport function getStagedEntriesFromLockfile(\n settings: Settings\n): Record<string, { versionId: string; fileName: string }> {\n const { data } = readLockfile(settings);\n const result: Record<string, { versionId: string; fileName: string }> = {};\n\n for (const entry of data.entries) {\n if (entry.staged && entry.fileName) {\n result[entry.fileId] = {\n versionId: entry.versionId,\n fileName: entry.fileName,\n };\n }\n }\n\n return result;\n}\n"],"mappings":";;;;AAKA,MAAM,eAAe;AAgDrB,SAAS,cACP,IACA,UACoB;CACpB,MAAM,gBAAgB,GAAG,UAAU;AACnC,KAAI,CAAC,cACH,QAAO;EAAE,SAAS;EAAG;EAAU,SAAS,EAAE;EAAE;CAG9C,MAAM,UAAoC,EAAE;AAE5C,MAAK,MAAM,CAAC,QAAQ,aAAa,OAAO,QAAQ,cAAc,EAAE;EAC9D,MAAM,aAAa,OAAO,KAAK,SAAS;AACxC,MAAI,WAAW,WAAW,EAAG;EAG7B,IAAI,kBAAkB,WAAW;EACjC,IAAI,aAAa;AAEjB,OAAK,MAAM,CAAC,WAAW,YAAY,OAAO,QAAQ,SAAS,CACzD,MAAK,MAAM,SAAS,OAAO,OAAO,QAAQ,EAAE;GAC1C,MAAM,IAAI,MAAM,YAAY,KAAK,MAAM,MAAM,UAAU,GAAG;AAC1D,OAAI,IAAI,YAAY;AAClB,iBAAa;AACb,sBAAkB;;;EAKxB,MAAM,gBAAgB,SAAS;EAC/B,MAAM,eAA4D,EAAE;AAEpE,OAAK,MAAM,CAAC,QAAQ,UAAU,OAAO,QAAQ,cAAc,CACzD,cAAa,UAAU;GACrB,GAAI,MAAM,YAAY,EAAE,WAAW,MAAM,WAAW,GAAG,EAAE;GACzD,GAAI,MAAM,kBACN,EAAE,iBAAiB,MAAM,iBAAiB,GAC1C,EAAE;GACP;AAGH,UAAQ,KAAK;GACX;GACA,WAAW;GACX;GACD,CAAC;;AAGJ,QAAO;EAAE,SAAS;EAAG;EAAU;EAAS;;AAG1C,SAAS,oBACP,IACyC;CACzC,MAAM,SAAkD,EAAE;AAE1D,MAA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AAK,WAAW;AAGlB,MAAK,MAAM,QAAQ,aAAa;EAC9B,MAAM,QAAQ,kBACZ,UACA,KAAK,SACL,KAAK,QACL,KAAK,UACN;AACD,QAAM,WAAW,KAAK;AACtB,QAAM,SAAS;;AAGjB,eAAc,MAAM,WAAW;;;;;;;AAQjC,SAAgB,6BACd,UACyD;CACzD,MAAM,EAAE,SAAS,aAAa,SAAS;CACvC,MAAM,SAAkE,EAAE;AAE1E,MAAK,MAAM,SAAS,KAAK,QACvB,KAAI,MAAM,UAAU,MAAM,SACxB,QAAO,MAAM,UAAU;EACrB,WAAW,MAAM;EACjB,UAAU,MAAM;EACjB;AAIL,QAAO"}
1
+ {"version":3,"file":"downloadedVersions.js","names":[],"sources":["../../../src/fs/config/downloadedVersions.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../../console/logger.js';\nimport { stringifyJson } from '../stringifyJson.js';\nimport type { Settings } from '../../types/index.js';\n\nconst GT_LOCK_FILE = 'gt-lock.json';\n\n// ── V2 types (internal working format) ──────────────────────────────\n\nexport type DownloadedTranslation = {\n updatedAt?: string;\n postProcessHash?: string;\n fileName?: string; // output path for this locale, e.g. \"es-US/my/file/path.mdx\"\n};\n\nexport type DownloadedVersionEntry = {\n fileId: string;\n versionId: string;\n fileName?: string; // source file path\n staged?: boolean; // true if this entry was staged but not yet downloaded\n translations: {\n [locale: string]: DownloadedTranslation;\n };\n};\n\nexport type DownloadedVersions = {\n version: 2;\n branchId: string;\n entries: DownloadedVersionEntry[];\n};\n\n// ── V1 types (backwards compatibility) ──────────────────────────────\n\nexport type DownloadedVersionEntryV1 = {\n fileName?: string;\n updatedAt?: string;\n postProcessHash?: string;\n sourceHash?: string;\n};\n\nexport type DownloadedVersionsV1 = {\n version: number;\n entries: {\n [branchId: string]: {\n [fileId: string]: {\n [versionId: string]: { [locale: string]: DownloadedVersionEntryV1 };\n };\n };\n };\n};\n\n// ── Conversion helpers ──────────────────────────────────────────────\n\nfunction convertV1ToV2(\n v1: DownloadedVersionsV1,\n branchId: string\n): DownloadedVersions {\n const branchEntries = v1.entries?.[branchId];\n if (!branchEntries) {\n return { version: 2, branchId, entries: [] };\n }\n\n const entries: DownloadedVersionEntry[] = [];\n\n for (const [fileId, versions] of Object.entries(branchEntries)) {\n const versionIds = Object.keys(versions);\n if (versionIds.length === 0) continue;\n\n // Pick the versionId with the most recent updatedAt, defaulting to the first\n let latestVersionId = versionIds[0];\n let latestTime = 0;\n\n for (const [versionId, locales] of Object.entries(versions)) {\n for (const entry of Object.values(locales)) {\n const t = entry.updatedAt ? Date.parse(entry.updatedAt) : 0;\n if (t > latestTime) {\n latestTime = t;\n latestVersionId = versionId;\n }\n }\n }\n\n const localeEntries = versions[latestVersionId];\n const translations: { [locale: string]: DownloadedTranslation } = {};\n\n for (const [locale, entry] of Object.entries(localeEntries)) {\n translations[locale] = {\n ...(entry.updatedAt ? { updatedAt: entry.updatedAt } : {}),\n ...(entry.postProcessHash\n ? { postProcessHash: entry.postProcessHash }\n : {}),\n };\n }\n\n entries.push({\n fileId,\n versionId: latestVersionId,\n translations,\n });\n }\n\n return { version: 2, branchId, entries };\n}\n\nfunction convertV2ToV1Branch(\n v2: DownloadedVersions\n): DownloadedVersionsV1['entries'][string] {\n const branch: DownloadedVersionsV1['entries'][string] = {};\n\n for (const entry of v2.entries) {\n if (!branch[entry.fileId]) {\n branch[entry.fileId] = {};\n }\n if (!branch[entry.fileId][entry.versionId]) {\n branch[entry.fileId][entry.versionId] = {};\n }\n\n for (const [locale, translation] of Object.entries(entry.translations)) {\n branch[entry.fileId][entry.versionId][locale] = {\n ...(translation.updatedAt ? { updatedAt: translation.updatedAt } : {}),\n ...(translation.postProcessHash\n ? { postProcessHash: translation.postProcessHash }\n : {}),\n };\n }\n }\n\n return branch;\n}\n\n// ── Public API ──────────────────────────────────────────────────────\n\n/**\n * Reads the lockfile and returns v2 data regardless of the on-disk format.\n * If the file is v1, `originalV1` contains the full v1 data so that\n * `writeLockfile` can merge changes back without losing other branches.\n */\nexport function readLockfile(settings: Settings): {\n data: DownloadedVersions;\n entryMap: EntryMap;\n originalV1: DownloadedVersionsV1 | null;\n} {\n let branchId = settings._branchId ?? '';\n\n let data: DownloadedVersions;\n let originalV1: DownloadedVersionsV1 | null = null;\n\n try {\n const rootPath = path.join(process.cwd(), GT_LOCK_FILE);\n if (!fs.existsSync(rootPath)) {\n data = { version: 2, branchId, entries: [] };\n } else {\n const raw = JSON.parse(fs.readFileSync(rootPath, 'utf8'));\n if (!raw || typeof raw !== 'object' || !raw.entries) {\n data = { version: 2, branchId, entries: [] };\n } else if (raw.version === 2 && Array.isArray(raw.entries)) {\n data = raw as DownloadedVersions;\n if (branchId) data.branchId = branchId;\n } else {\n originalV1 = raw as DownloadedVersionsV1;\n if (!branchId) {\n const branches = Object.keys(originalV1.entries);\n if (branches.length > 0) branchId = branches[0];\n }\n data = convertV1ToV2(originalV1, branchId);\n }\n }\n } catch (error) {\n logger.error(`An error occurred while reading ${GT_LOCK_FILE}: ${error}`);\n data = { version: 2, branchId, entries: [] };\n }\n\n return { data, entryMap: buildEntryMap(data.entries), originalV1 };\n}\n\n/**\n * Writes the lockfile. If `originalV1` is provided, merges the current\n * branch's data back into the v1 structure (preserving other branches)\n * and writes v1 format. Otherwise writes v2.\n */\nexport function writeLockfile(\n data: DownloadedVersions,\n originalV1: DownloadedVersionsV1 | null\n): void {\n try {\n const filepath = path.join(process.cwd(), GT_LOCK_FILE);\n fs.mkdirSync(path.dirname(filepath), { recursive: true });\n\n // V1 format can't represent the staged flag — upgrade to V2 if any entries are staged\n if (originalV1 && !data.entries.some((e) => e.staged)) {\n const mergedV1: DownloadedVersionsV1 = {\n ...originalV1,\n entries: {\n ...originalV1.entries,\n [data.branchId]: convertV2ToV1Branch(data),\n },\n };\n fs.writeFileSync(filepath, stringifyJson(mergedV1));\n } else {\n fs.writeFileSync(filepath, stringifyJson(data));\n }\n } catch (error) {\n logger.error(`An error occurred while updating ${GT_LOCK_FILE}: ${error}`);\n }\n}\n\n// ── Lookup helpers ──────────────────────────────────────────────────\n\nexport type EntryMap = Map<string, DownloadedVersionEntry>;\n\nexport function buildEntryMap(entries: DownloadedVersionEntry[]): EntryMap {\n return new Map(entries.map((e) => [e.fileId, e]));\n}\n\n/**\n * Finds or creates an entry, keeping the map and backing array in sync.\n * If the fileId exists but versionId changed, replaces it in-place.\n */\nexport function findOrCreateEntry(\n entryMap: EntryMap,\n entries: DownloadedVersionEntry[],\n fileId: string,\n versionId: string\n): DownloadedVersionEntry {\n const existing = entryMap.get(fileId);\n if (existing) {\n if (existing.versionId === versionId) return existing;\n // Version changed — replace in array and map\n const updated: DownloadedVersionEntry = {\n fileId,\n versionId,\n translations: {},\n };\n const idx = entries.indexOf(existing);\n if (idx !== -1) entries[idx] = updated;\n entryMap.set(fileId, updated);\n return updated;\n }\n const entry: DownloadedVersionEntry = {\n fileId,\n versionId,\n translations: {},\n };\n entries.push(entry);\n entryMap.set(fileId, entry);\n return entry;\n}\n\n// ── Staging helpers ─────────────────────────────────────────────────\n\n/**\n * Writes staged file entries into the lockfile.\n * Each entry is marked with `staged: true` and empty translations.\n */\nexport function writeStagedEntries(\n settings: Settings,\n stagedFiles: { fileId: string; versionId: string; fileName: string }[],\n branchId?: string\n): void {\n const { data, entryMap, originalV1 } = readLockfile(settings);\n\n if (branchId) {\n data.branchId = branchId;\n }\n\n for (const file of stagedFiles) {\n const entry = findOrCreateEntry(\n entryMap,\n data.entries,\n file.fileId,\n file.versionId\n );\n entry.fileName = file.fileName;\n entry.staged = true;\n }\n\n writeLockfile(data, originalV1);\n}\n\n/**\n * Reads staged entries from the lockfile.\n * Returns the same shape as FileTranslationData for compatibility\n * with the download workflow.\n */\nexport function getStagedEntriesFromLockfile(\n settings: Settings\n): Record<string, { versionId: string; fileName: string }> {\n const { data } = readLockfile(settings);\n const result: Record<string, { versionId: string; fileName: string }> = {};\n\n for (const entry of data.entries) {\n if (entry.staged && entry.fileName) {\n result[entry.fileId] = {\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UACyD;CACzD,MAAM,EAAE,SAAS,aAAa,SAAS;CACvC,MAAM,SAAkE,EAAE;AAE1E,MAAK,MAAM,SAAS,KAAK,QACvB,KAAI,MAAM,UAAU,MAAM,SACxB,QAAO,MAAM,UAAU;EACrB,WAAW,MAAM;EACjB,UAAU,MAAM;EACjB;AAIL,QAAO"}
@@ -1,4 +1,5 @@
1
1
  import { logger } from "../../console/logger.js";
2
+ import { stringifyJson } from "../stringifyJson.js";
2
3
  import { displayUpdatedConfigFile } from "../../console/logging.js";
3
4
  import fs from "node:fs";
4
5
  //#region src/fs/config/updateConfig.ts
@@ -21,15 +22,16 @@ async function updateConfig(configFilepath, options) {
21
22
  };
22
23
  try {
23
24
  let oldContent = {};
25
+ let originalText;
24
26
  if (fs.existsSync(configFilepath)) {
25
- const parsed = JSON.parse(await fs.promises.readFile(configFilepath, "utf-8"));
27
+ originalText = await fs.promises.readFile(configFilepath, "utf-8");
28
+ const parsed = JSON.parse(originalText);
26
29
  oldContent = typeof parsed === "object" && parsed !== null ? parsed : {};
27
30
  }
28
- const filteredContent = applyNullFilter({
31
+ const jsonContent = stringifyJson(applyNullFilter({
29
32
  ...oldContent,
30
33
  ...newContent
31
- }, options);
32
- const jsonContent = JSON.stringify(filteredContent, null, 2);
34
+ }, options), originalText);
33
35
  await fs.promises.writeFile(configFilepath, jsonContent, "utf-8");
34
36
  displayUpdatedConfigFile(configFilepath);
35
37
  } catch (error) {
@@ -1 +1 @@
1
- {"version":3,"file":"updateConfig.js","names":[],"sources":["../../../src/fs/config/updateConfig.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { displayUpdatedConfigFile } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\n\n/**\n * Options for updating the config file.\n *\n * Since these are all string values, we can use null to mark them for removal\n */\ntype UpdateConfigOptions = {\n projectId?: string | null;\n _versionId?: string | null;\n _branchId?: string | null;\n stageTranslations?: boolean | null;\n omitConfigIds?: boolean | null;\n};\n\n/**\n * Update the config file version id, locales, and projectId (if necessary)\n * @param {string} configFilepath - The path to the config file.\n * @param {UpdateConfigOptions} options - The options to update the config file with.\n * @returns {Promise<void>} - A promise that resolves when the config file is updated.\n *\n * Hint: Mark a field as null to remove it from the config file.\n */\nexport default async function updateConfig(\n configFilepath: string,\n options: UpdateConfigOptions\n): Promise<void> {\n // Filter out empty string values from the config object\n const { projectId, _versionId, _branchId, stageTranslations, omitConfigIds } =\n options;\n const newContent = {\n ...(projectId && { projectId }),\n ...(_versionId && { _versionId }),\n ...(_branchId && { _branchId }),\n // Omit when false\n ...(stageTranslations && { stageTranslations }),\n ...(omitConfigIds && { omitConfigIds }),\n };\n\n try {\n // if file exists\n let oldContent: Record<string, unknown> = {};\n if (fs.existsSync(configFilepath)) {\n const parsed = JSON.parse(\n await fs.promises.readFile(configFilepath, 'utf-8')\n );\n oldContent =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : {};\n }\n\n // merge old and new content\n const mergedContent = {\n ...oldContent,\n ...newContent,\n };\n\n // Apply null filter to remove values that were marked for removal\n const filteredContent = applyNullFilter(mergedContent, options);\n\n // write to file\n const jsonContent = JSON.stringify(filteredContent, null, 2);\n await fs.promises.writeFile(configFilepath, jsonContent, 'utf-8');\n\n // show update in console\n displayUpdatedConfigFile(configFilepath);\n } catch (error) {\n logger.error(\n `An error occurred while updating ${configFilepath}: ${error}`\n );\n }\n}\n\n// --- Helper functions --- //\n\n/**\n * Remove values from object if they were marked for removal\n */\nfunction applyNullFilter<T extends Record<string, unknown>>(\n obj: T,\n filter: Partial<Record<keyof T, null | unknown>>\n): T {\n const result = { ...obj };\n for (const key of Object.keys(filter)) {\n if (filter[key] === null) {\n delete result[key];\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,eAA8B,aAC5B,gBACA,SACe;CAEf,MAAM,EAAE,WAAW,YAAY,WAAW,mBAAmB,kBAC3D;CACF,MAAM,aAAa;EACjB,GAAI,aAAa,EAAE,WAAW;EAC9B,GAAI,cAAc,EAAE,YAAY;EAChC,GAAI,aAAa,EAAE,WAAW;EAE9B,GAAI,qBAAqB,EAAE,mBAAmB;EAC9C,GAAI,iBAAiB,EAAE,eAAe;EACvC;AAED,KAAI;EAEF,IAAI,aAAsC,EAAE;AAC5C,MAAI,GAAG,WAAW,eAAe,EAAE;GACjC,MAAM,SAAS,KAAK,MAClB,MAAM,GAAG,SAAS,SAAS,gBAAgB,QAAQ,CACpD;AACD,gBACE,OAAO,WAAW,YAAY,WAAW,OACpC,SACD,EAAE;;EAUV,MAAM,kBAAkB,gBAAgB;GALtC,GAAG;GACH,GAAG;GAIgD,EAAE,QAAQ;EAG/D,MAAM,cAAc,KAAK,UAAU,iBAAiB,MAAM,EAAE;AAC5D,QAAM,GAAG,SAAS,UAAU,gBAAgB,aAAa,QAAQ;AAGjE,2BAAyB,eAAe;UACjC,OAAO;AACd,SAAO,MACL,oCAAoC,eAAe,IAAI,QACxD;;;;;;AASL,SAAS,gBACP,KACA,QACG;CACH,MAAM,SAAS,EAAE,GAAG,KAAK;AACzB,MAAK,MAAM,OAAO,OAAO,KAAK,OAAO,CACnC,KAAI,OAAO,SAAS,KAClB,QAAO,OAAO;AAGlB,QAAO"}
1
+ {"version":3,"file":"updateConfig.js","names":[],"sources":["../../../src/fs/config/updateConfig.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { stringifyJson } from '../stringifyJson.js';\nimport { displayUpdatedConfigFile } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\n\n/**\n * Options for updating the config file.\n *\n * Since these are all string values, we can use null to mark them for removal\n */\ntype UpdateConfigOptions = {\n projectId?: string | null;\n _versionId?: string | null;\n _branchId?: string | null;\n stageTranslations?: boolean | null;\n omitConfigIds?: boolean | null;\n};\n\n/**\n * Update the config file version id, locales, and projectId (if necessary)\n * @param {string} configFilepath - The path to the config file.\n * @param {UpdateConfigOptions} options - The options to update the config file with.\n * @returns {Promise<void>} - A promise that resolves when the config file is updated.\n *\n * Hint: Mark a field as null to remove it from the config file.\n */\nexport default async function updateConfig(\n configFilepath: string,\n options: UpdateConfigOptions\n): Promise<void> {\n // Filter out empty string values from the config object\n const { projectId, _versionId, _branchId, stageTranslations, omitConfigIds } =\n options;\n const newContent = {\n ...(projectId && { projectId }),\n ...(_versionId && { _versionId }),\n ...(_branchId && { _branchId }),\n // Omit when false\n ...(stageTranslations && { stageTranslations }),\n ...(omitConfigIds && { omitConfigIds }),\n };\n\n try {\n // if file exists\n let oldContent: Record<string, unknown> = {};\n let originalText: string | undefined;\n if (fs.existsSync(configFilepath)) {\n originalText = await fs.promises.readFile(configFilepath, 'utf-8');\n const parsed = JSON.parse(originalText);\n oldContent =\n typeof parsed === 'object' && parsed !== null\n ? (parsed as Record<string, unknown>)\n : {};\n }\n\n // merge old and new content\n const mergedContent = {\n ...oldContent,\n ...newContent,\n };\n\n // Apply null filter to remove values that were marked for removal\n const filteredContent = applyNullFilter(mergedContent, options);\n\n // write to file\n const jsonContent = stringifyJson(filteredContent, originalText);\n await fs.promises.writeFile(configFilepath, jsonContent, 'utf-8');\n\n // show update in console\n displayUpdatedConfigFile(configFilepath);\n } catch (error) {\n logger.error(\n `An error occurred while updating ${configFilepath}: ${error}`\n );\n }\n}\n\n// --- Helper functions --- //\n\n/**\n * Remove values from object if they were marked for removal\n */\nfunction applyNullFilter<T extends Record<string, unknown>>(\n obj: T,\n filter: Partial<Record<keyof T, null | unknown>>\n): T {\n const result = { ...obj };\n for (const key of Object.keys(filter)) {\n if (filter[key] === null) {\n delete result[key];\n }\n }\n return result;\n}\n"],"mappings":";;;;;;;;;;;;;AA0BA,eAA8B,aAC5B,gBACA,SACe;CAEf,MAAM,EAAE,WAAW,YAAY,WAAW,mBAAmB,kBAC3D;CACF,MAAM,aAAa;EACjB,GAAI,aAAa,EAAE,WAAW;EAC9B,GAAI,cAAc,EAAE,YAAY;EAChC,GAAI,aAAa,EAAE,WAAW;EAE9B,GAAI,qBAAqB,EAAE,mBAAmB;EAC9C,GAAI,iBAAiB,EAAE,eAAe;EACvC;AAED,KAAI;EAEF,IAAI,aAAsC,EAAE;EAC5C,IAAI;AACJ,MAAI,GAAG,WAAW,eAAe,EAAE;AACjC,kBAAe,MAAM,GAAG,SAAS,SAAS,gBAAgB,QAAQ;GAClE,MAAM,SAAS,KAAK,MAAM,aAAa;AACvC,gBACE,OAAO,WAAW,YAAY,WAAW,OACpC,SACD,EAAE;;EAaV,MAAM,cAAc,cAHI,gBAAgB;GALtC,GAAG;GACH,GAAG;GAIgD,EAAE,QAGN,EAAE,aAAa;AAChE,QAAM,GAAG,SAAS,UAAU,gBAAgB,aAAa,QAAQ;AAGjE,2BAAyB,eAAe;UACjC,OAAO;AACd,SAAO,MACL,oCAAoC,eAAe,IAAI,QACxD;;;;;;AASL,SAAS,gBACP,KACA,QACG;CACH,MAAM,SAAS,EAAE,GAAG,KAAK;AACzB,MAAK,MAAM,OAAO,OAAO,KAAK,OAAO,CACnC,KAAI,OAAO,SAAS,KAClB,QAAO,OAAO;AAGlB,QAAO"}
@@ -1,4 +1,5 @@
1
1
  import { logger } from "../../console/logger.js";
2
+ import { stringifyJson } from "../stringifyJson.js";
2
3
  import { displayUpdatedVersionsFile } from "../../console/logging.js";
3
4
  import path from "node:path";
4
5
  import fs from "node:fs";
@@ -8,7 +9,7 @@ async function updateVersions({ configDirectory, versionData }) {
8
9
  const versionFilepath = path.join(configDirectory, STAGED_VERSIONS_FILE);
9
10
  try {
10
11
  fs.mkdirSync(configDirectory, { recursive: true });
11
- fs.writeFileSync(versionFilepath, JSON.stringify(versionData, null, 2));
12
+ fs.writeFileSync(versionFilepath, stringifyJson(versionData));
12
13
  displayUpdatedVersionsFile(versionFilepath);
13
14
  } catch (error) {
14
15
  logger.error(`An error occurred while updating ${versionFilepath}: ${error}`);
@@ -1 +1 @@
1
- {"version":3,"file":"updateVersions.js","names":[],"sources":["../../../src/fs/config/updateVersions.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { displayUpdatedVersionsFile } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\nimport path from 'node:path';\n\nconst STAGED_VERSIONS_FILE = 'staged-versions.json';\ntype StagedVersionData = Record<\n string, // fileId\n { fileName: string; versionId: string }\n>;\n// Update the versions.json file with the new version ids\n// of the translations that were sent to the API\nexport async function updateVersions({\n configDirectory,\n versionData,\n}: {\n configDirectory: string;\n versionData: StagedVersionData;\n}): Promise<void> {\n const versionFilepath = path.join(configDirectory, STAGED_VERSIONS_FILE);\n try {\n fs.mkdirSync(configDirectory, { recursive: true });\n fs.writeFileSync(versionFilepath, JSON.stringify(versionData, null, 2));\n\n // show update in console\n displayUpdatedVersionsFile(versionFilepath);\n } catch (error) {\n logger.error(\n `An error occurred while updating ${versionFilepath}: ${error}`\n );\n }\n}\n\nexport async function getStagedVersions(\n configDirectory: string\n): Promise<StagedVersionData> {\n try {\n const versionFilepath = path.join(configDirectory, STAGED_VERSIONS_FILE);\n const versionData = JSON.parse(fs.readFileSync(versionFilepath, 'utf8'));\n return versionData;\n } catch (error) {\n logger.error(`An error occurred while getting staged versions: ${error}`);\n return {};\n }\n}\n"],"mappings":";;;;;AAKA,MAAM,uBAAuB;AAO7B,eAAsB,eAAe,EACnC,iBACA,eAIgB;CAChB,MAAM,kBAAkB,KAAK,KAAK,iBAAiB,qBAAqB;AACxE,KAAI;AACF,KAAG,UAAU,iBAAiB,EAAE,WAAW,MAAM,CAAC;AAClD,KAAG,cAAc,iBAAiB,KAAK,UAAU,aAAa,MAAM,EAAE,CAAC;AAGvE,6BAA2B,gBAAgB;UACpC,OAAO;AACd,SAAO,MACL,oCAAoC,gBAAgB,IAAI,QACzD;;;AAIL,eAAsB,kBACpB,iBAC4B;AAC5B,KAAI;EACF,MAAM,kBAAkB,KAAK,KAAK,iBAAiB,qBAAqB;AAExE,SADoB,KAAK,MAAM,GAAG,aAAa,iBAAiB,OAAO,CACrD;UACX,OAAO;AACd,SAAO,MAAM,oDAAoD,QAAQ;AACzE,SAAO,EAAE"}
1
+ {"version":3,"file":"updateVersions.js","names":[],"sources":["../../../src/fs/config/updateVersions.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { displayUpdatedVersionsFile } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\nimport path from 'node:path';\nimport { stringifyJson } from '../stringifyJson.js';\n\nconst STAGED_VERSIONS_FILE = 'staged-versions.json';\ntype StagedVersionData = Record<\n string, // fileId\n { fileName: string; versionId: string }\n>;\n// Update the versions.json file with the new version ids\n// of the translations that were sent to the API\nexport async function updateVersions({\n configDirectory,\n versionData,\n}: {\n configDirectory: string;\n versionData: StagedVersionData;\n}): Promise<void> {\n const versionFilepath = path.join(configDirectory, STAGED_VERSIONS_FILE);\n try {\n fs.mkdirSync(configDirectory, { recursive: true });\n fs.writeFileSync(versionFilepath, stringifyJson(versionData));\n\n // show update in console\n displayUpdatedVersionsFile(versionFilepath);\n } catch (error) {\n logger.error(\n `An error occurred while updating ${versionFilepath}: ${error}`\n );\n }\n}\n\nexport async function getStagedVersions(\n configDirectory: string\n): Promise<StagedVersionData> {\n try {\n const versionFilepath = path.join(configDirectory, STAGED_VERSIONS_FILE);\n const versionData = JSON.parse(fs.readFileSync(versionFilepath, 'utf8'));\n return versionData;\n } catch (error) {\n logger.error(`An error occurred while getting staged versions: ${error}`);\n return {};\n }\n}\n"],"mappings":";;;;;;AAMA,MAAM,uBAAuB;AAO7B,eAAsB,eAAe,EACnC,iBACA,eAIgB;CAChB,MAAM,kBAAkB,KAAK,KAAK,iBAAiB,qBAAqB;AACxE,KAAI;AACF,KAAG,UAAU,iBAAiB,EAAE,WAAW,MAAM,CAAC;AAClD,KAAG,cAAc,iBAAiB,cAAc,YAAY,CAAC;AAG7D,6BAA2B,gBAAgB;UACpC,OAAO;AACd,SAAO,MACL,oCAAoC,gBAAgB,IAAI,QACzD;;;AAIL,eAAsB,kBACpB,iBAC4B;AAC5B,KAAI;EACF,MAAM,kBAAkB,KAAK,KAAK,iBAAiB,qBAAqB;AAExE,SADoB,KAAK,MAAM,GAAG,aAAa,iBAAiB,OAAO,CACrD;UACX,OAAO;AACd,SAAO,MAAM,oDAAoD,QAAQ;AACzE,SAAO,EAAE"}
@@ -1,9 +1,10 @@
1
+ import { stringifyJson } from "./stringifyJson.js";
1
2
  import path from "node:path";
2
3
  import fs from "node:fs";
3
4
  //#region src/fs/saveJSON.ts
4
5
  async function saveJSON(filepath, data) {
5
6
  await fs.promises.mkdir(path.dirname(filepath), { recursive: true });
6
- await fs.promises.writeFile(filepath, JSON.stringify(data, null, 2));
7
+ await fs.promises.writeFile(filepath, stringifyJson(data));
7
8
  }
8
9
  //#endregion
9
10
  export { saveJSON };
@@ -1 +1 @@
1
- {"version":3,"file":"saveJSON.js","names":[],"sources":["../../src/fs/saveJSON.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\n\nexport async function saveJSON(\n filepath: string,\n data: Record<string, unknown>\n) {\n // Ensure directory exists\n await fs.promises.mkdir(path.dirname(filepath), { recursive: true });\n\n await fs.promises.writeFile(filepath, JSON.stringify(data, null, 2));\n}\n"],"mappings":";;;AAGA,eAAsB,SACpB,UACA,MACA;AAEA,OAAM,GAAG,SAAS,MAAM,KAAK,QAAQ,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC;AAEpE,OAAM,GAAG,SAAS,UAAU,UAAU,KAAK,UAAU,MAAM,MAAM,EAAE,CAAC"}
1
+ {"version":3,"file":"saveJSON.js","names":[],"sources":["../../src/fs/saveJSON.ts"],"sourcesContent":["import path from 'node:path';\nimport fs from 'node:fs';\nimport { stringifyJson } from './stringifyJson.js';\n\nexport async function saveJSON(\n filepath: string,\n data: Record<string, unknown>\n) {\n // Ensure directory exists\n await fs.promises.mkdir(path.dirname(filepath), { recursive: true });\n\n await fs.promises.writeFile(filepath, stringifyJson(data));\n}\n"],"mappings":";;;;AAIA,eAAsB,SACpB,UACA,MACA;AAEA,OAAM,GAAG,SAAS,MAAM,KAAK,QAAQ,SAAS,EAAE,EAAE,WAAW,MAAM,CAAC;AAEpE,OAAM,GAAG,SAAS,UAAU,UAAU,cAAc,KAAK,CAAC"}
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Serializes JSON for writing to disk. Keeps the trailing newline convention
3
+ * of the file being overwritten, and ends new files with a newline.
4
+ * @param data - The value to serialize.
5
+ * @param original - The current contents of the file being overwritten, if any.
6
+ */
7
+ export declare function stringifyJson(data: unknown, original?: string): string;
@@ -0,0 +1,15 @@
1
+ //#region src/fs/stringifyJson.ts
2
+ /**
3
+ * Serializes JSON for writing to disk. Keeps the trailing newline convention
4
+ * of the file being overwritten, and ends new files with a newline.
5
+ * @param data - The value to serialize.
6
+ * @param original - The current contents of the file being overwritten, if any.
7
+ */
8
+ function stringifyJson(data, original) {
9
+ const finalNewline = original === void 0 || original.endsWith("\n");
10
+ return JSON.stringify(data, null, 2) + (finalNewline ? "\n" : "");
11
+ }
12
+ //#endregion
13
+ export { stringifyJson };
14
+
15
+ //# sourceMappingURL=stringifyJson.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stringifyJson.js","names":[],"sources":["../../src/fs/stringifyJson.ts"],"sourcesContent":["/**\n * Serializes JSON for writing to disk. Keeps the trailing newline convention\n * of the file being overwritten, and ends new files with a newline.\n * @param data - The value to serialize.\n * @param original - The current contents of the file being overwritten, if any.\n */\nexport function stringifyJson(data: unknown, original?: string): string {\n const finalNewline = original === undefined || original.endsWith('\\n');\n return JSON.stringify(data, null, 2) + (finalNewline ? '\\n' : '');\n}\n"],"mappings":";;;;;;;AAMA,SAAgB,cAAc,MAAe,UAA2B;CACtE,MAAM,eAAe,aAAa,KAAA,KAAa,SAAS,SAAS,KAAK;AACtE,QAAO,KAAK,UAAU,MAAM,MAAM,EAAE,IAAI,eAAe,OAAO"}
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.26.10";
1
+ export declare const PACKAGE_VERSION = "2.26.11";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.26.10";
2
+ const PACKAGE_VERSION = "2.26.11";
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.26.10';\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.26.11';\n"],"mappings":";AACA,MAAa,kBAAkB"}
@@ -1,3 +1,4 @@
1
+ import { stringifyJson } from "../fs/stringifyJson.js";
1
2
  import { createFileMapping } from "../formats/files/fileMapping.js";
2
3
  import { batchProcess } from "./batchProcess.js";
3
4
  import fs from "node:fs";
@@ -7,8 +8,9 @@ async function flattenJsonFiles(settings, includeFiles) {
7
8
  const { resolvedPaths: sourceFiles } = settings.files;
8
9
  const fileMapping = createFileMapping(sourceFiles, settings.files.placeholderPaths, settings.files.transformPaths, settings.files.transformFormats, settings.locales, settings.defaultLocale);
9
10
  for (const filesMap of Object.values(fileMapping)) await batchProcess(Object.values(filesMap).filter((p) => p.endsWith(".json") && (!includeFiles || includeFiles.has(p))), async (file) => {
10
- const flattenedJson = flattenJson(JSON.parse(fs.readFileSync(file, "utf8")));
11
- await fs.promises.writeFile(file, JSON.stringify(flattenedJson, null, 2));
11
+ const content = fs.readFileSync(file, "utf8");
12
+ const flattenedJson = flattenJson(JSON.parse(content));
13
+ await fs.promises.writeFile(file, stringifyJson(flattenedJson, content));
12
14
  return flattenedJson;
13
15
  }, 512);
14
16
  }
@@ -1 +1 @@
1
- {"version":3,"file":"flattenJsonFiles.js","names":[],"sources":["../../src/utils/flattenJsonFiles.ts"],"sourcesContent":["import { createFileMapping } from '../formats/files/fileMapping.js';\nimport fs from 'node:fs';\nimport { Settings } from '../types/index.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nexport default async function flattenJsonFiles(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n // One locale at a time so the concurrency bound covers the whole pass\n for (const filesMap of Object.values(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (p) => p.endsWith('.json') && (!includeFiles || includeFiles.has(p))\n );\n\n await batchProcess(\n targetFiles,\n async (file) => {\n // Read each json file\n const json = JSON.parse(fs.readFileSync(file, 'utf8'));\n // Flatten the json\n const flattenedJson = flattenJson(json);\n\n // Write the flattened json to the target file\n await fs.promises.writeFile(\n file,\n JSON.stringify(flattenedJson, null, 2)\n );\n return flattenedJson;\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n\nfunction flattenJson(json: unknown, prefix = ''): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(json as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(result, flattenJson(value, newKey));\n } else {\n result[newKey] = value;\n }\n }\n\n return result;\n}\n"],"mappings":";;;;AAKA,eAA8B,iBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC;CAEF,MAAM,EAAE,eAAe,gBAAgB,SAAS;CAEhD,MAAM,cAAc,kBAClB,aACA,SAAS,MAAM,kBACf,SAAS,MAAM,gBACf,SAAS,MAAM,kBACf,SAAS,SACT,SAAS,cACV;AAGD,MAAK,MAAM,YAAY,OAAO,OAAO,YAAY,CAK/C,OAAM,aAJc,OAAO,OAAO,SAAS,CAAC,QACzC,MAAM,EAAE,SAAS,QAAQ,KAAK,CAAC,gBAAgB,aAAa,IAAI,EAAE,EAIxD,EACX,OAAO,SAAS;EAId,MAAM,gBAAgB,YAFT,KAAK,MAAM,GAAG,aAAa,MAAM,OAAO,CAEf,CAAC;AAGvC,QAAM,GAAG,SAAS,UAChB,MACA,KAAK,UAAU,eAAe,MAAM,EAAE,CACvC;AACD,SAAO;QAGV;;AAIL,SAAS,YAAY,MAAe,SAAS,IAA6B;CACxE,MAAM,SAAkC,EAAE;AAE1C,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,EAAE;EAC1E,MAAM,SAAS,SAAS,GAAG,OAAO,GAAG,QAAQ;AAE7C,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,CACtE,QAAO,OAAO,QAAQ,YAAY,OAAO,OAAO,CAAC;MAEjD,QAAO,UAAU;;AAIrB,QAAO"}
1
+ {"version":3,"file":"flattenJsonFiles.js","names":[],"sources":["../../src/utils/flattenJsonFiles.ts"],"sourcesContent":["import { createFileMapping } from '../formats/files/fileMapping.js';\nimport fs from 'node:fs';\nimport { stringifyJson } from '../fs/stringifyJson.js';\nimport { Settings } from '../types/index.js';\nimport { batchProcess, FILE_IO_CONCURRENCY } from './batchProcess.js';\n\nexport default async function flattenJsonFiles(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n if (\n !settings.files ||\n (Object.keys(settings.files.placeholderPaths).length === 1 &&\n settings.files.placeholderPaths.gt)\n ) {\n return;\n }\n const { resolvedPaths: sourceFiles } = settings.files;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths,\n settings.files.transformFormats,\n settings.locales,\n settings.defaultLocale\n );\n\n // One locale at a time so the concurrency bound covers the whole pass\n for (const filesMap of Object.values(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (p) => p.endsWith('.json') && (!includeFiles || includeFiles.has(p))\n );\n\n await batchProcess(\n targetFiles,\n async (file) => {\n // Read each json file\n const content = fs.readFileSync(file, 'utf8');\n const json = JSON.parse(content);\n // Flatten the json\n const flattenedJson = flattenJson(json);\n\n // Write the flattened json to the target file\n await fs.promises.writeFile(\n file,\n stringifyJson(flattenedJson, content)\n );\n return flattenedJson;\n },\n FILE_IO_CONCURRENCY\n );\n }\n}\n\nfunction flattenJson(json: unknown, prefix = ''): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n\n for (const [key, value] of Object.entries(json as Record<string, unknown>)) {\n const newKey = prefix ? `${prefix}.${key}` : key;\n\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n Object.assign(result, flattenJson(value, newKey));\n } else {\n result[newKey] = value;\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;AAMA,eAA8B,iBAC5B,UACA,cACA;AACA,KACE,CAAC,SAAS,SACT,OAAO,KAAK,SAAS,MAAM,iBAAiB,CAAC,WAAW,KACvD,SAAS,MAAM,iBAAiB,GAElC;CAEF,MAAM,EAAE,eAAe,gBAAgB,SAAS;CAEhD,MAAM,cAAc,kBAClB,aACA,SAAS,MAAM,kBACf,SAAS,MAAM,gBACf,SAAS,MAAM,kBACf,SAAS,SACT,SAAS,cACV;AAGD,MAAK,MAAM,YAAY,OAAO,OAAO,YAAY,CAK/C,OAAM,aAJc,OAAO,OAAO,SAAS,CAAC,QACzC,MAAM,EAAE,SAAS,QAAQ,KAAK,CAAC,gBAAgB,aAAa,IAAI,EAAE,EAIxD,EACX,OAAO,SAAS;EAEd,MAAM,UAAU,GAAG,aAAa,MAAM,OAAO;EAG7C,MAAM,gBAAgB,YAFT,KAAK,MAAM,QAEc,CAAC;AAGvC,QAAM,GAAG,SAAS,UAChB,MACA,cAAc,eAAe,QAAQ,CACtC;AACD,SAAO;QAGV;;AAIL,SAAS,YAAY,MAAe,SAAS,IAA6B;CACxE,MAAM,SAAkC,EAAE;AAE1C,MAAK,MAAM,CAAC,KAAK,UAAU,OAAO,QAAQ,KAAgC,EAAE;EAC1E,MAAM,SAAS,SAAS,GAAG,OAAO,GAAG,QAAQ;AAE7C,MAAI,UAAU,QAAQ,OAAO,UAAU,YAAY,CAAC,MAAM,QAAQ,MAAM,CACtE,QAAO,OAAO,QAAQ,YAAY,OAAO,OAAO,CAAC;MAEjD,QAAO,UAAU;;AAIrB,QAAO"}
@@ -1,4 +1,5 @@
1
1
  import { logger } from "../console/logger.js";
2
+ import { stringifyJson } from "../fs/stringifyJson.js";
2
3
  import { PACKAGE_VERSION } from "../generated/version.js";
3
4
  import { exitSync } from "../console/logging.js";
4
5
  import chalk from "chalk";
@@ -28,7 +29,9 @@ function getCLIVersion() {
28
29
  }
29
30
  async function updatePackageJson(packageJson, cwd = process.cwd()) {
30
31
  try {
31
- await fs.promises.writeFile(path.join(cwd, "package.json"), JSON.stringify(packageJson, null, 2));
32
+ const packageJsonPath = path.join(cwd, "package.json");
33
+ const original = fs.existsSync(packageJsonPath) ? await fs.promises.readFile(packageJsonPath, "utf8") : void 0;
34
+ await fs.promises.writeFile(packageJsonPath, stringifyJson(packageJson, original));
32
35
  } catch (error) {
33
36
  logger.error(chalk.red("Error updating package.json: " + String(error)));
34
37
  exitSync(1);
@@ -1 +1 @@
1
- {"version":3,"file":"packageJson.js","names":[],"sources":["../../src/utils/packageJson.ts"],"sourcesContent":["import { logger } from '../console/logger.js';\n\nimport chalk from 'chalk';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport { exitSync } from '../console/logging.js';\nimport { PACKAGE_VERSION } from '../generated/version.js';\n\n// search for package.json such that we can run init in non-js projects\nexport async function searchForPackageJson(\n cwd: string = process.cwd()\n): Promise<Record<string, unknown> | null> {\n // Get the current working directory (where the CLI is being run)\n const packageJsonPath = path.join(cwd, 'package.json');\n\n // Check if package.json exists\n if (!fs.existsSync(packageJsonPath)) {\n return null;\n }\n try {\n return JSON.parse(await fs.promises.readFile(packageJsonPath, 'utf8'));\n } catch {\n return null;\n }\n}\n\nexport async function getPackageJson(\n cwd: string = process.cwd()\n): Promise<Record<string, unknown> | null> {\n const packageJsonPath = path.join(cwd, 'package.json');\n\n // Check if package.json exists\n if (!fs.existsSync(packageJsonPath)) {\n return null;\n }\n try {\n return JSON.parse(await fs.promises.readFile(packageJsonPath, 'utf8'));\n } catch {\n return null;\n }\n}\n\nexport function getCLIVersion(): string {\n return PACKAGE_VERSION;\n}\n\nexport async function updatePackageJson(\n packageJson: Record<string, unknown>,\n cwd: string = process.cwd()\n) {\n try {\n await fs.promises.writeFile(\n path.join(cwd, 'package.json'),\n JSON.stringify(packageJson, null, 2)\n );\n } catch (error) {\n logger.error(chalk.red('Error updating package.json: ' + String(error)));\n exitSync(1);\n }\n}\n\n// check if a package is installed in the package.json file\nexport function isPackageInstalled(\n packageName: string,\n packageJson: Record<string, unknown>,\n asDevDependency: boolean = false,\n checkBoth: boolean = false\n): boolean {\n const devDependencies =\n (packageJson.devDependencies as Record<string, string> | undefined) ?? {};\n const prodDependencies =\n (packageJson.dependencies as Record<string, string> | undefined) ?? {};\n const dependencies = checkBoth\n ? {\n ...devDependencies,\n ...prodDependencies,\n }\n : asDevDependency\n ? devDependencies\n : prodDependencies;\n\n if (!dependencies) {\n return false;\n }\n return dependencies[packageName] !== undefined;\n}\n\nexport function getPackageVersion(\n packageName: string,\n packageJson: Record<string, unknown>\n): string | undefined {\n const devDependencies =\n (packageJson.devDependencies as Record<string, string> | undefined) ?? {};\n const prodDependencies =\n (packageJson.dependencies as Record<string, string> | undefined) ?? {};\n const dependencies = {\n ...prodDependencies,\n ...devDependencies,\n };\n return dependencies[packageName] ?? undefined;\n}\n"],"mappings":";;;;;;;AASA,eAAsB,qBACpB,MAAc,QAAQ,KAAK,EACc;CAEzC,MAAM,kBAAkB,KAAK,KAAK,KAAK,eAAe;AAGtD,KAAI,CAAC,GAAG,WAAW,gBAAgB,CACjC,QAAO;AAET,KAAI;AACF,SAAO,KAAK,MAAM,MAAM,GAAG,SAAS,SAAS,iBAAiB,OAAO,CAAC;SAChE;AACN,SAAO;;;AAIX,eAAsB,eACpB,MAAc,QAAQ,KAAK,EACc;CACzC,MAAM,kBAAkB,KAAK,KAAK,KAAK,eAAe;AAGtD,KAAI,CAAC,GAAG,WAAW,gBAAgB,CACjC,QAAO;AAET,KAAI;AACF,SAAO,KAAK,MAAM,MAAM,GAAG,SAAS,SAAS,iBAAiB,OAAO,CAAC;SAChE;AACN,SAAO;;;AAIX,SAAgB,gBAAwB;AACtC,QAAO;;AAGT,eAAsB,kBACpB,aACA,MAAc,QAAQ,KAAK,EAC3B;AACA,KAAI;AACF,QAAM,GAAG,SAAS,UAChB,KAAK,KAAK,KAAK,eAAe,EAC9B,KAAK,UAAU,aAAa,MAAM,EAAE,CACrC;UACM,OAAO;AACd,SAAO,MAAM,MAAM,IAAI,kCAAkC,OAAO,MAAM,CAAC,CAAC;AACxE,WAAS,EAAE;;;AAKf,SAAgB,mBACd,aACA,aACA,kBAA2B,OAC3B,YAAqB,OACZ;CACT,MAAM,kBACH,YAAY,mBAA0D,EAAE;CAC3E,MAAM,mBACH,YAAY,gBAAuD,EAAE;CACxE,MAAM,eAAe,YACjB;EACE,GAAG;EACH,GAAG;EACJ,GACD,kBACE,kBACA;AAEN,KAAI,CAAC,aACH,QAAO;AAET,QAAO,aAAa,iBAAiB,KAAA;;AAGvC,SAAgB,kBACd,aACA,aACoB;CACpB,MAAM,kBACH,YAAY,mBAA0D,EAAE;AAO3E,QAAO;EAHL,GAFC,YAAY,gBAAuD,EAAE;EAGtE,GAAG;EAEc,CAAC,gBAAgB,KAAA"}
1
+ {"version":3,"file":"packageJson.js","names":[],"sources":["../../src/utils/packageJson.ts"],"sourcesContent":["import { logger } from '../console/logger.js';\n\nimport chalk from 'chalk';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport { stringifyJson } from '../fs/stringifyJson.js';\nimport { exitSync } from '../console/logging.js';\nimport { PACKAGE_VERSION } from '../generated/version.js';\n\n// search for package.json such that we can run init in non-js projects\nexport async function searchForPackageJson(\n cwd: string = process.cwd()\n): Promise<Record<string, unknown> | null> {\n // Get the current working directory (where the CLI is being run)\n const packageJsonPath = path.join(cwd, 'package.json');\n\n // Check if package.json exists\n if (!fs.existsSync(packageJsonPath)) {\n return null;\n }\n try {\n return JSON.parse(await fs.promises.readFile(packageJsonPath, 'utf8'));\n } catch {\n return null;\n }\n}\n\nexport async function getPackageJson(\n cwd: string = process.cwd()\n): Promise<Record<string, unknown> | null> {\n const packageJsonPath = path.join(cwd, 'package.json');\n\n // Check if package.json exists\n if (!fs.existsSync(packageJsonPath)) {\n return null;\n }\n try {\n return JSON.parse(await fs.promises.readFile(packageJsonPath, 'utf8'));\n } catch {\n return null;\n }\n}\n\nexport function getCLIVersion(): string {\n return PACKAGE_VERSION;\n}\n\nexport async function updatePackageJson(\n packageJson: Record<string, unknown>,\n cwd: string = process.cwd()\n) {\n try {\n const packageJsonPath = path.join(cwd, 'package.json');\n const original = fs.existsSync(packageJsonPath)\n ? await fs.promises.readFile(packageJsonPath, 'utf8')\n : undefined;\n await fs.promises.writeFile(\n packageJsonPath,\n stringifyJson(packageJson, original)\n );\n } catch (error) {\n logger.error(chalk.red('Error updating package.json: ' + String(error)));\n exitSync(1);\n }\n}\n\n// check if a package is installed in the package.json file\nexport function isPackageInstalled(\n packageName: string,\n packageJson: Record<string, unknown>,\n asDevDependency: boolean = false,\n checkBoth: boolean = false\n): boolean {\n const devDependencies =\n (packageJson.devDependencies as Record<string, string> | undefined) ?? {};\n const prodDependencies =\n (packageJson.dependencies as Record<string, string> | undefined) ?? {};\n const dependencies = checkBoth\n ? {\n ...devDependencies,\n ...prodDependencies,\n }\n : asDevDependency\n ? devDependencies\n : prodDependencies;\n\n if (!dependencies) {\n return false;\n }\n return dependencies[packageName] !== undefined;\n}\n\nexport function getPackageVersion(\n packageName: string,\n packageJson: Record<string, unknown>\n): string | undefined {\n const devDependencies =\n (packageJson.devDependencies as Record<string, string> | undefined) ?? {};\n const prodDependencies =\n (packageJson.dependencies as Record<string, string> | undefined) ?? {};\n const dependencies = {\n ...prodDependencies,\n ...devDependencies,\n };\n return dependencies[packageName] ?? undefined;\n}\n"],"mappings":";;;;;;;;AAUA,eAAsB,qBACpB,MAAc,QAAQ,KAAK,EACc;CAEzC,MAAM,kBAAkB,KAAK,KAAK,KAAK,eAAe;AAGtD,KAAI,CAAC,GAAG,WAAW,gBAAgB,CACjC,QAAO;AAET,KAAI;AACF,SAAO,KAAK,MAAM,MAAM,GAAG,SAAS,SAAS,iBAAiB,OAAO,CAAC;SAChE;AACN,SAAO;;;AAIX,eAAsB,eACpB,MAAc,QAAQ,KAAK,EACc;CACzC,MAAM,kBAAkB,KAAK,KAAK,KAAK,eAAe;AAGtD,KAAI,CAAC,GAAG,WAAW,gBAAgB,CACjC,QAAO;AAET,KAAI;AACF,SAAO,KAAK,MAAM,MAAM,GAAG,SAAS,SAAS,iBAAiB,OAAO,CAAC;SAChE;AACN,SAAO;;;AAIX,SAAgB,gBAAwB;AACtC,QAAO;;AAGT,eAAsB,kBACpB,aACA,MAAc,QAAQ,KAAK,EAC3B;AACA,KAAI;EACF,MAAM,kBAAkB,KAAK,KAAK,KAAK,eAAe;EACtD,MAAM,WAAW,GAAG,WAAW,gBAAgB,GAC3C,MAAM,GAAG,SAAS,SAAS,iBAAiB,OAAO,GACnD,KAAA;AACJ,QAAM,GAAG,SAAS,UAChB,iBACA,cAAc,aAAa,SAAS,CACrC;UACM,OAAO;AACd,SAAO,MAAM,MAAM,IAAI,kCAAkC,OAAO,MAAM,CAAC,CAAC;AACxE,WAAS,EAAE;;;AAKf,SAAgB,mBACd,aACA,aACA,kBAA2B,OAC3B,YAAqB,OACZ;CACT,MAAM,kBACH,YAAY,mBAA0D,EAAE;CAC3E,MAAM,mBACH,YAAY,gBAAuD,EAAE;CACxE,MAAM,eAAe,YACjB;EACE,GAAG;EACH,GAAG;EACJ,GACD,kBACE,kBACA;AAEN,KAAI,CAAC,aACH,QAAO;AAET,QAAO,aAAa,iBAAiB,KAAA;;AAGvC,SAAgB,kBACd,aACA,aACoB;CACpB,MAAM,kBACH,YAAY,mBAA0D,EAAE;AAO3E,QAAO;EAHL,GAFC,YAAY,gBAAuD,EAAE;EAGtE,GAAG;EAEc,CAAC,gBAAgB,KAAA"}
@@ -1,4 +1,5 @@
1
1
  import { logger } from "../console/logger.js";
2
+ import { stringifyJson } from "../fs/stringifyJson.js";
2
3
  import { createFileMapping } from "../formats/files/fileMapping.js";
3
4
  import path from "node:path";
4
5
  import fs from "node:fs";
@@ -162,7 +163,7 @@ function rewriteDocsJsonOpenApi(content, filePath, localeHint, specs, fileMappin
162
163
  if (!changed) return null;
163
164
  return {
164
165
  changed,
165
- content: JSON.stringify(json, null, 2)
166
+ content: stringifyJson(json, content)
166
167
  };
167
168
  }
168
169
  function stripLocaleFromOpenApiPage(value, locale) {
@@ -1 +1 @@
1
- {"version":3,"file":"processOpenApi.js","names":[],"sources":["../../src/utils/processOpenApi.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport YAML, { isMap, isScalar } from 'yaml';\nimport type { Root, Content, Yaml } from 'mdast';\nimport { logger } from '../console/logger.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport { Settings } from '../types/index.js';\n\ntype SpecAnalysis = {\n absPath: string;\n configPath: string; // as provided in config (for formatting)\n operations: Set<string>;\n schemas: Set<string>;\n webhooks: Set<string>;\n};\n\ntype ParsedOpenApiValue =\n | {\n kind: 'operation';\n specPath?: string;\n method: string;\n operationPath: string;\n }\n | {\n kind: 'webhook';\n specPath?: string;\n name: string;\n };\n\ntype ParsedSchemaValue = {\n specPath?: string;\n schemaName: string;\n};\n\nconst HTTP_METHODS = new Set([\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n 'TRACE',\n]);\nconst OPENAPI_SPEC_EXTENSIONS = new Set(['.json', '.yaml', '.yml']);\n\n/**\n * Postprocess Mintlify OpenAPI references to point to locale-specific spec files.\n * - Uses openapi.files (ordered) to resolve ambiguities (first match wins).\n * - Relies on the user's json transform rules for locale paths.\n * - Warns on missing/ambiguous references but keeps behavior deterministic.\n */\nexport default async function processOpenApi(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n const openapiConfig = settings.options?.mintlify?.openapi;\n if (!openapiConfig || !openapiConfig.files?.length) return;\n if (!settings.files) return;\n\n const configDir = path.dirname(settings.config);\n const specAnalyses = buildSpecAnalyses(openapiConfig.files, configDir);\n if (!specAnalyses.length) return;\n\n const warnings = new Set<string>();\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 const fileMappingAbs: Record<string, Record<string, string>> = {};\n for (const [locale, mapping] of Object.entries(fileMapping)) {\n fileMappingAbs[locale] = {};\n for (const [src, dest] of Object.entries(mapping)) {\n const absSrc = path.resolve(configDir, src);\n const absDest = path.resolve(configDir, dest);\n fileMappingAbs[locale][absSrc] = absDest;\n }\n }\n\n // Also rewrite default-locale source files so they use the deterministic spec selection\n const defaultFiles = [\n ...(resolvedPaths.mdx || []),\n ...(resolvedPaths.md || []),\n ];\n for (const filePath of defaultFiles) {\n if (!fs.existsSync(filePath)) continue;\n const content = fs.readFileSync(filePath, 'utf8');\n const updated = rewriteFrontmatter(\n content,\n filePath,\n settings.defaultLocale,\n specAnalyses,\n fileMappingAbs,\n warnings,\n configDir\n );\n if (updated?.changed) {\n await fs.promises.writeFile(filePath, updated.content, 'utf8');\n }\n }\n\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n (p.endsWith('.md') || p.endsWith('.mdx')) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n for (const filePath of targetFiles) {\n if (!fs.existsSync(filePath)) continue;\n const content = fs.readFileSync(filePath, 'utf8');\n const updated = rewriteFrontmatter(\n content,\n filePath,\n locale,\n specAnalyses,\n fileMappingAbs,\n warnings,\n configDir\n );\n\n if (updated?.changed) {\n await fs.promises.writeFile(filePath, updated.content, 'utf8');\n }\n }\n }\n\n const docsJsonTargets = collectDocsJsonTargets(\n settings,\n fileMapping,\n includeFiles\n );\n for (const target of docsJsonTargets) {\n if (!fs.existsSync(target.path)) continue;\n const content = fs.readFileSync(target.path, 'utf8');\n const updated = rewriteDocsJsonOpenApi(\n content,\n target.path,\n target.localeHint,\n specAnalyses,\n fileMappingAbs,\n fileMapping,\n warnings,\n configDir,\n settings.defaultLocale\n );\n if (updated?.changed) {\n await fs.promises.writeFile(target.path, updated.content, 'utf8');\n }\n }\n\n for (const message of warnings) {\n logger.warn(message);\n }\n}\n\nfunction collectDocsJsonTargets(\n settings: Settings,\n fileMapping: Record<string, Record<string, string>>,\n includeFiles?: Set<string>\n): Array<{ path: string; localeHint?: string }> {\n const targets: Array<{ path: string; localeHint?: string }> = [];\n const seen = new Map<string, Set<string>>();\n\n const addTarget = (filePath: string, locale?: string) => {\n const canonicalPath = path.resolve(filePath);\n if (\n includeFiles &&\n !includeFiles.has(filePath) &&\n !includeFiles.has(canonicalPath)\n ) {\n return;\n }\n const locales = seen.get(canonicalPath) ?? new Set<string>();\n if (locale) locales.add(locale);\n seen.set(canonicalPath, locales);\n };\n\n if (!includeFiles && settings.files?.resolvedPaths.json) {\n for (const filePath of settings.files.resolvedPaths.json) {\n addTarget(filePath, settings.defaultLocale);\n }\n }\n\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n for (const [sourcePath, filePath] of Object.entries(filesMap)) {\n if (!filePath.endsWith('.json')) continue;\n // Composite docs.json is translated in place and holds every locale.\n addTarget(\n filePath,\n sourcePath === filePath ? settings.defaultLocale : locale\n );\n }\n }\n\n for (const [filePath, locales] of seen.entries()) {\n const localeHint = locales.size === 1 ? Array.from(locales)[0] : undefined;\n targets.push({ path: filePath, localeHint });\n }\n\n return targets;\n}\n\nfunction isMintlifyDocsJson(filePath: string, json: unknown): boolean {\n if (!isRecord(json)) return false;\n const schema = json.$schema;\n if (typeof schema === 'string') {\n return (\n schema.includes('mintlify.com/docs.json') ||\n schema.includes('mintlify.com/mint.json')\n );\n }\n const base = path.basename(filePath);\n return base === 'docs.json' || base === 'mint.json';\n}\n\nfunction rewriteDocsJsonOpenApi(\n content: string,\n filePath: string,\n localeHint: string | undefined,\n specs: SpecAnalysis[],\n fileMappingAbs: Record<string, Record<string, string>>,\n fileMappingRel: Record<string, Record<string, string>>,\n warnings: Set<string>,\n configDir: string,\n defaultLocale: string\n): { changed: boolean; content: string } | null {\n let json: unknown;\n try {\n json = JSON.parse(content);\n } catch {\n return null;\n }\n\n if (!isMintlifyDocsJson(filePath, json)) return null;\n\n let changed = false;\n\n const visitNode = (node: unknown, activeLocale?: string) => {\n if (Array.isArray(node)) {\n node.forEach((item) => visitNode(item, activeLocale));\n return;\n }\n if (!isRecord(node)) return;\n\n let nextLocale = activeLocale;\n if (typeof node.language === 'string') {\n nextLocale = node.language;\n }\n\n const locale = nextLocale || localeHint || defaultLocale;\n\n if (typeof node.openapi === 'string') {\n const sourceValue = node.openapi;\n const localizedSource = localizeDocsJsonSpecPath(\n sourceValue,\n locale,\n filePath,\n specs,\n fileMappingAbs,\n fileMappingRel,\n warnings,\n configDir\n );\n if (localizedSource && localizedSource !== sourceValue) {\n node.openapi = localizedSource;\n changed = true;\n }\n } else if (isRecord(node.openapi)) {\n const openapiConfig = node.openapi as Record<string, unknown>;\n const sourceValue = openapiConfig.source;\n if (typeof sourceValue === 'string') {\n const localizedSource = localizeDocsJsonSpecPath(\n sourceValue,\n locale,\n filePath,\n specs,\n fileMappingAbs,\n fileMappingRel,\n warnings,\n configDir\n );\n if (localizedSource && localizedSource !== sourceValue) {\n openapiConfig.source = localizedSource;\n changed = true;\n }\n }\n\n const directoryValue = openapiConfig.directory;\n if (typeof directoryValue === 'string') {\n const localizedDirectory = localizeDocsJsonDirectory(\n directoryValue,\n locale,\n defaultLocale,\n new Set([defaultLocale, ...Object.keys(fileMappingRel)])\n );\n if (localizedDirectory && localizedDirectory !== directoryValue) {\n openapiConfig.directory = localizedDirectory;\n changed = true;\n }\n }\n }\n\n if (Array.isArray(node.pages)) {\n const pages = node.pages;\n for (let i = 0; i < pages.length; i += 1) {\n const page = pages[i];\n if (typeof page !== 'string') continue;\n const updated = stripLocaleFromOpenApiPage(page, locale);\n if (updated !== page) {\n pages[i] = updated;\n changed = true;\n }\n }\n }\n\n for (const value of Object.values(node)) {\n visitNode(value, nextLocale);\n }\n };\n\n visitNode(json, undefined);\n\n if (!changed) return null;\n return { changed, content: JSON.stringify(json, null, 2) };\n}\n\nfunction stripLocaleFromOpenApiPage(value: string, locale: string): string {\n const trimmed = value.trim();\n const prefix = `${locale}/`;\n if (!trimmed.startsWith(prefix)) return value;\n const candidate = trimmed.slice(prefix.length);\n const parsed = parseOpenApiValue(candidate);\n if (!parsed) return value;\n return candidate;\n}\n\nfunction localizeDocsJsonDirectory(\n directory: string,\n locale: string,\n defaultLocale: string,\n knownLocales: Set<string>\n): string | null {\n if (locale === defaultLocale) return null;\n\n const trimmed = directory.trim();\n if (!trimmed || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#|\\.\\/|\\.\\.\\/)/i.test(trimmed)) {\n return null;\n }\n\n const leadingWhitespace = directory.match(/^\\s*/)?.[0] ?? '';\n const trailingWhitespace = directory.match(/\\s*$/)?.[0] ?? '';\n const leadingSlash = trimmed.startsWith('/') ? '/' : '';\n const pathBody = trimmed.replace(/^\\/+/, '');\n const [firstSegment, ...restSegments] = pathBody.split('/');\n\n if (firstSegment === locale) {\n const normalized = `${leadingWhitespace}${leadingSlash}${pathBody}${trailingWhitespace}`;\n return normalized === directory ? null : normalized;\n }\n\n const unprefixedPath = knownLocales.has(firstSegment)\n ? restSegments.join('/')\n : pathBody;\n const localizedPath = unprefixedPath ? `${locale}/${unprefixedPath}` : locale;\n const normalized = `${leadingWhitespace}${leadingSlash}${localizedPath}${trailingWhitespace}`;\n\n return normalized === directory ? null : normalized;\n}\n\nfunction localizeDocsJsonSpecPath(\n source: string,\n locale: string,\n filePath: string,\n specs: SpecAnalysis[],\n fileMappingAbs: Record<string, Record<string, string>>,\n _fileMappingRel: Record<string, Record<string, string>>,\n warnings: Set<string>,\n configDir: string\n): string | null {\n const resolvedAbs = resolveDocsJsonSpecPath(source, filePath, configDir);\n const matched = matchSpecBySource(source, resolvedAbs, specs, warnings);\n if (!matched) return source;\n\n const localizedSpecPath = resolveLocalizedSpecPath(\n matched,\n locale,\n fileMappingAbs,\n configDir,\n source\n );\n const localizedAbs = resolveDocsJsonSpecPath(\n localizedSpecPath,\n filePath,\n configDir\n );\n if (!fs.existsSync(localizedAbs)) {\n warnings.add(\n `OpenAPI source \"${source}\" localized for locale \"${locale}\" points to a missing file (${localizedAbs}). Keeping original source.`\n );\n return source;\n }\n\n const rel = normalizeSlashes(path.relative(configDir, localizedAbs));\n return formatSpecPathForDocsJson(rel, source);\n}\n\nfunction resolveDocsJsonSpecPath(\n source: string,\n filePath: string,\n configDir: string\n): string {\n if (source.startsWith('/')) {\n return path.resolve(configDir, source.replace(/^\\/+/, ''));\n }\n if (source.startsWith('./') || source.startsWith('../')) {\n return path.resolve(path.dirname(filePath), source);\n }\n return path.resolve(configDir, source);\n}\n\nfunction matchSpecBySource(\n source: string,\n resolvedAbs: string,\n specs: SpecAnalysis[],\n warnings: Set<string>\n): SpecAnalysis | null {\n const exact = specs.find((spec) => samePath(resolvedAbs, spec.absPath));\n if (exact) return exact;\n\n const normalizedExplicit = normalizeSlashes(source).replace(/^\\.?\\/+/, '');\n const explicitWithoutExt = stripExtension(normalizedExplicit);\n const explicitBase = path.basename(normalizedExplicit);\n const explicitBaseWithoutExt = stripExtension(explicitBase);\n const matches = specs.filter((spec) => {\n const configPath = normalizeSlashes(spec.configPath).replace(/^\\.?\\/+/, '');\n const configBase = path.basename(configPath);\n const configPathNoExt = stripExtension(configPath);\n const configBaseNoExt = stripExtension(configBase);\n return (\n configPath === normalizedExplicit ||\n configPathNoExt === explicitWithoutExt ||\n configBase === explicitBase ||\n configBaseNoExt === explicitBaseWithoutExt\n );\n });\n\n if (matches.length === 1) return matches[0];\n if (matches.length > 1) {\n warnings.add(\n `OpenAPI source \"${source}\" matches multiple specs (${matches\n .map((m) => m.configPath)\n .join(\n ', '\n )}). Using the first configured match (${matches[0].configPath}).`\n );\n return matches[0];\n }\n\n return null;\n}\n\nfunction formatSpecPathForDocsJson(\n relativePath: string,\n originalPathText: string\n): string {\n const normalized = normalizeSlashes(relativePath);\n const base = normalized.replace(/^\\.\\//, '').replace(/\\/+/g, '/');\n\n if (originalPathText.startsWith('/')) {\n return `/${base.replace(/^\\/+/, '')}`;\n }\n if (originalPathText.startsWith('../')) {\n return normalized;\n }\n if (originalPathText.startsWith('./')) {\n return `./${base.replace(/^\\/+/, '')}`;\n }\n return base.replace(/^\\/+/, '');\n}\n\n/**\n * Resolve configured OpenAPI files to absolute paths and collect the operations,\n * schemas, and webhooks they expose. Warns and skips when files are missing,\n * unsupported (non-JSON/YAML), or fail to parse so later steps can continue gracefully.\n */\nfunction buildSpecAnalyses(\n openapiFiles: string[],\n configDir: string\n): SpecAnalysis[] {\n const analyses: SpecAnalysis[] = [];\n\n for (const configEntry of openapiFiles) {\n const absPath = path.resolve(configDir, configEntry);\n if (!fs.existsSync(absPath)) {\n logger.warn(`OpenAPI file not found: ${configEntry}`);\n continue;\n }\n const ext = path.extname(absPath).toLowerCase();\n if (!OPENAPI_SPEC_EXTENSIONS.has(ext)) {\n logger.warn(\n `Skipping OpenAPI file (only .json/.yml/.yaml supported): ${configEntry}`\n );\n continue;\n }\n\n let spec: unknown;\n try {\n const raw = fs.readFileSync(absPath, 'utf8');\n spec = ext === '.json' ? JSON.parse(raw) : YAML.parse(raw);\n } catch {\n const format = ext === '.json' ? 'JSON' : 'YAML';\n logger.warn(`Failed to parse OpenAPI ${format}: ${configEntry}`);\n continue;\n }\n\n analyses.push({\n absPath,\n configPath: configEntry,\n operations: extractOperations(spec),\n schemas: extractSchemas(spec),\n webhooks: extractWebhooks(spec),\n });\n }\n\n return analyses;\n}\n\nfunction isRecord(val: unknown): val is Record<string, unknown> {\n return typeof val === 'object' && val !== null;\n}\n\n/**\n * Collect path+method identifiers (e.g., \"POST /foo\") from an OpenAPI spec.\n * Safely no-ops when paths is missing or malformed.\n */\nfunction extractOperations(spec: unknown): Set<string> {\n const ops = new Set<string>();\n if (!isRecord(spec) || !isRecord(spec.paths)) return ops;\n const paths = spec.paths as Record<string, unknown>;\n\n for (const [route, methods] of Object.entries(paths)) {\n if (!isRecord(methods)) continue;\n for (const [method, operation] of Object.entries(methods)) {\n if (!isRecord(operation)) continue;\n const upper = method.toUpperCase();\n if (!HTTP_METHODS.has(upper)) continue;\n ops.add(`${upper} ${route}`);\n }\n }\n return ops;\n}\n\n/**\n * Collect schema names from components.schemas.\n * Returns empty set if components/schemas are missing or malformed.\n */\nfunction extractSchemas(spec: unknown): Set<string> {\n if (!isRecord(spec) || !isRecord(spec.components)) return new Set();\n const components = spec.components as Record<string, unknown>;\n if (!isRecord(components.schemas)) return new Set();\n return new Set(Object.keys(components.schemas as Record<string, unknown>));\n}\n\n/**\n * Collect webhook names from webhooks (OpenAPI 3.1+).\n * Returns empty set if webhooks is missing or malformed.\n */\nfunction extractWebhooks(spec: unknown): Set<string> {\n if (!isRecord(spec) || !isRecord(spec.webhooks)) return new Set();\n return new Set(Object.keys(spec.webhooks as Record<string, unknown>));\n}\n\n/**\n * Parse MDX/MD frontmatter, rewrite openapi/openapi-schema entries to the\n * resolved (possibly localized) spec path, and return updated content.\n * Uses remark to find the YAML node so the rest of the document remains\n * untouched. When parsing fails or no relevant keys exist, it returns null.\n */\nfunction rewriteFrontmatter(\n content: string,\n filePath: string,\n locale: string,\n specs: SpecAnalysis[],\n fileMapping: Record<string, Record<string, string>>,\n warnings: Set<string>,\n configDir: string\n): { changed: boolean; content: string } | null {\n let tree: Root;\n try {\n tree = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .parse(content) as Root;\n } catch {\n return null;\n }\n\n const yamlNode = (tree.children as Content[]).find(\n (node): node is Yaml => (node as Yaml).type === 'yaml'\n );\n if (\n !yamlNode ||\n !yamlNode.position ||\n yamlNode.position.start?.offset === undefined\n ) {\n return null;\n }\n\n const start = yamlNode.position.start.offset as number;\n const end = yamlNode.position.end.offset as number;\n const frontmatterRaw: string = yamlNode.value || '';\n\n const doc = YAML.parseDocument(frontmatterRaw, {\n prettyErrors: false,\n keepSourceTokens: true,\n });\n if (doc.errors?.length) return null;\n if (!isMap(doc.contents)) return null;\n\n let changed = false;\n\n const openapiNode = doc.get('openapi', true);\n if (isScalar(openapiNode) && typeof openapiNode.value === 'string') {\n const parsedValue = parseOpenApiValue(openapiNode.value);\n if (parsedValue) {\n const matchKey =\n parsedValue.kind === 'operation'\n ? {\n type: 'operation' as const,\n key: `${parsedValue.method.toUpperCase()} ${parsedValue.operationPath}`,\n }\n : { type: 'webhook' as const, key: parsedValue.name };\n\n const spec = resolveSpec(\n parsedValue.specPath,\n specs,\n filePath,\n configDir,\n warnings,\n describeOpenApiRef(parsedValue),\n matchKey\n );\n if (spec) {\n const descriptor = formatOpenApiDescriptor(parsedValue);\n const localizedSpecPath = resolveLocalizedSpecPath(\n spec,\n locale,\n fileMapping,\n configDir,\n parsedValue.specPath || spec.configPath\n );\n const newValue = `${localizedSpecPath} ${descriptor}`.trim();\n if (newValue !== openapiNode.value) {\n doc.set('openapi', newValue);\n changed = true;\n }\n }\n }\n }\n\n const schemaNode = doc.get('openapi-schema', true);\n if (isScalar(schemaNode) && typeof schemaNode.value === 'string') {\n const parsedValue = parseSchemaValue(schemaNode.value);\n if (parsedValue) {\n const spec = resolveSpec(\n parsedValue.specPath,\n specs,\n filePath,\n configDir,\n warnings,\n `schema \"${parsedValue.schemaName}\"`,\n { type: 'schema', key: parsedValue.schemaName }\n );\n if (spec) {\n const localizedSpecPath = resolveLocalizedSpecPath(\n spec,\n locale,\n fileMapping,\n configDir,\n parsedValue.specPath || spec.configPath\n );\n const newValue =\n `${localizedSpecPath} ${parsedValue.schemaName}`.trim();\n if (newValue !== schemaNode.value) {\n doc.set('openapi-schema', newValue);\n changed = true;\n }\n }\n }\n }\n\n if (!changed) return null;\n\n const fmString = doc.toString().trimEnd();\n const rebuilt = `${content.slice(0, start)}---\\n${fmString}\\n---${content.slice(end)}`;\n return { changed, content: rebuilt };\n}\n\nfunction stripWrappingQuotes(value: string): string {\n return value.trim().replace(/^['\"]|['\"]$/g, '');\n}\n\n/**\n * Parse frontmatter openapi string into spec/method/path or webhook.\n * Supports optional leading spec file, the webhook keyword, quoted values,\n * and forgiving whitespace. Returns null when the structure is unrecognized.\n */\nfunction parseOpenApiValue(value: string): ParsedOpenApiValue | null {\n const stripped = stripWrappingQuotes(value);\n const tokens = stripped.split(/\\s+/).filter(Boolean);\n if (!tokens.length) return null;\n\n let cursor = 0;\n let specPath: string | undefined;\n const first = tokens[0];\n const second = tokens[1];\n const methodCandidate = second?.toUpperCase();\n const firstLooksLikeSpec =\n hasOpenApiSpecExtension(first) ||\n (second &&\n (second.toLowerCase() === 'webhook' ||\n (methodCandidate && HTTP_METHODS.has(methodCandidate))));\n\n if (firstLooksLikeSpec) {\n specPath = tokens[0];\n cursor = 1;\n }\n if (cursor >= tokens.length) return null;\n\n const keyword = tokens[cursor];\n if (keyword.toLowerCase() === 'webhook') {\n const name = tokens.slice(cursor + 1).join(' ');\n if (!name) return null;\n return { kind: 'webhook', specPath, name };\n }\n\n const method = keyword.toUpperCase();\n if (!HTTP_METHODS.has(method)) return null;\n const operationPath = tokens.slice(cursor + 1).join(' ');\n if (!operationPath) return null;\n return { kind: 'operation', specPath, method, operationPath };\n}\n\n/**\n * Parse frontmatter openapi-schema string into spec/schemaName.\n * Accepts optional leading spec file and quoted values; returns null on invalid\n * shapes so callers can skip rewrites gracefully.\n */\nfunction parseSchemaValue(value: string): ParsedSchemaValue | null {\n const stripped = stripWrappingQuotes(value);\n const tokens = stripped.split(/\\s+/).filter(Boolean);\n if (!tokens.length) return null;\n let cursor = 0;\n let specPath: string | undefined;\n // Canonical form is \"<spec> <SchemaName>\". Treat the first token as the spec\n // when it has a spec file extension, or when more tokens follow — schema names\n // are single identifiers, so any leading token must be the spec. This covers\n // extensionless spec names (Mintlify auto-discovers specs by file stem, e.g.\n // `events-schema group.created`), mirroring parseOpenApiValue's heuristic.\n if (hasOpenApiSpecExtension(tokens[0]) || tokens.length > 1) {\n specPath = tokens[0];\n cursor = 1;\n }\n const schemaName = tokens.slice(cursor).join(' ');\n if (!schemaName) return null;\n return { specPath, schemaName };\n}\n\n/**\n * Choose which configured spec a reference should use.\n * - If an explicit spec path is provided, resolve it relative to the config\n * and the referencing file, warn when unknown, and bail.\n * - Otherwise, try to match by operation/webhook/schema name; resolve\n * ambiguity using config order and warn when ambiguous or missing.\n */\nfunction resolveSpec(\n explicitPath: string | undefined,\n specs: SpecAnalysis[],\n filePath: string,\n configDir: string,\n warnings: Set<string>,\n refDescription: string,\n match: { type: 'operation' | 'webhook' | 'schema'; key: string }\n): SpecAnalysis | null {\n if (!specs.length) return null;\n\n if (explicitPath) {\n const normalizedExplicit = normalizeSlashes(\n explicitPath.replace(/^\\.?\\/+/, '')\n );\n const candidates = [\n path.resolve(configDir, normalizedExplicit),\n path.resolve(path.dirname(filePath), normalizedExplicit),\n ];\n const foundSpec = specs.find((spec) => {\n const normalizedSpecPath = normalizeSlashes(spec.absPath);\n return candidates.some((candidate) =>\n samePath(candidate, normalizedSpecPath)\n );\n });\n if (foundSpec) {\n if (specHasMatch(foundSpec, match)) {\n return foundSpec;\n }\n\n const alternatives = specs.filter(\n (spec) => spec !== foundSpec && specHasMatch(spec, match)\n );\n if (alternatives.length === 1) {\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} points to ${foundSpec.configPath}, but the entry was not found there. Using ${alternatives[0].configPath} instead.`\n );\n return alternatives[0];\n }\n if (alternatives.length > 1) {\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} points to ${foundSpec.configPath}, but the entry was not found there and matches multiple specs (${alternatives\n .map((spec) => spec.configPath)\n .join(', ')}). Skipping localization for this reference.`\n );\n return null;\n }\n\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} points to ${foundSpec.configPath}, but the entry was not found in any configured spec. Skipping localization for this reference.`\n );\n return null;\n }\n\n const explicitWithoutExt = stripExtension(normalizedExplicit);\n const explicitBase = path.basename(normalizedExplicit);\n const explicitBaseWithoutExt = stripExtension(explicitBase);\n const matches = specs.filter((spec) => {\n const configPath = normalizeSlashes(spec.configPath).replace(\n /^\\.?\\/+/,\n ''\n );\n const configBase = path.basename(configPath);\n const configPathNoExt = stripExtension(configPath);\n const configBaseNoExt = stripExtension(configBase);\n return (\n configPath === normalizedExplicit ||\n configPathNoExt === explicitWithoutExt ||\n configBase === explicitBase ||\n configBaseNoExt === explicitBaseWithoutExt\n );\n });\n if (matches.length === 1) return matches[0];\n if (matches.length > 1) {\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} matches multiple specs (${matches\n .map((m) => m.configPath)\n .join(\n ', '\n )}). Using the first configured match (${matches[0].configPath}).`\n );\n return matches[0];\n }\n\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} points to an unconfigured spec (${explicitPath}). Skipping localization for this reference.`\n );\n return null;\n }\n\n // No explicit spec: try to find by contents\n const matches = specs.filter((spec) => {\n if (match.type === 'schema') {\n return spec.schemas.has(match.key);\n }\n if (match.type === 'webhook') {\n return spec.webhooks.has(match.key);\n }\n // operation\n return spec.operations.has(match.key);\n });\n\n if (matches.length === 1) return matches[0];\n if (matches.length > 1) {\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} is available in multiple specs. Skipping localization for this reference.`\n );\n return null;\n }\n\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} was not found in any configured spec. Skipping localization for this reference.`\n );\n return null;\n}\n\nfunction specHasMatch(\n spec: SpecAnalysis,\n match: { type: 'operation' | 'webhook' | 'schema'; key: string }\n): boolean {\n if (match.type === 'schema') {\n return spec.schemas.has(match.key);\n }\n if (match.type === 'webhook') {\n return spec.webhooks.has(match.key);\n }\n return spec.operations.has(match.key);\n}\n\n/**\n * Map a spec to the locale-specific file path when available and normalize it\n * for frontmatter. Falls back to the source spec when the locale copy does\n * not exist to preserve deterministic behavior.\n */\nfunction resolveLocalizedSpecPath(\n spec: SpecAnalysis,\n locale: string,\n fileMapping: Record<string, Record<string, string>>,\n configDir: string,\n originalPathText?: string\n): string {\n const mapping = fileMapping[locale]?.[spec.absPath];\n const chosenAbs = mapping || spec.absPath;\n const rel = normalizeSlashes(path.relative(configDir, chosenAbs));\n const rooted = `/${rel.replace(/^\\/+/, '')}`;\n return formatSpecPathForFrontmatter(\n rooted,\n originalPathText || spec.configPath\n );\n}\n\n/**\n * Format the path that will be written back to frontmatter:\n * - Preserve the user's absolute style when they used a leading slash.\n * - Preserve upward relative references (../) exactly.\n * - Otherwise return a repo-root-relative path with a leading slash so Mintlify\n * resolves consistently regardless of the MDX file location.\n */\nfunction formatSpecPathForFrontmatter(\n relativePath: string,\n originalPathText: string\n): string {\n const normalized = normalizeSlashes(relativePath);\n const base = normalized.replace(/^\\.\\//, '').replace(/\\/+/g, '/');\n\n if (originalPathText.startsWith('/')) {\n // Force repo-root absolute style\n return `/${base.replace(/^\\/+/, '')}`;\n }\n\n if (originalPathText.startsWith('../')) {\n // Preserve explicit relative upward references\n return normalized;\n }\n\n // Default to repo-root relative with leading slash to avoid resolving relative to the MDX directory\n return `/${base.replace(/^\\/+/, '')}`;\n}\n\n/** Normalize the descriptive portion after the spec path for frontmatter. */\nfunction formatOpenApiDescriptor(value: ParsedOpenApiValue): string {\n if (value.kind === 'webhook') return `webhook ${value.name}`;\n return `${value.method.toUpperCase()} ${value.operationPath}`;\n}\n\n/** Human-readable description a specific OpenAPI reference. */\nfunction describeOpenApiRef(value: ParsedOpenApiValue): string {\n if (value.kind === 'webhook') return `webhook ${value.name}`;\n return `${value.method.toUpperCase()} ${value.operationPath}`;\n}\n\n/** Remove a single trailing file extension while preserving directory segments. */\nfunction stripExtension(p: string): string {\n const parsed = path.parse(p);\n return normalizeSlashes(path.join(parsed.dir, parsed.name));\n}\n\nfunction hasOpenApiSpecExtension(value: string): boolean {\n return OPENAPI_SPEC_EXTENSIONS.has(path.extname(value).toLowerCase());\n}\n\n/** Normalize separators for stable comparisons and output. */\nfunction normalizeSlashes(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\n/** Compare paths after resolution to avoid casing/separator mismatches. */\nfunction samePath(a: string, b: string): boolean {\n return path.resolve(a) === path.resolve(b);\n}\n"],"mappings":";;;;;;;;;AAqCA,MAAM,eAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,MAAM,0BAA0B,IAAI,IAAI;CAAC;CAAS;CAAS;CAAO,CAAC;;;;;;;AAQnE,eAA8B,eAC5B,UACA,cACA;CACA,MAAM,gBAAgB,SAAS,SAAS,UAAU;AAClD,KAAI,CAAC,iBAAiB,CAAC,cAAc,OAAO,OAAQ;AACpD,KAAI,CAAC,SAAS,MAAO;CAErB,MAAM,YAAY,KAAK,QAAQ,SAAS,OAAO;CAC/C,MAAM,eAAe,kBAAkB,cAAc,OAAO,UAAU;AACtE,KAAI,CAAC,aAAa,OAAQ;CAE1B,MAAM,2BAAW,IAAI,KAAa;CAClC,MAAM,EAAE,eAAe,kBAAkB,gBAAgB,qBACvD,SAAS;CACX,MAAM,cAAc,kBAClB,eACA,kBACA,gBACA,kBACA,SAAS,SACT,SAAS,cACV;CACD,MAAM,iBAAyD,EAAE;AACjE,MAAK,MAAM,CAAC,QAAQ,YAAY,OAAO,QAAQ,YAAY,EAAE;AAC3D,iBAAe,UAAU,EAAE;AAC3B,OAAK,MAAM,CAAC,KAAK,SAAS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;;;AAIhD,SAAS,mBAAmB,OAAmC;AAC7D,KAAI,MAAM,SAAS,UAAW,QAAO,WAAW,MAAM;AACtD,QAAO,GAAG,MAAM,OAAO,aAAa,CAAC,GAAG,MAAM;;;AAIhD,SAAS,eAAe,GAAmB;CACzC,MAAM,SAAS,KAAK,MAAM,EAAE;AAC5B,QAAO,iBAAiB,KAAK,KAAK,OAAO,KAAK,OAAO,KAAK,CAAC;;AAG7D,SAAS,wBAAwB,OAAwB;AACvD,QAAO,wBAAwB,IAAI,KAAK,QAAQ,MAAM,CAAC,aAAa,CAAC;;;AAIvE,SAAS,iBAAiB,GAAmB;AAC3C,QAAO,EAAE,QAAQ,OAAO,IAAI;;;AAI9B,SAAS,SAAS,GAAW,GAAoB;AAC/C,QAAO,KAAK,QAAQ,EAAE,KAAK,KAAK,QAAQ,EAAE"}
1
+ {"version":3,"file":"processOpenApi.js","names":[],"sources":["../../src/utils/processOpenApi.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { unified } from 'unified';\nimport remarkParse from 'remark-parse';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport YAML, { isMap, isScalar } from 'yaml';\nimport type { Root, Content, Yaml } from 'mdast';\nimport { logger } from '../console/logger.js';\nimport { stringifyJson } from '../fs/stringifyJson.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport { Settings } from '../types/index.js';\n\ntype SpecAnalysis = {\n absPath: string;\n configPath: string; // as provided in config (for formatting)\n operations: Set<string>;\n schemas: Set<string>;\n webhooks: Set<string>;\n};\n\ntype ParsedOpenApiValue =\n | {\n kind: 'operation';\n specPath?: string;\n method: string;\n operationPath: string;\n }\n | {\n kind: 'webhook';\n specPath?: string;\n name: string;\n };\n\ntype ParsedSchemaValue = {\n specPath?: string;\n schemaName: string;\n};\n\nconst HTTP_METHODS = new Set([\n 'GET',\n 'POST',\n 'PUT',\n 'PATCH',\n 'DELETE',\n 'OPTIONS',\n 'HEAD',\n 'TRACE',\n]);\nconst OPENAPI_SPEC_EXTENSIONS = new Set(['.json', '.yaml', '.yml']);\n\n/**\n * Postprocess Mintlify OpenAPI references to point to locale-specific spec files.\n * - Uses openapi.files (ordered) to resolve ambiguities (first match wins).\n * - Relies on the user's json transform rules for locale paths.\n * - Warns on missing/ambiguous references but keeps behavior deterministic.\n */\nexport default async function processOpenApi(\n settings: Settings,\n includeFiles?: Set<string>\n) {\n const openapiConfig = settings.options?.mintlify?.openapi;\n if (!openapiConfig || !openapiConfig.files?.length) return;\n if (!settings.files) return;\n\n const configDir = path.dirname(settings.config);\n const specAnalyses = buildSpecAnalyses(openapiConfig.files, configDir);\n if (!specAnalyses.length) return;\n\n const warnings = new Set<string>();\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 const fileMappingAbs: Record<string, Record<string, string>> = {};\n for (const [locale, mapping] of Object.entries(fileMapping)) {\n fileMappingAbs[locale] = {};\n for (const [src, dest] of Object.entries(mapping)) {\n const absSrc = path.resolve(configDir, src);\n const absDest = path.resolve(configDir, dest);\n fileMappingAbs[locale][absSrc] = absDest;\n }\n }\n\n // Also rewrite default-locale source files so they use the deterministic spec selection\n const defaultFiles = [\n ...(resolvedPaths.mdx || []),\n ...(resolvedPaths.md || []),\n ];\n for (const filePath of defaultFiles) {\n if (!fs.existsSync(filePath)) continue;\n const content = fs.readFileSync(filePath, 'utf8');\n const updated = rewriteFrontmatter(\n content,\n filePath,\n settings.defaultLocale,\n specAnalyses,\n fileMappingAbs,\n warnings,\n configDir\n );\n if (updated?.changed) {\n await fs.promises.writeFile(filePath, updated.content, 'utf8');\n }\n }\n\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n (p.endsWith('.md') || p.endsWith('.mdx')) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n for (const filePath of targetFiles) {\n if (!fs.existsSync(filePath)) continue;\n const content = fs.readFileSync(filePath, 'utf8');\n const updated = rewriteFrontmatter(\n content,\n filePath,\n locale,\n specAnalyses,\n fileMappingAbs,\n warnings,\n configDir\n );\n\n if (updated?.changed) {\n await fs.promises.writeFile(filePath, updated.content, 'utf8');\n }\n }\n }\n\n const docsJsonTargets = collectDocsJsonTargets(\n settings,\n fileMapping,\n includeFiles\n );\n for (const target of docsJsonTargets) {\n if (!fs.existsSync(target.path)) continue;\n const content = fs.readFileSync(target.path, 'utf8');\n const updated = rewriteDocsJsonOpenApi(\n content,\n target.path,\n target.localeHint,\n specAnalyses,\n fileMappingAbs,\n fileMapping,\n warnings,\n configDir,\n settings.defaultLocale\n );\n if (updated?.changed) {\n await fs.promises.writeFile(target.path, updated.content, 'utf8');\n }\n }\n\n for (const message of warnings) {\n logger.warn(message);\n }\n}\n\nfunction collectDocsJsonTargets(\n settings: Settings,\n fileMapping: Record<string, Record<string, string>>,\n includeFiles?: Set<string>\n): Array<{ path: string; localeHint?: string }> {\n const targets: Array<{ path: string; localeHint?: string }> = [];\n const seen = new Map<string, Set<string>>();\n\n const addTarget = (filePath: string, locale?: string) => {\n const canonicalPath = path.resolve(filePath);\n if (\n includeFiles &&\n !includeFiles.has(filePath) &&\n !includeFiles.has(canonicalPath)\n ) {\n return;\n }\n const locales = seen.get(canonicalPath) ?? new Set<string>();\n if (locale) locales.add(locale);\n seen.set(canonicalPath, locales);\n };\n\n if (!includeFiles && settings.files?.resolvedPaths.json) {\n for (const filePath of settings.files.resolvedPaths.json) {\n addTarget(filePath, settings.defaultLocale);\n }\n }\n\n for (const [locale, filesMap] of Object.entries(fileMapping)) {\n for (const [sourcePath, filePath] of Object.entries(filesMap)) {\n if (!filePath.endsWith('.json')) continue;\n // Composite docs.json is translated in place and holds every locale.\n addTarget(\n filePath,\n sourcePath === filePath ? settings.defaultLocale : locale\n );\n }\n }\n\n for (const [filePath, locales] of seen.entries()) {\n const localeHint = locales.size === 1 ? Array.from(locales)[0] : undefined;\n targets.push({ path: filePath, localeHint });\n }\n\n return targets;\n}\n\nfunction isMintlifyDocsJson(filePath: string, json: unknown): boolean {\n if (!isRecord(json)) return false;\n const schema = json.$schema;\n if (typeof schema === 'string') {\n return (\n schema.includes('mintlify.com/docs.json') ||\n schema.includes('mintlify.com/mint.json')\n );\n }\n const base = path.basename(filePath);\n return base === 'docs.json' || base === 'mint.json';\n}\n\nfunction rewriteDocsJsonOpenApi(\n content: string,\n filePath: string,\n localeHint: string | undefined,\n specs: SpecAnalysis[],\n fileMappingAbs: Record<string, Record<string, string>>,\n fileMappingRel: Record<string, Record<string, string>>,\n warnings: Set<string>,\n configDir: string,\n defaultLocale: string\n): { changed: boolean; content: string } | null {\n let json: unknown;\n try {\n json = JSON.parse(content);\n } catch {\n return null;\n }\n\n if (!isMintlifyDocsJson(filePath, json)) return null;\n\n let changed = false;\n\n const visitNode = (node: unknown, activeLocale?: string) => {\n if (Array.isArray(node)) {\n node.forEach((item) => visitNode(item, activeLocale));\n return;\n }\n if (!isRecord(node)) return;\n\n let nextLocale = activeLocale;\n if (typeof node.language === 'string') {\n nextLocale = node.language;\n }\n\n const locale = nextLocale || localeHint || defaultLocale;\n\n if (typeof node.openapi === 'string') {\n const sourceValue = node.openapi;\n const localizedSource = localizeDocsJsonSpecPath(\n sourceValue,\n locale,\n filePath,\n specs,\n fileMappingAbs,\n fileMappingRel,\n warnings,\n configDir\n );\n if (localizedSource && localizedSource !== sourceValue) {\n node.openapi = localizedSource;\n changed = true;\n }\n } else if (isRecord(node.openapi)) {\n const openapiConfig = node.openapi as Record<string, unknown>;\n const sourceValue = openapiConfig.source;\n if (typeof sourceValue === 'string') {\n const localizedSource = localizeDocsJsonSpecPath(\n sourceValue,\n locale,\n filePath,\n specs,\n fileMappingAbs,\n fileMappingRel,\n warnings,\n configDir\n );\n if (localizedSource && localizedSource !== sourceValue) {\n openapiConfig.source = localizedSource;\n changed = true;\n }\n }\n\n const directoryValue = openapiConfig.directory;\n if (typeof directoryValue === 'string') {\n const localizedDirectory = localizeDocsJsonDirectory(\n directoryValue,\n locale,\n defaultLocale,\n new Set([defaultLocale, ...Object.keys(fileMappingRel)])\n );\n if (localizedDirectory && localizedDirectory !== directoryValue) {\n openapiConfig.directory = localizedDirectory;\n changed = true;\n }\n }\n }\n\n if (Array.isArray(node.pages)) {\n const pages = node.pages;\n for (let i = 0; i < pages.length; i += 1) {\n const page = pages[i];\n if (typeof page !== 'string') continue;\n const updated = stripLocaleFromOpenApiPage(page, locale);\n if (updated !== page) {\n pages[i] = updated;\n changed = true;\n }\n }\n }\n\n for (const value of Object.values(node)) {\n visitNode(value, nextLocale);\n }\n };\n\n visitNode(json, undefined);\n\n if (!changed) return null;\n return { changed, content: stringifyJson(json, content) };\n}\n\nfunction stripLocaleFromOpenApiPage(value: string, locale: string): string {\n const trimmed = value.trim();\n const prefix = `${locale}/`;\n if (!trimmed.startsWith(prefix)) return value;\n const candidate = trimmed.slice(prefix.length);\n const parsed = parseOpenApiValue(candidate);\n if (!parsed) return value;\n return candidate;\n}\n\nfunction localizeDocsJsonDirectory(\n directory: string,\n locale: string,\n defaultLocale: string,\n knownLocales: Set<string>\n): string | null {\n if (locale === defaultLocale) return null;\n\n const trimmed = directory.trim();\n if (!trimmed || /^(?:[a-z][a-z0-9+.-]*:|\\/\\/|#|\\.\\/|\\.\\.\\/)/i.test(trimmed)) {\n return null;\n }\n\n const leadingWhitespace = directory.match(/^\\s*/)?.[0] ?? '';\n const trailingWhitespace = directory.match(/\\s*$/)?.[0] ?? '';\n const leadingSlash = trimmed.startsWith('/') ? '/' : '';\n const pathBody = trimmed.replace(/^\\/+/, '');\n const [firstSegment, ...restSegments] = pathBody.split('/');\n\n if (firstSegment === locale) {\n const normalized = `${leadingWhitespace}${leadingSlash}${pathBody}${trailingWhitespace}`;\n return normalized === directory ? null : normalized;\n }\n\n const unprefixedPath = knownLocales.has(firstSegment)\n ? restSegments.join('/')\n : pathBody;\n const localizedPath = unprefixedPath ? `${locale}/${unprefixedPath}` : locale;\n const normalized = `${leadingWhitespace}${leadingSlash}${localizedPath}${trailingWhitespace}`;\n\n return normalized === directory ? null : normalized;\n}\n\nfunction localizeDocsJsonSpecPath(\n source: string,\n locale: string,\n filePath: string,\n specs: SpecAnalysis[],\n fileMappingAbs: Record<string, Record<string, string>>,\n _fileMappingRel: Record<string, Record<string, string>>,\n warnings: Set<string>,\n configDir: string\n): string | null {\n const resolvedAbs = resolveDocsJsonSpecPath(source, filePath, configDir);\n const matched = matchSpecBySource(source, resolvedAbs, specs, warnings);\n if (!matched) return source;\n\n const localizedSpecPath = resolveLocalizedSpecPath(\n matched,\n locale,\n fileMappingAbs,\n configDir,\n source\n );\n const localizedAbs = resolveDocsJsonSpecPath(\n localizedSpecPath,\n filePath,\n configDir\n );\n if (!fs.existsSync(localizedAbs)) {\n warnings.add(\n `OpenAPI source \"${source}\" localized for locale \"${locale}\" points to a missing file (${localizedAbs}). Keeping original source.`\n );\n return source;\n }\n\n const rel = normalizeSlashes(path.relative(configDir, localizedAbs));\n return formatSpecPathForDocsJson(rel, source);\n}\n\nfunction resolveDocsJsonSpecPath(\n source: string,\n filePath: string,\n configDir: string\n): string {\n if (source.startsWith('/')) {\n return path.resolve(configDir, source.replace(/^\\/+/, ''));\n }\n if (source.startsWith('./') || source.startsWith('../')) {\n return path.resolve(path.dirname(filePath), source);\n }\n return path.resolve(configDir, source);\n}\n\nfunction matchSpecBySource(\n source: string,\n resolvedAbs: string,\n specs: SpecAnalysis[],\n warnings: Set<string>\n): SpecAnalysis | null {\n const exact = specs.find((spec) => samePath(resolvedAbs, spec.absPath));\n if (exact) return exact;\n\n const normalizedExplicit = normalizeSlashes(source).replace(/^\\.?\\/+/, '');\n const explicitWithoutExt = stripExtension(normalizedExplicit);\n const explicitBase = path.basename(normalizedExplicit);\n const explicitBaseWithoutExt = stripExtension(explicitBase);\n const matches = specs.filter((spec) => {\n const configPath = normalizeSlashes(spec.configPath).replace(/^\\.?\\/+/, '');\n const configBase = path.basename(configPath);\n const configPathNoExt = stripExtension(configPath);\n const configBaseNoExt = stripExtension(configBase);\n return (\n configPath === normalizedExplicit ||\n configPathNoExt === explicitWithoutExt ||\n configBase === explicitBase ||\n configBaseNoExt === explicitBaseWithoutExt\n );\n });\n\n if (matches.length === 1) return matches[0];\n if (matches.length > 1) {\n warnings.add(\n `OpenAPI source \"${source}\" matches multiple specs (${matches\n .map((m) => m.configPath)\n .join(\n ', '\n )}). Using the first configured match (${matches[0].configPath}).`\n );\n return matches[0];\n }\n\n return null;\n}\n\nfunction formatSpecPathForDocsJson(\n relativePath: string,\n originalPathText: string\n): string {\n const normalized = normalizeSlashes(relativePath);\n const base = normalized.replace(/^\\.\\//, '').replace(/\\/+/g, '/');\n\n if (originalPathText.startsWith('/')) {\n return `/${base.replace(/^\\/+/, '')}`;\n }\n if (originalPathText.startsWith('../')) {\n return normalized;\n }\n if (originalPathText.startsWith('./')) {\n return `./${base.replace(/^\\/+/, '')}`;\n }\n return base.replace(/^\\/+/, '');\n}\n\n/**\n * Resolve configured OpenAPI files to absolute paths and collect the operations,\n * schemas, and webhooks they expose. Warns and skips when files are missing,\n * unsupported (non-JSON/YAML), or fail to parse so later steps can continue gracefully.\n */\nfunction buildSpecAnalyses(\n openapiFiles: string[],\n configDir: string\n): SpecAnalysis[] {\n const analyses: SpecAnalysis[] = [];\n\n for (const configEntry of openapiFiles) {\n const absPath = path.resolve(configDir, configEntry);\n if (!fs.existsSync(absPath)) {\n logger.warn(`OpenAPI file not found: ${configEntry}`);\n continue;\n }\n const ext = path.extname(absPath).toLowerCase();\n if (!OPENAPI_SPEC_EXTENSIONS.has(ext)) {\n logger.warn(\n `Skipping OpenAPI file (only .json/.yml/.yaml supported): ${configEntry}`\n );\n continue;\n }\n\n let spec: unknown;\n try {\n const raw = fs.readFileSync(absPath, 'utf8');\n spec = ext === '.json' ? JSON.parse(raw) : YAML.parse(raw);\n } catch {\n const format = ext === '.json' ? 'JSON' : 'YAML';\n logger.warn(`Failed to parse OpenAPI ${format}: ${configEntry}`);\n continue;\n }\n\n analyses.push({\n absPath,\n configPath: configEntry,\n operations: extractOperations(spec),\n schemas: extractSchemas(spec),\n webhooks: extractWebhooks(spec),\n });\n }\n\n return analyses;\n}\n\nfunction isRecord(val: unknown): val is Record<string, unknown> {\n return typeof val === 'object' && val !== null;\n}\n\n/**\n * Collect path+method identifiers (e.g., \"POST /foo\") from an OpenAPI spec.\n * Safely no-ops when paths is missing or malformed.\n */\nfunction extractOperations(spec: unknown): Set<string> {\n const ops = new Set<string>();\n if (!isRecord(spec) || !isRecord(spec.paths)) return ops;\n const paths = spec.paths as Record<string, unknown>;\n\n for (const [route, methods] of Object.entries(paths)) {\n if (!isRecord(methods)) continue;\n for (const [method, operation] of Object.entries(methods)) {\n if (!isRecord(operation)) continue;\n const upper = method.toUpperCase();\n if (!HTTP_METHODS.has(upper)) continue;\n ops.add(`${upper} ${route}`);\n }\n }\n return ops;\n}\n\n/**\n * Collect schema names from components.schemas.\n * Returns empty set if components/schemas are missing or malformed.\n */\nfunction extractSchemas(spec: unknown): Set<string> {\n if (!isRecord(spec) || !isRecord(spec.components)) return new Set();\n const components = spec.components as Record<string, unknown>;\n if (!isRecord(components.schemas)) return new Set();\n return new Set(Object.keys(components.schemas as Record<string, unknown>));\n}\n\n/**\n * Collect webhook names from webhooks (OpenAPI 3.1+).\n * Returns empty set if webhooks is missing or malformed.\n */\nfunction extractWebhooks(spec: unknown): Set<string> {\n if (!isRecord(spec) || !isRecord(spec.webhooks)) return new Set();\n return new Set(Object.keys(spec.webhooks as Record<string, unknown>));\n}\n\n/**\n * Parse MDX/MD frontmatter, rewrite openapi/openapi-schema entries to the\n * resolved (possibly localized) spec path, and return updated content.\n * Uses remark to find the YAML node so the rest of the document remains\n * untouched. When parsing fails or no relevant keys exist, it returns null.\n */\nfunction rewriteFrontmatter(\n content: string,\n filePath: string,\n locale: string,\n specs: SpecAnalysis[],\n fileMapping: Record<string, Record<string, string>>,\n warnings: Set<string>,\n configDir: string\n): { changed: boolean; content: string } | null {\n let tree: Root;\n try {\n tree = unified()\n .use(remarkParse)\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .parse(content) as Root;\n } catch {\n return null;\n }\n\n const yamlNode = (tree.children as Content[]).find(\n (node): node is Yaml => (node as Yaml).type === 'yaml'\n );\n if (\n !yamlNode ||\n !yamlNode.position ||\n yamlNode.position.start?.offset === undefined\n ) {\n return null;\n }\n\n const start = yamlNode.position.start.offset as number;\n const end = yamlNode.position.end.offset as number;\n const frontmatterRaw: string = yamlNode.value || '';\n\n const doc = YAML.parseDocument(frontmatterRaw, {\n prettyErrors: false,\n keepSourceTokens: true,\n });\n if (doc.errors?.length) return null;\n if (!isMap(doc.contents)) return null;\n\n let changed = false;\n\n const openapiNode = doc.get('openapi', true);\n if (isScalar(openapiNode) && typeof openapiNode.value === 'string') {\n const parsedValue = parseOpenApiValue(openapiNode.value);\n if (parsedValue) {\n const matchKey =\n parsedValue.kind === 'operation'\n ? {\n type: 'operation' as const,\n key: `${parsedValue.method.toUpperCase()} ${parsedValue.operationPath}`,\n }\n : { type: 'webhook' as const, key: parsedValue.name };\n\n const spec = resolveSpec(\n parsedValue.specPath,\n specs,\n filePath,\n configDir,\n warnings,\n describeOpenApiRef(parsedValue),\n matchKey\n );\n if (spec) {\n const descriptor = formatOpenApiDescriptor(parsedValue);\n const localizedSpecPath = resolveLocalizedSpecPath(\n spec,\n locale,\n fileMapping,\n configDir,\n parsedValue.specPath || spec.configPath\n );\n const newValue = `${localizedSpecPath} ${descriptor}`.trim();\n if (newValue !== openapiNode.value) {\n doc.set('openapi', newValue);\n changed = true;\n }\n }\n }\n }\n\n const schemaNode = doc.get('openapi-schema', true);\n if (isScalar(schemaNode) && typeof schemaNode.value === 'string') {\n const parsedValue = parseSchemaValue(schemaNode.value);\n if (parsedValue) {\n const spec = resolveSpec(\n parsedValue.specPath,\n specs,\n filePath,\n configDir,\n warnings,\n `schema \"${parsedValue.schemaName}\"`,\n { type: 'schema', key: parsedValue.schemaName }\n );\n if (spec) {\n const localizedSpecPath = resolveLocalizedSpecPath(\n spec,\n locale,\n fileMapping,\n configDir,\n parsedValue.specPath || spec.configPath\n );\n const newValue =\n `${localizedSpecPath} ${parsedValue.schemaName}`.trim();\n if (newValue !== schemaNode.value) {\n doc.set('openapi-schema', newValue);\n changed = true;\n }\n }\n }\n }\n\n if (!changed) return null;\n\n const fmString = doc.toString().trimEnd();\n const rebuilt = `${content.slice(0, start)}---\\n${fmString}\\n---${content.slice(end)}`;\n return { changed, content: rebuilt };\n}\n\nfunction stripWrappingQuotes(value: string): string {\n return value.trim().replace(/^['\"]|['\"]$/g, '');\n}\n\n/**\n * Parse frontmatter openapi string into spec/method/path or webhook.\n * Supports optional leading spec file, the webhook keyword, quoted values,\n * and forgiving whitespace. Returns null when the structure is unrecognized.\n */\nfunction parseOpenApiValue(value: string): ParsedOpenApiValue | null {\n const stripped = stripWrappingQuotes(value);\n const tokens = stripped.split(/\\s+/).filter(Boolean);\n if (!tokens.length) return null;\n\n let cursor = 0;\n let specPath: string | undefined;\n const first = tokens[0];\n const second = tokens[1];\n const methodCandidate = second?.toUpperCase();\n const firstLooksLikeSpec =\n hasOpenApiSpecExtension(first) ||\n (second &&\n (second.toLowerCase() === 'webhook' ||\n (methodCandidate && HTTP_METHODS.has(methodCandidate))));\n\n if (firstLooksLikeSpec) {\n specPath = tokens[0];\n cursor = 1;\n }\n if (cursor >= tokens.length) return null;\n\n const keyword = tokens[cursor];\n if (keyword.toLowerCase() === 'webhook') {\n const name = tokens.slice(cursor + 1).join(' ');\n if (!name) return null;\n return { kind: 'webhook', specPath, name };\n }\n\n const method = keyword.toUpperCase();\n if (!HTTP_METHODS.has(method)) return null;\n const operationPath = tokens.slice(cursor + 1).join(' ');\n if (!operationPath) return null;\n return { kind: 'operation', specPath, method, operationPath };\n}\n\n/**\n * Parse frontmatter openapi-schema string into spec/schemaName.\n * Accepts optional leading spec file and quoted values; returns null on invalid\n * shapes so callers can skip rewrites gracefully.\n */\nfunction parseSchemaValue(value: string): ParsedSchemaValue | null {\n const stripped = stripWrappingQuotes(value);\n const tokens = stripped.split(/\\s+/).filter(Boolean);\n if (!tokens.length) return null;\n let cursor = 0;\n let specPath: string | undefined;\n // Canonical form is \"<spec> <SchemaName>\". Treat the first token as the spec\n // when it has a spec file extension, or when more tokens follow — schema names\n // are single identifiers, so any leading token must be the spec. This covers\n // extensionless spec names (Mintlify auto-discovers specs by file stem, e.g.\n // `events-schema group.created`), mirroring parseOpenApiValue's heuristic.\n if (hasOpenApiSpecExtension(tokens[0]) || tokens.length > 1) {\n specPath = tokens[0];\n cursor = 1;\n }\n const schemaName = tokens.slice(cursor).join(' ');\n if (!schemaName) return null;\n return { specPath, schemaName };\n}\n\n/**\n * Choose which configured spec a reference should use.\n * - If an explicit spec path is provided, resolve it relative to the config\n * and the referencing file, warn when unknown, and bail.\n * - Otherwise, try to match by operation/webhook/schema name; resolve\n * ambiguity using config order and warn when ambiguous or missing.\n */\nfunction resolveSpec(\n explicitPath: string | undefined,\n specs: SpecAnalysis[],\n filePath: string,\n configDir: string,\n warnings: Set<string>,\n refDescription: string,\n match: { type: 'operation' | 'webhook' | 'schema'; key: string }\n): SpecAnalysis | null {\n if (!specs.length) return null;\n\n if (explicitPath) {\n const normalizedExplicit = normalizeSlashes(\n explicitPath.replace(/^\\.?\\/+/, '')\n );\n const candidates = [\n path.resolve(configDir, normalizedExplicit),\n path.resolve(path.dirname(filePath), normalizedExplicit),\n ];\n const foundSpec = specs.find((spec) => {\n const normalizedSpecPath = normalizeSlashes(spec.absPath);\n return candidates.some((candidate) =>\n samePath(candidate, normalizedSpecPath)\n );\n });\n if (foundSpec) {\n if (specHasMatch(foundSpec, match)) {\n return foundSpec;\n }\n\n const alternatives = specs.filter(\n (spec) => spec !== foundSpec && specHasMatch(spec, match)\n );\n if (alternatives.length === 1) {\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} points to ${foundSpec.configPath}, but the entry was not found there. Using ${alternatives[0].configPath} instead.`\n );\n return alternatives[0];\n }\n if (alternatives.length > 1) {\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} points to ${foundSpec.configPath}, but the entry was not found there and matches multiple specs (${alternatives\n .map((spec) => spec.configPath)\n .join(', ')}). Skipping localization for this reference.`\n );\n return null;\n }\n\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} points to ${foundSpec.configPath}, but the entry was not found in any configured spec. Skipping localization for this reference.`\n );\n return null;\n }\n\n const explicitWithoutExt = stripExtension(normalizedExplicit);\n const explicitBase = path.basename(normalizedExplicit);\n const explicitBaseWithoutExt = stripExtension(explicitBase);\n const matches = specs.filter((spec) => {\n const configPath = normalizeSlashes(spec.configPath).replace(\n /^\\.?\\/+/,\n ''\n );\n const configBase = path.basename(configPath);\n const configPathNoExt = stripExtension(configPath);\n const configBaseNoExt = stripExtension(configBase);\n return (\n configPath === normalizedExplicit ||\n configPathNoExt === explicitWithoutExt ||\n configBase === explicitBase ||\n configBaseNoExt === explicitBaseWithoutExt\n );\n });\n if (matches.length === 1) return matches[0];\n if (matches.length > 1) {\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} matches multiple specs (${matches\n .map((m) => m.configPath)\n .join(\n ', '\n )}). Using the first configured match (${matches[0].configPath}).`\n );\n return matches[0];\n }\n\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} points to an unconfigured spec (${explicitPath}). Skipping localization for this reference.`\n );\n return null;\n }\n\n // No explicit spec: try to find by contents\n const matches = specs.filter((spec) => {\n if (match.type === 'schema') {\n return spec.schemas.has(match.key);\n }\n if (match.type === 'webhook') {\n return spec.webhooks.has(match.key);\n }\n // operation\n return spec.operations.has(match.key);\n });\n\n if (matches.length === 1) return matches[0];\n if (matches.length > 1) {\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} is available in multiple specs. Skipping localization for this reference.`\n );\n return null;\n }\n\n warnings.add(\n `OpenAPI reference ${refDescription} in ${filePath} was not found in any configured spec. Skipping localization for this reference.`\n );\n return null;\n}\n\nfunction specHasMatch(\n spec: SpecAnalysis,\n match: { type: 'operation' | 'webhook' | 'schema'; key: string }\n): boolean {\n if (match.type === 'schema') {\n return spec.schemas.has(match.key);\n }\n if (match.type === 'webhook') {\n return spec.webhooks.has(match.key);\n }\n return spec.operations.has(match.key);\n}\n\n/**\n * Map a spec to the locale-specific file path when available and normalize it\n * for frontmatter. Falls back to the source spec when the locale copy does\n * not exist to preserve deterministic behavior.\n */\nfunction resolveLocalizedSpecPath(\n spec: SpecAnalysis,\n locale: string,\n fileMapping: Record<string, Record<string, string>>,\n configDir: string,\n originalPathText?: string\n): string {\n const mapping = fileMapping[locale]?.[spec.absPath];\n const chosenAbs = mapping || spec.absPath;\n const rel = normalizeSlashes(path.relative(configDir, chosenAbs));\n const rooted = `/${rel.replace(/^\\/+/, '')}`;\n return formatSpecPathForFrontmatter(\n rooted,\n originalPathText || spec.configPath\n );\n}\n\n/**\n * Format the path that will be written back to frontmatter:\n * - Preserve the user's absolute style when they used a leading slash.\n * - Preserve upward relative references (../) exactly.\n * - Otherwise return a repo-root-relative path with a leading slash so Mintlify\n * resolves consistently regardless of the MDX file location.\n */\nfunction formatSpecPathForFrontmatter(\n relativePath: string,\n originalPathText: string\n): string {\n const normalized = normalizeSlashes(relativePath);\n const base = normalized.replace(/^\\.\\//, '').replace(/\\/+/g, '/');\n\n if (originalPathText.startsWith('/')) {\n // Force repo-root absolute style\n return `/${base.replace(/^\\/+/, '')}`;\n }\n\n if (originalPathText.startsWith('../')) {\n // Preserve explicit relative upward references\n return normalized;\n }\n\n // Default to repo-root relative with leading slash to avoid resolving relative to the MDX directory\n return `/${base.replace(/^\\/+/, '')}`;\n}\n\n/** Normalize the descriptive portion after the spec path for frontmatter. */\nfunction formatOpenApiDescriptor(value: ParsedOpenApiValue): string {\n if (value.kind === 'webhook') return `webhook ${value.name}`;\n return `${value.method.toUpperCase()} ${value.operationPath}`;\n}\n\n/** Human-readable description a specific OpenAPI reference. */\nfunction describeOpenApiRef(value: ParsedOpenApiValue): string {\n if (value.kind === 'webhook') return `webhook ${value.name}`;\n return `${value.method.toUpperCase()} ${value.operationPath}`;\n}\n\n/** Remove a single trailing file extension while preserving directory segments. */\nfunction stripExtension(p: string): string {\n const parsed = path.parse(p);\n return normalizeSlashes(path.join(parsed.dir, parsed.name));\n}\n\nfunction hasOpenApiSpecExtension(value: string): boolean {\n return OPENAPI_SPEC_EXTENSIONS.has(path.extname(value).toLowerCase());\n}\n\n/** Normalize separators for stable comparisons and output. */\nfunction normalizeSlashes(p: string): string {\n return p.replace(/\\\\/g, '/');\n}\n\n/** Compare paths after resolution to avoid casing/separator mismatches. */\nfunction samePath(a: string, b: string): boolean {\n return path.resolve(a) === path.resolve(b);\n}\n"],"mappings":";;;;;;;;;;AAsCA,MAAM,eAAe,IAAI,IAAI;CAC3B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,MAAM,0BAA0B,IAAI,IAAI;CAAC;CAAS;CAAS;CAAO,CAAC;;;;;;;AAQnE,eAA8B,eAC5B,UACA,cACA;CACA,MAAM,gBAAgB,SAAS,SAAS,UAAU;AAClD,KAAI,CAAC,iBAAiB,CAAC,cAAc,OAAO,OAAQ;AACpD,KAAI,CAAC,SAAS,MAAO;CAErB,MAAM,YAAY,KAAK,QAAQ,SAAS,OAAO;CAC/C,MAAM,eAAe,kBAAkB,cAAc,OAAO,UAAU;AACtE,KAAI,CAAC,aAAa,OAAQ;CAE1B,MAAM,2BAAW,IAAI,KAAa;CAClC,MAAM,EAAE,eAAe,kBAAkB,gBAAgB,qBACvD,SAAS;CACX,MAAM,cAAc,kBAClB,eACA,kBACA,gBACA,kBACA,SAAS,SACT,SAAS,cACV;CACD,MAAM,iBAAyD,EAAE;AACjE,MAAK,MAAM,CAAC,QAAQ,YAAY,OAAO,QAAQ,YAAY,EAAE;AAC3D,iBAAe,UAAU,EAAE;AAC3B,OAAK,MAAM,C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MAAM;;;AAIhD,SAAS,mBAAmB,OAAmC;AAC7D,KAAI,MAAM,SAAS,UAAW,QAAO,WAAW,MAAM;AACtD,QAAO,GAAG,MAAM,OAAO,aAAa,CAAC,GAAG,MAAM;;;AAIhD,SAAS,eAAe,GAAmB;CACzC,MAAM,SAAS,KAAK,MAAM,EAAE;AAC5B,QAAO,iBAAiB,KAAK,KAAK,OAAO,KAAK,OAAO,KAAK,CAAC;;AAG7D,SAAS,wBAAwB,OAAwB;AACvD,QAAO,wBAAwB,IAAI,KAAK,QAAQ,MAAM,CAAC,aAAa,CAAC;;;AAIvE,SAAS,iBAAiB,GAAmB;AAC3C,QAAO,EAAE,QAAQ,OAAO,IAAI;;;AAI9B,SAAS,SAAS,GAAW,GAAoB;AAC/C,QAAO,KAAK,QAAQ,EAAE,KAAK,KAAK,QAAQ,EAAE"}
@@ -1,4 +1,5 @@
1
1
  import { logger } from "../console/logger.js";
2
+ import { stringifyJson } from "../fs/stringifyJson.js";
2
3
  import { validateJsonSchema } from "../formats/json/utils.js";
3
4
  import { clearStoredRefMap, getStoredRefMap } from "../state/mintlifyRefMap.js";
4
5
  import path from "node:path";
@@ -29,16 +30,18 @@ async function splitMintlifyLanguageRefs(settings) {
29
30
  if (!targetFile) return;
30
31
  const { filePath: compositeFilePath, splitConfig } = targetFile;
31
32
  if (!fs.existsSync(compositeFilePath)) return;
33
+ let fileContent;
32
34
  let fileJson;
33
35
  try {
34
- fileJson = JSON.parse(fs.readFileSync(compositeFilePath, "utf-8"));
36
+ fileContent = fs.readFileSync(compositeFilePath, "utf-8");
37
+ fileJson = JSON.parse(fileContent);
35
38
  } catch {
36
39
  return;
37
40
  }
38
41
  const docsDir = path.dirname(compositeFilePath);
39
42
  if (splitConfig) processSplitEntries(fileJson, compositeFilePath, docsDir, splitConfig, settings, refMap);
40
43
  if (refMap && refMap.size > 0) restoreTopLevelRefs(fileJson, refMap, splitConfig);
41
- fs.writeFileSync(compositeFilePath, JSON.stringify(fileJson, null, 2), "utf-8");
44
+ fs.writeFileSync(compositeFilePath, stringifyJson(fileJson, fileContent), "utf-8");
42
45
  } finally {
43
46
  clearStoredRefMap();
44
47
  }
@@ -264,7 +267,11 @@ function collectInternalRefs(refMap, entryPointerPrefix) {
264
267
  function writeJsonFile(filePath, data) {
265
268
  const dir = path.dirname(filePath);
266
269
  if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
267
- fs.writeFileSync(filePath, JSON.stringify(data, null, 2), "utf-8");
270
+ let original;
271
+ try {
272
+ original = fs.readFileSync(filePath, "utf-8");
273
+ } catch {}
274
+ fs.writeFileSync(filePath, stringifyJson(data, original), "utf-8");
268
275
  }
269
276
  /**
270
277
  * Build a relative $ref path (POSIX separators, "./"-prefixed when it isn't
@@ -1 +1 @@
1
- {"version":3,"file":"splitMintlifyLanguageRefs.js","names":[],"sources":["../../src/utils/splitMintlifyLanguageRefs.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport { Settings, JsonSchema, SourceObjectOptions } from '../types/index.js';\nimport type { RefMap } from './resolveMintlifyRefs.js';\nimport { validateJsonSchema } from '../formats/json/utils.js';\nimport { getStoredRefMap, clearStoredRefMap } from '../state/mintlifyRefMap.js';\nimport { JSONPath } from 'jsonpath-plus';\nimport { getLocaleProperties } from '@generaltranslation/format';\n\ntype JsonContainer = Record<string, unknown> | unknown[];\n\nfunction isJsonContainer(value: unknown): value is JsonContainer {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Post-processing step for composite JSON files with splitEntries enabled.\n *\n * After mergeJson writes a fully-inlined composite file, this function:\n * 1. Restores the original $ref structure (if the source used $ref / resolveRefs)\n * 2. Extracts non-default keyed entries into their own ref files\n * to keep the source file compact\n *\n * Driven entirely by the jsonSchema config — reads the composite path,\n * key field, and splitEntries flag from the schema.\n */\nexport async function splitMintlifyLanguageRefs(\n settings: Settings\n): Promise<void> {\n const refMap = getStoredRefMap();\n\n try {\n const resolvedJsonPaths = settings.files?.resolvedPaths?.json;\n if (!resolvedJsonPaths) return;\n\n // Find a JSON file that has splitEntries enabled or resolveRefs\n const targetFile = findTargetFile(resolvedJsonPaths, settings);\n if (!targetFile) return;\n\n const { filePath: compositeFilePath, splitConfig } = targetFile;\n if (!fs.existsSync(compositeFilePath)) return;\n\n let fileJson: unknown;\n try {\n fileJson = JSON.parse(fs.readFileSync(compositeFilePath, 'utf-8'));\n } catch {\n return;\n }\n\n const docsDir = path.dirname(compositeFilePath);\n\n // If splitEntries is configured, process it\n if (splitConfig) {\n processSplitEntries(\n fileJson,\n compositeFilePath,\n docsDir,\n splitConfig,\n settings,\n refMap\n );\n }\n\n // Restore top-level refs if any exist\n if (refMap && refMap.size > 0) {\n restoreTopLevelRefs(fileJson, refMap, splitConfig);\n }\n\n // Always write the composite file back — splitEntries modified the\n // languages array, and restoreTopLevelRefs may not have written it\n // (e.g., when all refs are inside language entries, not top-level)\n fs.writeFileSync(\n compositeFilePath,\n JSON.stringify(fileJson, null, 2),\n 'utf-8'\n );\n } finally {\n clearStoredRefMap();\n }\n}\n\ntype SplitConfig = {\n compositePath: string;\n jsonPointer: string;\n keyField: string;\n keyJsonPath: string;\n sourceObjectOptions: SourceObjectOptions;\n};\n\n/**\n * Find the target file and extract split configuration from the schema.\n */\nfunction findTargetFile(\n resolvedPaths: string[],\n settings: Settings\n): {\n filePath: string;\n schema: JsonSchema;\n splitConfig: SplitConfig | null;\n} | null {\n if (!settings.options?.jsonSchema) return null;\n\n for (const filePath of resolvedPaths) {\n const schema = validateJsonSchema(settings.options, filePath);\n if (!schema) continue;\n\n const hasSplitEntries = schema.composite\n ? Object.entries(schema.composite).some(([, opts]) => opts.splitEntries)\n : false;\n\n const hasResolveRefs = schema.resolveRefs;\n\n if (!hasSplitEntries && !hasResolveRefs) continue;\n\n // Extract split config if available\n let splitConfig: SplitConfig | null = null;\n if (schema.composite) {\n for (const [compositePath, opts] of Object.entries(schema.composite)) {\n if (opts.splitEntries && opts.type === 'array' && opts.key) {\n splitConfig = {\n compositePath,\n jsonPointer: jsonPathToPointer(compositePath),\n keyField: opts.key,\n keyJsonPath: opts.key,\n sourceObjectOptions: opts,\n };\n break;\n }\n }\n }\n\n return { filePath, schema, splitConfig };\n }\n\n return null;\n}\n\n/**\n * Process splitEntries: extract non-default keyed entries into ref files.\n */\nfunction processSplitEntries(\n fileJson: unknown,\n compositeFilePath: string,\n docsDir: string,\n splitConfig: SplitConfig,\n settings: Settings,\n refMap: RefMap | null\n): void {\n const { jsonPointer, keyJsonPath } = splitConfig;\n\n // Find the composite array — may be behind a $ref\n const parentPointer = jsonPointer.split('/').slice(0, -1).join('/') || '';\n const arrayKey = jsonPointer.split('/').pop() || '';\n const navRefEntry = parentPointer ? refMap?.get(parentPointer) : undefined;\n\n // Get the array from the file\n const arrayContainer = parentPointer\n ? getAtPointer(fileJson, parentPointer)\n : fileJson;\n if (!isJsonContainer(arrayContainer)) return;\n\n const entries = Array.isArray(arrayContainer)\n ? arrayContainer[Number(arrayKey)]\n : arrayContainer[arrayKey];\n if (!Array.isArray(entries) || entries.length <= 1) return;\n\n // Determine the default key value (the source entry)\n const defaultKeyValue = getDefaultKeyValue(\n settings.defaultLocale,\n splitConfig.sourceObjectOptions\n );\n\n const defaultIndex = entries.findIndex((e: unknown) => {\n if (!e || typeof e !== 'object') return false;\n const values = JSONPath({\n json: e,\n path: keyJsonPath,\n resultType: 'value',\n flatten: true,\n wrap: true,\n }) as unknown[];\n return values?.[0] === defaultKeyValue;\n });\n if (defaultIndex < 0) return;\n\n // Detect whether each language entry is itself a $ref (per-entry refs), as\n // opposed to the case where the *container* of the languages array is a $ref\n // (navRefEntry). With per-entry refs, the languages array still lives in the\n // composite file, but each entry's content lives in a separate ref file.\n const defaultEntryPointer = `${jsonPointer}/${defaultIndex}`;\n const defaultEntryRef = refMap?.get(defaultEntryPointer);\n\n // arrayHostDir: directory of the file that physically holds the languages\n // array — entry $refs in the array are written relative to this.\n // entryBaseDir: directory under which per-entry ref files (and their nested\n // refs) are written — mirrors the source entry file's location.\n // These coincide for the container-ref and fully-inline cases; they differ\n // only for per-entry refs, where the array lives in the composite file but\n // the entry files live next to the (default) entry's source ref.\n const arrayHostDir = navRefEntry\n ? path.dirname(navRefEntry.sourceFile)\n : docsDir;\n const entryBaseDir = navRefEntry\n ? path.dirname(navRefEntry.sourceFile)\n : defaultEntryRef\n ? path.dirname(defaultEntryRef.sourceFile)\n : docsDir;\n const navFileName = navRefEntry\n ? path.basename(navRefEntry.sourceFile)\n : defaultEntryRef\n ? path.basename(defaultEntryRef.sourceFile)\n : path.basename(compositeFilePath);\n\n // Restore $ref structure if the source used $ref\n if (refMap && refMap.size > 0) {\n const internalRefs = collectInternalRefs(refMap, defaultEntryPointer);\n\n if (internalRefs.length > 0) {\n // When the default entry is itself a $ref, it is restored to that single\n // $ref below and its source file is left untouched, so we must not restore\n // its nested refs in place. Otherwise (inlined default entry) we do.\n if (!defaultEntryRef) {\n const defaultEntry = entries[defaultIndex];\n for (const ref of internalRefs) {\n setAtPointer(defaultEntry, ref.relativePointer, {\n ...ref.siblings,\n $ref: ref.refPath,\n });\n }\n }\n\n // For each non-default entry, write localized copies of the nested ref\n // files (mirroring the source topology under the locale dir) and replace\n // the inlined subtrees with their $refs.\n for (let i = 0; i < entries.length; i++) {\n if (i === defaultIndex) continue;\n const entry = entries[i];\n\n const entryKeyValues = JSONPath({\n json: entry,\n path: keyJsonPath,\n resultType: 'value',\n flatten: true,\n wrap: true,\n }) as unknown[];\n if (entryKeyValues?.[0] === defaultKeyValue) continue;\n const keyValue =\n typeof entryKeyValues?.[0] === 'string'\n ? entryKeyValues[0]\n : 'unknown';\n\n for (const ref of internalRefs) {\n const subtree = getAtPointer(entry, ref.relativePointer);\n if (subtree === undefined) continue;\n\n const originalAbsPath = path.resolve(ref.resolvedDir, ref.refPath);\n const relToBaseDir = path.relative(entryBaseDir, originalAbsPath);\n const localeRelPath = path.join(keyValue, relToBaseDir);\n const outputPath = path.resolve(entryBaseDir, localeRelPath);\n\n const { siblings, content } = extractRefSiblings(subtree, ref);\n writeJsonFile(outputPath, content);\n\n setAtPointer(entry, ref.relativePointer, {\n ...siblings,\n $ref: ref.refPath,\n });\n }\n }\n\n logger.info(`Restored $ref structure for default entry`);\n }\n }\n\n // Get the actual property name from the key JSONPath (e.g., \"$.language\" → \"language\")\n const keyPropertyName = keyJsonPath.replace(/^\\$\\.?/, '');\n\n // Extract each non-default entry into its own ref file\n for (let i = 0; i < entries.length; i++) {\n if (i === defaultIndex) continue;\n const entry = entries[i];\n if (!entry || typeof entry !== 'object') continue;\n\n const keyValues = JSONPath({\n json: entry,\n path: keyJsonPath,\n resultType: 'value',\n flatten: true,\n wrap: true,\n }) as unknown[];\n const keyValue = keyValues?.[0];\n if (typeof keyValue !== 'string' || keyValue === defaultKeyValue) continue;\n\n if (!isJsonContainer(entry) || Array.isArray(entry)) continue;\n const { [keyPropertyName]: _, ...contentWithoutKey } = entry;\n\n // If the entry still carries a top-level $ref, it was never inlined this\n // run (e.g. the merge step didn't process this file). There is no content\n // to extract — writing would produce a self-referential stub that\n // overwrites or shadows the real ref file. Leave the entry untouched.\n if (typeof contentWithoutKey.$ref === 'string') {\n continue;\n }\n\n const entryFilePath = path.resolve(\n entryBaseDir,\n path.join(keyValue, navFileName)\n );\n writeJsonFile(entryFilePath, contentWithoutKey);\n\n entries[i] = {\n [keyPropertyName]: keyValue,\n $ref: toRelativeRefPath(arrayHostDir, entryFilePath),\n };\n }\n\n // When the default entry was itself a $ref, restore it to that single $ref;\n // its source file is the untouched English source already on disk.\n if (defaultEntryRef) {\n entries[defaultIndex] = {\n ...defaultEntryRef.siblings,\n $ref: defaultEntryRef.refPath,\n };\n }\n\n logger.info(`Split keyed entries into ref files`);\n}\n\n/**\n * Get the identifying key value for the default locale.\n */\nfunction getDefaultKeyValue(\n defaultLocale: string,\n sourceObjectOptions: SourceObjectOptions\n): string {\n const localeProperty = sourceObjectOptions.localeProperty || 'code';\n const localeProperties = getLocaleProperties(defaultLocale);\n return (\n (localeProperties as Record<string, string | undefined>)[localeProperty] ||\n localeProperties.code ||\n defaultLocale\n );\n}\n\n/**\n * Convert a JSONPath like \"$.navigation.languages\" to a JSON pointer like \"/navigation/languages\".\n */\nfunction jsonPathToPointer(jsonPath: string): string {\n return jsonPath\n .replace(/^\\$\\.?/, '')\n .split('.')\n .filter(Boolean)\n .map((segment) => `/${segment}`)\n .join('');\n}\n\n/**\n * Restore top-level $ref pointers in the composite file.\n * Sorted deepest-first so nested refs are written before parents.\n */\nfunction restoreTopLevelRefs(\n fileJson: unknown,\n refMap: RefMap,\n splitConfig: SplitConfig | null\n): void {\n // Build a regex to exclude entries inside the composite array\n const arrayPointerPattern = splitConfig\n ? new RegExp(\n `^${splitConfig.jsonPointer.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\/\\\\d+`\n )\n : null;\n\n const entries = [...refMap.entries()]\n .filter(\n ([pointer]) => !arrayPointerPattern || !arrayPointerPattern.test(pointer)\n )\n .sort(([a], [b]) => b.length - a.length);\n\n for (const [pointer, entry] of entries) {\n const subtree = getAtPointer(fileJson, pointer);\n if (subtree === undefined) continue;\n\n // If the value here is still an unresolved $ref placeholder, the referenced\n // file was never inlined at this pointer (e.g. mergeJson leaves non-composite\n // refs like `redirects` collapsed). Writing it back would overwrite the\n // source file with a self-referential stub and destroy its real contents —\n // the source already holds the correct data, so leave it untouched.\n if (\n isJsonContainer(subtree) &&\n !Array.isArray(subtree) &&\n typeof (subtree as Record<string, unknown>).$ref === 'string'\n ) {\n continue;\n }\n\n const { siblings, content } = extractRefSiblings(subtree, entry);\n writeJsonFile(entry.sourceFile, content);\n setAtPointer(fileJson, pointer, { ...siblings, $ref: entry.refPath });\n }\n}\n\n/**\n * Mintlify merges keys placed next to a `$ref` on top of the referenced file's\n * content, so ref resolution folds them into the inlined subtree. When\n * restoring the `$ref`, lift those keys back out: they stay next to the `$ref`\n * (with their possibly translated values) and are dropped from the content\n * written to the ref file — unless the referenced file also defined the key,\n * in which case it stays in both, preserving the source topology and\n * Mintlify's sibling-precedence semantics.\n */\nfunction extractRefSiblings(\n subtree: unknown,\n ref: {\n siblings?: Record<string, unknown>;\n originalContent?: unknown;\n refPath?: string;\n }\n): { siblings: Record<string, unknown>; content: unknown } {\n const originalSiblings = ref.siblings ?? {};\n const siblingKeys = Object.keys(originalSiblings);\n if (siblingKeys.length === 0) {\n return { siblings: {}, content: subtree };\n }\n if (!isJsonContainer(subtree) || Array.isArray(subtree)) {\n // Non-object content cannot carry merged siblings; restore the originals\n return { siblings: { ...originalSiblings }, content: subtree };\n }\n const content = { ...subtree };\n const siblings: Record<string, unknown> = {};\n const original = ref.originalContent;\n const originalContentHasKey = (key: string) =>\n isJsonContainer(original) && !Array.isArray(original) && key in original;\n for (const key of siblingKeys) {\n if (key in content) {\n siblings[key] = content[key];\n if (!originalContentHasKey(key)) {\n delete content[key];\n }\n } else {\n // Object resolutions always merge siblings into the subtree, so this\n // only fires if that invariant breaks upstream. Restoring the source\n // value keeps the output schema-valid, but it skips translation — warn\n // so the regression is visible.\n logger.warn(\n `Sibling key \"${key}\" missing from translated content for $ref ${ref.refPath ?? '(unknown)'}; restoring source value`\n );\n siblings[key] = originalSiblings[key];\n }\n }\n return { siblings, content };\n}\n\n/**\n * Collect refMap entries that describe an entry's internal $ref chain.\n * Sorted deepest-first so nested content is extracted before parents.\n */\nfunction collectInternalRefs(\n refMap: RefMap,\n entryPointerPrefix: string\n): {\n relativePointer: string;\n refPath: string;\n resolvedDir: string;\n siblings?: Record<string, unknown>;\n originalContent?: unknown;\n}[] {\n const refs: {\n relativePointer: string;\n refPath: string;\n resolvedDir: string;\n siblings?: Record<string, unknown>;\n originalContent?: unknown;\n }[] = [];\n\n for (const [pointer, entry] of refMap.entries()) {\n if (!pointer.startsWith(entryPointerPrefix + '/')) continue;\n refs.push({\n relativePointer: pointer.slice(entryPointerPrefix.length),\n refPath: entry.refPath,\n resolvedDir: entry.containingDir,\n siblings: entry.siblings,\n originalContent: entry.originalContent,\n });\n }\n\n refs.sort((a, b) => b.relativePointer.length - a.relativePointer.length);\n return refs;\n}\n\nfunction writeJsonFile(filePath: string, data: unknown): void {\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n fs.writeFileSync(filePath, JSON.stringify(data, null, 2), 'utf-8');\n}\n\n/**\n * Build a relative $ref path (POSIX separators, \"./\"-prefixed when it isn't\n * already a relative or absolute path) from the directory that hosts the\n * languages array to a written entry file.\n */\nfunction toRelativeRefPath(fromDir: string, toPath: string): string {\n const rel = path.relative(fromDir, toPath).split(path.sep).join('/');\n return rel.startsWith('.') || rel.startsWith('/') ? rel : `./${rel}`;\n}\n\nfunction getAtPointer(obj: unknown, pointer: string): unknown {\n if (!pointer || pointer === '/') return obj;\n const parts = pointer.split('/').filter(Boolean);\n let current = obj;\n for (const part of parts) {\n if (!isJsonContainer(current)) return undefined;\n const index = /^\\d+$/.test(part) ? parseInt(part) : part;\n current = Array.isArray(current)\n ? current[index as number]\n : current[index];\n }\n return current;\n}\n\nfunction setAtPointer(obj: unknown, pointer: string, value: unknown): void {\n if (!pointer || pointer === '/') return;\n const parts = pointer.split('/').filter(Boolean);\n let current = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n if (!isJsonContainer(current)) return;\n const index = /^\\d+$/.test(parts[i]) ? parseInt(parts[i]) : parts[i];\n const next = Array.isArray(current)\n ? current[index as number]\n : current[index];\n if (next === undefined) return;\n current = next;\n }\n const lastPart = parts[parts.length - 1];\n const lastIndex = /^\\d+$/.test(lastPart) ? parseInt(lastPart) : lastPart;\n if (!isJsonContainer(current)) return;\n if (Array.isArray(current)) {\n current[lastIndex as number] = value;\n } else {\n current[lastIndex] = value;\n }\n}\n"],"mappings":";;;;;;;;AAYA,SAAS,gBAAgB,OAAwC;AAC/D,QAAO,OAAO,UAAU,YAAY,UAAU;;;;;;;;;;;;;AAchD,eAAsB,0BACpB,UACe;CACf,MA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,MAAM,GAAG,GAAG,MAAM;EAClE,MAAM,OAAO,MAAM,QAAQ,QAAQ,GAC/B,QAAQ,SACR,QAAQ;AACZ,MAAI,SAAS,KAAA,EAAW;AACxB,YAAU;;CAEZ,MAAM,WAAW,MAAM,MAAM,SAAS;CACtC,MAAM,YAAY,QAAQ,KAAK,SAAS,GAAG,SAAS,SAAS,GAAG;AAChE,KAAI,CAAC,gBAAgB,QAAQ,CAAE;AAC/B,KAAI,MAAM,QAAQ,QAAQ,CACxB,SAAQ,aAAuB;KAE/B,SAAQ,aAAa"}
1
+ {"version":3,"file":"splitMintlifyLanguageRefs.js","names":[],"sources":["../../src/utils/splitMintlifyLanguageRefs.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport { stringifyJson } from '../fs/stringifyJson.js';\nimport { Settings, JsonSchema, SourceObjectOptions } from '../types/index.js';\nimport type { RefMap } from './resolveMintlifyRefs.js';\nimport { validateJsonSchema } from '../formats/json/utils.js';\nimport { getStoredRefMap, clearStoredRefMap } from '../state/mintlifyRefMap.js';\nimport { JSONPath } from 'jsonpath-plus';\nimport { getLocaleProperties } from '@generaltranslation/format';\n\ntype JsonContainer = Record<string, unknown> | unknown[];\n\nfunction isJsonContainer(value: unknown): value is JsonContainer {\n return typeof value === 'object' && value !== null;\n}\n\n/**\n * Post-processing step for composite JSON files with splitEntries enabled.\n *\n * After mergeJson writes a fully-inlined composite file, this function:\n * 1. Restores the original $ref structure (if the source used $ref / resolveRefs)\n * 2. Extracts non-default keyed entries into their own ref files\n * to keep the source file compact\n *\n * Driven entirely by the jsonSchema config — reads the composite path,\n * key field, and splitEntries flag from the schema.\n */\nexport async function splitMintlifyLanguageRefs(\n settings: Settings\n): Promise<void> {\n const refMap = getStoredRefMap();\n\n try {\n const resolvedJsonPaths = settings.files?.resolvedPaths?.json;\n if (!resolvedJsonPaths) return;\n\n // Find a JSON file that has splitEntries enabled or resolveRefs\n const targetFile = findTargetFile(resolvedJsonPaths, settings);\n if (!targetFile) return;\n\n const { filePath: compositeFilePath, splitConfig } = targetFile;\n if (!fs.existsSync(compositeFilePath)) return;\n\n let fileContent: string;\n let fileJson: unknown;\n try {\n fileContent = fs.readFileSync(compositeFilePath, 'utf-8');\n fileJson = JSON.parse(fileContent);\n } catch {\n return;\n }\n\n const docsDir = path.dirname(compositeFilePath);\n\n // If splitEntries is configured, process it\n if (splitConfig) {\n processSplitEntries(\n fileJson,\n compositeFilePath,\n docsDir,\n splitConfig,\n settings,\n refMap\n );\n }\n\n // Restore top-level refs if any exist\n if (refMap && refMap.size > 0) {\n restoreTopLevelRefs(fileJson, refMap, splitConfig);\n }\n\n // Always write the composite file back — splitEntries modified the\n // languages array, and restoreTopLevelRefs may not have written it\n // (e.g., when all refs are inside language entries, not top-level)\n fs.writeFileSync(\n compositeFilePath,\n stringifyJson(fileJson, fileContent),\n 'utf-8'\n );\n } finally {\n clearStoredRefMap();\n }\n}\n\ntype SplitConfig = {\n compositePath: string;\n jsonPointer: string;\n keyField: string;\n keyJsonPath: string;\n sourceObjectOptions: SourceObjectOptions;\n};\n\n/**\n * Find the target file and extract split configuration from the schema.\n */\nfunction findTargetFile(\n resolvedPaths: string[],\n settings: Settings\n): {\n filePath: string;\n schema: JsonSchema;\n splitConfig: SplitConfig | null;\n} | null {\n if (!settings.options?.jsonSchema) return null;\n\n for (const filePath of resolvedPaths) {\n const schema = validateJsonSchema(settings.options, filePath);\n if (!schema) continue;\n\n const hasSplitEntries = schema.composite\n ? Object.entries(schema.composite).some(([, opts]) => opts.splitEntries)\n : false;\n\n const hasResolveRefs = schema.resolveRefs;\n\n if (!hasSplitEntries && !hasResolveRefs) continue;\n\n // Extract split config if available\n let splitConfig: SplitConfig | null = null;\n if (schema.composite) {\n for (const [compositePath, opts] of Object.entries(schema.composite)) {\n if (opts.splitEntries && opts.type === 'array' && opts.key) {\n splitConfig = {\n compositePath,\n jsonPointer: jsonPathToPointer(compositePath),\n keyField: opts.key,\n keyJsonPath: opts.key,\n sourceObjectOptions: opts,\n };\n break;\n }\n }\n }\n\n return { filePath, schema, splitConfig };\n }\n\n return null;\n}\n\n/**\n * Process splitEntries: extract non-default keyed entries into ref files.\n */\nfunction processSplitEntries(\n fileJson: unknown,\n compositeFilePath: string,\n docsDir: string,\n splitConfig: SplitConfig,\n settings: Settings,\n refMap: RefMap | null\n): void {\n const { jsonPointer, keyJsonPath } = splitConfig;\n\n // Find the composite array — may be behind a $ref\n const parentPointer = jsonPointer.split('/').slice(0, -1).join('/') || '';\n const arrayKey = jsonPointer.split('/').pop() || '';\n const navRefEntry = parentPointer ? refMap?.get(parentPointer) : undefined;\n\n // Get the array from the file\n const arrayContainer = parentPointer\n ? getAtPointer(fileJson, parentPointer)\n : fileJson;\n if (!isJsonContainer(arrayContainer)) return;\n\n const entries = Array.isArray(arrayContainer)\n ? arrayContainer[Number(arrayKey)]\n : arrayContainer[arrayKey];\n if (!Array.isArray(entries) || entries.length <= 1) return;\n\n // Determine the default key value (the source entry)\n const defaultKeyValue = getDefaultKeyValue(\n settings.defaultLocale,\n splitConfig.sourceObjectOptions\n );\n\n const defaultIndex = entries.findIndex((e: unknown) => {\n if (!e || typeof e !== 'object') return false;\n const values = JSONPath({\n json: e,\n path: keyJsonPath,\n resultType: 'value',\n flatten: true,\n wrap: true,\n }) as unknown[];\n return values?.[0] === defaultKeyValue;\n });\n if (defaultIndex < 0) return;\n\n // Detect whether each language entry is itself a $ref (per-entry refs), as\n // opposed to the case where the *container* of the languages array is a $ref\n // (navRefEntry). With per-entry refs, the languages array still lives in the\n // composite file, but each entry's content lives in a separate ref file.\n const defaultEntryPointer = `${jsonPointer}/${defaultIndex}`;\n const defaultEntryRef = refMap?.get(defaultEntryPointer);\n\n // arrayHostDir: directory of the file that physically holds the languages\n // array — entry $refs in the array are written relative to this.\n // entryBaseDir: directory under which per-entry ref files (and their nested\n // refs) are written — mirrors the source entry file's location.\n // These coincide for the container-ref and fully-inline cases; they differ\n // only for per-entry refs, where the array lives in the composite file but\n // the entry files live next to the (default) entry's source ref.\n const arrayHostDir = navRefEntry\n ? path.dirname(navRefEntry.sourceFile)\n : docsDir;\n const entryBaseDir = navRefEntry\n ? path.dirname(navRefEntry.sourceFile)\n : defaultEntryRef\n ? path.dirname(defaultEntryRef.sourceFile)\n : docsDir;\n const navFileName = navRefEntry\n ? path.basename(navRefEntry.sourceFile)\n : defaultEntryRef\n ? path.basename(defaultEntryRef.sourceFile)\n : path.basename(compositeFilePath);\n\n // Restore $ref structure if the source used $ref\n if (refMap && refMap.size > 0) {\n const internalRefs = collectInternalRefs(refMap, defaultEntryPointer);\n\n if (internalRefs.length > 0) {\n // When the default entry is itself a $ref, it is restored to that single\n // $ref below and its source file is left untouched, so we must not restore\n // its nested refs in place. Otherwise (inlined default entry) we do.\n if (!defaultEntryRef) {\n const defaultEntry = entries[defaultIndex];\n for (const ref of internalRefs) {\n setAtPointer(defaultEntry, ref.relativePointer, {\n ...ref.siblings,\n $ref: ref.refPath,\n });\n }\n }\n\n // For each non-default entry, write localized copies of the nested ref\n // files (mirroring the source topology under the locale dir) and replace\n // the inlined subtrees with their $refs.\n for (let i = 0; i < entries.length; i++) {\n if (i === defaultIndex) continue;\n const entry = entries[i];\n\n const entryKeyValues = JSONPath({\n json: entry,\n path: keyJsonPath,\n resultType: 'value',\n flatten: true,\n wrap: true,\n }) as unknown[];\n if (entryKeyValues?.[0] === defaultKeyValue) continue;\n const keyValue =\n typeof entryKeyValues?.[0] === 'string'\n ? entryKeyValues[0]\n : 'unknown';\n\n for (const ref of internalRefs) {\n const subtree = getAtPointer(entry, ref.relativePointer);\n if (subtree === undefined) continue;\n\n const originalAbsPath = path.resolve(ref.resolvedDir, ref.refPath);\n const relToBaseDir = path.relative(entryBaseDir, originalAbsPath);\n const localeRelPath = path.join(keyValue, relToBaseDir);\n const outputPath = path.resolve(entryBaseDir, localeRelPath);\n\n const { siblings, content } = extractRefSiblings(subtree, ref);\n writeJsonFile(outputPath, content);\n\n setAtPointer(entry, ref.relativePointer, {\n ...siblings,\n $ref: ref.refPath,\n });\n }\n }\n\n logger.info(`Restored $ref structure for default entry`);\n }\n }\n\n // Get the actual property name from the key JSONPath (e.g., \"$.language\" → \"language\")\n const keyPropertyName = keyJsonPath.replace(/^\\$\\.?/, '');\n\n // Extract each non-default entry into its own ref file\n for (let i = 0; i < entries.length; i++) {\n if (i === defaultIndex) continue;\n const entry = entries[i];\n if (!entry || typeof entry !== 'object') continue;\n\n const keyValues = JSONPath({\n json: entry,\n path: keyJsonPath,\n resultType: 'value',\n flatten: true,\n wrap: true,\n }) as unknown[];\n const keyValue = keyValues?.[0];\n if (typeof keyValue !== 'string' || keyValue === defaultKeyValue) continue;\n\n if (!isJsonContainer(entry) || Array.isArray(entry)) continue;\n const { [keyPropertyName]: _, ...contentWithoutKey } = entry;\n\n // If the entry still carries a top-level $ref, it was never inlined this\n // run (e.g. the merge step didn't process this file). There is no content\n // to extract — writing would produce a self-referential stub that\n // overwrites or shadows the real ref file. Leave the entry untouched.\n if (typeof contentWithoutKey.$ref === 'string') {\n continue;\n }\n\n const entryFilePath = path.resolve(\n entryBaseDir,\n path.join(keyValue, navFileName)\n );\n writeJsonFile(entryFilePath, contentWithoutKey);\n\n entries[i] = {\n [keyPropertyName]: keyValue,\n $ref: toRelativeRefPath(arrayHostDir, entryFilePath),\n };\n }\n\n // When the default entry was itself a $ref, restore it to that single $ref;\n // its source file is the untouched English source already on disk.\n if (defaultEntryRef) {\n entries[defaultIndex] = {\n ...defaultEntryRef.siblings,\n $ref: defaultEntryRef.refPath,\n };\n }\n\n logger.info(`Split keyed entries into ref files`);\n}\n\n/**\n * Get the identifying key value for the default locale.\n */\nfunction getDefaultKeyValue(\n defaultLocale: string,\n sourceObjectOptions: SourceObjectOptions\n): string {\n const localeProperty = sourceObjectOptions.localeProperty || 'code';\n const localeProperties = getLocaleProperties(defaultLocale);\n return (\n (localeProperties as Record<string, string | undefined>)[localeProperty] ||\n localeProperties.code ||\n defaultLocale\n );\n}\n\n/**\n * Convert a JSONPath like \"$.navigation.languages\" to a JSON pointer like \"/navigation/languages\".\n */\nfunction jsonPathToPointer(jsonPath: string): string {\n return jsonPath\n .replace(/^\\$\\.?/, '')\n .split('.')\n .filter(Boolean)\n .map((segment) => `/${segment}`)\n .join('');\n}\n\n/**\n * Restore top-level $ref pointers in the composite file.\n * Sorted deepest-first so nested refs are written before parents.\n */\nfunction restoreTopLevelRefs(\n fileJson: unknown,\n refMap: RefMap,\n splitConfig: SplitConfig | null\n): void {\n // Build a regex to exclude entries inside the composite array\n const arrayPointerPattern = splitConfig\n ? new RegExp(\n `^${splitConfig.jsonPointer.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')}\\\\/\\\\d+`\n )\n : null;\n\n const entries = [...refMap.entries()]\n .filter(\n ([pointer]) => !arrayPointerPattern || !arrayPointerPattern.test(pointer)\n )\n .sort(([a], [b]) => b.length - a.length);\n\n for (const [pointer, entry] of entries) {\n const subtree = getAtPointer(fileJson, pointer);\n if (subtree === undefined) continue;\n\n // If the value here is still an unresolved $ref placeholder, the referenced\n // file was never inlined at this pointer (e.g. mergeJson leaves non-composite\n // refs like `redirects` collapsed). Writing it back would overwrite the\n // source file with a self-referential stub and destroy its real contents —\n // the source already holds the correct data, so leave it untouched.\n if (\n isJsonContainer(subtree) &&\n !Array.isArray(subtree) &&\n typeof (subtree as Record<string, unknown>).$ref === 'string'\n ) {\n continue;\n }\n\n const { siblings, content } = extractRefSiblings(subtree, entry);\n writeJsonFile(entry.sourceFile, content);\n setAtPointer(fileJson, pointer, { ...siblings, $ref: entry.refPath });\n }\n}\n\n/**\n * Mintlify merges keys placed next to a `$ref` on top of the referenced file's\n * content, so ref resolution folds them into the inlined subtree. When\n * restoring the `$ref`, lift those keys back out: they stay next to the `$ref`\n * (with their possibly translated values) and are dropped from the content\n * written to the ref file — unless the referenced file also defined the key,\n * in which case it stays in both, preserving the source topology and\n * Mintlify's sibling-precedence semantics.\n */\nfunction extractRefSiblings(\n subtree: unknown,\n ref: {\n siblings?: Record<string, unknown>;\n originalContent?: unknown;\n refPath?: string;\n }\n): { siblings: Record<string, unknown>; content: unknown } {\n const originalSiblings = ref.siblings ?? {};\n const siblingKeys = Object.keys(originalSiblings);\n if (siblingKeys.length === 0) {\n return { siblings: {}, content: subtree };\n }\n if (!isJsonContainer(subtree) || Array.isArray(subtree)) {\n // Non-object content cannot carry merged siblings; restore the originals\n return { siblings: { ...originalSiblings }, content: subtree };\n }\n const content = { ...subtree };\n const siblings: Record<string, unknown> = {};\n const original = ref.originalContent;\n const originalContentHasKey = (key: string) =>\n isJsonContainer(original) && !Array.isArray(original) && key in original;\n for (const key of siblingKeys) {\n if (key in content) {\n siblings[key] = content[key];\n if (!originalContentHasKey(key)) {\n delete content[key];\n }\n } else {\n // Object resolutions always merge siblings into the subtree, so this\n // only fires if that invariant breaks upstream. Restoring the source\n // value keeps the output schema-valid, but it skips translation — warn\n // so the regression is visible.\n logger.warn(\n `Sibling key \"${key}\" missing from translated content for $ref ${ref.refPath ?? '(unknown)'}; restoring source value`\n );\n siblings[key] = originalSiblings[key];\n }\n }\n return { siblings, content };\n}\n\n/**\n * Collect refMap entries that describe an entry's internal $ref chain.\n * Sorted deepest-first so nested content is extracted before parents.\n */\nfunction collectInternalRefs(\n refMap: RefMap,\n entryPointerPrefix: string\n): {\n relativePointer: string;\n refPath: string;\n resolvedDir: string;\n siblings?: Record<string, unknown>;\n originalContent?: unknown;\n}[] {\n const refs: {\n relativePointer: string;\n refPath: string;\n resolvedDir: string;\n siblings?: Record<string, unknown>;\n originalContent?: unknown;\n }[] = [];\n\n for (const [pointer, entry] of refMap.entries()) {\n if (!pointer.startsWith(entryPointerPrefix + '/')) continue;\n refs.push({\n relativePointer: pointer.slice(entryPointerPrefix.length),\n refPath: entry.refPath,\n resolvedDir: entry.containingDir,\n siblings: entry.siblings,\n originalContent: entry.originalContent,\n });\n }\n\n refs.sort((a, b) => b.relativePointer.length - a.relativePointer.length);\n return refs;\n}\n\nfunction writeJsonFile(filePath: string, data: unknown): void {\n const dir = path.dirname(filePath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n let original: string | undefined;\n try {\n original = fs.readFileSync(filePath, 'utf-8');\n } catch {\n // New file\n }\n fs.writeFileSync(filePath, stringifyJson(data, original), 'utf-8');\n}\n\n/**\n * Build a relative $ref path (POSIX separators, \"./\"-prefixed when it isn't\n * already a relative or absolute path) from the directory that hosts the\n * languages array to a written entry file.\n */\nfunction toRelativeRefPath(fromDir: string, toPath: string): string {\n const rel = path.relative(fromDir, toPath).split(path.sep).join('/');\n return rel.startsWith('.') || rel.startsWith('/') ? rel : `./${rel}`;\n}\n\nfunction getAtPointer(obj: unknown, pointer: string): unknown {\n if (!pointer || pointer === '/') return obj;\n const parts = pointer.split('/').filter(Boolean);\n let current = obj;\n for (const part of parts) {\n if (!isJsonContainer(current)) return undefined;\n const index = /^\\d+$/.test(part) ? parseInt(part) : part;\n current = Array.isArray(current)\n ? current[index as number]\n : current[index];\n }\n return current;\n}\n\nfunction setAtPointer(obj: unknown, pointer: string, value: unknown): void {\n if (!pointer || pointer === '/') return;\n const parts = pointer.split('/').filter(Boolean);\n let current = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n if (!isJsonContainer(current)) return;\n const index = /^\\d+$/.test(parts[i]) ? parseInt(parts[i]) : parts[i];\n const next = Array.isArray(current)\n ? current[index as number]\n : current[index];\n if (next === undefined) return;\n current = next;\n }\n const lastPart = parts[parts.length - 1];\n const lastIndex = /^\\d+$/.test(lastPart) ? parseInt(lastPart) : lastPart;\n if (!isJsonContainer(current)) return;\n if (Array.isArray(current)) {\n current[lastIndex as number] = value;\n } else {\n current[lastIndex] = value;\n }\n}\n"],"mappings":";;;;;;;;;AAaA,SAAS,gBAAgB,OAAwC;AAC/D,QAAO,OAAO,UAAU,YAAY,UAAU;;;;;;;;;;;;;AAchD,eAAsB,0BACpB,UACe;CACf,MAAM,SAAS,iBAAi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B,MAAM,QAAQ,QAAQ,KAAK,MAAM,GAAG,GAAG,SAAS,MAAM,GAAG,GAAG,MAAM;EAClE,MAAM,OAAO,MAAM,QAAQ,QAAQ,GAC/B,QAAQ,SACR,QAAQ;AACZ,MAAI,SAAS,KAAA,EAAW;AACxB,YAAU;;CAEZ,MAAM,WAAW,MAAM,MAAM,SAAS;CACtC,MAAM,YAAY,QAAQ,KAAK,SAAS,GAAG,SAAS,SAAS,GAAG;AAChE,KAAI,CAAC,gBAAgB,QAAQ,CAAE;AAC/B,KAAI,MAAM,QAAQ,QAAQ,CACxB,SAAQ,aAAuB;KAE/B,SAAQ,aAAa"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gt",
3
- "version": "2.26.10",
3
+ "version": "2.26.11",
4
4
  "main": "dist/index.js",
5
5
  "bin": "bin/main.js",
6
6
  "files": [
@@ -117,12 +117,12 @@
117
117
  "unist-util-visit": "^5.0.0",
118
118
  "yaml": "^2.8.0",
119
119
  "@generaltranslation/icu": "0.1.2",
120
+ "@generaltranslation/format": "0.1.9",
120
121
  "@generaltranslation/python-extractor": "0.2.63",
121
- "@generaltranslation/supported-locales": "2.1.44",
122
122
  "@generaltranslation/vue-extractor": "0.1.22",
123
123
  "generaltranslation": "9.5.8",
124
- "gt-remark": "1.0.12",
125
- "@generaltranslation/format": "0.1.9"
124
+ "@generaltranslation/supported-locales": "2.1.44",
125
+ "gt-remark": "1.0.12"
126
126
  },
127
127
  "devDependencies": {
128
128
  "@types/babel__generator": "^7.27.0",