gt 2.26.9 → 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 +12 -0
- package/dist/console/logger.d.ts +6 -2
- package/dist/console/logger.js +25 -5
- package/dist/console/logger.js.map +1 -1
- package/dist/console/logging.js +1 -1
- package/dist/console/logging.js.map +1 -1
- package/dist/formats/files/postprocess/keepUntranslatedPagePaths.js +4 -2
- package/dist/formats/files/postprocess/keepUntranslatedPagePaths.js.map +1 -1
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.js +3 -2
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.js.map +1 -1
- package/dist/fs/config/downloadedVersions.js +3 -2
- package/dist/fs/config/downloadedVersions.js.map +1 -1
- package/dist/fs/config/setupConfig.js +1 -1
- package/dist/fs/config/updateConfig.js +6 -4
- package/dist/fs/config/updateConfig.js.map +1 -1
- package/dist/fs/config/updateVersions.js +2 -1
- package/dist/fs/config/updateVersions.js.map +1 -1
- package/dist/fs/saveJSON.js +2 -1
- package/dist/fs/saveJSON.js.map +1 -1
- package/dist/fs/stringifyJson.d.ts +7 -0
- package/dist/fs/stringifyJson.js +15 -0
- package/dist/fs/stringifyJson.js.map +1 -0
- package/dist/generated/version.d.ts +1 -1
- package/dist/generated/version.js +1 -1
- package/dist/generated/version.js.map +1 -1
- package/dist/git/setupMergeDrivers.js +1 -1
- package/dist/utils/credentials.js +1 -1
- package/dist/utils/flattenJsonFiles.js +4 -2
- package/dist/utils/flattenJsonFiles.js.map +1 -1
- package/dist/utils/gitDiff.js +1 -1
- package/dist/utils/packageJson.js +4 -1
- package/dist/utils/packageJson.js.map +1 -1
- package/dist/utils/processOpenApi.js +2 -1
- package/dist/utils/processOpenApi.js.map +1 -1
- package/dist/utils/splitMintlifyLanguageRefs.js +10 -3
- package/dist/utils/splitMintlifyLanguageRefs.js.map +1 -1
- package/package.json +4 -3
|
@@ -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
|
|
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,
|
|
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,
|
|
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"}
|
package/dist/fs/saveJSON.js
CHANGED
|
@@ -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,
|
|
7
|
+
await fs.promises.writeFile(filepath, stringifyJson(data));
|
|
7
8
|
}
|
|
8
9
|
//#endregion
|
|
9
10
|
export { saveJSON };
|
package/dist/fs/saveJSON.js.map
CHANGED
|
@@ -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,
|
|
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.
|
|
1
|
+
export declare const PACKAGE_VERSION = "2.26.11";
|
|
@@ -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.
|
|
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,9 +1,9 @@
|
|
|
1
1
|
import updateConfig from "../fs/config/updateConfig.js";
|
|
2
|
+
import { promisify } from "node:util";
|
|
2
3
|
import path from "node:path";
|
|
3
4
|
import fs from "node:fs";
|
|
4
5
|
import { createDiagnosticMessage } from "generaltranslation/diagnostics";
|
|
5
6
|
import { execFile } from "node:child_process";
|
|
6
|
-
import { promisify } from "node:util";
|
|
7
7
|
//#region src/git/setupMergeDrivers.ts
|
|
8
8
|
const execFileAsync = promisify(execFile);
|
|
9
9
|
const GT_LOCK_DRIVER = "merge=gt-lock";
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { createDiagnosticMessage, formatDiagnosticErrorDetails } from "generaltranslation/internal";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
+
import { promisify } from "node:util";
|
|
3
4
|
import path from "node:path";
|
|
4
5
|
import fs from "node:fs";
|
|
5
6
|
import { execFile } from "node:child_process";
|
|
6
|
-
import { promisify } from "node:util";
|
|
7
7
|
import dotenv from "dotenv";
|
|
8
8
|
//#region src/utils/credentials.ts
|
|
9
9
|
const execFileAsync = promisify(execFile);
|
|
@@ -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
|
|
11
|
-
|
|
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
|
|
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"}
|
package/dist/utils/gitDiff.js
CHANGED
|
@@ -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
|
-
|
|
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
|
|
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:
|
|
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,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s';\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;AAC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Json } 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
|
-
|
|
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,
|
|
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
|
-
|
|
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
|