gt 2.26.1 → 2.26.3
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/config/generateSettings.js +2 -1
- package/dist/config/generateSettings.js.map +1 -1
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.js +12 -4
- package/dist/formats/files/postprocess/localizeMintlifyRedirects.js.map +1 -1
- 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/types/index.d.ts +1 -1
- package/dist/types/index.js.map +1 -1
- package/dist/utils/localizeStaticUrls.d.ts +11 -0
- package/dist/utils/localizeStaticUrls.js +24 -11
- package/dist/utils/localizeStaticUrls.js.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,17 @@
|
|
|
1
1
|
# gtx-cli
|
|
2
2
|
|
|
3
|
+
## 2.26.3
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- [#2443](https://github.com/generaltranslation/gt/pull/2443) [`77d1437`](https://github.com/generaltranslation/gt/commit/77d14376ca70fd00c11806d6a721add6481b48cb) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Accept a list for `options.docsUrlPattern`, such as `["/docs/[locale]", "/ai/docs/[locale]"]`, so static URL and Mintlify redirect localization cover docs served from several URL prefixes. Each URL is localized with the longest pattern it matches.
|
|
8
|
+
|
|
9
|
+
## 2.26.2
|
|
10
|
+
|
|
11
|
+
### Patch Changes
|
|
12
|
+
|
|
13
|
+
- [#2437](https://github.com/generaltranslation/gt/pull/2437) [`d7943fe`](https://github.com/generaltranslation/gt/commit/d7943fee01740975387a6e1ff43a71c8ed78b886) Thanks [@fernando-aviles](https://github.com/fernando-aviles)! - Stop `options.mintlify.localizeRedirects` from adding nested-locale redirects (such as `/docs/ja-jp/fr-ca/...`) when translated pages are orphaned.
|
|
14
|
+
|
|
3
15
|
## 2.26.1
|
|
4
16
|
|
|
5
17
|
### Patch Changes
|
|
@@ -70,7 +70,8 @@ async function generateSettings(flags, cwd = process.cwd(), options) {
|
|
|
70
70
|
const projectIdEnv = resolveProjectId();
|
|
71
71
|
if (gtConfig.projectId && flags.projectId && gtConfig.projectId !== flags.projectId) logErrorAndExit(`Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but the CLI flag uses ${chalk.green(flags.projectId)}. Use the same projectId in all configs.`);
|
|
72
72
|
else if (gtConfig.projectId && projectIdEnv && gtConfig.projectId !== projectIdEnv) logErrorAndExit(`Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but GT_PROJECT_ID uses ${chalk.green(projectIdEnv)}. Use the same projectId in all configs.`);
|
|
73
|
-
|
|
73
|
+
const docsUrlPatterns = flags.options?.docsUrlPattern;
|
|
74
|
+
if (docsUrlPatterns && (Array.isArray(docsUrlPatterns) ? docsUrlPatterns : [docsUrlPatterns]).some((pattern) => !pattern.includes("[locale]"))) logErrorAndExit("Static URLs could not be localized because the URL pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated URL.");
|
|
74
75
|
if (flags.options?.docsImportPattern && !flags.options?.docsImportPattern.includes("[locale]")) logErrorAndExit("Static imports could not be localized because the import pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated import path.");
|
|
75
76
|
if (flags.options?.copyFiles) {
|
|
76
77
|
for (const file of flags.options.copyFiles) if (!file.includes("[locale]")) logErrorAndExit("Files could not be copied because the file path is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the copied path.");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"generateSettings.js","names":[],"sources":["../../src/config/generateSettings.ts"],"sourcesContent":["import {\n displayProjectId,\n exitSync,\n logErrorAndExit,\n warnApiKeyInConfig,\n warnDeprecatedField,\n} from '../console/logging.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport { FilesOptions, Settings } from '../types/index.js';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport { resolveFiles } from '../fs/config/parseFilesConfig.js';\nimport { validateSettings } from './validateSettings.js';\nimport {\n DEFAULT_GIT_REMOTE_NAME,\n GT_DASHBOARD_URL,\n} from '../utils/constants.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport { createUserTokenProvider } from '../auth/oauth.js';\nimport crypto from 'node:crypto';\nimport { execSync } from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport chalk from 'chalk';\nimport { resolveConfig } from './resolveConfig.js';\nimport { configureApiClient } from '../utils/api.js';\nimport { resolveApiBaseUrl } from '../utils/apiBaseUrl.js';\nimport { generatePreset } from './optionPresets.js';\nimport { GT_PARSING_FLAGS_DEFAULT } from './defaults.js';\nimport { normalizeFilesOptions } from '../formats/files/transformFormat.js';\nimport { logger } from '../console/logger.js';\n\nexport const DEFAULT_SRC_PATTERNS = [\n 'src/**/*.{js,jsx,ts,tsx}',\n 'app/**/*.{js,jsx,ts,tsx}',\n 'pages/**/*.{js,jsx,ts,tsx}',\n 'components/**/*.{js,jsx,ts,tsx}',\n];\n\nexport const DEFAULT_PYTHON_SRC_PATTERNS = ['**/*.py'];\nexport const DEFAULT_PYTHON_SRC_EXCLUDES = [\n 'venv/**',\n '.venv/**',\n '__pycache__/**',\n '**/migrations/**',\n '**/tests/**',\n '**/test_*.py',\n '**/*_test.py',\n];\n\ntype GenerateSettingsInput = Partial<Omit<Settings, 'tag'>> & {\n config?: string;\n projectId?: string;\n locales?: string[];\n options?: Settings['options'];\n files?: unknown;\n publish?: boolean;\n omitConfigIds?: boolean;\n saveLocal?: boolean;\n tag?: string | boolean;\n message?: string;\n branch?: string;\n enableBranching?: boolean;\n disableBranchDetection?: boolean;\n remoteName?: string;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalClearLocaleDirs?: boolean;\n clearLocaleDirsExclude?: string[];\n [key: string]: unknown;\n};\n\nfunction hasConfiguredTranslationFiles(files: unknown): boolean {\n if (!files || typeof files !== 'object' || Array.isArray(files)) {\n return false;\n }\n return Object.keys(files).some((key) => key !== 'gt');\n}\n\n/**\n * Generates settings from any\n * @param flags - The CLI flags to generate settings from\n * @param cwd - The current working directory\n * @param options - Additional options\n * @param options.requireConfig - If true, exit with an error when no config file is found\n * @param options.resolvedConfig - Config content to validate instead of the file, e.g. what setup is about to write\n * @returns The generated settings\n */\nexport async function generateSettings(\n flags: GenerateSettingsInput,\n cwd: string = process.cwd(),\n options?: {\n requireConfig?: boolean;\n resolvedConfig?: Record<string, unknown>;\n }\n): Promise<Settings> {\n // Load config file\n let gtConfig: GenerateSettingsInput = {};\n\n if (flags.config) {\n flags.config = withJsonExtension(flags.config);\n }\n if (options?.resolvedConfig) {\n gtConfig = options.resolvedConfig as GenerateSettingsInput;\n } else if (flags.config) {\n gtConfig = loadConfig(flags.config);\n } else {\n const config = resolveConfig(cwd);\n if (config) {\n gtConfig = config.config as GenerateSettingsInput;\n flags.config = config.path;\n } else {\n if (options?.requireConfig) {\n return logErrorAndExit(\n 'No gt.config.json file was found. Run `npx gt init` to create one, pass --config, or run this command from your project root.'\n );\n }\n gtConfig = {};\n }\n }\n\n // Warn if apiKey is present in gt.config.json\n if (gtConfig.apiKey) {\n warnApiKeyInConfig(flags.config ?? 'gt.config.json');\n exitSync(1);\n }\n const projectIdEnv = resolveProjectId();\n // Resolve mismatched projectIds\n if (\n gtConfig.projectId &&\n flags.projectId &&\n gtConfig.projectId !== flags.projectId\n ) {\n logErrorAndExit(\n `Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but the CLI flag uses ${chalk.green(flags.projectId)}. Use the same projectId in all configs.`\n );\n } else if (\n gtConfig.projectId &&\n projectIdEnv &&\n gtConfig.projectId !== projectIdEnv\n ) {\n logErrorAndExit(\n `Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but GT_PROJECT_ID uses ${chalk.green(projectIdEnv)}. Use the same projectId in all configs.`\n );\n }\n\n if (\n flags.options?.docsUrlPattern &&\n !flags.options?.docsUrlPattern.includes('[locale]')\n ) {\n logErrorAndExit(\n 'Static URLs could not be localized because the URL pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated URL.'\n );\n }\n\n if (\n flags.options?.docsImportPattern &&\n !flags.options?.docsImportPattern.includes('[locale]')\n ) {\n logErrorAndExit(\n 'Static imports could not be localized because the import pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated import path.'\n );\n }\n\n if (flags.options?.copyFiles) {\n for (const file of flags.options.copyFiles) {\n if (!file.includes('[locale]')) {\n logErrorAndExit(\n 'Files could not be copied because the file path is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the copied path.'\n );\n }\n }\n }\n\n // Warn on deprecated includeSourceCodeContext\n const configuredFiles = gtConfig.files as FilesOptions | undefined;\n if (configuredFiles?.gt?.includeSourceCodeContext != null) {\n warnDeprecatedField(\n 'files.gt.includeSourceCodeContext',\n 'files.gt.parsingFlags.includeSourceCodeContext'\n );\n }\n\n // merge options\n const mergedOptions: Settings = { ...gtConfig, ...flags } as Settings;\n\n if (\n !hasConfiguredTranslationFiles(mergedOptions.files) &&\n !['package.json', 'pyproject.toml', 'requirements.txt', 'setup.py'].some(\n (file) => fs.existsSync(path.join(cwd, file))\n )\n ) {\n logger.warn(\n chalk.yellow(\n 'No package.json or Python project file found in the current directory. Run this command from the root of your project.'\n )\n );\n }\n\n // Add defaultLocale if not provided\n mergedOptions.defaultLocale =\n mergedOptions.defaultLocale || libraryDefaultLocale;\n\n // merge locales\n mergedOptions.locales = Array.from(\n new Set([...(gtConfig.locales || []), ...(flags.locales || [])])\n );\n // Separate defaultLocale from locales\n mergedOptions.locales = mergedOptions.locales.filter(\n (locale) => locale !== mergedOptions.defaultLocale\n );\n\n // Add projectId if not provided\n mergedOptions.projectId = mergedOptions.projectId || resolveProjectId();\n\n mergedOptions.baseUrl = resolveApiBaseUrl(mergedOptions.baseUrl);\n\n // The API client prefers apiKey when both are set; the provider is lazy.\n mergedOptions.apiKey = mergedOptions.apiKey || process.env.GT_API_KEY;\n mergedOptions.userTokenProvider = createUserTokenProvider({\n baseUrl: mergedOptions.baseUrl,\n });\n\n // Add dashboardUrl if not provided\n mergedOptions.dashboardUrl = mergedOptions.dashboardUrl || GT_DASHBOARD_URL;\n\n // Add locales if not provided\n mergedOptions.locales = mergedOptions.locales || [];\n\n // Only set config path if one was actually found or explicitly provided.\n // Do not default to a phantom path — that would cause downstream writes\n // (e.g. updateConfig) to silently create a config file.\n if (!mergedOptions.config) {\n mergedOptions.config = '';\n }\n\n // Display projectId if present\n if (mergedOptions.projectId) {\n displayProjectId(mergedOptions.projectId);\n }\n\n // Add stageTranslations if not provided\n // For human review, always stage the project\n mergedOptions.stageTranslations = mergedOptions.stageTranslations ?? false;\n\n // Top-level default for whether translated files require approval before use.\n // Effective policy is hash-changing, so reject anything but a real boolean.\n if (\n mergedOptions.requiresReview !== undefined &&\n typeof mergedOptions.requiresReview !== 'boolean'\n ) {\n logErrorAndExit(\n 'requiresReview in gt.config.json must be a boolean. Use files.<type>.requiresReview for glob-scoped overrides.'\n );\n }\n mergedOptions.requiresReview = mergedOptions.requiresReview ?? false;\n\n // Add publish — only set if explicitly configured or passed via flag.\n // When neither is set, leave undefined so the publish step knows\n // there is no global publish intent.\n if (flags.publish) {\n mergedOptions.publish = true;\n } else if (gtConfig.publish !== undefined) {\n mergedOptions.publish = gtConfig.publish;\n } else {\n mergedOptions.publish = undefined;\n }\n\n mergedOptions.omitConfigIds =\n flags.omitConfigIds === true || gtConfig.omitConfigIds === true;\n\n // Don't default src here — each pipeline (JS/Python) has its own defaults.\n // Only set src if the user explicitly provided it via flags or config.\n\n // Resolve all glob patterns in the files object\n const compositePatterns = Object.entries(\n mergedOptions.options?.jsonSchema || {}\n )\n .filter(([, schema]) => schema.composite)\n .map(([key]) => key);\n mergedOptions.files = mergedOptions.files\n ? resolveFiles(\n normalizeFilesOptions(mergedOptions.files as FilesOptions),\n mergedOptions.defaultLocale,\n mergedOptions.locales,\n cwd,\n compositePatterns,\n mergedOptions.requiresReview\n )\n : {\n resolvedPaths: {},\n placeholderPaths: {},\n transformPaths: {},\n transformFormats: {},\n publishPaths: new Set<string>(),\n unpublishPaths: new Set<string>(),\n requiresReviewPaths: new Set<string>(),\n parsingFlags: {},\n gtJson: {\n parsingFlags: GT_PARSING_FLAGS_DEFAULT,\n },\n };\n\n mergedOptions.options = {\n ...mergedOptions.options,\n mintlify: {\n ...mergedOptions.options?.mintlify,\n inferTitleFromFilename:\n gtConfig.options?.mintlify?.inferTitleFromFilename ||\n mergedOptions.options?.mintlify?.inferTitleFromFilename,\n },\n experimentalLocalizeStaticImports:\n gtConfig.options?.experimentalLocalizeStaticImports ||\n flags.experimentalLocalizeStaticImports,\n experimentalLocalizeStaticUrls:\n gtConfig.options?.experimentalLocalizeStaticUrls ||\n flags.experimentalLocalizeStaticUrls,\n experimentalLocalizeRelativeAssets:\n gtConfig.options?.experimentalLocalizeRelativeAssets ||\n flags.experimentalLocalizeRelativeAssets,\n experimentalHideDefaultLocale:\n gtConfig.options?.experimentalHideDefaultLocale ||\n flags.experimentalHideDefaultLocale,\n experimentalFlattenJsonFiles:\n gtConfig.options?.experimentalFlattenJsonFiles ||\n flags.experimentalFlattenJsonFiles,\n experimentalClearLocaleDirs:\n gtConfig.options?.experimentalClearLocaleDirs ||\n flags.experimentalClearLocaleDirs,\n clearLocaleDirsExclude:\n gtConfig.options?.clearLocaleDirsExclude || flags.clearLocaleDirsExclude,\n saveLocal: flags.saveLocal ?? gtConfig.options?.saveLocal ?? false,\n };\n\n if (\n mergedOptions.omitConfigIds &&\n (mergedOptions.publish === true ||\n mergedOptions.files.gtJson.publish === true)\n ) {\n logger.warn(\n chalk.yellow(\n 'Config IDs will be omitted even though CDN publishing is enabled. Remote cache/CDN consumers may load the latest available translations instead of a pinned version.'\n )\n );\n }\n\n // Add additional options if provided\n if (mergedOptions.options) {\n if (mergedOptions.options.jsonSchema) {\n for (const fileGlob of Object.keys(mergedOptions.options.jsonSchema)) {\n const jsonSchema = mergedOptions.options.jsonSchema[fileGlob];\n if (jsonSchema.preset) {\n mergedOptions.options.jsonSchema[fileGlob] = {\n ...generatePreset(jsonSchema.preset, 'json'),\n ...jsonSchema,\n };\n }\n }\n }\n if (mergedOptions.options.yamlSchema) {\n for (const fileGlob of Object.keys(mergedOptions.options.yamlSchema)) {\n const yamlSchema = mergedOptions.options.yamlSchema[fileGlob];\n if (yamlSchema.preset) {\n mergedOptions.options.yamlSchema[fileGlob] = {\n ...generatePreset(yamlSchema.preset, 'yaml'),\n ...yamlSchema,\n };\n }\n }\n }\n }\n\n // Add parsing options if not provided\n mergedOptions.parsingOptions = mergedOptions.parsingOptions || {};\n mergedOptions.parsingOptions.conditionNames = mergedOptions.parsingOptions\n .conditionNames || [\n 'development',\n 'browser',\n 'module',\n 'import',\n 'require',\n 'default',\n ];\n\n // Add branch options if not provided\n const branchOptions = mergedOptions.branchOptions || {};\n // If --branch is set, enable branching\n branchOptions.enabled =\n flags.enableBranching ??\n gtConfig.branchOptions?.enabled ??\n (flags.branch ? true : false);\n branchOptions.currentBranch =\n flags.branch ?? gtConfig.branchOptions?.currentBranch ?? undefined;\n branchOptions.autoDetectBranches = flags.disableBranchDetection\n ? false\n : (gtConfig.branchOptions?.autoDetectBranches ?? true);\n branchOptions.remoteName =\n flags.remoteName ??\n gtConfig.branchOptions?.remoteName ??\n DEFAULT_GIT_REMOTE_NAME;\n mergedOptions.branchOptions = branchOptions;\n\n // Map -m/--message flag to tagMessage\n if (flags.message) {\n mergedOptions.tagMessage = flags.message;\n }\n\n // Resolve tag:\n // --tag (bare) or -m without --tag: try git SHA, fall back to random hex\n // --tag <value>: use as-is\n // No flags: no tag\n if (flags.tag === true || (!flags.tag && mergedOptions.tagMessage)) {\n try {\n mergedOptions.tag = execSync('git rev-parse --short HEAD', {\n encoding: 'utf-8',\n }).trim();\n // If no message provided, use git commit message\n if (!mergedOptions.tagMessage) {\n mergedOptions.tagMessage = execSync('git log -1 --format=%s', {\n encoding: 'utf-8',\n }).trim();\n }\n } catch {\n // Not in a git repo or git unavailable — fall back to random hex\n mergedOptions.tag = crypto.randomBytes(4).toString('hex');\n }\n }\n\n mergedOptions.configDirectory = path.join(cwd, '.gt');\n\n validateSettings(mergedOptions);\n\n configureApiClient({\n projectId: mergedOptions.projectId,\n apiKey: mergedOptions.apiKey,\n userTokenProvider: mergedOptions.userTokenProvider,\n baseUrl: mergedOptions.baseUrl,\n customMapping: mergedOptions.customMapping,\n });\n\n return mergedOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACD;AAED,MAAa,8BAA8B,CAAC,UAAU;AACtD,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AA2BD,SAAS,8BAA8B,OAAyB;AAC9D,KAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,CAC7D,QAAO;AAET,QAAO,OAAO,KAAK,MAAM,CAAC,MAAM,QAAQ,QAAQ,KAAK;;;;;;;;;;;AAYvD,eAAsB,iBACpB,OACA,MAAc,QAAQ,KAAK,EAC3B,SAImB;CAEnB,IAAI,WAAkC,EAAE;AAExC,KAAI,MAAM,OACR,OAAM,SAAS,kBAAkB,MAAM,OAAO;AAEhD,KAAI,SAAS,eACX,YAAW,QAAQ;UACV,MAAM,OACf,YAAW,WAAW,MAAM,OAAO;MAC9B;EACL,MAAM,SAAS,cAAc,IAAI;AACjC,MAAI,QAAQ;AACV,cAAW,OAAO;AAClB,SAAM,SAAS,OAAO;SACjB;AACL,OAAI,SAAS,cACX,QAAO,gBACL,gIACD;AAEH,cAAW,EAAE;;;AAKjB,KAAI,SAAS,QAAQ;AACnB,qBAAmB,M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BAAgB;AAG9B,KAAI,MAAM,QACR,eAAc,aAAa,MAAM;AAOnC,KAAI,MAAM,QAAQ,QAAS,CAAC,MAAM,OAAO,cAAc,WACrD,KAAI;AACF,gBAAc,MAAM,SAAS,8BAA8B,EACzD,UAAU,SACX,CAAC,CAAC,MAAM;AAET,MAAI,CAAC,cAAc,WACjB,eAAc,aAAa,SAAS,0BAA0B,EAC5D,UAAU,SACX,CAAC,CAAC,MAAM;SAEL;AAEN,gBAAc,MAAM,OAAO,YAAY,EAAE,CAAC,SAAS,MAAM;;AAI7D,eAAc,kBAAkB,KAAK,KAAK,KAAK,MAAM;AAErD,kBAAiB,cAAc;AAE/B,oBAAmB;EACjB,WAAW,cAAc;EACzB,QAAQ,cAAc;EACtB,mBAAmB,cAAc;EACjC,SAAS,cAAc;EACvB,eAAe,cAAc;EAC9B,CAAC;AAEF,QAAO"}
|
|
1
|
+
{"version":3,"file":"generateSettings.js","names":[],"sources":["../../src/config/generateSettings.ts"],"sourcesContent":["import {\n displayProjectId,\n exitSync,\n logErrorAndExit,\n warnApiKeyInConfig,\n warnDeprecatedField,\n} from '../console/logging.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport { FilesOptions, Settings } from '../types/index.js';\nimport { libraryDefaultLocale } from 'generaltranslation/internal';\nimport { resolveFiles } from '../fs/config/parseFilesConfig.js';\nimport { validateSettings } from './validateSettings.js';\nimport {\n DEFAULT_GIT_REMOTE_NAME,\n GT_DASHBOARD_URL,\n} from '../utils/constants.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport { createUserTokenProvider } from '../auth/oauth.js';\nimport crypto from 'node:crypto';\nimport { execSync } from 'node:child_process';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport chalk from 'chalk';\nimport { resolveConfig } from './resolveConfig.js';\nimport { configureApiClient } from '../utils/api.js';\nimport { resolveApiBaseUrl } from '../utils/apiBaseUrl.js';\nimport { generatePreset } from './optionPresets.js';\nimport { GT_PARSING_FLAGS_DEFAULT } from './defaults.js';\nimport { normalizeFilesOptions } from '../formats/files/transformFormat.js';\nimport { logger } from '../console/logger.js';\n\nexport const DEFAULT_SRC_PATTERNS = [\n 'src/**/*.{js,jsx,ts,tsx}',\n 'app/**/*.{js,jsx,ts,tsx}',\n 'pages/**/*.{js,jsx,ts,tsx}',\n 'components/**/*.{js,jsx,ts,tsx}',\n];\n\nexport const DEFAULT_PYTHON_SRC_PATTERNS = ['**/*.py'];\nexport const DEFAULT_PYTHON_SRC_EXCLUDES = [\n 'venv/**',\n '.venv/**',\n '__pycache__/**',\n '**/migrations/**',\n '**/tests/**',\n '**/test_*.py',\n '**/*_test.py',\n];\n\ntype GenerateSettingsInput = Partial<Omit<Settings, 'tag'>> & {\n config?: string;\n projectId?: string;\n locales?: string[];\n options?: Settings['options'];\n files?: unknown;\n publish?: boolean;\n omitConfigIds?: boolean;\n saveLocal?: boolean;\n tag?: string | boolean;\n message?: string;\n branch?: string;\n enableBranching?: boolean;\n disableBranchDetection?: boolean;\n remoteName?: string;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalClearLocaleDirs?: boolean;\n clearLocaleDirsExclude?: string[];\n [key: string]: unknown;\n};\n\nfunction hasConfiguredTranslationFiles(files: unknown): boolean {\n if (!files || typeof files !== 'object' || Array.isArray(files)) {\n return false;\n }\n return Object.keys(files).some((key) => key !== 'gt');\n}\n\n/**\n * Generates settings from any\n * @param flags - The CLI flags to generate settings from\n * @param cwd - The current working directory\n * @param options - Additional options\n * @param options.requireConfig - If true, exit with an error when no config file is found\n * @param options.resolvedConfig - Config content to validate instead of the file, e.g. what setup is about to write\n * @returns The generated settings\n */\nexport async function generateSettings(\n flags: GenerateSettingsInput,\n cwd: string = process.cwd(),\n options?: {\n requireConfig?: boolean;\n resolvedConfig?: Record<string, unknown>;\n }\n): Promise<Settings> {\n // Load config file\n let gtConfig: GenerateSettingsInput = {};\n\n if (flags.config) {\n flags.config = withJsonExtension(flags.config);\n }\n if (options?.resolvedConfig) {\n gtConfig = options.resolvedConfig as GenerateSettingsInput;\n } else if (flags.config) {\n gtConfig = loadConfig(flags.config);\n } else {\n const config = resolveConfig(cwd);\n if (config) {\n gtConfig = config.config as GenerateSettingsInput;\n flags.config = config.path;\n } else {\n if (options?.requireConfig) {\n return logErrorAndExit(\n 'No gt.config.json file was found. Run `npx gt init` to create one, pass --config, or run this command from your project root.'\n );\n }\n gtConfig = {};\n }\n }\n\n // Warn if apiKey is present in gt.config.json\n if (gtConfig.apiKey) {\n warnApiKeyInConfig(flags.config ?? 'gt.config.json');\n exitSync(1);\n }\n const projectIdEnv = resolveProjectId();\n // Resolve mismatched projectIds\n if (\n gtConfig.projectId &&\n flags.projectId &&\n gtConfig.projectId !== flags.projectId\n ) {\n logErrorAndExit(\n `Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but the CLI flag uses ${chalk.green(flags.projectId)}. Use the same projectId in all configs.`\n );\n } else if (\n gtConfig.projectId &&\n projectIdEnv &&\n gtConfig.projectId !== projectIdEnv\n ) {\n logErrorAndExit(\n `Project ID mismatch: gt.config.json uses ${chalk.green(gtConfig.projectId)}, but GT_PROJECT_ID uses ${chalk.green(projectIdEnv)}. Use the same projectId in all configs.`\n );\n }\n\n const docsUrlPatterns = flags.options?.docsUrlPattern;\n if (\n docsUrlPatterns &&\n (Array.isArray(docsUrlPatterns) ? docsUrlPatterns : [docsUrlPatterns]).some(\n (pattern) => !pattern.includes('[locale]')\n )\n ) {\n logErrorAndExit(\n 'Static URLs could not be localized because the URL pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated URL.'\n );\n }\n\n if (\n flags.options?.docsImportPattern &&\n !flags.options?.docsImportPattern.includes('[locale]')\n ) {\n logErrorAndExit(\n 'Static imports could not be localized because the import pattern is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the generated import path.'\n );\n }\n\n if (flags.options?.copyFiles) {\n for (const file of flags.options.copyFiles) {\n if (!file.includes('[locale]')) {\n logErrorAndExit(\n 'Files could not be copied because the file path is missing \"[locale]\". Add \"[locale]\" where the locale should appear in the copied path.'\n );\n }\n }\n }\n\n // Warn on deprecated includeSourceCodeContext\n const configuredFiles = gtConfig.files as FilesOptions | undefined;\n if (configuredFiles?.gt?.includeSourceCodeContext != null) {\n warnDeprecatedField(\n 'files.gt.includeSourceCodeContext',\n 'files.gt.parsingFlags.includeSourceCodeContext'\n );\n }\n\n // merge options\n const mergedOptions: Settings = { ...gtConfig, ...flags } as Settings;\n\n if (\n !hasConfiguredTranslationFiles(mergedOptions.files) &&\n !['package.json', 'pyproject.toml', 'requirements.txt', 'setup.py'].some(\n (file) => fs.existsSync(path.join(cwd, file))\n )\n ) {\n logger.warn(\n chalk.yellow(\n 'No package.json or Python project file found in the current directory. Run this command from the root of your project.'\n )\n );\n }\n\n // Add defaultLocale if not provided\n mergedOptions.defaultLocale =\n mergedOptions.defaultLocale || libraryDefaultLocale;\n\n // merge locales\n mergedOptions.locales = Array.from(\n new Set([...(gtConfig.locales || []), ...(flags.locales || [])])\n );\n // Separate defaultLocale from locales\n mergedOptions.locales = mergedOptions.locales.filter(\n (locale) => locale !== mergedOptions.defaultLocale\n );\n\n // Add projectId if not provided\n mergedOptions.projectId = mergedOptions.projectId || resolveProjectId();\n\n mergedOptions.baseUrl = resolveApiBaseUrl(mergedOptions.baseUrl);\n\n // The API client prefers apiKey when both are set; the provider is lazy.\n mergedOptions.apiKey = mergedOptions.apiKey || process.env.GT_API_KEY;\n mergedOptions.userTokenProvider = createUserTokenProvider({\n baseUrl: mergedOptions.baseUrl,\n });\n\n // Add dashboardUrl if not provided\n mergedOptions.dashboardUrl = mergedOptions.dashboardUrl || GT_DASHBOARD_URL;\n\n // Add locales if not provided\n mergedOptions.locales = mergedOptions.locales || [];\n\n // Only set config path if one was actually found or explicitly provided.\n // Do not default to a phantom path — that would cause downstream writes\n // (e.g. updateConfig) to silently create a config file.\n if (!mergedOptions.config) {\n mergedOptions.config = '';\n }\n\n // Display projectId if present\n if (mergedOptions.projectId) {\n displayProjectId(mergedOptions.projectId);\n }\n\n // Add stageTranslations if not provided\n // For human review, always stage the project\n mergedOptions.stageTranslations = mergedOptions.stageTranslations ?? false;\n\n // Top-level default for whether translated files require approval before use.\n // Effective policy is hash-changing, so reject anything but a real boolean.\n if (\n mergedOptions.requiresReview !== undefined &&\n typeof mergedOptions.requiresReview !== 'boolean'\n ) {\n logErrorAndExit(\n 'requiresReview in gt.config.json must be a boolean. Use files.<type>.requiresReview for glob-scoped overrides.'\n );\n }\n mergedOptions.requiresReview = mergedOptions.requiresReview ?? false;\n\n // Add publish — only set if explicitly configured or passed via flag.\n // When neither is set, leave undefined so the publish step knows\n // there is no global publish intent.\n if (flags.publish) {\n mergedOptions.publish = true;\n } else if (gtConfig.publish !== undefined) {\n mergedOptions.publish = gtConfig.publish;\n } else {\n mergedOptions.publish = undefined;\n }\n\n mergedOptions.omitConfigIds =\n flags.omitConfigIds === true || gtConfig.omitConfigIds === true;\n\n // Don't default src here — each pipeline (JS/Python) has its own defaults.\n // Only set src if the user explicitly provided it via flags or config.\n\n // Resolve all glob patterns in the files object\n const compositePatterns = Object.entries(\n mergedOptions.options?.jsonSchema || {}\n )\n .filter(([, schema]) => schema.composite)\n .map(([key]) => key);\n mergedOptions.files = mergedOptions.files\n ? resolveFiles(\n normalizeFilesOptions(mergedOptions.files as FilesOptions),\n mergedOptions.defaultLocale,\n mergedOptions.locales,\n cwd,\n compositePatterns,\n mergedOptions.requiresReview\n )\n : {\n resolvedPaths: {},\n placeholderPaths: {},\n transformPaths: {},\n transformFormats: {},\n publishPaths: new Set<string>(),\n unpublishPaths: new Set<string>(),\n requiresReviewPaths: new Set<string>(),\n parsingFlags: {},\n gtJson: {\n parsingFlags: GT_PARSING_FLAGS_DEFAULT,\n },\n };\n\n mergedOptions.options = {\n ...mergedOptions.options,\n mintlify: {\n ...mergedOptions.options?.mintlify,\n inferTitleFromFilename:\n gtConfig.options?.mintlify?.inferTitleFromFilename ||\n mergedOptions.options?.mintlify?.inferTitleFromFilename,\n },\n experimentalLocalizeStaticImports:\n gtConfig.options?.experimentalLocalizeStaticImports ||\n flags.experimentalLocalizeStaticImports,\n experimentalLocalizeStaticUrls:\n gtConfig.options?.experimentalLocalizeStaticUrls ||\n flags.experimentalLocalizeStaticUrls,\n experimentalLocalizeRelativeAssets:\n gtConfig.options?.experimentalLocalizeRelativeAssets ||\n flags.experimentalLocalizeRelativeAssets,\n experimentalHideDefaultLocale:\n gtConfig.options?.experimentalHideDefaultLocale ||\n flags.experimentalHideDefaultLocale,\n experimentalFlattenJsonFiles:\n gtConfig.options?.experimentalFlattenJsonFiles ||\n flags.experimentalFlattenJsonFiles,\n experimentalClearLocaleDirs:\n gtConfig.options?.experimentalClearLocaleDirs ||\n flags.experimentalClearLocaleDirs,\n clearLocaleDirsExclude:\n gtConfig.options?.clearLocaleDirsExclude || flags.clearLocaleDirsExclude,\n saveLocal: flags.saveLocal ?? gtConfig.options?.saveLocal ?? false,\n };\n\n if (\n mergedOptions.omitConfigIds &&\n (mergedOptions.publish === true ||\n mergedOptions.files.gtJson.publish === true)\n ) {\n logger.warn(\n chalk.yellow(\n 'Config IDs will be omitted even though CDN publishing is enabled. Remote cache/CDN consumers may load the latest available translations instead of a pinned version.'\n )\n );\n }\n\n // Add additional options if provided\n if (mergedOptions.options) {\n if (mergedOptions.options.jsonSchema) {\n for (const fileGlob of Object.keys(mergedOptions.options.jsonSchema)) {\n const jsonSchema = mergedOptions.options.jsonSchema[fileGlob];\n if (jsonSchema.preset) {\n mergedOptions.options.jsonSchema[fileGlob] = {\n ...generatePreset(jsonSchema.preset, 'json'),\n ...jsonSchema,\n };\n }\n }\n }\n if (mergedOptions.options.yamlSchema) {\n for (const fileGlob of Object.keys(mergedOptions.options.yamlSchema)) {\n const yamlSchema = mergedOptions.options.yamlSchema[fileGlob];\n if (yamlSchema.preset) {\n mergedOptions.options.yamlSchema[fileGlob] = {\n ...generatePreset(yamlSchema.preset, 'yaml'),\n ...yamlSchema,\n };\n }\n }\n }\n }\n\n // Add parsing options if not provided\n mergedOptions.parsingOptions = mergedOptions.parsingOptions || {};\n mergedOptions.parsingOptions.conditionNames = mergedOptions.parsingOptions\n .conditionNames || [\n 'development',\n 'browser',\n 'module',\n 'import',\n 'require',\n 'default',\n ];\n\n // Add branch options if not provided\n const branchOptions = mergedOptions.branchOptions || {};\n // If --branch is set, enable branching\n branchOptions.enabled =\n flags.enableBranching ??\n gtConfig.branchOptions?.enabled ??\n (flags.branch ? true : false);\n branchOptions.currentBranch =\n flags.branch ?? gtConfig.branchOptions?.currentBranch ?? undefined;\n branchOptions.autoDetectBranches = flags.disableBranchDetection\n ? false\n : (gtConfig.branchOptions?.autoDetectBranches ?? true);\n branchOptions.remoteName =\n flags.remoteName ??\n gtConfig.branchOptions?.remoteName ??\n DEFAULT_GIT_REMOTE_NAME;\n mergedOptions.branchOptions = branchOptions;\n\n // Map -m/--message flag to tagMessage\n if (flags.message) {\n mergedOptions.tagMessage = flags.message;\n }\n\n // Resolve tag:\n // --tag (bare) or -m without --tag: try git SHA, fall back to random hex\n // --tag <value>: use as-is\n // No flags: no tag\n if (flags.tag === true || (!flags.tag && mergedOptions.tagMessage)) {\n try {\n mergedOptions.tag = execSync('git rev-parse --short HEAD', {\n encoding: 'utf-8',\n }).trim();\n // If no message provided, use git commit message\n if (!mergedOptions.tagMessage) {\n mergedOptions.tagMessage = execSync('git log -1 --format=%s', {\n encoding: 'utf-8',\n }).trim();\n }\n } catch {\n // Not in a git repo or git unavailable — fall back to random hex\n mergedOptions.tag = crypto.randomBytes(4).toString('hex');\n }\n }\n\n mergedOptions.configDirectory = path.join(cwd, '.gt');\n\n validateSettings(mergedOptions);\n\n configureApiClient({\n projectId: mergedOptions.projectId,\n apiKey: mergedOptions.apiKey,\n userTokenProvider: mergedOptions.userTokenProvider,\n baseUrl: mergedOptions.baseUrl,\n customMapping: mergedOptions.customMapping,\n });\n\n return mergedOptions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA+BA,MAAa,uBAAuB;CAClC;CACA;CACA;CACA;CACD;AAED,MAAa,8BAA8B,CAAC,UAAU;AACtD,MAAa,8BAA8B;CACzC;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AA2BD,SAAS,8BAA8B,OAAyB;AAC9D,KAAI,CAAC,SAAS,OAAO,UAAU,YAAY,MAAM,QAAQ,MAAM,CAC7D,QAAO;AAET,QAAO,OAAO,KAAK,MAAM,CAAC,MAAM,QAAQ,QAAQ,KAAK;;;;;;;;;;;AAYvD,eAAsB,iBACpB,OACA,MAAc,QAAQ,KAAK,EAC3B,SAImB;CAEnB,IAAI,WAAkC,EAAE;AAExC,KAAI,MAAM,OACR,OAAM,SAAS,kBAAkB,MAAM,OAAO;AAEhD,KAAI,SAAS,eACX,YAAW,QAAQ;UACV,MAAM,OACf,YAAW,WAAW,MAAM,OAAO;MAC9B;EACL,MAAM,SAAS,cAAc,IAAI;AACjC,MAAI,QAAQ;AACV,cAAW,OAAO;AAClB,SAAM,SAAS,OAAO;SACjB;AACL,OAAI,SAAS,cACX,QAAO,gBACL,gIACD;AAEH,cAAW,EAAE;;;AAKjB,KAAI,SAAS,QAAQ;AACnB,qBAAmB,MAAM,UAAU,iBAAiB;AACpD,WAAS,EAAE;;CAEb,MAAM,eAAe,kBAAkB;AAEvC,KACE,SAAS,aACT,MAAM,aACN,SAAS,cAAc,MAAM,UAE7B,iBACE,4CAA4C,MAAM,MAAM,SAAS,UAAU,CAAC,0BAA0B,MAAM,MAAM,MAAM,UAAU,CAAC,0CACpI;UAED,SAAS,aACT,gBACA,SAAS,cAAc,aAEvB,iBACE,4CAA4C,MAAM,MAAM,SAAS,UAAU,CAAC,2BAA2B,MAAM,MAAM,aAAa,CAAC,0CAClI;CAGH,MAAM,kBAAkB,MAAM,SAAS;AACvC,KACE,oBACC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AO,YAAY,EAAE,CAAC,SAAS,MAAM;;AAI7D,eAAc,kBAAkB,KAAK,KAAK,KAAK,MAAM;AAErD,kBAAiB,cAAc;AAE/B,oBAAmB;EACjB,WAAW,cAAc;EACzB,QAAQ,cAAc;EACtB,mBAAmB,cAAc;EACjC,SAAS,cAAc;EACvB,eAAe,cAAc;EAC9B,CAAC;AAEF,QAAO"}
|
|
@@ -2,7 +2,7 @@ import { logger } from "../../../console/logger.js";
|
|
|
2
2
|
import { getRelative } from "../../../fs/findFilepath.js";
|
|
3
3
|
import loadJSON from "../../../fs/loadJSON.js";
|
|
4
4
|
import { createFileMapping } from "../fileMapping.js";
|
|
5
|
-
import { PAGE_EXTENSIONS, transformUrlPath, translationMissing } from "../../../utils/localizeStaticUrls.js";
|
|
5
|
+
import { PAGE_EXTENSIONS, findPatternHead, getPatternHeads, transformUrlPath, translationMissing } from "../../../utils/localizeStaticUrls.js";
|
|
6
6
|
import path from "node:path";
|
|
7
7
|
import fs from "node:fs";
|
|
8
8
|
import { createDiagnosticMessage } from "generaltranslation/diagnostics";
|
|
@@ -25,7 +25,7 @@ const missingDocsUrlPatternWarning = createDiagnosticMessage({
|
|
|
25
25
|
function localizeMintlifyRedirects(settings, orphanedFileNames) {
|
|
26
26
|
if (settings.options?.mintlify?.localizeRedirects !== true || !settings.files) return [];
|
|
27
27
|
const urlPattern = settings.options.docsUrlPattern;
|
|
28
|
-
if (!urlPattern) {
|
|
28
|
+
if (!urlPattern || urlPattern.length === 0) {
|
|
29
29
|
logger.warn(missingDocsUrlPatternWarning);
|
|
30
30
|
return [];
|
|
31
31
|
}
|
|
@@ -35,11 +35,19 @@ function localizeMintlifyRedirects(settings, orphanedFileNames) {
|
|
|
35
35
|
const targetLocales = settings.locales.filter((locale) => locale !== settings.defaultLocale);
|
|
36
36
|
const { files } = settings;
|
|
37
37
|
const fileMapping = createFileMapping(files.resolvedPaths, files.placeholderPaths, files.transformPaths, files.transformFormats, targetLocales, settings.defaultLocale);
|
|
38
|
-
const
|
|
38
|
+
const urlPatternHeads = getPatternHeads(urlPattern);
|
|
39
39
|
const localizeUrl = (url, locale) => {
|
|
40
|
+
const urlPatternHead = findPatternHead(url, urlPatternHeads);
|
|
41
|
+
if (urlPatternHead === void 0) return null;
|
|
40
42
|
const localized = transformUrlPath(url, urlPatternHead, locale, settings.defaultLocale, settings.options?.experimentalHideDefaultLocale ?? false);
|
|
41
43
|
return localized === null ? null : normalizeUrl(localized);
|
|
42
44
|
};
|
|
45
|
+
const isLocalized = (url) => {
|
|
46
|
+
const urlPatternHead = findPatternHead(url, urlPatternHeads);
|
|
47
|
+
if (urlPatternHead === void 0) return false;
|
|
48
|
+
const localeSegmentIndex = urlPatternHead.split("/").filter(Boolean).length;
|
|
49
|
+
return targetLocales.includes(url.split("/").filter(Boolean)[localeSegmentIndex]);
|
|
50
|
+
};
|
|
43
51
|
const takenSources = new Set(location.redirects.filter(isRedirect).map((r) => normalizeUrl(r.source)));
|
|
44
52
|
const added = [];
|
|
45
53
|
const updated = location.redirects.flatMap((entry) => {
|
|
@@ -47,7 +55,7 @@ function localizeMintlifyRedirects(settings, orphanedFileNames) {
|
|
|
47
55
|
const [destinationPath, anchor] = splitAnchor(entry.destination);
|
|
48
56
|
const sourceUrl = normalizeUrl(entry.source);
|
|
49
57
|
const destinationUrl = normalizeUrl(destinationPath);
|
|
50
|
-
if (!oldPageUrls.has(sourceUrl)) return [entry];
|
|
58
|
+
if (!oldPageUrls.has(sourceUrl) || isLocalized(sourceUrl) || isLocalized(destinationUrl)) return [entry];
|
|
51
59
|
const localized = [];
|
|
52
60
|
for (const locale of targetLocales) {
|
|
53
61
|
const localizedSource = localizeUrl(sourceUrl, locale);
|
|
@@ -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 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) {\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 urlPatternHead = urlPattern.split('[locale]')[0];\n const localizeUrl = (url: string, locale: string) => {\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 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 (!oldPageUrls.has(sourceUrl)) return [entry];\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":";;;;;;;;;AAiBA,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,YAAY;AACf,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,W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}
|
|
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,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,CAAC;;;;;;AAOzD,SAAS,QAAQ,UAA0B;CACzC,MAAM,WAAW,YAAY,SAAS;AACtC,QAAO,aACL,SACG,MAAM,GAAG,SAAS,SAAS,KAAK,QAAQ,SAAS,CAAC,OAAO,CACzD,MAAM,KAAK,IAAI,CACf,KAAK,IAAI,CACb;;;;;;AAOH,SAAS,aAAa,KAAqB;CACzC,MAAM,WAAW,IAAI,MAAM,IAAI,CAAC,OAAO,QAAQ;AAC/C,KAAI,SAAS,GAAG,GAAG,KAAA,QAAiB,UAAS,KAAK;AAClD,QAAO,IAAI,SAAS,KAAK,IAAI;;;;;;AAO/B,SAAS,cACP,cACwE;CACxE,MAAM,WAAW,SAAS,aAAa;CACvC,IAAI,SAAS;CACb,IAAI,QAAiB,UAAU;CAC/B,MAAM,UAAU,IAAI,IAAI,CAAC,OAAO,CAAC;AACjC,QAAO,OAAQ,OAA8B,SAAS,UAAU;AAC9D,WAAS,KAAK,QACZ,KAAK,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 +1 @@
|
|
|
1
|
-
export declare const PACKAGE_VERSION = "2.26.
|
|
1
|
+
export declare const PACKAGE_VERSION = "2.26.3";
|
|
@@ -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.3';\n"],"mappings":";AACA,MAAa,kBAAkB"}
|
package/dist/types/index.d.ts
CHANGED
|
@@ -249,7 +249,7 @@ export type AdditionalOptions = {
|
|
|
249
249
|
mdx?: boolean;
|
|
250
250
|
};
|
|
251
251
|
mintlify?: MintlifyOptions;
|
|
252
|
-
docsUrlPattern?: string;
|
|
252
|
+
docsUrlPattern?: string | string[];
|
|
253
253
|
docsImportPattern?: string;
|
|
254
254
|
excludeStaticUrls?: string[];
|
|
255
255
|
excludeStaticImports?: string[];
|
package/dist/types/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["import type { CustomMapping } from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport type { ModelProvider } from 'generaltranslation/internal';\nimport type { FileFormat } from 'generaltranslation/types';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport {\n ParsingConfigOptions,\n GTParsingFlags,\n BaseParsingFlags,\n ParseFlagsByFileType,\n} from './parsing.js';\nimport { Libraries, InlineLibrary } from './libraries.js';\n\nexport type { Updates } from 'generaltranslation/types';\n\nexport type Options = {\n config: string;\n apiKey?: string;\n projectId?: string;\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n src?: string[];\n defaultLocale?: string;\n locales?: string[];\n baseUrl: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n dryRun: boolean;\n timeout: number;\n force?: boolean;\n stageTranslations?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type OpenApiConfig = {\n files: string[];\n translateFields?: string[];\n};\n\nexport type MintlifyOptions = {\n openapi?: OpenApiConfig;\n inferTitleFromFilename?: boolean;\n localizeRedirects?: boolean; // add localized redirects for pages renamed or removed in a translate run\n};\n\nexport type SharedFlags = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n};\n\nexport type TranslateFlags = SharedFlags & {\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n defaultLocale?: string;\n locales?: string[];\n ignoreErrors?: boolean;\n src?: string[];\n timeout: number;\n dryRun: boolean;\n saveLocal?: boolean;\n stageTranslations?: boolean;\n setupProject?: boolean; // if true, skip enqueue step\n publish?: boolean;\n force?: boolean;\n forceDownload?: boolean;\n tag?: string;\n message?: string;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n omitConfigIds?: boolean;\n excludeStaticUrls?: string[];\n excludeStaticImports?: string[];\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type WrapOptions = {\n src?: string[];\n config: string;\n skipTs: boolean;\n disableIds: boolean;\n disableFormatting: boolean;\n addGTProvider: boolean;\n};\n\nexport type SetupOptions = {\n src?: string[];\n config: string;\n};\n\nexport type GenerateSourceOptions = {\n src?: string[];\n config: string;\n defaultLocale: string;\n dictionary?: string;\n jsconfig?: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n};\n\nexport type Framework =\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_REACT\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START;\n\nexport const SUPPORTED_REACT_FRAMEWORKS = [\n 'next-app',\n 'next-pages',\n 'vite',\n 'gatsby',\n 'react',\n 'redwood',\n 'tanstack-start',\n 'react-router',\n] as const;\n\nexport type FrameworkObject =\n | {\n name: 'mintlify';\n type?: undefined;\n }\n | {\n name: (typeof SUPPORTED_REACT_FRAMEWORKS)[number];\n type: 'react';\n };\nexport type ReactFrameworkObject = Extract<FrameworkObject, { type: 'react' }>;\n\nexport type FrameworkType = FrameworkObject['type'];\n\nexport type SupportedFrameworks = FrameworkObject['name'];\nexport type SupportedReactFrameworks = Extract<\n FrameworkObject,\n { type: 'react' }\n>['name'];\n\nexport type SupportedLibraries =\n | InlineLibrary\n | 'next-intl'\n | 'react-i18next'\n | 'next-i18next'\n | 'i18next'\n | 'i18next-icu'\n | 'base';\n\nexport interface ContentScanner {\n scanForContent(\n options: WrapOptions,\n framework: Framework\n ): Promise<{\n errors: string[];\n filesUpdated: string[];\n warnings: string[];\n }>;\n}\n\n// Create a type based on the supported file extensions\nexport type SupportedFileExtension = (typeof SUPPORTED_FILE_EXTENSIONS)[number];\n\n// Update ResolvedFiles to use the dynamic keys\nexport type ResolvedFiles = {\n [K in SupportedFileExtension]?: string[];\n} & {\n gt?: string; // Output glob: /path/[locale].json\n};\n\nexport type TransformOption = {\n match?: string; // regex to match strings, supports capture groups\n replace: string; // string or regex pattern to replace the match with\n // Special placeholders:\n // -> if used in the match string, they will be replaced with the corresponding default locale property value\n // -> if used in the replace string, they will be replaced with the corresponding target locale property value\n // {locale} -> will be replaced with the locale code\n // And any other property from getLocaleProperties()\n};\n\nexport type TransformFiles = {\n [K in SupportedFileExtension]?: TransformOption | string | TransformOption[]; // if a string, only transform the file name\n};\n\nexport type TransformFormats = {\n [K in SupportedFileExtension]?: FileFormat;\n};\n\n// Include patterns can be plain strings or objects with a publish flag\nexport type IncludePattern = string | { pattern: string; publish?: boolean };\n\n// Review requirement for matched files: a boolean applies to all files of the\n// type; the object form opts path groups in/out with globs. exclude wins over\n// include; files matching neither inherit the top-level requiresReview default.\nexport type RequiresReviewConfig =\n | boolean\n | {\n include?: string[];\n exclude?: string[];\n };\n\n// Update FilesOptions to fix the error\nexport type FilesOptions = {\n [K in SupportedFileExtension]?: {\n include: IncludePattern[];\n exclude?: string[];\n transform?: string | TransformOption | TransformOption[];\n transformationFormat?: FileFormat;\n parsingFlags?: BaseParsingFlags; // Flags for parsing inline content\n requiresReview?: RequiresReviewConfig; // Whether translated versions of matched files require approval before use\n };\n} & {\n gt?: {\n output: string; // Output glob: /path/[locale].json\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags?: Partial<GTParsingFlags>; // Flags for parsing inline content\n /**\n * @deprecated\n * use `files.gt.parsingFlags.includeSourceCodeContext` instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n};\n\n// Shared settings between all API-related commands\nexport type FontsConfig = {\n include: string[]; // globs of .ttf/.otf files\n exclude?: string[];\n};\n\nexport type Settings = {\n config: string;\n configDirectory: string;\n baseUrl: string;\n dashboardUrl: string;\n apiKey?: string;\n userTokenProvider?: UserTokenProvider;\n projectId?: string;\n defaultLocale: string;\n locales: string[];\n customMapping?: CustomMapping;\n files: {\n resolvedPaths: ResolvedFiles; // Absolute resolved paths for the default locale\n placeholderPaths: ResolvedFiles; // Absolute placeholder paths for all locales containing [locale]\n transformPaths: TransformFiles; // Absolute transform paths for all locales containing [locale]\n transformFormats: TransformFormats; // Output file format transforms keyed by config file type\n publishPaths: Set<string>; // Absolute paths explicitly opted IN to publishing\n unpublishPaths: Set<string>; // Absolute paths explicitly opted OUT of publishing\n requiresReviewPaths: Set<string>; // Absolute paths whose effective requiresReview policy is true\n parsingFlags: ParseFlagsByFileType;\n gtJson: {\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags: GTParsingFlags; // Flags for parsing inline content\n /**\n * @deprecated\n * use {@link files.gt.GTParsingFlags.parsingFlags.includeSourceCodeContext} instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n };\n stageTranslations: boolean; // if true, always stage the project during translate command\n requiresReview?: boolean; // top-level default: translated artifacts require approval before the client uses them\n publish?: boolean; // if true, publish the translations to the CDN; undefined means no global publish intent\n omitConfigIds?: boolean; // if true, do not write _versionId or _branchId to gt.config.json\n _versionId?: string; // internal use only\n _branchId?: string; // internal use only\n version?: string; // for specifying a custom version id to use. Should be unique\n description?: string;\n src?: string[]; // list of glob patterns for source file scanning\n fonts?: FontsConfig; // fonts to sync to the API before translating\n framework?: SupportedFrameworks;\n options?: AdditionalOptions;\n modelProvider?: ModelProvider;\n tag?: string;\n tagMessage?: string;\n parsingOptions: ParsingConfigOptions;\n branchOptions: BranchOptions;\n // Optional shared static assets config\n sharedStaticAssets?: SharedStaticAssetsConfig;\n};\n\nexport type StaticLocalizationFiles = Pick<\n Settings['files'],\n 'placeholderPaths' | 'resolvedPaths'\n> &\n Partial<Pick<Settings['files'], 'transformPaths' | 'transformFormats'>>;\n\nexport type StaticLocalizationSettings = Pick<\n Settings,\n 'defaultLocale' | 'locales' | 'options'\n> & {\n files?: StaticLocalizationFiles | null;\n};\n\nexport type BranchOptions = {\n currentBranch?: string;\n autoDetectBranches?: boolean;\n remoteName: string; // default 'origin'. The name of the remote to use for auto-detection.\n enabled: boolean; // if true, branching is enabled for the project\n};\n\nexport type AdditionalOptions = {\n // Optional schema to follow while translating JSON files\n jsonSchema?: {\n [fileGlob: string]: JsonSchema;\n };\n // Optional schema to follow while translating YAML files\n yamlSchema?: {\n [fileGlob: string]: YamlSchema;\n };\n // Skip pre-parse validation checks for specific file types\n skipFileValidation?: {\n json?: boolean;\n yaml?: boolean;\n mdx?: boolean;\n };\n // Optional Mintlify-specific options container\n mintlify?: MintlifyOptions;\n docsUrlPattern?: string; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files\n docsImportPattern?: string; // eg /docs/[locale]/foo.md or /[locale]/foo.md for localizing static imports in markdown files\n excludeStaticUrls?: string[]; // A list of file globs to include for static url localization\n excludeStaticImports?: string[]; // A list of file globs to include for static import localization\n docsHideDefaultLocaleImport?: boolean; // if true, hide the default locale in the import path\n copyFiles?: string[]; // array of files to copy to the target locale\n experimentalClearLocaleDirs?: boolean; // if true, clear locale directories before writing translations (default: false)\n clearLocaleDirsExclude?: string[]; // array of glob patterns with [locale] or [locales] placeholder to exclude from clearing (e.g., \"./snippets/[locale]/preserved/**\" or \"./[locales]/static/**\")\n experimentalLocalizeStaticImports?: boolean; // Inserts locale in static import paths in md/mdx files\n // Inserts locale in static url paths in md/mdx files and adds anchor IDs to\n // preserve navigation. The object form enables it with extra behavior.\n experimentalLocalizeStaticUrls?:\n | boolean\n | {\n // Keep links to source pages that have no translation\n skipUntranslatedPages?: boolean;\n // Extra JSX attribute names or globs to localize\n attributes?: string[];\n };\n experimentalLocalizeRelativeAssets?: boolean; // Rewrites relative asset URLs in translated md/mdx files to valid paths\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default'; // Format for anchor IDs: 'mintlify' for Mintlify's native {#id} on every heading, 'default' or undefined for escaped inline \\{#id\\}. Can run independently of static url localization\n experimentalHideDefaultLocale?: boolean; // Hides the default locale in the import path\n experimentalFlattenJsonFiles?: boolean; // Flattens JSON files into a single file\n baseDomain?: string; // The base http:// url where the project is hosted\n docsImportRewrites?: Array<{\n match: string; // prefix to match, e.g. '@site/docs'\n replace: string; // replacement prefix, can include [locale] or [defaultLocale]\n }>;\n experimentalCanonicalLocaleKeys?: boolean; // For composite JSON schemas with locale keys, force canonical locale even when alias provided\n saveLocal?: boolean; // if true, detect and save local edits to translated output before enqueuing translations (default: false)\n};\n\nexport type SharedStaticAssetsConfig = {\n include: string | string[];\n outDir?: string;\n publicPath?: string;\n mirrorToLocales?: boolean;\n};\n\nexport type StructuralTransform = {\n sourcePointer: string; // e.g., \"/msg\"\n destinationPointer: string; // e.g., \"/translations/en\"\n};\n\nexport type JsonSchema = {\n preset?: 'mintlify' | 'mintlify-hide-default' | 'openapi';\n structuralTransform?: StructuralTransform[];\n\n // when true, resolve $ref entries in this file before processing\n resolveRefs?: boolean;\n\n // exactly 1 of include or composite must be provided; not both\n\n // specify include if file is not composite\n // multiple target JSONs will be created for each locale,\n // with the only differing content being the specified JSONPath values\n include?: string[]; // array of JSONPaths to include\n\n // specify composite if no new JSONs should be created\n composite?: {\n // The sourceObjectPath is a JSONPath to the array or object containing\n // content in the source and target locales\n // This value is denoted as the \"sourceObject\"\n // Array elements or object sub-elements are denoted as \"sourceItem\"\n [sourceObjectPath: string]: SourceObjectOptions;\n };\n};\n\nexport type YamlSchema = {\n preset?: 'mintlify' | 'openapi';\n include?: string[];\n transform?: TransformOptions;\n};\n\nexport type SourceObjectOptions = {\n type: 'array' | 'object'; // type of the sourceObject;\n // array if the sourceObject is an array\n // -> We will simply add duplicated sourceItems for each locale\n // object if the sourceObject is an object\n // -> We will duplicate the sourceItem for each locale and set the corresponding\n // key with the locale property\n // In both cases, we search the sourceObject for the key that matches the source locale\n\n // Below, relative JSONPaths are relative to the sourceItem root, NOT the sourceObject\n\n include: string[]; // array of relative JSONPaths to include in the translated JSON\n\n // if type is array, there must be a key property in the array element\n // corresponding value should be a locale code\n key?: string; // relative jsonPath to the key to use to distinguish between source and target locales\n // if type is object, the key is simply the JSON key for the sourceItem - this is unnecessary in this case\n\n localeProperty?: string; // specific locale property to use for the key for target locales, default 'code'\n // ex: code, name, nativeName, languageCode, languageName, etc. (values returned by getLocaleProperties)\n\n // optional config for transforming specific fields in the sourceItem\n // for example, helpful for handling urls with locale-specific paths\n transform?: TransformOptions;\n\n // optional list of top-level properties to remove from generated\n // non-default-locale entries (e.g. Mintlify's `default: true` flag on the\n // default language entry, which must not be cloned into other locales)\n omitProperties?: string[];\n\n // optional sorting behavior for array sourceObjects. When set to 'locale',\n // the array will be ordered to match the locales array provided to mergeJson\n // When set to 'localesAlphabetical', the default locale will be placed first\n // and the remaining locales will be ordered alphabetically by locale code\n experimentalSort?: 'locales' | 'localesAlphabetical';\n\n // when true, non-default keyed entries in this composite array are extracted\n // into separate files (using the key value as the directory name) and replaced\n // with $ref pointers. Keeps the source file compact.\n splitEntries?: boolean;\n};\n\nexport type TransformOptions = {\n // relative jsonPath to content to mutate\n [transformPath: string]: TransformOption;\n};\n"],"mappings":";AA8HA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/types/index.ts"],"sourcesContent":["import type { CustomMapping } from '@generaltranslation/format/types';\nimport type { UserTokenProvider } from 'generaltranslation/api';\nimport type { ModelProvider } from 'generaltranslation/internal';\nimport type { FileFormat } from 'generaltranslation/types';\nimport { SUPPORTED_FILE_EXTENSIONS } from '../formats/files/supportedFiles.js';\nimport {\n ParsingConfigOptions,\n GTParsingFlags,\n BaseParsingFlags,\n ParseFlagsByFileType,\n} from './parsing.js';\nimport { Libraries, InlineLibrary } from './libraries.js';\n\nexport type { Updates } from 'generaltranslation/types';\n\nexport type Options = {\n config: string;\n apiKey?: string;\n projectId?: string;\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n src?: string[];\n defaultLocale?: string;\n locales?: string[];\n baseUrl: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n dryRun: boolean;\n timeout: number;\n force?: boolean;\n stageTranslations?: boolean;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type OpenApiConfig = {\n files: string[];\n translateFields?: string[];\n};\n\nexport type MintlifyOptions = {\n openapi?: OpenApiConfig;\n inferTitleFromFilename?: boolean;\n localizeRedirects?: boolean; // add localized redirects for pages renamed or removed in a translate run\n};\n\nexport type SharedFlags = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n};\n\nexport type TranslateFlags = SharedFlags & {\n versionId?: string;\n jsconfig?: string;\n dictionary?: string;\n defaultLocale?: string;\n locales?: string[];\n ignoreErrors?: boolean;\n src?: string[];\n timeout: number;\n dryRun: boolean;\n saveLocal?: boolean;\n stageTranslations?: boolean;\n setupProject?: boolean; // if true, skip enqueue step\n publish?: boolean;\n force?: boolean;\n forceDownload?: boolean;\n tag?: string;\n message?: string;\n experimentalLocalizeStaticUrls?: boolean;\n experimentalHideDefaultLocale?: boolean;\n experimentalFlattenJsonFiles?: boolean;\n experimentalLocalizeStaticImports?: boolean;\n experimentalLocalizeRelativeAssets?: boolean;\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default';\n omitConfigIds?: boolean;\n excludeStaticUrls?: string[];\n excludeStaticImports?: string[];\n docsImportRewrites?: Array<{\n match: string;\n replace: string;\n }>;\n};\n\nexport type WrapOptions = {\n src?: string[];\n config: string;\n skipTs: boolean;\n disableIds: boolean;\n disableFormatting: boolean;\n addGTProvider: boolean;\n};\n\nexport type SetupOptions = {\n src?: string[];\n config: string;\n};\n\nexport type GenerateSourceOptions = {\n src?: string[];\n config: string;\n defaultLocale: string;\n dictionary?: string;\n jsconfig?: string;\n inline?: boolean;\n ignoreErrors: boolean;\n suppressWarnings: boolean;\n};\n\nexport type Framework =\n | typeof Libraries.GT_NEXT\n | typeof Libraries.GT_REACT\n | typeof Libraries.GT_REACT_NATIVE\n | typeof Libraries.GT_TANSTACK_START;\n\nexport const SUPPORTED_REACT_FRAMEWORKS = [\n 'next-app',\n 'next-pages',\n 'vite',\n 'gatsby',\n 'react',\n 'redwood',\n 'tanstack-start',\n 'react-router',\n] as const;\n\nexport type FrameworkObject =\n | {\n name: 'mintlify';\n type?: undefined;\n }\n | {\n name: (typeof SUPPORTED_REACT_FRAMEWORKS)[number];\n type: 'react';\n };\nexport type ReactFrameworkObject = Extract<FrameworkObject, { type: 'react' }>;\n\nexport type FrameworkType = FrameworkObject['type'];\n\nexport type SupportedFrameworks = FrameworkObject['name'];\nexport type SupportedReactFrameworks = Extract<\n FrameworkObject,\n { type: 'react' }\n>['name'];\n\nexport type SupportedLibraries =\n | InlineLibrary\n | 'next-intl'\n | 'react-i18next'\n | 'next-i18next'\n | 'i18next'\n | 'i18next-icu'\n | 'base';\n\nexport interface ContentScanner {\n scanForContent(\n options: WrapOptions,\n framework: Framework\n ): Promise<{\n errors: string[];\n filesUpdated: string[];\n warnings: string[];\n }>;\n}\n\n// Create a type based on the supported file extensions\nexport type SupportedFileExtension = (typeof SUPPORTED_FILE_EXTENSIONS)[number];\n\n// Update ResolvedFiles to use the dynamic keys\nexport type ResolvedFiles = {\n [K in SupportedFileExtension]?: string[];\n} & {\n gt?: string; // Output glob: /path/[locale].json\n};\n\nexport type TransformOption = {\n match?: string; // regex to match strings, supports capture groups\n replace: string; // string or regex pattern to replace the match with\n // Special placeholders:\n // -> if used in the match string, they will be replaced with the corresponding default locale property value\n // -> if used in the replace string, they will be replaced with the corresponding target locale property value\n // {locale} -> will be replaced with the locale code\n // And any other property from getLocaleProperties()\n};\n\nexport type TransformFiles = {\n [K in SupportedFileExtension]?: TransformOption | string | TransformOption[]; // if a string, only transform the file name\n};\n\nexport type TransformFormats = {\n [K in SupportedFileExtension]?: FileFormat;\n};\n\n// Include patterns can be plain strings or objects with a publish flag\nexport type IncludePattern = string | { pattern: string; publish?: boolean };\n\n// Review requirement for matched files: a boolean applies to all files of the\n// type; the object form opts path groups in/out with globs. exclude wins over\n// include; files matching neither inherit the top-level requiresReview default.\nexport type RequiresReviewConfig =\n | boolean\n | {\n include?: string[];\n exclude?: string[];\n };\n\n// Update FilesOptions to fix the error\nexport type FilesOptions = {\n [K in SupportedFileExtension]?: {\n include: IncludePattern[];\n exclude?: string[];\n transform?: string | TransformOption | TransformOption[];\n transformationFormat?: FileFormat;\n parsingFlags?: BaseParsingFlags; // Flags for parsing inline content\n requiresReview?: RequiresReviewConfig; // Whether translated versions of matched files require approval before use\n };\n} & {\n gt?: {\n output: string; // Output glob: /path/[locale].json\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags?: Partial<GTParsingFlags>; // Flags for parsing inline content\n /**\n * @deprecated\n * use `files.gt.parsingFlags.includeSourceCodeContext` instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n};\n\n// Shared settings between all API-related commands\nexport type FontsConfig = {\n include: string[]; // globs of .ttf/.otf files\n exclude?: string[];\n};\n\nexport type Settings = {\n config: string;\n configDirectory: string;\n baseUrl: string;\n dashboardUrl: string;\n apiKey?: string;\n userTokenProvider?: UserTokenProvider;\n projectId?: string;\n defaultLocale: string;\n locales: string[];\n customMapping?: CustomMapping;\n files: {\n resolvedPaths: ResolvedFiles; // Absolute resolved paths for the default locale\n placeholderPaths: ResolvedFiles; // Absolute placeholder paths for all locales containing [locale]\n transformPaths: TransformFiles; // Absolute transform paths for all locales containing [locale]\n transformFormats: TransformFormats; // Output file format transforms keyed by config file type\n publishPaths: Set<string>; // Absolute paths explicitly opted IN to publishing\n unpublishPaths: Set<string>; // Absolute paths explicitly opted OUT of publishing\n requiresReviewPaths: Set<string>; // Absolute paths whose effective requiresReview policy is true\n parsingFlags: ParseFlagsByFileType;\n gtJson: {\n publish?: boolean; // if true, publish gtjson translations to the CDN\n parsingFlags: GTParsingFlags; // Flags for parsing inline content\n /**\n * @deprecated\n * use {@link files.gt.GTParsingFlags.parsingFlags.includeSourceCodeContext} instead\n */\n includeSourceCodeContext?: boolean; // Include surrounding source code lines as context for translations (default: false)\n };\n };\n stageTranslations: boolean; // if true, always stage the project during translate command\n requiresReview?: boolean; // top-level default: translated artifacts require approval before the client uses them\n publish?: boolean; // if true, publish the translations to the CDN; undefined means no global publish intent\n omitConfigIds?: boolean; // if true, do not write _versionId or _branchId to gt.config.json\n _versionId?: string; // internal use only\n _branchId?: string; // internal use only\n version?: string; // for specifying a custom version id to use. Should be unique\n description?: string;\n src?: string[]; // list of glob patterns for source file scanning\n fonts?: FontsConfig; // fonts to sync to the API before translating\n framework?: SupportedFrameworks;\n options?: AdditionalOptions;\n modelProvider?: ModelProvider;\n tag?: string;\n tagMessage?: string;\n parsingOptions: ParsingConfigOptions;\n branchOptions: BranchOptions;\n // Optional shared static assets config\n sharedStaticAssets?: SharedStaticAssetsConfig;\n};\n\nexport type StaticLocalizationFiles = Pick<\n Settings['files'],\n 'placeholderPaths' | 'resolvedPaths'\n> &\n Partial<Pick<Settings['files'], 'transformPaths' | 'transformFormats'>>;\n\nexport type StaticLocalizationSettings = Pick<\n Settings,\n 'defaultLocale' | 'locales' | 'options'\n> & {\n files?: StaticLocalizationFiles | null;\n};\n\nexport type BranchOptions = {\n currentBranch?: string;\n autoDetectBranches?: boolean;\n remoteName: string; // default 'origin'. The name of the remote to use for auto-detection.\n enabled: boolean; // if true, branching is enabled for the project\n};\n\nexport type AdditionalOptions = {\n // Optional schema to follow while translating JSON files\n jsonSchema?: {\n [fileGlob: string]: JsonSchema;\n };\n // Optional schema to follow while translating YAML files\n yamlSchema?: {\n [fileGlob: string]: YamlSchema;\n };\n // Skip pre-parse validation checks for specific file types\n skipFileValidation?: {\n json?: boolean;\n yaml?: boolean;\n mdx?: boolean;\n };\n // Optional Mintlify-specific options container\n mintlify?: MintlifyOptions;\n docsUrlPattern?: string | string[]; // eg /docs/[locale] or /[locale] for localizing static urls in markdown files; a list localizes several URL prefixes\n docsImportPattern?: string; // eg /docs/[locale]/foo.md or /[locale]/foo.md for localizing static imports in markdown files\n excludeStaticUrls?: string[]; // A list of file globs to include for static url localization\n excludeStaticImports?: string[]; // A list of file globs to include for static import localization\n docsHideDefaultLocaleImport?: boolean; // if true, hide the default locale in the import path\n copyFiles?: string[]; // array of files to copy to the target locale\n experimentalClearLocaleDirs?: boolean; // if true, clear locale directories before writing translations (default: false)\n clearLocaleDirsExclude?: string[]; // array of glob patterns with [locale] or [locales] placeholder to exclude from clearing (e.g., \"./snippets/[locale]/preserved/**\" or \"./[locales]/static/**\")\n experimentalLocalizeStaticImports?: boolean; // Inserts locale in static import paths in md/mdx files\n // Inserts locale in static url paths in md/mdx files and adds anchor IDs to\n // preserve navigation. The object form enables it with extra behavior.\n experimentalLocalizeStaticUrls?:\n | boolean\n | {\n // Keep links to source pages that have no translation\n skipUntranslatedPages?: boolean;\n // Extra JSX attribute names or globs to localize\n attributes?: string[];\n };\n experimentalLocalizeRelativeAssets?: boolean; // Rewrites relative asset URLs in translated md/mdx files to valid paths\n experimentalAddHeaderAnchorIds?: 'mintlify' | 'default'; // Format for anchor IDs: 'mintlify' for Mintlify's native {#id} on every heading, 'default' or undefined for escaped inline \\{#id\\}. Can run independently of static url localization\n experimentalHideDefaultLocale?: boolean; // Hides the default locale in the import path\n experimentalFlattenJsonFiles?: boolean; // Flattens JSON files into a single file\n baseDomain?: string; // The base http:// url where the project is hosted\n docsImportRewrites?: Array<{\n match: string; // prefix to match, e.g. '@site/docs'\n replace: string; // replacement prefix, can include [locale] or [defaultLocale]\n }>;\n experimentalCanonicalLocaleKeys?: boolean; // For composite JSON schemas with locale keys, force canonical locale even when alias provided\n saveLocal?: boolean; // if true, detect and save local edits to translated output before enqueuing translations (default: false)\n};\n\nexport type SharedStaticAssetsConfig = {\n include: string | string[];\n outDir?: string;\n publicPath?: string;\n mirrorToLocales?: boolean;\n};\n\nexport type StructuralTransform = {\n sourcePointer: string; // e.g., \"/msg\"\n destinationPointer: string; // e.g., \"/translations/en\"\n};\n\nexport type JsonSchema = {\n preset?: 'mintlify' | 'mintlify-hide-default' | 'openapi';\n structuralTransform?: StructuralTransform[];\n\n // when true, resolve $ref entries in this file before processing\n resolveRefs?: boolean;\n\n // exactly 1 of include or composite must be provided; not both\n\n // specify include if file is not composite\n // multiple target JSONs will be created for each locale,\n // with the only differing content being the specified JSONPath values\n include?: string[]; // array of JSONPaths to include\n\n // specify composite if no new JSONs should be created\n composite?: {\n // The sourceObjectPath is a JSONPath to the array or object containing\n // content in the source and target locales\n // This value is denoted as the \"sourceObject\"\n // Array elements or object sub-elements are denoted as \"sourceItem\"\n [sourceObjectPath: string]: SourceObjectOptions;\n };\n};\n\nexport type YamlSchema = {\n preset?: 'mintlify' | 'openapi';\n include?: string[];\n transform?: TransformOptions;\n};\n\nexport type SourceObjectOptions = {\n type: 'array' | 'object'; // type of the sourceObject;\n // array if the sourceObject is an array\n // -> We will simply add duplicated sourceItems for each locale\n // object if the sourceObject is an object\n // -> We will duplicate the sourceItem for each locale and set the corresponding\n // key with the locale property\n // In both cases, we search the sourceObject for the key that matches the source locale\n\n // Below, relative JSONPaths are relative to the sourceItem root, NOT the sourceObject\n\n include: string[]; // array of relative JSONPaths to include in the translated JSON\n\n // if type is array, there must be a key property in the array element\n // corresponding value should be a locale code\n key?: string; // relative jsonPath to the key to use to distinguish between source and target locales\n // if type is object, the key is simply the JSON key for the sourceItem - this is unnecessary in this case\n\n localeProperty?: string; // specific locale property to use for the key for target locales, default 'code'\n // ex: code, name, nativeName, languageCode, languageName, etc. (values returned by getLocaleProperties)\n\n // optional config for transforming specific fields in the sourceItem\n // for example, helpful for handling urls with locale-specific paths\n transform?: TransformOptions;\n\n // optional list of top-level properties to remove from generated\n // non-default-locale entries (e.g. Mintlify's `default: true` flag on the\n // default language entry, which must not be cloned into other locales)\n omitProperties?: string[];\n\n // optional sorting behavior for array sourceObjects. When set to 'locale',\n // the array will be ordered to match the locales array provided to mergeJson\n // When set to 'localesAlphabetical', the default locale will be placed first\n // and the remaining locales will be ordered alphabetically by locale code\n experimentalSort?: 'locales' | 'localesAlphabetical';\n\n // when true, non-default keyed entries in this composite array are extracted\n // into separate files (using the key value as the directory name) and replaced\n // with $ref pointers. Keeps the source file compact.\n splitEntries?: boolean;\n};\n\nexport type TransformOptions = {\n // relative jsonPath to content to mutate\n [transformPath: string]: TransformOption;\n};\n"],"mappings":";AA8HA,MAAa,6BAA6B;CACxC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD"}
|
|
@@ -26,3 +26,14 @@ export default function localizeStaticUrls(settings: StaticUrlSettings, targetLo
|
|
|
26
26
|
* Main URL transformation function that delegates to specific scenarios
|
|
27
27
|
*/
|
|
28
28
|
export declare function transformUrlPath(originalUrl: string, patternHead: string, targetLocale: string, defaultLocale: string, hideDefaultLocale: boolean): string | null;
|
|
29
|
+
/**
|
|
30
|
+
* The part of each docsUrlPattern before `[locale]`, with a leading slash,
|
|
31
|
+
* longest first so the most specific pattern matches a URL.
|
|
32
|
+
*/
|
|
33
|
+
export declare function getPatternHeads(pattern: string | string[]): string[];
|
|
34
|
+
/**
|
|
35
|
+
* The most specific pattern head a URL falls under. URLs are localized with
|
|
36
|
+
* that pattern only, so a URL a longer pattern leaves alone (e.g. one already
|
|
37
|
+
* localized) never falls through to a shorter one.
|
|
38
|
+
*/
|
|
39
|
+
export declare function findPatternHead(url: string, patternHeads: string[]): string | undefined;
|
|
@@ -229,16 +229,8 @@ function transformUrlPath(originalUrl, patternHead, targetLocale, defaultLocale,
|
|
|
229
229
|
*/
|
|
230
230
|
function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles, urlAttributes) {
|
|
231
231
|
const transformedUrls = [];
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
if (targetLocale === defaultLocale) {
|
|
235
|
-
const patternWithoutSlash = patternHead.replace(/\/$/, "");
|
|
236
|
-
if (!mdxContent.includes(patternWithoutSlash)) return {
|
|
237
|
-
content: mdxContent,
|
|
238
|
-
hasChanges: false,
|
|
239
|
-
transformedUrls: []
|
|
240
|
-
};
|
|
241
|
-
} else if (!mdxContent.includes(patternHead.replace(/\/$/, ""))) return {
|
|
232
|
+
const patternHeads = getPatternHeads(pattern);
|
|
233
|
+
if (!patternHeads.some((patternHead) => mdxContent.includes(patternHead.replace(/\/$/, "")))) return {
|
|
242
234
|
content: mdxContent,
|
|
243
235
|
hasChanges: false,
|
|
244
236
|
transformedUrls: []
|
|
@@ -263,6 +255,8 @@ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLo
|
|
|
263
255
|
const looksAbsoluteWithDomain = baseDomain ? shouldProcessAbsoluteUrl(originalUrl, baseDomain) : false;
|
|
264
256
|
if (!isAbsoluteRoot && !looksAbsoluteWithDomain && !isFragment) return null;
|
|
265
257
|
}
|
|
258
|
+
const patternHead = findPatternHead(baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain) ? originalUrl.substring(baseDomain.length) : originalUrl, patternHeads);
|
|
259
|
+
if (!patternHead) return null;
|
|
266
260
|
if (!shouldProcessUrl(originalUrl, patternHead, targetLocale, defaultLocale, baseDomain)) return null;
|
|
267
261
|
if (baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)) {
|
|
268
262
|
const afterDomain = originalUrl.substring(baseDomain.length);
|
|
@@ -378,11 +372,30 @@ function transformMdxUrls(mdxContent, defaultLocale, targetLocale, hideDefaultLo
|
|
|
378
372
|
function localizeStaticUrlsForFile(file, defaultLocale, targetLocale, hideDefaultLocale, pattern = "/[locale]", exclude = [], baseDomain, localizedFiles, urlAttributes) {
|
|
379
373
|
return transformMdxUrls(file, defaultLocale, targetLocale, hideDefaultLocale, pattern, exclude, baseDomain || "", localizedFiles, urlAttributes);
|
|
380
374
|
}
|
|
375
|
+
/**
|
|
376
|
+
* The part of each docsUrlPattern before `[locale]`, with a leading slash,
|
|
377
|
+
* longest first so the most specific pattern matches a URL.
|
|
378
|
+
*/
|
|
379
|
+
function getPatternHeads(pattern) {
|
|
380
|
+
return (Array.isArray(pattern) ? pattern : [pattern]).map((p) => (p.startsWith("/") ? p : `/${p}`).split("[locale]")[0]).sort((a, b) => pathSegments(b).length - pathSegments(a).length);
|
|
381
|
+
}
|
|
382
|
+
/**
|
|
383
|
+
* The most specific pattern head a URL falls under. URLs are localized with
|
|
384
|
+
* that pattern only, so a URL a longer pattern leaves alone (e.g. one already
|
|
385
|
+
* localized) never falls through to a shorter one.
|
|
386
|
+
*/
|
|
387
|
+
function findPatternHead(url, patternHeads) {
|
|
388
|
+
const urlSegments = pathSegments(url.split(/[?#]/)[0]);
|
|
389
|
+
return patternHeads.find((patternHead) => checkIfPathMatchesPattern(urlSegments, pathSegments(patternHead)));
|
|
390
|
+
}
|
|
391
|
+
function pathSegments(url) {
|
|
392
|
+
return url.split("/").filter((segment) => segment !== "");
|
|
393
|
+
}
|
|
381
394
|
function checkIfPathMatchesPattern(originalUrlArray, patternHeadArray) {
|
|
382
395
|
for (let i = 0; i < patternHeadArray.length; i++) if (patternHeadArray[i] !== originalUrlArray?.[i]) return false;
|
|
383
396
|
return true;
|
|
384
397
|
}
|
|
385
398
|
//#endregion
|
|
386
|
-
export { INDEX_PAGE, PAGE_EXTENSIONS, localizeStaticUrls as default, transformUrlPath, translationMissing };
|
|
399
|
+
export { INDEX_PAGE, PAGE_EXTENSIONS, localizeStaticUrls as default, findPatternHead, getPatternHeads, transformUrlPath, translationMissing };
|
|
387
400
|
|
|
388
401
|
//# sourceMappingURL=localizeStaticUrls.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"localizeStaticUrls.js","names":["path","fs","parseBabel"],"sources":["../../src/utils/localizeStaticUrls.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { StaticLocalizationSettings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport micromatch from 'micromatch';\nimport { unified } from 'unified';\nimport remarkMdx from 'remark-mdx';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkStringify from 'remark-stringify';\nimport { visit } from 'unist-util-visit';\nimport type { Root, Link, Literal } from 'mdast';\nimport type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parse as parseBabel } from '@babel/parser';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\n\nconst { isMatch } = micromatch;\n\n/**\n * URL-bearing JSX attributes that we localize by default. Intentionally limited\n * to link attributes (`href`) — NOT asset attributes like `src`, which usually\n * point at shared, locale-agnostic assets (e.g. `/docs/images/...`) that would\n * 404 if a locale prefix were added. Projects add their own link attributes\n * with `experimentalLocalizeStaticUrls.attributes`.\n */\nconst DEFAULT_URL_ATTRIBUTES = ['href'];\n\n// Docs routing conventions: page file formats, and the file that serves a\n// folder URL (`/a/` -> `a/index.mdx`).\nexport const PAGE_EXTENSIONS = ['.mdx', '.md'];\nexport const INDEX_PAGE = 'index';\n\n/**\n * The page file a root-relative docs URL points to, relative to the working\n * directory like file mapping keys: `/a/b#x` -> `a/b.mdx`, `a/b.md`, or\n * `a/b/index.mdx`.\n */\nfunction findPage(url: string): string | undefined {\n const base = url.split(/[?#]/)[0].replace(/^\\/+|\\/+$/g, '');\n return PAGE_EXTENSIONS.flatMap((ext) => [\n `${base}${ext}`,\n path.join(base, `${INDEX_PAGE}${ext}`),\n ]).find((page) => fs.existsSync(page));\n}\n\n/**\n * Whether a URL points to a source page with no translation on disk, either at\n * its mapped output path or at the localized URL. URLs with no source page,\n * such as pages generated from an OpenAPI spec, are not missing a translation.\n */\nexport function translationMissing(\n url: string,\n localizedUrl: string,\n localizedFiles: Record<string, string>\n): boolean {\n const sourcePage = findPage(url);\n if (!sourcePage) return false;\n const mappedPage = localizedFiles[sourcePage];\n return !(mappedPage && fs.existsSync(mappedPage)) && !findPage(localizedUrl);\n}\n\n/**\n * Localize URL string literals that live inside an MDX expression's raw source.\n *\n * URLs can be nested arbitrarily deep inside `{...}` expressions — e.g. an\n * `<a href>` buried inside a component prop:\n * <ParamField type={<span><a href=\"/docs/x\">Error</a></span>} />\n * Such hrefs never appear as mdast nodes (they live in the expression's embedded\n * JS), so the mdast visitors can't reach them. We re-parse the expression source\n * with Babel — positions are local to `source`, which avoids any document-offset\n * mapping — find JSX url-attribute string literals at any depth, and surgically\n * rewrite them in place.\n *\n * `rootStringIsUrl` covers `href={\"/docs/x\"}`, where the expression itself is a\n * bare string literal that a url-named attribute should treat as a URL.\n *\n * Only static string literals are localized; dynamically-computed URLs\n * (template literals, identifiers, concatenation) are left untouched — a\n * fundamental limit of static localization, not a parser shortcoming.\n */\nfunction localizeUrlsInExpressionSource(\n source: string,\n transformUrl: (url: string, linkType: 'markdown' | 'href') => string | null,\n urlAttributes: string[],\n rootStringIsUrl: boolean = false\n): string {\n if (!source.trim()) return source;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ast: any;\n try {\n ast = parseBabel(source, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['jsx', 'typescript'],\n });\n } catch {\n // Dynamic / unparseable expression — leave it untouched.\n return source;\n }\n\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const pushLiteralReplacement = (literal: any) => {\n if (\n !literal ||\n // A bare string at statement position is parsed by Babel as a\n // DirectiveLiteral (cf. \"use strict\") rather than a StringLiteral.\n (literal.type !== 'StringLiteral' &&\n literal.type !== 'DirectiveLiteral') ||\n typeof literal.value !== 'string' ||\n typeof literal.start !== 'number' ||\n typeof literal.end !== 'number'\n ) {\n return;\n }\n const newUrl = transformUrl(literal.value, 'href');\n if (!newUrl) return;\n // Preserve the original quote style; URLs never contain quote chars.\n const quote = source[literal.start] === \"'\" ? \"'\" : '\"';\n replacements.push({\n start: literal.start,\n end: literal.end,\n text: `${quote}${newUrl}${quote}`,\n });\n };\n\n // `href={\"/docs/x\"}`: the entire expression is the URL string.\n if (rootStringIsUrl) {\n const program = ast.program;\n const body = (program?.body ?? []) as Array<{\n type: string;\n expression?: unknown;\n }>;\n if (body.length === 1 && body[0]?.type === 'ExpressionStatement') {\n pushLiteralReplacement(body[0].expression);\n } else if (body.length === 0 && program?.directives?.length === 1) {\n // Babel parses a lone string literal as a directive, not a statement.\n pushLiteralReplacement(program.directives[0]?.value);\n }\n }\n\n // Walk the AST for JSX url-attributes anywhere in the expression.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const seen = new Set<any>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const walk = (node: any) => {\n if (!node || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (seen.has(node)) return;\n seen.add(node);\n\n if (\n node.type === 'JSXAttribute' &&\n node.name?.type === 'JSXIdentifier' &&\n isMatch(node.name.name, urlAttributes) &&\n node.value\n ) {\n if (node.value.type === 'StringLiteral') {\n pushLiteralReplacement(node.value);\n } else if (\n node.value.type === 'JSXExpressionContainer' &&\n node.value.expression?.type === 'StringLiteral'\n ) {\n pushLiteralReplacement(node.value.expression);\n }\n }\n\n for (const key in node) {\n if (\n key === 'loc' ||\n key === 'start' ||\n key === 'end' ||\n key === 'range'\n ) {\n continue;\n }\n const child = node[key];\n if (child && typeof child === 'object') walk(child);\n }\n };\n walk(ast.program ?? ast);\n\n if (replacements.length === 0) return source;\n\n // Apply end-to-start so earlier offsets remain valid.\n let result = source;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, text }) => {\n result = result.slice(0, start) + text + result.slice(end);\n });\n return result;\n}\n\nexport type StaticUrlSettings = StaticLocalizationSettings;\n\n/**\n * Localizes static urls in content files.\n * Currently only supported for md and mdx files. (/docs/ -> /[locale]/docs/)\n * @param settings - The settings object containing the project configuration.\n * @returns void\n *\n * @TODO This is an experimental feature, and only works in very specific cases. This needs to be improved before\n * it can be enabled by default.\n *\n * Before this becomes a non-experimental feature, we need to:\n * - Support more file types\n * - Support more complex paths\n */\nexport default async function localizeStaticUrls(\n settings: StaticUrlSettings,\n targetLocales?: string[],\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 const localizeOptions = settings.options?.experimentalLocalizeStaticUrls;\n const skipUntranslatedPages =\n typeof localizeOptions === 'object' &&\n localizeOptions.skipUntranslatedPages === true;\n const urlAttributes = [\n ...DEFAULT_URL_ATTRIBUTES,\n ...((typeof localizeOptions === 'object' && localizeOptions.attributes) ||\n []),\n ];\n\n // Use filtered locales if provided, otherwise use all locales\n const locales = targetLocales || settings.locales;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales, // Always use all locales for mapping, filter later\n settings.defaultLocale\n );\n\n // Process all file types at once with a single call\n const processPromises = [];\n\n // First, process default locale files (from source files)\n // This is needed because they might not be in the fileMapping if they're not being translated\n // Only process default locale if it's in the target locales filter\n if (\n !fileMapping[settings.defaultLocale] &&\n locales.includes(settings.defaultLocale) &&\n !includeFiles // when filtering, skip default-locale pass\n ) {\n const defaultLocaleFiles: string[] = [];\n\n // Collect all .md and .mdx files from sourceFiles\n if (sourceFiles.md) {\n defaultLocaleFiles.push(...sourceFiles.md);\n }\n if (sourceFiles.mdx) {\n defaultLocaleFiles.push(...sourceFiles.mdx);\n }\n\n if (defaultLocaleFiles.length > 0) {\n const defaultPromise = Promise.all(\n defaultLocaleFiles.map(async (filePath: string) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file using default locale\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n settings.defaultLocale, // Process as default locale\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n undefined,\n urlAttributes\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n processPromises.push(defaultPromise);\n }\n }\n\n // Then process all other locales from fileMapping\n const mappingPromises = Object.entries(fileMapping)\n .filter(([locale]) => locales.includes(locale)) // Filter by target locales\n .map(async ([locale, filesMap]) => {\n // Get all files that are md or mdx\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n // Replace the placeholder path with the target path\n await Promise.all(\n targetFiles.map(async (filePath) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file (handles both URLs and hrefs in single AST pass)\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n locale,\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n skipUntranslatedPages ? filesMap : undefined,\n urlAttributes\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n });\n processPromises.push(...mappingPromises);\n\n await Promise.all(processPromises);\n}\n\ninterface UrlTransformResult {\n content: string;\n hasChanges: boolean;\n transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }>;\n}\n\n/**\n * Determines if a URL should be processed based on pattern matching\n */\nfunction shouldProcessUrl(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n baseDomain?: string\n): boolean {\n // Check fragment-only URLs like \"#id-name\"\n if (/^\\s*#/.test(originalUrl)) {\n return false;\n }\n\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n\n // Handle absolute URLs with baseDomain\n let urlToCheck = originalUrl;\n if (baseDomain && originalUrl.startsWith(baseDomain)) {\n urlToCheck = originalUrl.substring(baseDomain.length);\n }\n\n if (targetLocale === defaultLocale) {\n // For default locale processing, check if URL contains the pattern\n return urlToCheck.includes(patternWithoutSlash);\n } else {\n // For non-default locales, check if URL starts with pattern\n return urlToCheck.startsWith(patternWithoutSlash);\n }\n}\n\n/**\n * Determines if a URL should be processed based on the base domain\n */\nfunction shouldProcessAbsoluteUrl(\n originalUrl: string,\n baseDomain: string\n): boolean {\n return originalUrl.startsWith(baseDomain);\n}\n\n/**\n * Checks if a URL should be excluded based on exclusion patterns\n */\nfunction isUrlExcluded(\n originalUrl: string,\n exclude: string[],\n defaultLocale: string\n): boolean {\n const excludePatterns = exclude.map((p) =>\n p.replace(/\\[locale\\]/g, defaultLocale)\n );\n return excludePatterns.some((pattern) => isMatch(originalUrl, pattern));\n}\n\n/**\n * Main URL transformation function that delegates to specific scenarios\n */\nexport function transformUrlPath(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean\n): string | null {\n const originalPathArray = originalUrl\n .split('/')\n .filter((path) => path !== '');\n const patternHeadArray = patternHead.split('/').filter((path) => path !== '');\n\n // check if the pattern head matches the original path\n if (!checkIfPathMatchesPattern(originalPathArray, patternHeadArray)) {\n return null;\n }\n\n if (patternHeadArray.length > originalPathArray.length) {\n return null; // Pattern is longer than the URL path\n }\n\n let result = null;\n if (targetLocale === defaultLocale) {\n if (hideDefaultLocale) {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // remove default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n ...originalPathArray.slice(patternHeadArray.length + 1),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] === defaultLocale) {\n return null;\n }\n\n // insert default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n defaultLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n }\n } else if (hideDefaultLocale) {\n // Avoid duplicating target locale if already present\n if (originalPathArray?.[patternHeadArray.length] === targetLocale) {\n return null;\n }\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n targetLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check default locale\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // replace default locale with target locale\n const newPathArray = [...originalPathArray];\n newPathArray[patternHeadArray.length] = targetLocale;\n\n result = newPathArray.join('/');\n }\n\n // check for leading and trailing slashes\n if (originalUrl.startsWith('/')) {\n result = '/' + result;\n }\n if (originalUrl.endsWith('/')) {\n result = result + '/';\n }\n\n return result;\n}\n\n/**\n * AST-based transformation for MDX files using remark-mdx\n */\nfunction transformMdxUrls(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]',\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: string[]\n): UrlTransformResult {\n const transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }> = [];\n\n if (!pattern.startsWith('/')) {\n pattern = '/' + pattern;\n }\n\n const patternHead = pattern.split('[locale]')[0];\n\n // Quick check: if the file doesn't contain the pattern, skip expensive AST parsing\n // For default locale processing, we also need to check if content might need adjustment\n if (targetLocale === defaultLocale) {\n // For default locale files, we always need to check as we're looking for either:\n // - paths without locale (when hideDefaultLocale=false)\n // - paths with default locale (when hideDefaultLocale=true)\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n if (!mdxContent.includes(patternWithoutSlash)) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n } else {\n // For non-default locales, use the original logic\n if (!mdxContent.includes(patternHead.replace(/\\/$/, ''))) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n }\n\n // Parse the MDX content into an AST\n let processedAst: Root;\n let neutralizedAnchors: boolean;\n try {\n const parsed = parseMdxForRoundTrip(mdxContent);\n processedAst = parsed.ast;\n neutralizedAnchors = parsed.neutralized;\n } catch {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls,\n };\n }\n\n // Helper function to transform URL based on pattern\n const transformUrl = (\n originalUrl: string,\n linkType: 'markdown' | 'href'\n ): string | null => {\n // For Markdown links [text](path), only process absolute-root paths starting with '/'\n // Relative markdown links should remain relative to the current page and not be localized.\n if (linkType === 'markdown') {\n const isFragment = /^\\s*#/.test(originalUrl);\n const isAbsoluteRoot = originalUrl.startsWith('/');\n const looksAbsoluteWithDomain = baseDomain\n ? shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n : false;\n if (!isAbsoluteRoot && !looksAbsoluteWithDomain && !isFragment) {\n return null;\n }\n }\n // Check if URL should be processed\n if (\n !shouldProcessUrl(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n baseDomain\n )\n ) {\n return null;\n }\n\n // Skip absolute URLs (http://, https://, //, etc.)\n if (baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)) {\n // Get everything after the base domain\n const afterDomain = originalUrl.substring(baseDomain.length);\n\n const transformedPath = transformUrlPath(\n afterDomain,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n if (!transformedPath) {\n return null;\n }\n if (\n localizedFiles &&\n translationMissing(afterDomain, transformedPath, localizedFiles)\n ) {\n return null;\n }\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: transformedPath,\n type: linkType,\n });\n return transformedPath ? baseDomain + transformedPath : null;\n }\n\n // Exclude colon-prefixed URLs (http://, https://, //, etc.)\n if (originalUrl.split('?')[0].includes(':')) {\n return null;\n }\n\n // Transform the URL based on locale and configuration\n const newUrl = transformUrlPath(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n\n if (!newUrl) {\n return null;\n }\n\n // Check exclusions\n if (isUrlExcluded(originalUrl, exclude, defaultLocale)) {\n return null;\n }\n\n // Links to pages with no translation keep the default locale.\n if (\n localizedFiles &&\n translationMissing(originalUrl, newUrl, localizedFiles)\n ) {\n return null;\n }\n\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: newUrl,\n type: linkType,\n });\n return newUrl;\n };\n\n // Visit markdown link nodes: [text](url)\n visit(processedAst, 'link', (node: Link) => {\n if (node.url) {\n const newUrl = transformUrl(node.url, 'markdown');\n if (newUrl) {\n node.url = newUrl;\n }\n }\n });\n\n // Visit JSX/HTML elements for href attributes: <a href=\"url\"> or <Card href=\"url\">\n visit(processedAst, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node) => {\n const jsxNode = node as MdxJsxFlowElement | MdxJsxTextElement;\n if (!jsxNode.attributes) return;\n for (const attr of jsxNode.attributes) {\n if (attr.type !== 'mdxJsxAttribute' || !attr.value) continue;\n\n // Plain string attribute value, e.g. <a href=\"/docs/x\">\n if (typeof attr.value === 'string') {\n if (isMatch(attr.name, urlAttributes)) {\n const newUrl = transformUrl(attr.value, 'href');\n if (newUrl) {\n attr.value = newUrl;\n }\n }\n continue;\n }\n\n // Expression attribute value. Two shapes are handled:\n // href={\"/docs/x\"} (url attr, bare string)\n // type={<span><a href=\"/docs/x\">…</a></span>} (url attr nested deep\n // inside a non-url prop)\n // The nested case never surfaces as an mdast node — it lives in the\n // expression's embedded JS — so it's localized via the source-level walk.\n if (\n typeof attr.value === 'object' &&\n attr.value.type === 'mdxJsxAttributeValueExpression' &&\n typeof attr.value.value === 'string'\n ) {\n const newValue = localizeUrlsInExpressionSource(\n attr.value.value,\n transformUrl,\n urlAttributes,\n isMatch(attr.name, urlAttributes)\n );\n if (newValue !== attr.value.value) {\n attr.value.value = newValue;\n }\n }\n }\n });\n\n // Visit standalone MDX expressions for URLs inside embedded JSX, e.g.\n // {isBeta && <a href=\"/docs/x\">Beta</a>}\n visit(processedAst, ['mdxFlowExpression', 'mdxTextExpression'], (node) => {\n const exprNode = node as unknown as Literal;\n if (typeof exprNode.value === 'string' && exprNode.value) {\n const newValue = localizeUrlsInExpressionSource(\n exprNode.value,\n transformUrl,\n urlAttributes\n );\n if (newValue !== exprNode.value) {\n exprNode.value = newValue;\n }\n }\n });\n\n // Visit raw JSX nodes for href attributes in JSX strings\n visit(processedAst, 'jsx', (node: Literal) => {\n if (node.value && typeof node.value === 'string') {\n const jsxContent = node.value;\n\n // Use regex to find href attributes in the JSX string\n const hrefRegex = /href\\s*=\\s*[\"']([^\"']+)[\"']/g;\n let match;\n const replacements: Array<{\n start: number;\n end: number;\n oldHrefAttr: string;\n newHrefAttr: string;\n }> = [];\n\n // Reset regex lastIndex to avoid issues with global flag\n hrefRegex.lastIndex = 0;\n\n while ((match = hrefRegex.exec(jsxContent)) !== null) {\n const originalHref = match[1];\n const newUrl = transformUrl(originalHref, 'href');\n\n if (newUrl) {\n // Store replacement info\n const oldHrefAttr = match[0]; // The full match like 'href=\"/quickstart\"'\n const quote = oldHrefAttr.includes('\"') ? '\"' : \"'\";\n const newHrefAttr = `href=${quote}${newUrl}${quote}`;\n\n replacements.push({\n start: match.index!,\n end: match.index! + oldHrefAttr.length,\n oldHrefAttr,\n newHrefAttr,\n });\n }\n }\n\n // Apply replacements in reverse order (from end to start) to avoid position shifts\n if (replacements.length > 0) {\n let newJsxContent = jsxContent;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, newHrefAttr }) => {\n newJsxContent =\n newJsxContent.slice(0, start) +\n newHrefAttr +\n newJsxContent.slice(end);\n });\n\n node.value = newJsxContent;\n }\n }\n });\n\n // Convert the modified AST back to MDX string\n let content: string;\n try {\n const stringifyProcessor = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n // Handler to prevent escaping (avoids '<' -> '\\<')\n text(node: Literal) {\n return node.value;\n },\n },\n });\n\n const outTree = stringifyProcessor.runSync(processedAst) as Root;\n content = stringifyProcessor.stringify(outTree);\n if (neutralizedAnchors) {\n content = restoreAnchorIds(content);\n }\n } catch (error) {\n console.warn(\n `Failed to stringify MDX content: ${error instanceof Error ? error.message : String(error)}`\n );\n console.warn(\n 'Returning original content unchanged due to stringify error.'\n );\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n\n // Handle newline formatting to match original input\n if (content.endsWith('\\n') && !mdxContent.endsWith('\\n')) {\n content = content.slice(0, -1);\n }\n\n // Preserve leading newlines from original content\n if (mdxContent.startsWith('\\n') && !content.startsWith('\\n')) {\n content = '\\n' + content;\n }\n\n return {\n content,\n hasChanges: transformedUrls.length > 0,\n transformedUrls,\n };\n}\n\n// AST-based transformation for MDX files using remark\nfunction localizeStaticUrlsForFile(\n file: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string = '/[locale]', // eg /docs/[locale] or /[locale]\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: string[]\n): UrlTransformResult {\n // Use AST-based transformation for MDX files\n return transformMdxUrls(\n file,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n baseDomain || '',\n localizedFiles,\n urlAttributes\n );\n}\n\nfunction checkIfPathMatchesPattern(\n originalUrlArray: string[],\n patternHeadArray: string[]\n): boolean {\n // check if the pattern head matches the original path\n for (let i = 0; i < patternHeadArray.length; i++) {\n if (patternHeadArray[i] !== originalUrlArray?.[i]) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,EAAE,YAAY;;;;;;;;AASpB,MAAM,yBAAyB,CAAC,OAAO;AAIvC,MAAa,kBAAkB,CAAC,QAAQ,MAAM;AAC9C,MAAa,aAAa;;;;;;AAO1B,SAAS,SAAS,KAAiC;CACjD,MAAM,OAAO,IAAI,MAAM,OAAO,CAAC,GAAG,QAAQ,cAAc,GAAG;AAC3D,QAAO,gBAAgB,SAAS,QAAQ,CACtC,GAAG,OAAO,OACVA,OAAK,KAAK,MAAM,GAAG,aAAa,MAAM,CACvC,CAAC,CAAC,MAAM,SAASC,KAAG,WAAW,KAAK,CAAC;;;;;;;AAQxC,SAAgB,mBACd,KACA,cACA,gBACS;CACT,MAAM,aAAa,SAAS,IAAI;AAChC,KAAI,CAAC,WAAY,QAAO;CACxB,MAAM,aAAa,eAAe;AAClC,QAAO,EAAE,cAAcA,KAAG,WAAW,WAAW,KAAK,CAAC,SAAS,aAAa;;;;;;;;;;;;;;;;;;;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
|
1
|
+
{"version":3,"file":"localizeStaticUrls.js","names":["path","fs","parseBabel"],"sources":["../../src/utils/localizeStaticUrls.ts"],"sourcesContent":["import * as fs from 'fs';\nimport * as path from 'path';\nimport type { StaticLocalizationSettings } from '../types/index.js';\nimport { createFileMapping } from '../formats/files/fileMapping.js';\nimport micromatch from 'micromatch';\nimport { unified } from 'unified';\nimport remarkMdx from 'remark-mdx';\nimport remarkFrontmatter from 'remark-frontmatter';\nimport remarkStringify from 'remark-stringify';\nimport { visit } from 'unist-util-visit';\nimport type { Root, Link, Literal } from 'mdast';\nimport type { MdxJsxFlowElement, MdxJsxTextElement } from 'mdast-util-mdx-jsx';\nimport { escapeHtmlInTextNodes, normalizeCJKCharacters } from 'gt-remark';\nimport { parse as parseBabel } from '@babel/parser';\nimport { parseMdxForRoundTrip, restoreAnchorIds } from './mdxAnchorSyntax.js';\n\nconst { isMatch } = micromatch;\n\n/**\n * URL-bearing JSX attributes that we localize by default. Intentionally limited\n * to link attributes (`href`) — NOT asset attributes like `src`, which usually\n * point at shared, locale-agnostic assets (e.g. `/docs/images/...`) that would\n * 404 if a locale prefix were added. Projects add their own link attributes\n * with `experimentalLocalizeStaticUrls.attributes`.\n */\nconst DEFAULT_URL_ATTRIBUTES = ['href'];\n\n// Docs routing conventions: page file formats, and the file that serves a\n// folder URL (`/a/` -> `a/index.mdx`).\nexport const PAGE_EXTENSIONS = ['.mdx', '.md'];\nexport const INDEX_PAGE = 'index';\n\n/**\n * The page file a root-relative docs URL points to, relative to the working\n * directory like file mapping keys: `/a/b#x` -> `a/b.mdx`, `a/b.md`, or\n * `a/b/index.mdx`.\n */\nfunction findPage(url: string): string | undefined {\n const base = url.split(/[?#]/)[0].replace(/^\\/+|\\/+$/g, '');\n return PAGE_EXTENSIONS.flatMap((ext) => [\n `${base}${ext}`,\n path.join(base, `${INDEX_PAGE}${ext}`),\n ]).find((page) => fs.existsSync(page));\n}\n\n/**\n * Whether a URL points to a source page with no translation on disk, either at\n * its mapped output path or at the localized URL. URLs with no source page,\n * such as pages generated from an OpenAPI spec, are not missing a translation.\n */\nexport function translationMissing(\n url: string,\n localizedUrl: string,\n localizedFiles: Record<string, string>\n): boolean {\n const sourcePage = findPage(url);\n if (!sourcePage) return false;\n const mappedPage = localizedFiles[sourcePage];\n return !(mappedPage && fs.existsSync(mappedPage)) && !findPage(localizedUrl);\n}\n\n/**\n * Localize URL string literals that live inside an MDX expression's raw source.\n *\n * URLs can be nested arbitrarily deep inside `{...}` expressions — e.g. an\n * `<a href>` buried inside a component prop:\n * <ParamField type={<span><a href=\"/docs/x\">Error</a></span>} />\n * Such hrefs never appear as mdast nodes (they live in the expression's embedded\n * JS), so the mdast visitors can't reach them. We re-parse the expression source\n * with Babel — positions are local to `source`, which avoids any document-offset\n * mapping — find JSX url-attribute string literals at any depth, and surgically\n * rewrite them in place.\n *\n * `rootStringIsUrl` covers `href={\"/docs/x\"}`, where the expression itself is a\n * bare string literal that a url-named attribute should treat as a URL.\n *\n * Only static string literals are localized; dynamically-computed URLs\n * (template literals, identifiers, concatenation) are left untouched — a\n * fundamental limit of static localization, not a parser shortcoming.\n */\nfunction localizeUrlsInExpressionSource(\n source: string,\n transformUrl: (url: string, linkType: 'markdown' | 'href') => string | null,\n urlAttributes: string[],\n rootStringIsUrl: boolean = false\n): string {\n if (!source.trim()) return source;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n let ast: any;\n try {\n ast = parseBabel(source, {\n sourceType: 'module',\n errorRecovery: true,\n plugins: ['jsx', 'typescript'],\n });\n } catch {\n // Dynamic / unparseable expression — leave it untouched.\n return source;\n }\n\n const replacements: Array<{ start: number; end: number; text: string }> = [];\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const pushLiteralReplacement = (literal: any) => {\n if (\n !literal ||\n // A bare string at statement position is parsed by Babel as a\n // DirectiveLiteral (cf. \"use strict\") rather than a StringLiteral.\n (literal.type !== 'StringLiteral' &&\n literal.type !== 'DirectiveLiteral') ||\n typeof literal.value !== 'string' ||\n typeof literal.start !== 'number' ||\n typeof literal.end !== 'number'\n ) {\n return;\n }\n const newUrl = transformUrl(literal.value, 'href');\n if (!newUrl) return;\n // Preserve the original quote style; URLs never contain quote chars.\n const quote = source[literal.start] === \"'\" ? \"'\" : '\"';\n replacements.push({\n start: literal.start,\n end: literal.end,\n text: `${quote}${newUrl}${quote}`,\n });\n };\n\n // `href={\"/docs/x\"}`: the entire expression is the URL string.\n if (rootStringIsUrl) {\n const program = ast.program;\n const body = (program?.body ?? []) as Array<{\n type: string;\n expression?: unknown;\n }>;\n if (body.length === 1 && body[0]?.type === 'ExpressionStatement') {\n pushLiteralReplacement(body[0].expression);\n } else if (body.length === 0 && program?.directives?.length === 1) {\n // Babel parses a lone string literal as a directive, not a statement.\n pushLiteralReplacement(program.directives[0]?.value);\n }\n }\n\n // Walk the AST for JSX url-attributes anywhere in the expression.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const seen = new Set<any>();\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const walk = (node: any) => {\n if (!node || typeof node !== 'object') return;\n if (Array.isArray(node)) {\n for (const item of node) walk(item);\n return;\n }\n if (seen.has(node)) return;\n seen.add(node);\n\n if (\n node.type === 'JSXAttribute' &&\n node.name?.type === 'JSXIdentifier' &&\n isMatch(node.name.name, urlAttributes) &&\n node.value\n ) {\n if (node.value.type === 'StringLiteral') {\n pushLiteralReplacement(node.value);\n } else if (\n node.value.type === 'JSXExpressionContainer' &&\n node.value.expression?.type === 'StringLiteral'\n ) {\n pushLiteralReplacement(node.value.expression);\n }\n }\n\n for (const key in node) {\n if (\n key === 'loc' ||\n key === 'start' ||\n key === 'end' ||\n key === 'range'\n ) {\n continue;\n }\n const child = node[key];\n if (child && typeof child === 'object') walk(child);\n }\n };\n walk(ast.program ?? ast);\n\n if (replacements.length === 0) return source;\n\n // Apply end-to-start so earlier offsets remain valid.\n let result = source;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, text }) => {\n result = result.slice(0, start) + text + result.slice(end);\n });\n return result;\n}\n\nexport type StaticUrlSettings = StaticLocalizationSettings;\n\n/**\n * Localizes static urls in content files.\n * Currently only supported for md and mdx files. (/docs/ -> /[locale]/docs/)\n * @param settings - The settings object containing the project configuration.\n * @returns void\n *\n * @TODO This is an experimental feature, and only works in very specific cases. This needs to be improved before\n * it can be enabled by default.\n *\n * Before this becomes a non-experimental feature, we need to:\n * - Support more file types\n * - Support more complex paths\n */\nexport default async function localizeStaticUrls(\n settings: StaticUrlSettings,\n targetLocales?: string[],\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 const localizeOptions = settings.options?.experimentalLocalizeStaticUrls;\n const skipUntranslatedPages =\n typeof localizeOptions === 'object' &&\n localizeOptions.skipUntranslatedPages === true;\n const urlAttributes = [\n ...DEFAULT_URL_ATTRIBUTES,\n ...((typeof localizeOptions === 'object' && localizeOptions.attributes) ||\n []),\n ];\n\n // Use filtered locales if provided, otherwise use all locales\n const locales = targetLocales || settings.locales;\n\n const fileMapping = createFileMapping(\n sourceFiles,\n settings.files.placeholderPaths,\n settings.files.transformPaths ?? {},\n settings.files.transformFormats ?? {},\n settings.locales, // Always use all locales for mapping, filter later\n settings.defaultLocale\n );\n\n // Process all file types at once with a single call\n const processPromises = [];\n\n // First, process default locale files (from source files)\n // This is needed because they might not be in the fileMapping if they're not being translated\n // Only process default locale if it's in the target locales filter\n if (\n !fileMapping[settings.defaultLocale] &&\n locales.includes(settings.defaultLocale) &&\n !includeFiles // when filtering, skip default-locale pass\n ) {\n const defaultLocaleFiles: string[] = [];\n\n // Collect all .md and .mdx files from sourceFiles\n if (sourceFiles.md) {\n defaultLocaleFiles.push(...sourceFiles.md);\n }\n if (sourceFiles.mdx) {\n defaultLocaleFiles.push(...sourceFiles.mdx);\n }\n\n if (defaultLocaleFiles.length > 0) {\n const defaultPromise = Promise.all(\n defaultLocaleFiles.map(async (filePath: string) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file using default locale\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n settings.defaultLocale, // Process as default locale\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n undefined,\n urlAttributes\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n processPromises.push(defaultPromise);\n }\n }\n\n // Then process all other locales from fileMapping\n const mappingPromises = Object.entries(fileMapping)\n .filter(([locale]) => locales.includes(locale)) // Filter by target locales\n .map(async ([locale, filesMap]) => {\n // Get all files that are md or mdx\n const targetFiles = Object.values(filesMap).filter(\n (p) =>\n PAGE_EXTENSIONS.some((ext) => p.endsWith(ext)) &&\n (!includeFiles || includeFiles.has(p))\n );\n\n // Replace the placeholder path with the target path\n await Promise.all(\n targetFiles.map(async (filePath) => {\n // Check if file exists before processing\n if (!fs.existsSync(filePath)) {\n return;\n }\n // Get file content\n const fileContent = await fs.promises.readFile(filePath, 'utf8');\n // Localize the file (handles both URLs and hrefs in single AST pass)\n const result = localizeStaticUrlsForFile(\n fileContent,\n settings.defaultLocale,\n locale,\n settings.options?.experimentalHideDefaultLocale || false,\n settings.options?.docsUrlPattern,\n settings.options?.excludeStaticUrls,\n settings.options?.baseDomain,\n skipUntranslatedPages ? filesMap : undefined,\n urlAttributes\n );\n // Only write the file if there were changes\n if (result.hasChanges) {\n await fs.promises.writeFile(filePath, result.content);\n }\n })\n );\n });\n processPromises.push(...mappingPromises);\n\n await Promise.all(processPromises);\n}\n\ninterface UrlTransformResult {\n content: string;\n hasChanges: boolean;\n transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }>;\n}\n\n/**\n * Determines if a URL should be processed based on pattern matching\n */\nfunction shouldProcessUrl(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n baseDomain?: string\n): boolean {\n // Check fragment-only URLs like \"#id-name\"\n if (/^\\s*#/.test(originalUrl)) {\n return false;\n }\n\n const patternWithoutSlash = patternHead.replace(/\\/$/, '');\n\n // Handle absolute URLs with baseDomain\n let urlToCheck = originalUrl;\n if (baseDomain && originalUrl.startsWith(baseDomain)) {\n urlToCheck = originalUrl.substring(baseDomain.length);\n }\n\n if (targetLocale === defaultLocale) {\n // For default locale processing, check if URL contains the pattern\n return urlToCheck.includes(patternWithoutSlash);\n } else {\n // For non-default locales, check if URL starts with pattern\n return urlToCheck.startsWith(patternWithoutSlash);\n }\n}\n\n/**\n * Determines if a URL should be processed based on the base domain\n */\nfunction shouldProcessAbsoluteUrl(\n originalUrl: string,\n baseDomain: string\n): boolean {\n return originalUrl.startsWith(baseDomain);\n}\n\n/**\n * Checks if a URL should be excluded based on exclusion patterns\n */\nfunction isUrlExcluded(\n originalUrl: string,\n exclude: string[],\n defaultLocale: string\n): boolean {\n const excludePatterns = exclude.map((p) =>\n p.replace(/\\[locale\\]/g, defaultLocale)\n );\n return excludePatterns.some((pattern) => isMatch(originalUrl, pattern));\n}\n\n/**\n * Main URL transformation function that delegates to specific scenarios\n */\nexport function transformUrlPath(\n originalUrl: string,\n patternHead: string,\n targetLocale: string,\n defaultLocale: string,\n hideDefaultLocale: boolean\n): string | null {\n const originalPathArray = originalUrl\n .split('/')\n .filter((path) => path !== '');\n const patternHeadArray = patternHead.split('/').filter((path) => path !== '');\n\n // check if the pattern head matches the original path\n if (!checkIfPathMatchesPattern(originalPathArray, patternHeadArray)) {\n return null;\n }\n\n if (patternHeadArray.length > originalPathArray.length) {\n return null; // Pattern is longer than the URL path\n }\n\n let result = null;\n if (targetLocale === defaultLocale) {\n if (hideDefaultLocale) {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // remove default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n ...originalPathArray.slice(patternHeadArray.length + 1),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check if default locale is already present\n if (originalPathArray?.[patternHeadArray.length] === defaultLocale) {\n return null;\n }\n\n // insert default locale\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n defaultLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n }\n } else if (hideDefaultLocale) {\n // Avoid duplicating target locale if already present\n if (originalPathArray?.[patternHeadArray.length] === targetLocale) {\n return null;\n }\n const newPathArray = [\n ...originalPathArray.slice(0, patternHeadArray.length),\n targetLocale,\n ...originalPathArray.slice(patternHeadArray.length),\n ];\n\n result = newPathArray.join('/');\n } else {\n // check default locale\n if (originalPathArray?.[patternHeadArray.length] !== defaultLocale) {\n return null;\n }\n\n // replace default locale with target locale\n const newPathArray = [...originalPathArray];\n newPathArray[patternHeadArray.length] = targetLocale;\n\n result = newPathArray.join('/');\n }\n\n // check for leading and trailing slashes\n if (originalUrl.startsWith('/')) {\n result = '/' + result;\n }\n if (originalUrl.endsWith('/')) {\n result = result + '/';\n }\n\n return result;\n}\n\n/**\n * AST-based transformation for MDX files using remark-mdx\n */\nfunction transformMdxUrls(\n mdxContent: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string | string[] = '/[locale]',\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: string[]\n): UrlTransformResult {\n const transformedUrls: Array<{\n originalPath: string;\n newPath: string;\n type: 'markdown' | 'href';\n }> = [];\n\n const patternHeads = getPatternHeads(pattern);\n\n // Quick check: if the file doesn't contain any pattern, skip expensive AST parsing\n if (\n !patternHeads.some((patternHead) =>\n mdxContent.includes(patternHead.replace(/\\/$/, ''))\n )\n ) {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n\n // Parse the MDX content into an AST\n let processedAst: Root;\n let neutralizedAnchors: boolean;\n try {\n const parsed = parseMdxForRoundTrip(mdxContent);\n processedAst = parsed.ast;\n neutralizedAnchors = parsed.neutralized;\n } catch {\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls,\n };\n }\n\n // Helper function to transform URL based on pattern\n const transformUrl = (\n originalUrl: string,\n linkType: 'markdown' | 'href'\n ): string | null => {\n // For Markdown links [text](path), only process absolute-root paths starting with '/'\n // Relative markdown links should remain relative to the current page and not be localized.\n if (linkType === 'markdown') {\n const isFragment = /^\\s*#/.test(originalUrl);\n const isAbsoluteRoot = originalUrl.startsWith('/');\n const looksAbsoluteWithDomain = baseDomain\n ? shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n : false;\n if (!isAbsoluteRoot && !looksAbsoluteWithDomain && !isFragment) {\n return null;\n }\n }\n // Localize with the pattern that matches this URL\n const patternHead = findPatternHead(\n baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)\n ? originalUrl.substring(baseDomain.length)\n : originalUrl,\n patternHeads\n );\n if (!patternHead) {\n return null;\n }\n\n // Check if URL should be processed\n if (\n !shouldProcessUrl(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n baseDomain\n )\n ) {\n return null;\n }\n\n // Skip absolute URLs (http://, https://, //, etc.)\n if (baseDomain && shouldProcessAbsoluteUrl(originalUrl, baseDomain)) {\n // Get everything after the base domain\n const afterDomain = originalUrl.substring(baseDomain.length);\n\n const transformedPath = transformUrlPath(\n afterDomain,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n if (!transformedPath) {\n return null;\n }\n if (\n localizedFiles &&\n translationMissing(afterDomain, transformedPath, localizedFiles)\n ) {\n return null;\n }\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: transformedPath,\n type: linkType,\n });\n return transformedPath ? baseDomain + transformedPath : null;\n }\n\n // Exclude colon-prefixed URLs (http://, https://, //, etc.)\n if (originalUrl.split('?')[0].includes(':')) {\n return null;\n }\n\n // Transform the URL based on locale and configuration\n const newUrl = transformUrlPath(\n originalUrl,\n patternHead,\n targetLocale,\n defaultLocale,\n hideDefaultLocale\n );\n\n if (!newUrl) {\n return null;\n }\n\n // Check exclusions\n if (isUrlExcluded(originalUrl, exclude, defaultLocale)) {\n return null;\n }\n\n // Links to pages with no translation keep the default locale.\n if (\n localizedFiles &&\n translationMissing(originalUrl, newUrl, localizedFiles)\n ) {\n return null;\n }\n\n transformedUrls.push({\n originalPath: originalUrl,\n newPath: newUrl,\n type: linkType,\n });\n return newUrl;\n };\n\n // Visit markdown link nodes: [text](url)\n visit(processedAst, 'link', (node: Link) => {\n if (node.url) {\n const newUrl = transformUrl(node.url, 'markdown');\n if (newUrl) {\n node.url = newUrl;\n }\n }\n });\n\n // Visit JSX/HTML elements for href attributes: <a href=\"url\"> or <Card href=\"url\">\n visit(processedAst, ['mdxJsxFlowElement', 'mdxJsxTextElement'], (node) => {\n const jsxNode = node as MdxJsxFlowElement | MdxJsxTextElement;\n if (!jsxNode.attributes) return;\n for (const attr of jsxNode.attributes) {\n if (attr.type !== 'mdxJsxAttribute' || !attr.value) continue;\n\n // Plain string attribute value, e.g. <a href=\"/docs/x\">\n if (typeof attr.value === 'string') {\n if (isMatch(attr.name, urlAttributes)) {\n const newUrl = transformUrl(attr.value, 'href');\n if (newUrl) {\n attr.value = newUrl;\n }\n }\n continue;\n }\n\n // Expression attribute value. Two shapes are handled:\n // href={\"/docs/x\"} (url attr, bare string)\n // type={<span><a href=\"/docs/x\">…</a></span>} (url attr nested deep\n // inside a non-url prop)\n // The nested case never surfaces as an mdast node — it lives in the\n // expression's embedded JS — so it's localized via the source-level walk.\n if (\n typeof attr.value === 'object' &&\n attr.value.type === 'mdxJsxAttributeValueExpression' &&\n typeof attr.value.value === 'string'\n ) {\n const newValue = localizeUrlsInExpressionSource(\n attr.value.value,\n transformUrl,\n urlAttributes,\n isMatch(attr.name, urlAttributes)\n );\n if (newValue !== attr.value.value) {\n attr.value.value = newValue;\n }\n }\n }\n });\n\n // Visit standalone MDX expressions for URLs inside embedded JSX, e.g.\n // {isBeta && <a href=\"/docs/x\">Beta</a>}\n visit(processedAst, ['mdxFlowExpression', 'mdxTextExpression'], (node) => {\n const exprNode = node as unknown as Literal;\n if (typeof exprNode.value === 'string' && exprNode.value) {\n const newValue = localizeUrlsInExpressionSource(\n exprNode.value,\n transformUrl,\n urlAttributes\n );\n if (newValue !== exprNode.value) {\n exprNode.value = newValue;\n }\n }\n });\n\n // Visit raw JSX nodes for href attributes in JSX strings\n visit(processedAst, 'jsx', (node: Literal) => {\n if (node.value && typeof node.value === 'string') {\n const jsxContent = node.value;\n\n // Use regex to find href attributes in the JSX string\n const hrefRegex = /href\\s*=\\s*[\"']([^\"']+)[\"']/g;\n let match;\n const replacements: Array<{\n start: number;\n end: number;\n oldHrefAttr: string;\n newHrefAttr: string;\n }> = [];\n\n // Reset regex lastIndex to avoid issues with global flag\n hrefRegex.lastIndex = 0;\n\n while ((match = hrefRegex.exec(jsxContent)) !== null) {\n const originalHref = match[1];\n const newUrl = transformUrl(originalHref, 'href');\n\n if (newUrl) {\n // Store replacement info\n const oldHrefAttr = match[0]; // The full match like 'href=\"/quickstart\"'\n const quote = oldHrefAttr.includes('\"') ? '\"' : \"'\";\n const newHrefAttr = `href=${quote}${newUrl}${quote}`;\n\n replacements.push({\n start: match.index!,\n end: match.index! + oldHrefAttr.length,\n oldHrefAttr,\n newHrefAttr,\n });\n }\n }\n\n // Apply replacements in reverse order (from end to start) to avoid position shifts\n if (replacements.length > 0) {\n let newJsxContent = jsxContent;\n replacements\n .sort((a, b) => b.start - a.start)\n .forEach(({ start, end, newHrefAttr }) => {\n newJsxContent =\n newJsxContent.slice(0, start) +\n newHrefAttr +\n newJsxContent.slice(end);\n });\n\n node.value = newJsxContent;\n }\n }\n });\n\n // Convert the modified AST back to MDX string\n let content: string;\n try {\n const stringifyProcessor = unified()\n .use(remarkFrontmatter, ['yaml', 'toml'])\n .use(remarkMdx)\n .use(normalizeCJKCharacters)\n .use(escapeHtmlInTextNodes)\n .use(remarkStringify, {\n handlers: {\n // Handler to prevent escaping (avoids '<' -> '\\<')\n text(node: Literal) {\n return node.value;\n },\n },\n });\n\n const outTree = stringifyProcessor.runSync(processedAst) as Root;\n content = stringifyProcessor.stringify(outTree);\n if (neutralizedAnchors) {\n content = restoreAnchorIds(content);\n }\n } catch (error) {\n console.warn(\n `Failed to stringify MDX content: ${error instanceof Error ? error.message : String(error)}`\n );\n console.warn(\n 'Returning original content unchanged due to stringify error.'\n );\n return {\n content: mdxContent,\n hasChanges: false,\n transformedUrls: [],\n };\n }\n\n // Handle newline formatting to match original input\n if (content.endsWith('\\n') && !mdxContent.endsWith('\\n')) {\n content = content.slice(0, -1);\n }\n\n // Preserve leading newlines from original content\n if (mdxContent.startsWith('\\n') && !content.startsWith('\\n')) {\n content = '\\n' + content;\n }\n\n return {\n content,\n hasChanges: transformedUrls.length > 0,\n transformedUrls,\n };\n}\n\n// AST-based transformation for MDX files using remark\nfunction localizeStaticUrlsForFile(\n file: string,\n defaultLocale: string,\n targetLocale: string,\n hideDefaultLocale: boolean,\n pattern: string | string[] = '/[locale]', // eg /docs/[locale] or /[locale]\n exclude: string[] = [],\n baseDomain: string | undefined,\n localizedFiles: Record<string, string> | undefined,\n urlAttributes: string[]\n): UrlTransformResult {\n // Use AST-based transformation for MDX files\n return transformMdxUrls(\n file,\n defaultLocale,\n targetLocale,\n hideDefaultLocale,\n pattern,\n exclude,\n baseDomain || '',\n localizedFiles,\n urlAttributes\n );\n}\n\n/**\n * The part of each docsUrlPattern before `[locale]`, with a leading slash,\n * longest first so the most specific pattern matches a URL.\n */\nexport function getPatternHeads(pattern: string | string[]): string[] {\n return (Array.isArray(pattern) ? pattern : [pattern])\n .map((p) => (p.startsWith('/') ? p : `/${p}`).split('[locale]')[0])\n .sort((a, b) => pathSegments(b).length - pathSegments(a).length);\n}\n\n/**\n * The most specific pattern head a URL falls under. URLs are localized with\n * that pattern only, so a URL a longer pattern leaves alone (e.g. one already\n * localized) never falls through to a shorter one.\n */\nexport function findPatternHead(\n url: string,\n patternHeads: string[]\n): string | undefined {\n // Query strings and fragments are not part of the path\n const urlSegments = pathSegments(url.split(/[?#]/)[0]);\n return patternHeads.find((patternHead) =>\n checkIfPathMatchesPattern(urlSegments, pathSegments(patternHead))\n );\n}\n\nfunction pathSegments(url: string): string[] {\n return url.split('/').filter((segment) => segment !== '');\n}\n\nfunction checkIfPathMatchesPattern(\n originalUrlArray: string[],\n patternHeadArray: string[]\n): boolean {\n // check if the pattern head matches the original path\n for (let i = 0; i < patternHeadArray.length; i++) {\n if (patternHeadArray[i] !== originalUrlArray?.[i]) {\n return false;\n }\n }\n\n return true;\n}\n"],"mappings":";;;;;;;;;;;;;AAgBA,MAAM,EAAE,YAAY;;;;;;;;AASpB,MAAM,yBAAyB,CAAC,OAAO;AAIvC,MAAa,kBAAkB,CAAC,QAAQ,MAAM;AAC9C,MAAa,aAAa;;;;;;AAO1B,SAAS,SAAS,KAAiC;CACjD,MAAM,OAAO,IAAI,MAAM,OAAO,CAAC,GAAG,QAAQ,cAAc,GAAG;AAC3D,QAAO,gBAAgB,SAAS,QAAQ,CACtC,GAAG,OAAO,OACVA,OAAK,KAAK,MAAM,GAAG,aAAa,MAAM,CACvC,CAAC,CAAC,MAAM,SAASC,KAAG,WAAW,KAAK,CAAC;;;;;;;AAQxC,SAAgB,mBACd,KACA,cACA,gBACS;CACT,MAAM,aAAa,SAAS,IAAI;AAChC,KAAI,CAAC,WAAY,QAAO;CACxB,MAAM,aAAa,eAAe;AAClC,QAAO,EAAE,cAAcA,KAAG,WAAW,WAAW,KAAK,CAAC,SAAS,aAAa;;;;;;;;;;;;;;;;;;;;;AAsB9E,SAAS,+BACP,QACA,cACA,eACA,kBAA2B,OACnB;AACR,KAAI,CAAC,OAAO,MAAM,CAAE,QAAO;CAG3B,IAAI;AACJ,KAAI;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