gt 2.23.2 → 2.24.0

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.
Files changed (79) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/cli/base.js +23 -15
  3. package/dist/cli/base.js.map +1 -1
  4. package/dist/cli/flags.js +3 -2
  5. package/dist/cli/flags.js.map +1 -1
  6. package/dist/formats/files/postprocess/localizeMintlifyRedirects.d.ts +16 -0
  7. package/dist/formats/files/postprocess/localizeMintlifyRedirects.js +122 -0
  8. package/dist/formats/files/postprocess/localizeMintlifyRedirects.js.map +1 -0
  9. package/dist/fs/config/setupConfig.d.ts +14 -1
  10. package/dist/fs/config/setupConfig.js +33 -9
  11. package/dist/fs/config/setupConfig.js.map +1 -1
  12. package/dist/fs/createLoadTranslationsFile.js +1 -1
  13. package/dist/fs/createLoadTranslationsFile.js.map +1 -1
  14. package/dist/generated/version.d.ts +1 -1
  15. package/dist/generated/version.js +1 -1
  16. package/dist/generated/version.js.map +1 -1
  17. package/dist/react/config/createESBuildConfig.d.ts +1 -1
  18. package/dist/react/config/createESBuildConfig.js.map +1 -1
  19. package/dist/react/parse/createDictionaryUpdates.d.ts +1 -1
  20. package/dist/react/parse/createDictionaryUpdates.js +1 -1
  21. package/dist/react/parse/createDictionaryUpdates.js.map +1 -1
  22. package/dist/setup/buildTools/index.d.ts +2 -0
  23. package/dist/setup/buildTools/index.js +2 -1
  24. package/dist/setup/buildTools/index.js.map +1 -1
  25. package/dist/setup/buildTools/tanstackStart/edits.d.ts +21 -0
  26. package/dist/setup/buildTools/tanstackStart/edits.js +44 -0
  27. package/dist/setup/buildTools/tanstackStart/edits.js.map +1 -0
  28. package/dist/setup/buildTools/tanstackStart/index.d.ts +2 -0
  29. package/dist/setup/buildTools/tanstackStart/index.js +127 -0
  30. package/dist/setup/buildTools/tanstackStart/index.js.map +1 -0
  31. package/dist/setup/buildTools/tanstackStart/middleware.d.ts +9 -0
  32. package/dist/setup/buildTools/tanstackStart/middleware.js +59 -0
  33. package/dist/setup/buildTools/tanstackStart/middleware.js.map +1 -0
  34. package/dist/setup/buildTools/tanstackStart/root.d.ts +30 -0
  35. package/dist/setup/buildTools/tanstackStart/root.js +178 -0
  36. package/dist/setup/buildTools/tanstackStart/root.js.map +1 -0
  37. package/dist/setup/buildTools/tanstackStart/router.d.ts +15 -0
  38. package/dist/setup/buildTools/tanstackStart/router.js +64 -0
  39. package/dist/setup/buildTools/tanstackStart/router.js.map +1 -0
  40. package/dist/setup/buildTools/tanstackStart/source.d.ts +19 -0
  41. package/dist/setup/buildTools/tanstackStart/source.js +66 -0
  42. package/dist/setup/buildTools/tanstackStart/source.js.map +1 -0
  43. package/dist/setup/buildTools/vite.d.ts +1 -0
  44. package/dist/setup/buildTools/vite.js +3 -3
  45. package/dist/setup/buildTools/vite.js.map +1 -1
  46. package/dist/setup/detectFramework.d.ts +1 -1
  47. package/dist/setup/detectFramework.js +5 -1
  48. package/dist/setup/detectFramework.js.map +1 -1
  49. package/dist/setup/developmentCredentials.d.ts +1 -0
  50. package/dist/setup/developmentCredentials.js +12 -4
  51. package/dist/setup/developmentCredentials.js.map +1 -1
  52. package/dist/setup/frameworkUtils.js +4 -1
  53. package/dist/setup/frameworkUtils.js.map +1 -1
  54. package/dist/setup/onboarding.js +3 -3
  55. package/dist/setup/onboarding.js.map +1 -1
  56. package/dist/setup/setupViteSPA.d.ts +10 -1
  57. package/dist/setup/setupViteSPA.js +16 -3
  58. package/dist/setup/setupViteSPA.js.map +1 -1
  59. package/dist/setup/wizard.js +13 -2
  60. package/dist/setup/wizard.js.map +1 -1
  61. package/dist/state/orphanedFileNames.d.ts +4 -0
  62. package/dist/state/orphanedFileNames.js +16 -0
  63. package/dist/state/orphanedFileNames.js.map +1 -0
  64. package/dist/types/index.d.ts +2 -1
  65. package/dist/types/index.js +2 -1
  66. package/dist/types/index.js.map +1 -1
  67. package/dist/utils/constants.d.ts +1 -0
  68. package/dist/utils/constants.js +2 -1
  69. package/dist/utils/constants.js.map +1 -1
  70. package/dist/utils/credentials.js +2 -1
  71. package/dist/utils/credentials.js.map +1 -1
  72. package/dist/utils/localizeStaticUrls.d.ts +6 -0
  73. package/dist/utils/localizeStaticUrls.js +1 -1
  74. package/dist/utils/localizeStaticUrls.js.map +1 -1
  75. package/dist/utils/packageManager.js +21 -11
  76. package/dist/utils/packageManager.js.map +1 -1
  77. package/dist/workflows/steps/UploadSourcesStep.js +3 -0
  78. package/dist/workflows/steps/UploadSourcesStep.js.map +1 -1
  79. package/package.json +4 -3
@@ -1 +1 @@
1
- {"version":3,"file":"setupViteSPA.js","names":[],"sources":["../../src/setup/setupViteSPA.ts"],"sourcesContent":["import { parse } from '@babel/parser';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport { Libraries } from '../types/libraries.js';\n\ntype SetupViteSPAOptions = {\n appDirectory: string;\n configFilepath: string;\n defaultLocale: string;\n locales: string[];\n translationsDir?: string;\n previousTranslationsDir?: string;\n};\n\nconst defaultBootstrapFilename = 'gt-entry.ts';\nconst alternateBootstrapFilename = 'gt-bootstrap.ts';\n\nfunction getBootstrapConflictError(filename: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The Vite bootstrap file already exists',\n why: `GT will not overwrite an existing src/${filename} file`,\n fix: 'Move or rename that file and rerun `npx gt@latest`',\n });\n}\n\nfunction getLoaderContent(translationsImport: string): string {\n return `export default async function loadTranslations(locale: string) {\n const translations = await import(\\`${translationsImport}/\\${locale}.json\\`);\n return translations.default;\n}\n`;\n}\n\n/**\n * Top-level statements, or undefined for syntax this inspector cannot parse\n * but Vite may accept, such as decorators.\n */\nfunction parseModule(content: string, filename: string) {\n try {\n return parse(content, {\n sourceType: 'module',\n // JSX would reject `<T>x` assertions, which .ts files may use.\n plugins: /\\.[cm]?ts$/i.test(filename)\n ? ['typescript']\n : ['typescript', 'jsx'],\n }).program.body;\n } catch {\n return undefined;\n }\n}\n\nfunction toRelativeImport(fromDirectory: string, toPath: string): string {\n const relativePath = path\n .relative(fromDirectory, toPath)\n .split(path.sep)\n .join(path.posix.sep);\n return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;\n}\n\nfunction getEntryPath(appDirectory: string, source: string): string {\n const sourcePath = source.replace(/[?#].*$/, '');\n return sourcePath.startsWith('/')\n ? path.resolve(appDirectory, `.${sourcePath}`)\n : path.resolve(appDirectory, sourcePath);\n}\n\nfunction getBootstrapEntry(bootstrap: string): string | undefined {\n return bootstrap.match(/await\\s+import\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/)?.[2];\n}\n\nfunction getModuleEntry(indexHtml: string): {\n script: string;\n source: string;\n} {\n const moduleScripts = indexHtml.match(\n /<script\\b[^>]*\\btype=(['\"])module\\1[^>]*>\\s*<\\/script>/gi\n );\n for (const script of moduleScripts ?? []) {\n const source = script.match(/\\bsrc=(['\"])([^'\"]+)\\1/i)?.[2];\n if (source) return { script, source };\n }\n\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No Vite module entry was found in index.html',\n fix: 'Add a module script for the app entry and rerun `npx gt@latest`',\n })\n );\n}\n\n/**\n * Reads the Vite entry and bootstrap without writing, so setup can report an\n * unsupported layout before changing any file.\n */\nexport async function inspectViteSPA(appDirectory: string) {\n const indexHtmlPath = path.join(appDirectory, 'index.html');\n const sourceDirectory = path.join(appDirectory, 'src');\n const indexHtml = await fs.promises.readFile(indexHtmlPath, 'utf8');\n const { script, source } = getModuleEntry(indexHtml);\n const declaredEntryPath = getEntryPath(appDirectory, source);\n const declaredEntryImport = toRelativeImport(\n sourceDirectory,\n declaredEntryPath\n ).replace(/\\.(?:[cm]?[jt]sx?)$/i, '');\n const configuredBootstrap = source.match(\n /^\\/?src\\/(gt-entry\\.ts|gt-bootstrap\\.ts)(?:[?#].*)?$/\n )?.[1];\n let customBootstrap: string | undefined;\n if (!configuredBootstrap && fs.existsSync(declaredEntryPath)) {\n const entry = await fs.promises.readFile(declaredEntryPath, 'utf8');\n const mentionsInitializer = entry.includes('initializeGTSPA');\n // Unparseable entries fall back to the text check: a false positive only\n // asks for manual review, while a miss would initialize GT twice.\n const importsInitializer =\n parseModule(entry, declaredEntryPath)?.some(\n (statement) =>\n statement.type === 'ImportDeclaration' &&\n statement.source.value === Libraries.GT_REACT &&\n statement.importKind !== 'type' &&\n statement.specifiers.some(\n (specifier) =>\n (specifier.type === 'ImportNamespaceSpecifier' &&\n mentionsInitializer) ||\n (specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type' &&\n specifier.imported.type === 'Identifier' &&\n specifier.imported.name === 'initializeGTSPA')\n )\n ) ?? mentionsInitializer;\n if (importsInitializer) {\n customBootstrap = path.relative(appDirectory, declaredEntryPath);\n }\n }\n const isAlreadyConfigured = configuredBootstrap !== undefined;\n const bootstrapFilename =\n configuredBootstrap ??\n (declaredEntryImport === './gt-entry'\n ? alternateBootstrapFilename\n : defaultBootstrapFilename);\n const bootstrapPath = path.join(sourceDirectory, bootstrapFilename);\n let existingBootstrap: string | undefined;\n\n if (!customBootstrap && fs.existsSync(bootstrapPath)) {\n existingBootstrap = await fs.promises.readFile(bootstrapPath, 'utf8');\n if (!existingBootstrap.includes('initializeGTSPA')) {\n throw new Error(getBootstrapConflictError(bootstrapFilename));\n }\n }\n\n const entryImport = isAlreadyConfigured\n ? existingBootstrap && getBootstrapEntry(existingBootstrap)\n : declaredEntryImport;\n if (!entryImport) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The existing Vite bootstrap has no app entry import',\n fix: 'Restore the app entry import and rerun `npx gt@latest`',\n })\n );\n }\n return {\n indexHtmlPath,\n sourceDirectory,\n indexHtml,\n script,\n source,\n isAlreadyConfigured,\n customBootstrap,\n bootstrapFilename,\n bootstrapPath,\n entryImport,\n };\n}\n\nexport type ViteLoaderResult = 'written' | 'custom' | 'missing';\n\n/**\n * Points the generated src/loadTranslations.ts at translationsDir and adds\n * empty locale stubs. Only a template matching the previous config is\n * refreshed; other existing loaders are left unchanged. An absent loader\n * is only created with `create`.\n */\nexport async function writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create,\n}: Omit<SetupViteSPAOptions, 'configFilepath' | 'translationsDir'> & {\n translationsDir: string;\n create: boolean;\n}): Promise<ViteLoaderResult> {\n const sourceDirectory = path.join(appDirectory, 'src');\n const translationsPath = path.resolve(appDirectory, translationsDir);\n const loaderPath = path.join(sourceDirectory, 'loadTranslations.ts');\n const existingLoader = fs.existsSync(loaderPath)\n ? await fs.promises.readFile(loaderPath, 'utf8')\n : undefined;\n if (existingLoader === undefined && !create) return 'missing';\n const content = getLoaderContent(\n toRelativeImport(sourceDirectory, translationsPath)\n );\n const previousContent =\n previousTranslationsDir === undefined\n ? undefined\n : getLoaderContent(\n toRelativeImport(\n sourceDirectory,\n path.resolve(appDirectory, previousTranslationsDir)\n )\n );\n const normalizedLoader = existingLoader?.replace(/\\r\\n/g, '\\n').trimEnd();\n const custom =\n existingLoader !== undefined &&\n normalizedLoader !== content.trimEnd() &&\n normalizedLoader !== previousContent?.trimEnd();\n\n // Stubs first, so a directory failure leaves no loader pointing at it.\n await fs.promises.mkdir(translationsPath, { recursive: true });\n for (const locale of new Set(locales)) {\n if (locale === defaultLocale) continue;\n const stubPath = path.join(translationsPath, `${locale}.json`);\n if (!fs.existsSync(stubPath)) {\n await fs.promises.writeFile(stubPath, '{}\\n');\n }\n }\n if (custom) return 'custom';\n await fs.promises.writeFile(loaderPath, content);\n return 'written';\n}\n\nfunction getLoaderExport(\n content: string\n): 'default' | 'loadTranslations' | undefined {\n const statements = parseModule(content, 'loadTranslations.ts');\n if (!statements) return undefined;\n const names = new Set<string>();\n for (const statement of statements) {\n // @babel/types omits the interface form the parser emits, which is erased\n // at compile time and leaves no runtime default export.\n if (\n statement.type === 'ExportDefaultDeclaration' &&\n (statement.declaration.type as string) !== 'TSInterfaceDeclaration'\n )\n names.add('default');\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.exportKind === 'type'\n )\n continue;\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exportKind !== 'type'\n ) {\n names.add(\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value\n );\n }\n }\n const declaration = statement.declaration;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n !declaration.declare &&\n declaration.id\n ) {\n names.add(declaration.id.name);\n }\n if (declaration?.type === 'VariableDeclaration' && !declaration.declare) {\n for (const variable of declaration.declarations) {\n if (variable.id.type === 'Identifier') names.add(variable.id.name);\n }\n }\n }\n if (names.has('default')) return 'default';\n if (names.has('loadTranslations')) return 'loadTranslations';\n return undefined;\n}\n\nexport async function setupViteSPA({\n appDirectory,\n configFilepath,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n}: SetupViteSPAOptions): Promise<{\n loader?: ViteLoaderResult;\n manualAction?: string;\n}> {\n const {\n indexHtmlPath,\n sourceDirectory,\n indexHtml,\n script,\n source,\n isAlreadyConfigured,\n customBootstrap,\n bootstrapFilename,\n bootstrapPath,\n entryImport,\n } = await inspectViteSPA(appDirectory);\n\n // An app-owned initializer may have custom imports and options. Nesting a\n // generated initializer around it would initialize GT twice.\n if (customBootstrap) {\n return {\n manualAction: `Verify the existing GT bootstrap ${customBootstrap} uses ${configFilepath}${translationsDir ? ` and loads translations from ${translationsDir}` : ' with CDN loading'}`,\n };\n }\n\n await fs.promises.mkdir(sourceDirectory, { recursive: true });\n\n let loadTranslationsImport = '';\n let loadTranslationsOption = 'gtConfig';\n let loader: ViteLoaderResult | undefined;\n if (translationsDir) {\n loader = await writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create: true,\n });\n const loaderExport =\n loader === 'custom'\n ? getLoaderExport(\n await fs.promises.readFile(\n path.join(sourceDirectory, 'loadTranslations.ts'),\n 'utf8'\n )\n )\n : 'default';\n if (!loaderExport) {\n return {\n loader,\n manualAction: `Update your custom src/loadTranslations.ts to load translations from ${translationsDir} and export a default or named loadTranslations function, then rerun gt init`,\n };\n }\n loadTranslationsImport =\n loaderExport === 'default'\n ? \"import loadTranslations from './loadTranslations';\\n\"\n : \"import { loadTranslations } from './loadTranslations';\\n\";\n loadTranslationsOption = '{ ...gtConfig, loadTranslations }';\n }\n\n const configImport = toRelativeImport(\n sourceDirectory,\n path.resolve(appDirectory, configFilepath)\n );\n await fs.promises.writeFile(\n bootstrapPath,\n `import { initializeGTSPA } from '${Libraries.GT_REACT}';\nimport gtConfig from '${configImport}';\n${loadTranslationsImport}\nawait initializeGTSPA(${loadTranslationsOption});\n\nawait import('${entryImport}');\n`\n );\n\n if (!isAlreadyConfigured) {\n const updatedScript = script.replace(source, `/src/${bootstrapFilename}`);\n await fs.promises.writeFile(\n indexHtmlPath,\n indexHtml.replace(script, updatedScript)\n );\n }\n\n logger.success('Configured initializeGTSPA for this Vite application.');\n return {\n loader,\n ...(loader === 'custom' && {\n manualAction: `Verify your preserved custom src/loadTranslations.ts loads translations from ${translationsDir}`,\n }),\n };\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;AAEnC,SAAS,0BAA0B,UAA0B;AAC3D,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc;EACd,KAAK,yCAAyC,SAAS;EACvD,KAAK;EACN,CAAC;;AAGJ,SAAS,iBAAiB,oBAAoC;AAC5D,QAAO;wCAC+B,mBAAmB;;;;;;;;;AAU3D,SAAS,YAAY,SAAiB,UAAkB;AACtD,KAAI;AACF,SAAO,MAAM,SAAS;GACpB,YAAY;GAEZ,SAAS,cAAc,KAAK,SAAS,GACjC,CAAC,aAAa,GACd,CAAC,cAAc,MAAM;GAC1B,CAAC,CAAC,QAAQ;SACL;AACN;;;AAIJ,SAAS,i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AAGH,QAAO,QAAQ,wDAAwD;AACvE,QAAO;EACL;EACA,GAAI,WAAW,YAAY,EACzB,cAAc,gFAAgF,mBAC/F;EACF"}
1
+ {"version":3,"file":"setupViteSPA.js","names":[],"sources":["../../src/setup/setupViteSPA.ts"],"sourcesContent":["import { parse } from '@babel/parser';\nimport { createDiagnosticMessage } from 'generaltranslation/diagnostics';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { logger } from '../console/logger.js';\nimport { Libraries } from '../types/libraries.js';\n\ntype SetupViteSPAOptions = {\n appDirectory: string;\n configFilepath: string;\n defaultLocale: string;\n locales: string[];\n translationsDir?: string;\n previousTranslationsDir?: string;\n};\n\nconst defaultBootstrapFilename = 'gt-entry.ts';\nconst alternateBootstrapFilename = 'gt-bootstrap.ts';\n\nfunction getBootstrapConflictError(filename: string): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The Vite bootstrap file already exists',\n why: `GT will not overwrite an existing src/${filename} file`,\n fix: 'Move or rename that file and rerun `npx gt@latest`',\n });\n}\n\nfunction getLoaderContent(translationsImport: string): string {\n return `export default async function loadTranslations(locale: string) {\n const translations = await import(\\`${translationsImport}/\\${locale}.json\\`);\n return translations.default;\n}\n`;\n}\n\n/**\n * Top-level statements, or undefined for syntax this inspector cannot parse\n * but Vite may accept, such as decorators.\n */\nexport function parseModule(content: string, filename: string) {\n try {\n return parse(content, {\n sourceType: 'module',\n // JSX would reject `<T>x` assertions, which .ts files may use.\n plugins: /\\.[cm]?ts$/i.test(filename)\n ? ['typescript']\n : ['typescript', 'jsx'],\n }).program.body;\n } catch {\n return undefined;\n }\n}\n\nexport function toRelativeImport(\n fromDirectory: string,\n toPath: string\n): string {\n const relativePath = path\n .relative(fromDirectory, toPath)\n .split(path.sep)\n .join(path.posix.sep);\n return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;\n}\n\nfunction getEntryPath(appDirectory: string, source: string): string {\n const sourcePath = source.replace(/[?#].*$/, '');\n return sourcePath.startsWith('/')\n ? path.resolve(appDirectory, `.${sourcePath}`)\n : path.resolve(appDirectory, sourcePath);\n}\n\nfunction getBootstrapEntry(bootstrap: string): string | undefined {\n return bootstrap.match(/await\\s+import\\(\\s*(['\"])([^'\"]+)\\1\\s*\\)/)?.[2];\n}\n\nfunction getModuleEntry(indexHtml: string): {\n script: string;\n source: string;\n} {\n const moduleScripts = indexHtml.match(\n /<script\\b[^>]*\\btype=(['\"])module\\1[^>]*>\\s*<\\/script>/gi\n );\n for (const script of moduleScripts ?? []) {\n const source = script.match(/\\bsrc=(['\"])([^'\"]+)\\1/i)?.[2];\n if (source) return { script, source };\n }\n\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'No Vite module entry was found in index.html',\n fix: 'Add a module script for the app entry and rerun `npx gt@latest`',\n })\n );\n}\n\n/**\n * Reads the Vite entry and bootstrap without writing, so setup can report an\n * unsupported layout before changing any file.\n */\nexport async function inspectViteSPA(appDirectory: string) {\n const indexHtmlPath = path.join(appDirectory, 'index.html');\n const sourceDirectory = path.join(appDirectory, 'src');\n if (!fs.existsSync(indexHtmlPath)) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'This is not a Vite single-page app',\n why: 'index.html was not found',\n reassurance: 'Nothing was changed',\n fix: 'Rerun `npx gt@latest init` with `--framework` set to your framework, or set up GT manually',\n })\n );\n }\n const indexHtml = await fs.promises.readFile(indexHtmlPath, 'utf8');\n const { script, source } = getModuleEntry(indexHtml);\n const declaredEntryPath = getEntryPath(appDirectory, source);\n const declaredEntryImport = toRelativeImport(\n sourceDirectory,\n declaredEntryPath\n ).replace(/\\.(?:[cm]?[jt]sx?)$/i, '');\n const configuredBootstrap = source.match(\n /^\\/?src\\/(gt-entry\\.ts|gt-bootstrap\\.ts)(?:[?#].*)?$/\n )?.[1];\n let customBootstrap: string | undefined;\n if (!configuredBootstrap && fs.existsSync(declaredEntryPath)) {\n const entry = await fs.promises.readFile(declaredEntryPath, 'utf8');\n const mentionsInitializer = entry.includes('initializeGTSPA');\n // Unparseable entries fall back to the text check: a false positive only\n // asks for manual review, while a miss would initialize GT twice.\n const importsInitializer =\n parseModule(entry, declaredEntryPath)?.some(\n (statement) =>\n statement.type === 'ImportDeclaration' &&\n statement.source.value === Libraries.GT_REACT &&\n statement.importKind !== 'type' &&\n statement.specifiers.some(\n (specifier) =>\n (specifier.type === 'ImportNamespaceSpecifier' &&\n mentionsInitializer) ||\n (specifier.type === 'ImportSpecifier' &&\n specifier.importKind !== 'type' &&\n specifier.imported.type === 'Identifier' &&\n specifier.imported.name === 'initializeGTSPA')\n )\n ) ?? mentionsInitializer;\n if (importsInitializer) {\n customBootstrap = path.relative(appDirectory, declaredEntryPath);\n }\n }\n const isAlreadyConfigured = configuredBootstrap !== undefined;\n const bootstrapFilename =\n configuredBootstrap ??\n (declaredEntryImport === './gt-entry'\n ? alternateBootstrapFilename\n : defaultBootstrapFilename);\n const bootstrapPath = path.join(sourceDirectory, bootstrapFilename);\n let existingBootstrap: string | undefined;\n\n if (!customBootstrap && fs.existsSync(bootstrapPath)) {\n existingBootstrap = await fs.promises.readFile(bootstrapPath, 'utf8');\n if (!existingBootstrap.includes('initializeGTSPA')) {\n throw new Error(getBootstrapConflictError(bootstrapFilename));\n }\n }\n\n const entryImport = isAlreadyConfigured\n ? existingBootstrap && getBootstrapEntry(existingBootstrap)\n : declaredEntryImport;\n if (!entryImport) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'The existing Vite bootstrap has no app entry import',\n fix: 'Restore the app entry import and rerun `npx gt@latest`',\n })\n );\n }\n return {\n indexHtmlPath,\n sourceDirectory,\n indexHtml,\n script,\n source,\n isAlreadyConfigured,\n customBootstrap,\n bootstrapFilename,\n bootstrapPath,\n entryImport,\n };\n}\n\nexport type ViteLoaderResult =\n | 'created'\n | 'updated'\n | 'unchanged'\n | 'custom'\n | 'missing';\n\n/**\n * Points the generated src/loadTranslations.ts at translationsDir and adds\n * empty locale stubs. Only a template matching the previous config is\n * refreshed; other existing loaders are left unchanged. An absent loader\n * is only created with `create`.\n */\nexport async function writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create,\n}: Omit<SetupViteSPAOptions, 'configFilepath' | 'translationsDir'> & {\n translationsDir: string;\n create: boolean;\n}): Promise<ViteLoaderResult> {\n const sourceDirectory = path.join(appDirectory, 'src');\n const translationsPath = path.resolve(appDirectory, translationsDir);\n const loaderPath = path.join(sourceDirectory, 'loadTranslations.ts');\n const existingLoader = fs.existsSync(loaderPath)\n ? await fs.promises.readFile(loaderPath, 'utf8')\n : undefined;\n if (existingLoader === undefined && !create) return 'missing';\n const content = getLoaderContent(\n toRelativeImport(sourceDirectory, translationsPath)\n );\n const previousContent =\n previousTranslationsDir === undefined\n ? undefined\n : getLoaderContent(\n toRelativeImport(\n sourceDirectory,\n path.resolve(appDirectory, previousTranslationsDir)\n )\n );\n const normalizedLoader = existingLoader?.replace(/\\r\\n/g, '\\n').trimEnd();\n const custom =\n existingLoader !== undefined &&\n normalizedLoader !== content.trimEnd() &&\n normalizedLoader !== previousContent?.trimEnd();\n\n // Stubs first, so a directory failure leaves no loader pointing at it.\n await fs.promises.mkdir(translationsPath, { recursive: true });\n for (const locale of new Set(locales)) {\n if (locale === defaultLocale) continue;\n const stubPath = path.join(translationsPath, `${locale}.json`);\n if (!fs.existsSync(stubPath)) {\n await fs.promises.writeFile(stubPath, '{}\\n');\n }\n }\n if (custom) return 'custom';\n if (existingLoader === content) return 'unchanged';\n await fs.promises.writeFile(loaderPath, content);\n return existingLoader === undefined ? 'created' : 'updated';\n}\n\nexport type ViteLoaderExport = 'default' | 'loadTranslations' | undefined;\n\n/** The generated loader's export, or a custom loader's own if it has one. */\nexport async function getViteLoaderExport(\n appDirectory: string,\n loader: ViteLoaderResult\n): Promise<ViteLoaderExport> {\n return loader === 'custom'\n ? getLoaderExport(\n await fs.promises.readFile(\n path.join(appDirectory, 'src', 'loadTranslations.ts'),\n 'utf8'\n )\n )\n : 'default';\n}\n\nfunction getLoaderExport(content: string): ViteLoaderExport {\n const statements = parseModule(content, 'loadTranslations.ts');\n if (!statements) return undefined;\n const names = new Set<string>();\n for (const statement of statements) {\n // @babel/types omits the interface form the parser emits, which is erased\n // at compile time and leaves no runtime default export.\n if (\n statement.type === 'ExportDefaultDeclaration' &&\n (statement.declaration.type as string) !== 'TSInterfaceDeclaration'\n )\n names.add('default');\n if (\n statement.type !== 'ExportNamedDeclaration' ||\n statement.exportKind === 'type'\n )\n continue;\n for (const specifier of statement.specifiers) {\n if (\n specifier.type === 'ExportSpecifier' &&\n specifier.exportKind !== 'type'\n ) {\n names.add(\n specifier.exported.type === 'Identifier'\n ? specifier.exported.name\n : specifier.exported.value\n );\n }\n }\n const declaration = statement.declaration;\n if (\n declaration?.type === 'FunctionDeclaration' &&\n !declaration.declare &&\n declaration.id\n ) {\n names.add(declaration.id.name);\n }\n if (declaration?.type === 'VariableDeclaration' && !declaration.declare) {\n for (const variable of declaration.declarations) {\n if (variable.id.type === 'Identifier') names.add(variable.id.name);\n }\n }\n }\n if (names.has('default')) return 'default';\n if (names.has('loadTranslations')) return 'loadTranslations';\n return undefined;\n}\n\nexport async function setupViteSPA({\n appDirectory,\n configFilepath,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n}: SetupViteSPAOptions): Promise<{\n loader?: ViteLoaderResult;\n manualAction?: string;\n}> {\n const {\n indexHtmlPath,\n sourceDirectory,\n indexHtml,\n script,\n source,\n isAlreadyConfigured,\n customBootstrap,\n bootstrapFilename,\n bootstrapPath,\n entryImport,\n } = await inspectViteSPA(appDirectory);\n\n // An app-owned initializer may have custom imports and options. Nesting a\n // generated initializer around it would initialize GT twice.\n if (customBootstrap) {\n return {\n manualAction: `Verify the existing GT bootstrap ${customBootstrap} uses ${configFilepath}${translationsDir ? ` and loads translations from ${translationsDir}` : ' with CDN loading'}`,\n };\n }\n\n await fs.promises.mkdir(sourceDirectory, { recursive: true });\n\n let loadTranslationsImport = '';\n let loadTranslationsOption = 'gtConfig';\n let loader: ViteLoaderResult | undefined;\n if (translationsDir) {\n loader = await writeViteLoader({\n appDirectory,\n defaultLocale,\n locales,\n translationsDir,\n previousTranslationsDir,\n create: true,\n });\n const loaderExport = await getViteLoaderExport(appDirectory, loader);\n if (!loaderExport) {\n return {\n loader,\n manualAction: `Update your custom src/loadTranslations.ts to load translations from ${translationsDir} and export a default or named loadTranslations function, then rerun gt init`,\n };\n }\n loadTranslationsImport =\n loaderExport === 'default'\n ? \"import loadTranslations from './loadTranslations';\\n\"\n : \"import { loadTranslations } from './loadTranslations';\\n\";\n loadTranslationsOption = '{ ...gtConfig, loadTranslations }';\n }\n\n const configImport = toRelativeImport(\n sourceDirectory,\n path.resolve(appDirectory, configFilepath)\n );\n await fs.promises.writeFile(\n bootstrapPath,\n `import { initializeGTSPA } from '${Libraries.GT_REACT}';\nimport gtConfig from '${configImport}';\n${loadTranslationsImport}\nawait initializeGTSPA(${loadTranslationsOption});\n\nawait import('${entryImport}');\n`\n );\n\n if (!isAlreadyConfigured) {\n const updatedScript = script.replace(source, `/src/${bootstrapFilename}`);\n await fs.promises.writeFile(\n indexHtmlPath,\n indexHtml.replace(script, updatedScript)\n );\n }\n\n logger.success('Configured initializeGTSPA for this Vite application.');\n return {\n loader,\n ...(loader === 'custom' && {\n manualAction: `Verify your preserved custom src/loadTranslations.ts loads translations from ${translationsDir}`,\n }),\n };\n}\n"],"mappings":";;;;;;;AAgBA,MAAM,2BAA2B;AACjC,MAAM,6BAA6B;AAEnC,SAAS,0BAA0B,UAA0B;AAC3D,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV,cAAc;EACd,KAAK,yCAAyC,SAAS;EACvD,KAAK;EACN,CAAC;;AAGJ,SAAS,iBAAiB,oBAAoC;AAC5D,QAAO;wCAC+B,mBAAmB;;;;;;;;;AAU3D,SAAgB,YAA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T,CAAC;EACF,MAAM,eAAe,MAAM,oBAAoB,cAAc,OAAO;AACpE,MAAI,CAAC,aACH,QAAO;GACL;GACA,cAAc,wEAAwE,gBAAgB;GACvG;AAEH,2BACE,iBAAiB,YACb,yDACA;AACN,2BAAyB;;CAG3B,MAAM,eAAe,iBACnB,iBACA,KAAK,QAAQ,cAAc,eAAe,CAC3C;AACD,OAAM,GAAG,SAAS,UAChB,eACA;wBACoB,aAAa;EACnC,uBAAuB;wBACD,uBAAuB;;gBAE/B,YAAY;EAEzB;AAED,KAAI,CAAC,qBAAqB;EACxB,MAAM,gBAAgB,OAAO,QAAQ,QAAQ,QAAQ,oBAAoB;AACzE,QAAM,GAAG,SAAS,UAChB,eACA,UAAU,QAAQ,QAAQ,cAAc,CACzC;;AAGH,QAAO,QAAQ,wDAAwD;AACvE,QAAO;EACL;EACA,GAAI,WAAW,YAAY,EACzB,cAAc,gFAAgF,mBAC/F;EACF"}
@@ -1,5 +1,6 @@
1
1
  import { logger } from "../console/logger.js";
2
2
  import { getPackageJson, isPackageInstalled } from "../utils/packageJson.js";
3
+ import "../utils/constants.js";
3
4
  import "../types/libraries.js";
4
5
  import { exitSync, promptConfirm, promptSelect } from "../console/logging.js";
5
6
  import findFilepath from "../fs/findFilepath.js";
@@ -8,6 +9,7 @@ import { detectFormatter, formatFiles } from "../hooks/postProcess.js";
8
9
  import { handleInitGT } from "../next/parse/handleInitGT.js";
9
10
  import { wrapContentNext } from "../next/parse/wrapContent.js";
10
11
  import { getFrameworkDisplayName, getReactFrameworkLibrary } from "./frameworkUtils.js";
12
+ import { getBuildToolSetup } from "./buildTools/index.js";
11
13
  import chalk from "chalk";
12
14
  import { createDiagnosticMessage } from "generaltranslation/internal";
13
15
  //#region src/setup/wizard.ts
@@ -18,12 +20,14 @@ const cancelledMessage = "Operation cancelled. You can re-run this wizard with:
18
20
  */
19
21
  async function resolveReactSetup(session, options, detected, configuredFramework) {
20
22
  const library = getReactFrameworkLibrary(detected);
23
+ const buildTool = getBuildToolSetup(detected.name);
24
+ const initializer = buildTool?.initializer;
21
25
  if (!await session.answer("--react-setup", {
22
26
  explicit: options.reactSetup,
23
27
  recommended: true,
24
28
  ask: async () => {
25
29
  const answer = await promptConfirm({
26
- message: detected.name === "vite" ? `Would you like to install ${library} and configure initializeGTSPA? See the docs for more information: https://generaltranslation.com/docs/react/tutorials/quickstart` : `Would you like to install ${library} and add the GTProvider? See the docs for more information: https://generaltranslation.com/docs/react/tutorials/quickstart`,
30
+ message: `Would you like to install ${library} and ${initializer ? `configure ${initializer}` : "add the GTProvider"}? See the docs for more information: ${buildTool?.docsUrl ?? "https://generaltranslation.com/docs/react/tutorials/quickstart"}`,
27
31
  defaultValue: true
28
32
  });
29
33
  if (answer && !await promptConfirm({
@@ -70,6 +74,10 @@ Make sure you have committed or stashed any changes. Do you want to continue?`),
70
74
  value: "redwood",
71
75
  label: chalk.red("RedwoodJS")
72
76
  },
77
+ {
78
+ value: "tanstack-start",
79
+ label: chalk.cyan("TanStack Start")
80
+ },
73
81
  {
74
82
  value: "other",
75
83
  label: chalk.dim("Other")
@@ -89,7 +97,10 @@ Please let us know what you would like to see added at https://github.com/genera
89
97
  session.reject("No package.json found in the current directory. Run this command from the root of your project");
90
98
  return;
91
99
  }
92
- const install = framework === "next-app" ? "gt-next" : "gt-react";
100
+ const install = getReactFrameworkLibrary({
101
+ name: framework,
102
+ type: "react"
103
+ });
93
104
  const plan = {
94
105
  framework,
95
106
  packageJson,
@@ -1 +1 @@
1
- {"version":3,"file":"wizard.js","names":[],"sources":["../../src/setup/wizard.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { detectFormatter, formatFiles } from '../hooks/postProcess.js';\nimport type { Formatter } from '../hooks/postProcess.js';\nimport { exitSync, promptConfirm, promptSelect } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport type {\n ReactFrameworkObject,\n SupportedReactFrameworks,\n} from '../types/index.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport { handleInitGT } from '../next/parse/handleInitGT.js';\nimport { getPackageJson, isPackageInstalled } from '../utils/packageJson.js';\nimport { wrapContentNext } from '../next/parse/wrapContent.js';\nimport { loadConfig } from '../fs/config/loadConfig.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport { Libraries } from '../types/libraries.js';\nimport type { InitOptions, OnboardingSession } from './onboarding.js';\n\n/** Everything the React application setup will do, resolved before changes. */\nexport type ReactSetupPlan = {\n framework: SupportedReactFrameworks;\n packageJson: Record<string, unknown>;\n /** GT library to install, when it is not installed yet. */\n install?: string;\n nextConfigPath?: string;\n formatter?: Formatter;\n};\n\nconst cancelledMessage =\n 'Operation cancelled. You can re-run this wizard with: npx gt init';\n\n/**\n * Resolves whether and how to set up the React application. Returns\n * undefined when the setup is declined or an answer is still missing.\n */\nexport async function resolveReactSetup(\n session: OnboardingSession,\n options: InitOptions,\n detected: ReactFrameworkObject,\n configuredFramework?: SupportedReactFrameworks\n): Promise<ReactSetupPlan | undefined> {\n const library = getReactFrameworkLibrary(detected);\n const setupApp = await session.answer('--react-setup', {\n explicit: options.reactSetup,\n recommended: true,\n ask: async () => {\n const answer = await promptConfirm({\n message:\n detected.name === 'vite'\n ? `Would you like to install ${library} and configure initializeGTSPA? See the docs for more information: https://generaltranslation.com/docs/react/tutorials/quickstart`\n : `Would you like to install ${library} and add the GTProvider? See the docs for more information: https://generaltranslation.com/docs/react/tutorials/quickstart`,\n defaultValue: true,\n });\n // A prompted opt-in gets a last warning; flags and defaults already chose.\n if (\n answer &&\n !(await promptConfirm({\n message: chalk.yellow(\n `This wizard will configure your ${getFrameworkDisplayName(detected)} project for internationalization with GT. If your project is already using a different i18n library, this wizard may cause issues.\n\nMake sure you have committed or stashed any changes. Do you want to continue?`\n ),\n defaultValue: true,\n cancelMessage: cancelledMessage,\n }))\n ) {\n logger.info(cancelledMessage);\n return exitSync(0);\n }\n return answer;\n },\n });\n if (!setupApp) return undefined;\n\n const framework = await session.answer<SupportedReactFrameworks | 'other'>(\n '--framework',\n {\n explicit: options.framework,\n configured: configuredFramework,\n recommended: detected.name,\n ask: () =>\n promptSelect<SupportedReactFrameworks | 'other'>({\n message: 'Which framework are you using?',\n options: [\n { value: 'next-app', label: chalk.blue('Next.js App Router') },\n { value: 'next-pages', label: chalk.green('Next.js Pages Router') },\n { value: 'vite', label: chalk.cyan('Vite + React') },\n { value: 'gatsby', label: chalk.magenta('Gatsby') },\n { value: 'react', label: chalk.yellow('React') },\n { value: 'redwood', label: chalk.red('RedwoodJS') },\n { value: 'other', label: chalk.dim('Other') },\n ],\n defaultValue: detected.name,\n }),\n }\n );\n if (framework === 'other') {\n logger.error(\n `Sorry, the wizard doesn't currently support other React frameworks.\nPlease let us know what you would like to see added at https://github.com/generaltranslation/gt/issues`\n );\n return exitSync(0);\n }\n if (!framework) return undefined;\n\n const packageJson = await getPackageJson();\n if (!packageJson) {\n session.reject(\n 'No package.json found in the current directory. Run this command from the root of your project'\n );\n return undefined;\n }\n const install =\n framework === 'next-app' ? Libraries.GT_NEXT : Libraries.GT_REACT;\n const plan: ReactSetupPlan = {\n framework,\n packageJson,\n install: isPackageInstalled(install, packageJson) ? undefined : install,\n };\n\n if (framework === 'next-app') {\n plan.nextConfigPath = findFilepath([\n './next.config.js',\n './next.config.ts',\n './next.config.mjs',\n './next.config.mts',\n ]);\n if (!plan.nextConfigPath) {\n session.reject('No next.config.[js|ts|mjs|mts] file found');\n }\n const formatter = await detectFormatter();\n if (\n formatter &&\n (await session.answer('--format', {\n explicit: options.format,\n recommended: true,\n ask: () =>\n promptConfirm({\n message: `Would you like the wizard to auto-format the modified files? ${chalk.dim(\n `(${formatter})`\n )}`,\n defaultValue: true,\n }),\n }))\n ) {\n plan.formatter = formatter;\n }\n }\n return plan;\n}\n\n/** Wraps Next.js App Router content and adds withGTConfig(); installs happen first. */\nexport async function executeReactSetup(\n session: OnboardingSession,\n plan: ReactSetupPlan,\n options: InitOptions\n): Promise<void> {\n if (plan.framework !== 'next-app' || !plan.nextConfigPath) return;\n\n const errors: string[] = [];\n const warnings: string[] = [];\n const spinner = logger.createSpinner();\n spinner.start('Wrapping JSX content with <T> tags...');\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated } = await wrapContentNext(\n {\n ...options,\n disableIds: true,\n disableFormatting: true,\n skipTs: true,\n addGTProvider: true,\n },\n Libraries.GT_NEXT,\n errors,\n warnings\n );\n spinner.stop(\n chalk.green(\n `Success! Updated ${chalk.bold.cyan(filesUpdated.length)} files:\\n`\n ) + filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\\n')\n );\n if (filesUpdated.length > 0) session.step('wrapped JSX content');\n\n // Add the withGTConfig() function to the next.config.js file\n const tsconfigPath = findFilepath(['tsconfig.json']);\n await handleInitGT(\n plan.nextConfigPath,\n errors,\n warnings,\n filesUpdated,\n plan.packageJson,\n tsconfigPath ? loadConfig(tsconfigPath) : undefined\n );\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow('Warnings encountered:') +\n '\\n' +\n warnings.map((warning) => `${chalk.yellow('-')} ${warning}`).join('\\n')\n );\n }\n if (errors.length > 0) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'Setup could not update some application files',\n details: errors,\n fix: 'Fix the reported files, then rerun `npx gt init`',\n })\n );\n }\n logger.step(\n chalk.green(`Added withGTConfig() to your ${plan.nextConfigPath} file.`)\n );\n session.step(`added withGTConfig() to ${plan.nextConfigPath}`);\n\n if (plan.formatter) await formatFiles(filesUpdated, plan.formatter);\n}\n"],"mappings":";;;;;;;;;;;;;AAgCA,MAAM,mBACJ;;;;;AAMF,eAAsB,kBACpB,SACA,SACA,UACA,qBACqC;CACrC,MAAM,UAAU,yBAAyB,SAAS;AA+BlD,KAAI,CAAC,MA9BkB,QAAQ,OAAO,iBAAiB;EACrD,UAAU,QAAQ;EAClB,aAAa;EACb,KAAK,YAAY;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SAAS,EAClB,OAAM,IAAI,MACR,wBAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAAS;EACT,KAAK;EACN,CAAC,CACH;AAEH,QAAO,KACL,MAAM,MAAM,gCAAgC,KAAK,eAAe,QAAQ,CACzE;AACD,SAAQ,KAAK,2BAA2B,KAAK,iBAAiB;AAE9D,KAAI,KAAK,UAAW,OAAM,YAAY,cAAc,KAAK,UAAU"}
1
+ {"version":3,"file":"wizard.js","names":[],"sources":["../../src/setup/wizard.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { createDiagnosticMessage } from 'generaltranslation/internal';\nimport { detectFormatter, formatFiles } from '../hooks/postProcess.js';\nimport type { Formatter } from '../hooks/postProcess.js';\nimport { exitSync, promptConfirm, promptSelect } from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport type {\n ReactFrameworkObject,\n SupportedReactFrameworks,\n} from '../types/index.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport { handleInitGT } from '../next/parse/handleInitGT.js';\nimport { getPackageJson, isPackageInstalled } from '../utils/packageJson.js';\nimport { wrapContentNext } from '../next/parse/wrapContent.js';\nimport { loadConfig } from '../fs/config/loadConfig.js';\nimport {\n getFrameworkDisplayName,\n getReactFrameworkLibrary,\n} from './frameworkUtils.js';\nimport { Libraries } from '../types/libraries.js';\nimport { getBuildToolSetup } from './buildTools/index.js';\nimport { REACT_QUICKSTART_URL } from '../utils/constants.js';\nimport type { InitOptions, OnboardingSession } from './onboarding.js';\n\n/** Everything the React application setup will do, resolved before changes. */\nexport type ReactSetupPlan = {\n framework: SupportedReactFrameworks;\n packageJson: Record<string, unknown>;\n /** GT library to install, when it is not installed yet. */\n install?: string;\n nextConfigPath?: string;\n formatter?: Formatter;\n};\n\nconst cancelledMessage =\n 'Operation cancelled. You can re-run this wizard with: npx gt init';\n\n/**\n * Resolves whether and how to set up the React application. Returns\n * undefined when the setup is declined or an answer is still missing.\n */\nexport async function resolveReactSetup(\n session: OnboardingSession,\n options: InitOptions,\n detected: ReactFrameworkObject,\n configuredFramework?: SupportedReactFrameworks\n): Promise<ReactSetupPlan | undefined> {\n const library = getReactFrameworkLibrary(detected);\n const buildTool = getBuildToolSetup(detected.name);\n const initializer = buildTool?.initializer;\n const setupApp = await session.answer('--react-setup', {\n explicit: options.reactSetup,\n recommended: true,\n ask: async () => {\n const answer = await promptConfirm({\n message: `Would you like to install ${library} and ${initializer ? `configure ${initializer}` : 'add the GTProvider'}? See the docs for more information: ${buildTool?.docsUrl ?? REACT_QUICKSTART_URL}`,\n defaultValue: true,\n });\n // A prompted opt-in gets a last warning; flags and defaults already chose.\n if (\n answer &&\n !(await promptConfirm({\n message: chalk.yellow(\n `This wizard will configure your ${getFrameworkDisplayName(detected)} project for internationalization with GT. If your project is already using a different i18n library, this wizard may cause issues.\n\nMake sure you have committed or stashed any changes. Do you want to continue?`\n ),\n defaultValue: true,\n cancelMessage: cancelledMessage,\n }))\n ) {\n logger.info(cancelledMessage);\n return exitSync(0);\n }\n return answer;\n },\n });\n if (!setupApp) return undefined;\n\n const framework = await session.answer<SupportedReactFrameworks | 'other'>(\n '--framework',\n {\n explicit: options.framework,\n configured: configuredFramework,\n recommended: detected.name,\n ask: () =>\n promptSelect<SupportedReactFrameworks | 'other'>({\n message: 'Which framework are you using?',\n options: [\n { value: 'next-app', label: chalk.blue('Next.js App Router') },\n { value: 'next-pages', label: chalk.green('Next.js Pages Router') },\n { value: 'vite', label: chalk.cyan('Vite + React') },\n { value: 'gatsby', label: chalk.magenta('Gatsby') },\n { value: 'react', label: chalk.yellow('React') },\n { value: 'redwood', label: chalk.red('RedwoodJS') },\n { value: 'tanstack-start', label: chalk.cyan('TanStack Start') },\n { value: 'other', label: chalk.dim('Other') },\n ],\n defaultValue: detected.name,\n }),\n }\n );\n if (framework === 'other') {\n logger.error(\n `Sorry, the wizard doesn't currently support other React frameworks.\nPlease let us know what you would like to see added at https://github.com/generaltranslation/gt/issues`\n );\n return exitSync(0);\n }\n if (!framework) return undefined;\n\n const packageJson = await getPackageJson();\n if (!packageJson) {\n session.reject(\n 'No package.json found in the current directory. Run this command from the root of your project'\n );\n return undefined;\n }\n const install = getReactFrameworkLibrary({ name: framework, type: 'react' });\n const plan: ReactSetupPlan = {\n framework,\n packageJson,\n install: isPackageInstalled(install, packageJson) ? undefined : install,\n };\n\n if (framework === 'next-app') {\n plan.nextConfigPath = findFilepath([\n './next.config.js',\n './next.config.ts',\n './next.config.mjs',\n './next.config.mts',\n ]);\n if (!plan.nextConfigPath) {\n session.reject('No next.config.[js|ts|mjs|mts] file found');\n }\n const formatter = await detectFormatter();\n if (\n formatter &&\n (await session.answer('--format', {\n explicit: options.format,\n recommended: true,\n ask: () =>\n promptConfirm({\n message: `Would you like the wizard to auto-format the modified files? ${chalk.dim(\n `(${formatter})`\n )}`,\n defaultValue: true,\n }),\n }))\n ) {\n plan.formatter = formatter;\n }\n }\n return plan;\n}\n\n/** Wraps Next.js App Router content and adds withGTConfig(); installs happen first. */\nexport async function executeReactSetup(\n session: OnboardingSession,\n plan: ReactSetupPlan,\n options: InitOptions\n): Promise<void> {\n if (plan.framework !== 'next-app' || !plan.nextConfigPath) return;\n\n const errors: string[] = [];\n const warnings: string[] = [];\n const spinner = logger.createSpinner();\n spinner.start('Wrapping JSX content with <T> tags...');\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated } = await wrapContentNext(\n {\n ...options,\n disableIds: true,\n disableFormatting: true,\n skipTs: true,\n addGTProvider: true,\n },\n Libraries.GT_NEXT,\n errors,\n warnings\n );\n spinner.stop(\n chalk.green(\n `Success! Updated ${chalk.bold.cyan(filesUpdated.length)} files:\\n`\n ) + filesUpdated.map((file) => `${chalk.green('-')} ${file}`).join('\\n')\n );\n if (filesUpdated.length > 0) session.step('wrapped JSX content');\n\n // Add the withGTConfig() function to the next.config.js file\n const tsconfigPath = findFilepath(['tsconfig.json']);\n await handleInitGT(\n plan.nextConfigPath,\n errors,\n warnings,\n filesUpdated,\n plan.packageJson,\n tsconfigPath ? loadConfig(tsconfigPath) : undefined\n );\n\n if (warnings.length > 0) {\n logger.warn(\n chalk.yellow('Warnings encountered:') +\n '\\n' +\n warnings.map((warning) => `${chalk.yellow('-')} ${warning}`).join('\\n')\n );\n }\n if (errors.length > 0) {\n throw new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: 'Setup could not update some application files',\n details: errors,\n fix: 'Fix the reported files, then rerun `npx gt init`',\n })\n );\n }\n logger.step(\n chalk.green(`Added withGTConfig() to your ${plan.nextConfigPath} file.`)\n );\n session.step(`added withGTConfig() to ${plan.nextConfigPath}`);\n\n if (plan.formatter) await formatFiles(filesUpdated, plan.formatter);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAkCA,MAAM,mBACJ;;;;;AAMF,eAAsB,kBACpB,SACA,SACA,UACA,qBACqC;CACrC,MAAM,UAAU,yBAAyB,SAAS;CAClD,MAAM,YAAY,kBAAkB,SAAS,KAAK;CAClD,MAAM,cAAc,WAAW;AA4B/B,KAAI,CAAC,MA3BkB,QAAQ,OAAO,iBAAiB;EACrD,UAAU,QAAQ;EAClB,aAAa;EACb,KAAK,YAAY;GACf,MAAM,SAAS,MAAM,cAAc;IACjC,SAAS,6BAA6B,QAAQ,OAAO,cAAc,aAAa,gBAAgB,qBAAqB,uCAAuC,WAAW,WAAA;IACvK,cAAc;IACf,CAAC;AAEF,OACE,UACA,CAAE,MAAM,cAAc;IACpB,SAAS,MAAM,OACb,mCAAmC,wBAAwB,SAAS,CAAC;;+EAGtE;IACD,cAAc;IACd,eAAe;IAChB,CAAC,EACF;AACA,WAAO,KAAK,iBAAiB;AAC7B,WAAO,SAAS,EAAE;;AAEpB,UAAO;;EAEV,CAAC,CACa,QAAO,KAAA;CAEtB,MAAM,YAAY,MAAM,QAAQ,OAC9B,eACA;EACE,UAAU,QAAQ;EAClB,YAAY;EACZ,aAAa,SAAS;EACtB,WACE,aAAiD;GAC/C,SAAS;GACT,SAAS;IACP;K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,SACe;AACf,KAAI,KAAK,cAAc,cAAc,CAAC,KAAK,eAAgB;CAE3D,MAAM,SAAmB,EAAE;CAC3B,MAAM,WAAqB,EAAE;CAC7B,MAAM,UAAU,OAAO,eAAe;AACtC,SAAQ,MAAM,wCAAwC;CAEtD,MAAM,EAAE,iBAAiB,MAAM,gBAC7B;EACE,GAAG;EACH,YAAY;EACZ,mBAAmB;EACnB,QAAQ;EACR,eAAe;EAChB,EAAA,WAED,QACA,SACD;AACD,SAAQ,KACN,MAAM,MACJ,oBAAoB,MAAM,KAAK,KAAK,aAAa,OAAO,CAAC,WAC1D,GAAG,aAAa,KAAK,SAAS,GAAG,MAAM,MAAM,IAAI,CAAC,GAAG,OAAO,CAAC,KAAK,KAAK,CACzE;AACD,KAAI,aAAa,SAAS,EAAG,SAAQ,KAAK,sBAAsB;CAGhE,MAAM,eAAe,aAAa,CAAC,gBAAgB,CAAC;AACpD,OAAM,aACJ,KAAK,gBACL,QACA,UACA,cACA,KAAK,aACL,eAAe,WAAW,aAAa,GAAG,KAAA,EAC3C;AAED,KAAI,SAAS,SAAS,EACpB,QAAO,KACL,MAAM,OAAO,wBAAwB,GACnC,OACA,SAAS,KAAK,YAAY,GAAG,MAAM,OAAO,IAAI,CAAC,GAAG,UAAU,CAAC,KAAK,KAAK,CAC1E;AAEH,KAAI,OAAO,SAAS,EAClB,OAAM,IAAI,MACR,wBAAwB;EACtB,QAAQ;EACR,UAAU;EACV,cAAc;EACd,SAAS;EACT,KAAK;EACN,CAAC,CACH;AAEH,QAAO,KACL,MAAM,MAAM,gCAAgC,KAAK,eAAe,QAAQ,CACzE;AACD,SAAQ,KAAK,2BAA2B,KAAK,iBAAiB;AAE9D,KAAI,KAAK,UAAW,OAAM,YAAY,cAAc,KAAK,UAAU"}
@@ -0,0 +1,4 @@
1
+ /** Records the files the upload step found missing locally (renamed or removed). */
2
+ export declare function recordOrphanedFileNames(fileNames: string[]): void;
3
+ export declare function getOrphanedFileNames(): string[] | null;
4
+ export declare function clearOrphanedFileNames(): void;
@@ -0,0 +1,16 @@
1
+ //#region src/state/orphanedFileNames.ts
2
+ let storedFileNames = null;
3
+ /** Records the files the upload step found missing locally (renamed or removed). */
4
+ function recordOrphanedFileNames(fileNames) {
5
+ storedFileNames = fileNames;
6
+ }
7
+ function getOrphanedFileNames() {
8
+ return storedFileNames;
9
+ }
10
+ function clearOrphanedFileNames() {
11
+ storedFileNames = null;
12
+ }
13
+ //#endregion
14
+ export { clearOrphanedFileNames, getOrphanedFileNames, recordOrphanedFileNames };
15
+
16
+ //# sourceMappingURL=orphanedFileNames.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"orphanedFileNames.js","names":[],"sources":["../../src/state/orphanedFileNames.ts"],"sourcesContent":["let storedFileNames: string[] | null = null;\n\n/** Records the files the upload step found missing locally (renamed or removed). */\nexport function recordOrphanedFileNames(fileNames: string[]): void {\n storedFileNames = fileNames;\n}\n\nexport function getOrphanedFileNames(): string[] | null {\n return storedFileNames;\n}\n\nexport function clearOrphanedFileNames(): void {\n storedFileNames = null;\n}\n"],"mappings":";AAAA,IAAI,kBAAmC;;AAGvC,SAAgB,wBAAwB,WAA2B;AACjE,mBAAkB;;AAGpB,SAAgB,uBAAwC;AACtD,QAAO;;AAGT,SAAgB,yBAA+B;AAC7C,mBAAkB"}
@@ -42,6 +42,7 @@ export type OpenApiConfig = {
42
42
  export type MintlifyOptions = {
43
43
  openapi?: OpenApiConfig;
44
44
  inferTitleFromFilename?: boolean;
45
+ localizeRedirects?: boolean;
45
46
  };
46
47
  export type SharedFlags = {
47
48
  config?: string;
@@ -103,7 +104,7 @@ export type GenerateSourceOptions = {
103
104
  suppressWarnings: boolean;
104
105
  };
105
106
  export type Framework = typeof Libraries.GT_NEXT | typeof Libraries.GT_REACT | typeof Libraries.GT_REACT_NATIVE | typeof Libraries.GT_TANSTACK_START;
106
- export declare const SUPPORTED_REACT_FRAMEWORKS: readonly ["next-app", "next-pages", "vite", "gatsby", "react", "redwood"];
107
+ export declare const SUPPORTED_REACT_FRAMEWORKS: readonly ["next-app", "next-pages", "vite", "gatsby", "react", "redwood", "tanstack-start"];
107
108
  export type FrameworkObject = {
108
109
  name: 'mintlify';
109
110
  type?: undefined;
@@ -5,7 +5,8 @@ const SUPPORTED_REACT_FRAMEWORKS = [
5
5
  "vite",
6
6
  "gatsby",
7
7
  "react",
8
- "redwood"
8
+ "redwood",
9
+ "tanstack-start"
9
10
  ];
10
11
  //#endregion
11
12
  export { SUPPORTED_REACT_FRAMEWORKS };
@@ -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};\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] 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 };\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":";AA6HA,MAAa,6BAA6B;CACxC;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] 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 };\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;CACD"}
@@ -1,4 +1,5 @@
1
1
  export declare const GT_DASHBOARD_URL = "https://dash.generaltranslation.com";
2
+ export declare const REACT_QUICKSTART_URL = "https://generaltranslation.com/docs/react/tutorials/quickstart";
2
3
  export declare const GT_CONFIG_SCHEMA_URL = "https://assets.gtx.dev/config-schema.json";
3
4
  export declare const TEMPLATE_FILE_NAME = "__INTERNAL_GT_TEMPLATE_NAME__";
4
5
  export declare const TEMPLATE_FILE_ID: string;
@@ -1,6 +1,7 @@
1
1
  import { hashStringSync } from "./hash.js";
2
2
  //#region src/utils/constants.ts
3
3
  const GT_DASHBOARD_URL = "https://dash.generaltranslation.com";
4
+ const REACT_QUICKSTART_URL = "https://generaltranslation.com/docs/react/tutorials/quickstart";
4
5
  const GT_CONFIG_SCHEMA_URL = "https://assets.gtx.dev/config-schema.json";
5
6
  const TEMPLATE_FILE_NAME = "__INTERNAL_GT_TEMPLATE_NAME__";
6
7
  const TEMPLATE_FILE_ID = hashStringSync(TEMPLATE_FILE_NAME);
@@ -10,6 +11,6 @@ const SURROUNDING_LINE_COUNT = 5;
10
11
  const DEFAULT_TRANSLATIONS_DIR = "./public/_gt";
11
12
  const DEFAULT_VITE_TRANSLATIONS_DIR = "./src/_gt";
12
13
  //#endregion
13
- export { DEFAULT_GIT_REMOTE_NAME, DEFAULT_TIMEOUT_SECONDS, DEFAULT_TRANSLATIONS_DIR, DEFAULT_VITE_TRANSLATIONS_DIR, GT_CONFIG_SCHEMA_URL, GT_DASHBOARD_URL, SURROUNDING_LINE_COUNT, TEMPLATE_FILE_ID, TEMPLATE_FILE_NAME };
14
+ export { DEFAULT_GIT_REMOTE_NAME, DEFAULT_TIMEOUT_SECONDS, DEFAULT_TRANSLATIONS_DIR, DEFAULT_VITE_TRANSLATIONS_DIR, GT_CONFIG_SCHEMA_URL, GT_DASHBOARD_URL, REACT_QUICKSTART_URL, SURROUNDING_LINE_COUNT, TEMPLATE_FILE_ID, TEMPLATE_FILE_NAME };
14
15
 
15
16
  //# sourceMappingURL=constants.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"constants.js","names":[],"sources":["../../src/utils/constants.ts"],"sourcesContent":["import { hashStringSync } from './hash.js';\n\nexport const GT_DASHBOARD_URL = 'https://dash.generaltranslation.com';\n\nexport const GT_CONFIG_SCHEMA_URL = 'https://assets.gtx.dev/config-schema.json';\n\nexport const TEMPLATE_FILE_NAME = '__INTERNAL_GT_TEMPLATE_NAME__';\nexport const TEMPLATE_FILE_ID = hashStringSync(TEMPLATE_FILE_NAME);\n\nexport const DEFAULT_GIT_REMOTE_NAME = 'origin';\n\nexport const DEFAULT_TIMEOUT_SECONDS = 900;\n\n// Number of source code lines to capture above and below a translation site\nexport const SURROUNDING_LINE_COUNT = 5;\n\n// Default translations directory paths\nexport const DEFAULT_TRANSLATIONS_DIR = './public/_gt';\nexport const DEFAULT_VITE_TRANSLATIONS_DIR = './src/_gt';\n"],"mappings":";;AAEA,MAAa,mBAAmB;AAEhC,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAClC,MAAa,mBAAmB,eAAe,mBAAmB;AAElE,MAAa,0BAA0B;AAEvC,MAAa,0BAA0B;AAGvC,MAAa,yBAAyB;AAGtC,MAAa,2BAA2B;AACxC,MAAa,gCAAgC"}
1
+ {"version":3,"file":"constants.js","names":[],"sources":["../../src/utils/constants.ts"],"sourcesContent":["import { hashStringSync } from './hash.js';\n\nexport const GT_DASHBOARD_URL = 'https://dash.generaltranslation.com';\n\nexport const REACT_QUICKSTART_URL =\n 'https://generaltranslation.com/docs/react/tutorials/quickstart';\n\nexport const GT_CONFIG_SCHEMA_URL = 'https://assets.gtx.dev/config-schema.json';\n\nexport const TEMPLATE_FILE_NAME = '__INTERNAL_GT_TEMPLATE_NAME__';\nexport const TEMPLATE_FILE_ID = hashStringSync(TEMPLATE_FILE_NAME);\n\nexport const DEFAULT_GIT_REMOTE_NAME = 'origin';\n\nexport const DEFAULT_TIMEOUT_SECONDS = 900;\n\n// Number of source code lines to capture above and below a translation site\nexport const SURROUNDING_LINE_COUNT = 5;\n\n// Default translations directory paths\nexport const DEFAULT_TRANSLATIONS_DIR = './public/_gt';\nexport const DEFAULT_VITE_TRANSLATIONS_DIR = './src/_gt';\n"],"mappings":";;AAEA,MAAa,mBAAmB;AAEhC,MAAa,uBACX;AAEF,MAAa,uBAAuB;AAEpC,MAAa,qBAAqB;AAClC,MAAa,mBAAmB,eAAe,mBAAmB;AAElE,MAAa,0BAA0B;AAEvC,MAAa,0BAA0B;AAGvC,MAAa,yBAAyB;AAGtC,MAAa,2BAA2B;AACxC,MAAa,gCAAgC"}
@@ -73,7 +73,8 @@ const FRAMEWORK_ENV_PREFIXES = {
73
73
  vite: "VITE_",
74
74
  gatsby: "GATSBY_",
75
75
  react: "REACT_APP_",
76
- redwood: "REDWOOD_ENV_"
76
+ redwood: "REDWOOD_ENV_",
77
+ "tanstack-start": "VITE_"
77
78
  };
78
79
  /** Names of the runtime variables init writes for this framework. */
79
80
  function getDevelopmentEnvNames(framework) {
@@ -1 +1 @@
1
- {"version":3,"file":"credentials.js","names":[],"sources":["../../src/utils/credentials.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport { promisify } from 'node:util';\nimport dotenv from 'dotenv';\nimport { Settings, SupportedFrameworks } from '../types/index.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\n\nconst execFileAsync = promisify(execFile);\n\nconst unsafeCredentialsEnvError = createDiagnosticMessage({\n whatHappened: 'Cannot safely update .env.local',\n reassurance: 'The existing .env.local file was not changed',\n fix: 'Move multiline values away from project/key assignments or set the development credentials manually, then retry',\n});\n\nfunction unwritableEnvFileError(envFile: string): string {\n return createDiagnosticMessage({\n whatHappened: `${envFile} is not a regular file`,\n reassurance: 'Nothing was changed',\n fix: 'Replace it with a regular file or a symlink to one, or set the development credentials manually, then retry',\n });\n}\n\nfunction trackedEnvFileError(file: string): string {\n return createDiagnosticMessage({\n whatHappened: `${file} is tracked by Git`,\n why: 'development credentials saved there would be committed',\n reassurance: 'Nothing was changed',\n fix: `Run \\`git rm --cached ${path.basename(file)}\\` in ${path.dirname(file)} and add the file to .gitignore, then retry`,\n });\n}\n\nfunction unignoredEnvFileError(file: string): string {\n return createDiagnosticMessage({\n whatHappened: `${file} is not ignored by Git`,\n why: 'development credentials saved there could be committed',\n reassurance: 'Nothing was changed',\n fix: `Add the file to a .gitignore that applies to ${path.dirname(file)}, then retry`,\n });\n}\n\nfunction unignoredEnvFileReferentError(envFile: string, referent: string) {\n return createDiagnosticMessage({\n whatHappened: `${envFile} links to ${referent}, which Git does not ignore`,\n why: 'development credentials saved there could be committed',\n reassurance: 'Nothing was changed',\n fix: `Add ${referent} to a .gitignore in its repository or set the development credentials manually, then retry`,\n });\n}\n\nfunction gitUnavailableError(file: string, error: unknown): string {\n return createDiagnosticMessage({\n whatHappened: `Could not run Git to verify that ${file} is untracked and ignored`,\n reassurance: 'Nothing was changed',\n fix: 'Install Git or make it available on PATH, then retry',\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nfunction gitOverrideError(file: string, names: string[]): string {\n return createDiagnosticMessage({\n whatHappened: `Git repository overrides are set in the environment: ${names.join(', ')}`,\n why: `they could point the untracked and ignore checks for ${file} at a different repository or index`,\n reassurance: 'Nothing was changed',\n fix: 'Unset them (for example, run outside a Git hook), then retry',\n });\n}\n\nfunction gitCheckFailedError(file: string, stderr: string): string {\n return createDiagnosticMessage({\n whatHappened: `Git could not check whether ${file} is untracked and ignored`,\n reassurance: 'Nothing was changed',\n fix: 'Fix the reported Git problem, then retry',\n details: stderr.trim(),\n });\n}\n\nexport type Credentials = { apiKey: string; projectId: string };\n\n// Include server-rendered frameworks with client-side development translation.\nconst FRAMEWORK_ENV_PREFIXES: Partial<\n Record<NonNullable<SupportedFrameworks>, string>\n> = {\n 'next-app': 'NEXT_PUBLIC_',\n 'next-pages': 'NEXT_PUBLIC_',\n vite: 'VITE_',\n gatsby: 'GATSBY_',\n react: 'REACT_APP_',\n redwood: 'REDWOOD_ENV_',\n};\n\n/** Names of the runtime variables init writes for this framework. */\nexport function getDevelopmentEnvNames(framework?: SupportedFrameworks) {\n const prefix = (framework && FRAMEWORK_ENV_PREFIXES[framework]) ?? '';\n return {\n projectId: `${prefix}GT_PROJECT_ID`,\n devApiKey: `${prefix}GT_DEV_API_KEY`,\n };\n}\n\n/**\n * Whether the project has the framework's development key, or an explicit\n * API key for a server-only runtime. A tooling key cannot enable client-side\n * hot reload, including in Next.js App Router. `settings.projectId` already\n * resolves every framework prefix. Login is checked separately.\n */\nexport function areCredentialsSet(\n settings: Pick<Settings, 'projectId' | 'apiKey'>,\n framework?: SupportedFrameworks\n): boolean {\n const { devApiKey } = getDevelopmentEnvNames(framework);\n const needsPublicKey = Boolean(\n framework && FRAMEWORK_ENV_PREFIXES[framework]\n );\n return Boolean(\n settings.projectId &&\n (process.env[devApiKey] || (!needsPublicKey && settings.apiKey))\n );\n}\n\nfunction assignedName(line: string): string | undefined {\n return /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=/.exec(line)?.[1];\n}\n\n/**\n * dotenv continues a quoted value onto later lines until its closing quote.\n * Replacing such a line would orphan the continuation, even when a later\n * duplicate hides the multiline value from dotenv's effective values.\n */\nfunction opensMultilineValue(line: string): boolean {\n const value = line.slice(line.indexOf('=') + 1).trim();\n const quote = value[0];\n return (\n ['\"', \"'\", '`'].includes(quote) &&\n !value.slice(1).replaceAll(`\\\\${quote}`, '').includes(quote)\n );\n}\n\nfunction upsertEnvAssignment(\n content: string,\n name: string,\n value: string\n): string {\n const assignsName = (line: string) => assignedName(line) === name;\n const lines = content.split('\\n');\n const first = lines.findIndex(assignsName);\n if (first === -1) {\n const separator = content && !content.endsWith('\\n') ? '\\n' : '';\n return `${content}${separator}${name}=${value}\\n`;\n }\n // Replace the first assignment in place and drop stale duplicates.\n return lines\n .map((line, index) => (index === first ? `${name}=${value}` : line))\n .filter((line, index) => index === first || !assignsName(line))\n .join('\\n');\n}\n\n/**\n * Where .env.local content lives and its mode. Follows an existing symlink so\n * its referent is replaced, never the link itself; anything but a regular\n * file (dangling link, directory) fails before any write.\n */\nasync function resolveEnvFile(\n envFile: string\n): Promise<{ target: string; mode: number } | undefined> {\n const entry = await fs.promises.lstat(envFile).catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (!entry) return undefined;\n // stat follows the link and fails on a dangling one.\n const stat = await fs.promises.stat(envFile).catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (!stat?.isFile()) throw new Error(unwritableEnvFileError(envFile));\n return {\n target: entry.isSymbolicLink()\n ? await fs.promises.realpath(envFile)\n : envFile,\n mode: stat.mode & 0o777,\n };\n}\n\ntype GitExposure = 'no-repository' | 'tracked' | 'ignored' | 'unignored';\n\n// Git honors these over discovering the repository from the working\n// directory, so an inherited value could select another repository, hide this\n// one, or substitute an empty index. Configuration variables stay in effect.\nconst GIT_LOCATION_OVERRIDES = [\n 'GIT_DIR',\n 'GIT_WORK_TREE',\n 'GIT_INDEX_FILE',\n 'GIT_COMMON_DIR',\n 'GIT_CEILING_DIRECTORIES',\n];\n\n/**\n * How Git in the file's own repository treats the path, using Git's real\n * index and effective ignore rules (comments, negations, nested .gitignore,\n * excludes). Only a Git-confirmed non-repository counts as no repository;\n * a missing binary, a repository override, or any other Git error fails\n * closed.\n */\nasync function inspectGitExposure(file: string): Promise<GitExposure> {\n const overrides = GIT_LOCATION_OVERRIDES.filter(\n (name) => process.env[name] !== undefined\n );\n if (overrides.length > 0) throw new Error(gitOverrideError(file, overrides));\n const cwd = path.dirname(file);\n const run = async (args: string[]) => {\n try {\n await execFileAsync('git', args, {\n cwd,\n encoding: 'utf8',\n windowsHide: true,\n // The no-repository check reads Git's untranslated message.\n env: { ...process.env, LC_ALL: 'C' },\n });\n return { code: 0, stderr: '' };\n } catch (error) {\n const { code, stderr } = error as { code?: unknown; stderr?: unknown };\n if (typeof code !== 'number')\n throw new Error(gitUnavailableError(file, error));\n return { code, stderr: typeof stderr === 'string' ? stderr : '' };\n }\n };\n\n const toplevel = await run(['rev-parse', '--show-toplevel']);\n if (toplevel.code === 128 && /not a git repository/i.test(toplevel.stderr)) {\n return 'no-repository';\n }\n if (toplevel.code !== 0) {\n throw new Error(gitCheckFailedError(file, toplevel.stderr));\n }\n // check-ignore ignores tracked files, so the index is consulted first.\n const tracked = await run(['ls-files', '--error-unmatch', '--', file]);\n if (tracked.code === 0) return 'tracked';\n if (tracked.code !== 1)\n throw new Error(gitCheckFailedError(file, tracked.stderr));\n const ignored = await run(['check-ignore', '-q', '--', file]);\n if (ignored.code === 0) return 'ignored';\n if (ignored.code === 1) return 'unignored';\n throw new Error(gitCheckFailedError(file, ignored.stderr));\n}\n\ntype CredentialsEnvFile = {\n envFile: string;\n existing: Awaited<ReturnType<typeof resolveEnvFile>>;\n exposure: GitExposure;\n};\n\n/**\n * Everything that must hold before credentials may be saved to .env.local,\n * so callers can fail before minting a key: the path is a regular file (or a\n * link to one) or absent, and neither it nor a link's referent is tracked by\n * Git. A referent inside any worktree must already be ignored there; only\n * .env.local itself gets an ignore rule added, by setCredentials.\n */\nexport async function inspectCredentialsEnvFile(\n cwd: string = process.cwd(),\n /** Also checks that the framework's credentials can be saved safely. */\n contentCheck?: { framework?: SupportedFrameworks }\n): Promise<CredentialsEnvFile> {\n const envFile = path.resolve(cwd, '.env.local');\n const existing = await resolveEnvFile(envFile);\n if (existing && contentCheck) {\n updateCredentialsEnvContent(\n await fs.promises.readFile(existing.target, 'utf8'),\n { projectId: 'gt-preflight', apiKey: 'gt-preflight' },\n contentCheck.framework\n );\n }\n const exposure = await inspectGitExposure(envFile);\n if (exposure === 'tracked') throw new Error(trackedEnvFileError(envFile));\n if (existing && existing.target !== envFile) {\n const referentExposure = await inspectGitExposure(existing.target);\n if (referentExposure === 'tracked') {\n throw new Error(trackedEnvFileError(existing.target));\n }\n if (referentExposure === 'unignored') {\n throw new Error(unignoredEnvFileReferentError(envFile, existing.target));\n }\n }\n return { envFile, existing, exposure };\n}\n\nasync function appendGitignoreRule(cwd: string): Promise<void> {\n const gitignoreFile = path.join(cwd, '.gitignore');\n const content = await fs.promises\n .readFile(gitignoreFile, 'utf8')\n .catch((error) => {\n if (error.code === 'ENOENT') return '';\n throw error;\n });\n const separator = content && !content.endsWith('\\n') ? '\\n' : '';\n await fs.promises.appendFile(\n gitignoreFile,\n `${separator}.env.local\\n`,\n 'utf8'\n );\n}\n\n// Same-directory temporary file and rename, as in auth/credentialStore.ts:\n// a failed write never truncates the existing file.\nasync function writeEnvFileAtomically(\n target: string,\n content: string,\n mode: number\n): Promise<void> {\n const temporaryPath = path.join(\n path.dirname(target),\n `.env.local.${randomUUID()}.tmp`\n );\n try {\n await fs.promises.writeFile(temporaryPath, content, {\n encoding: 'utf8',\n flag: 'wx',\n mode,\n });\n await fs.promises.chmod(temporaryPath, mode);\n await fs.promises.rename(temporaryPath, target);\n } catch (error) {\n await fs.promises.rm(temporaryPath, { force: true });\n throw error;\n }\n}\n\n/**\n * .env.local content with the runtime credentials set. Only the hot-reload\n * key: the CLI itself acts as the signed-in user, and CI keys are created\n * deliberately rather than dropped into .env.local. Other lines, comments,\n * and any GT_API_KEY are left untouched. Throws when the edit could corrupt\n * a multiline value.\n */\nfunction updateCredentialsEnvContent(\n envContent: string,\n credentials: Credentials,\n framework?: SupportedFrameworks\n): string {\n const names = getDevelopmentEnvNames(framework);\n const targetNames = Object.values(names);\n const targetOpensMultiline = envContent\n .split('\\n')\n .some(\n (line) =>\n targetNames.includes(assignedName(line) ?? '') &&\n opensMultilineValue(line)\n );\n const original = dotenv.parse(envContent);\n const expected = {\n ...original,\n [names.projectId]: credentials.projectId,\n [names.devApiKey]: credentials.apiKey,\n };\n let updatedContent = upsertEnvAssignment(\n envContent,\n names.projectId,\n credentials.projectId\n );\n updatedContent = upsertEnvAssignment(\n updatedContent,\n names.devApiKey,\n credentials.apiKey\n );\n\n const updated = dotenv.parse(updatedContent);\n if (\n targetOpensMultiline ||\n targetNames.some((name) => original[name]?.includes('\\n')) ||\n Object.keys(updated).length !== Object.keys(expected).length ||\n Object.entries(expected).some(([name, value]) => updated[name] !== value)\n ) {\n throw new Error(unsafeCredentialsEnvError);\n }\n return updatedContent;\n}\n\n// Sets the credentials in .env.local file\nexport async function setCredentials(\n credentials: Credentials,\n framework?: SupportedFrameworks,\n cwd: string = process.cwd()\n) {\n const {\n envFile,\n existing: existingEnvFile,\n exposure,\n } = await inspectCredentialsEnvFile(cwd);\n // Rechecked here: the file may have changed since the setup preflight.\n const envContent = updateCredentialsEnvContent(\n existingEnvFile\n ? await fs.promises.readFile(existingEnvFile.target, 'utf8')\n : '',\n credentials,\n framework\n );\n\n if (exposure === 'unignored') {\n // A rule appended to the same-directory .gitignore is the last match at\n // the deepest level, so it wins over earlier negations; verify anyway.\n await appendGitignoreRule(cwd);\n if ((await inspectGitExposure(envFile)) !== 'ignored') {\n throw new Error(unignoredEnvFileError(envFile));\n }\n } else if (exposure === 'no-repository') {\n // Without a repository there are no effective rules to consult, so this\n // is unverified: seed a .gitignore so a later `git init` ignores the file.\n const gitignoreFile = path.join(cwd, '.gitignore');\n if (\n !fs.existsSync(gitignoreFile) ||\n (await fs.promises.readFile(gitignoreFile, 'utf8'))\n .trimEnd()\n .split(/\\r?\\n/)\n .at(-1) !== '.env.local'\n ) {\n await appendGitignoreRule(cwd);\n }\n }\n\n await writeEnvFileAtomically(\n existingEnvFile?.target ?? envFile,\n envContent,\n existingEnvFile?.mode ?? 0o600\n );\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,gBAAgB,UAAU,SAAS;AAEzC,MAAM,4BAA4B,wBAAwB;CACxD,cAAc;CACd,aAAa;CACb,KAAK;CACN,CAAC;AAEF,SAAS,uBAAuB,SAAyB;AACvD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,QAAQ;EACzB,aAAa;EACb,KAAK;EACN,CAAC;;AAGJ,SAAS,oBAAoB,MAAsB;AACjD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,KAAK;EACtB,KAAK;EACL,aAAa;EACb,KAAK,yBAAyB,KAAK,SAAS,KAAK,CAAC,QAAQ,KAAK,QAAQ,KAAK,CAAC;EAC9E,CAAC;;AAGJ,SAAS,sBAAsB,MAAsB;AACnD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,KAAK;EACtB,KAAK;EACL,aAAa;EACb,KAAK,gDAAgD,KAAK,QAAQ,KAAK,CAAC;EACzE,CAAC;;AAGJ,SAAS,8BAA8B,SAAiB,UAAkB;AACxE,QAAO,wBAAwB;EAC7B,cAAc,GAAG,QAAQ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iB,UAAU,SAC3B,YACA,iBAAiB,QAAQ,IAC1B"}
1
+ {"version":3,"file":"credentials.js","names":[],"sources":["../../src/utils/credentials.ts"],"sourcesContent":["import { execFile } from 'node:child_process';\nimport { randomUUID } from 'node:crypto';\nimport path from 'node:path';\nimport fs from 'node:fs';\nimport { promisify } from 'node:util';\nimport dotenv from 'dotenv';\nimport { Settings, SupportedFrameworks } from '../types/index.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/internal';\n\nconst execFileAsync = promisify(execFile);\n\nconst unsafeCredentialsEnvError = createDiagnosticMessage({\n whatHappened: 'Cannot safely update .env.local',\n reassurance: 'The existing .env.local file was not changed',\n fix: 'Move multiline values away from project/key assignments or set the development credentials manually, then retry',\n});\n\nfunction unwritableEnvFileError(envFile: string): string {\n return createDiagnosticMessage({\n whatHappened: `${envFile} is not a regular file`,\n reassurance: 'Nothing was changed',\n fix: 'Replace it with a regular file or a symlink to one, or set the development credentials manually, then retry',\n });\n}\n\nfunction trackedEnvFileError(file: string): string {\n return createDiagnosticMessage({\n whatHappened: `${file} is tracked by Git`,\n why: 'development credentials saved there would be committed',\n reassurance: 'Nothing was changed',\n fix: `Run \\`git rm --cached ${path.basename(file)}\\` in ${path.dirname(file)} and add the file to .gitignore, then retry`,\n });\n}\n\nfunction unignoredEnvFileError(file: string): string {\n return createDiagnosticMessage({\n whatHappened: `${file} is not ignored by Git`,\n why: 'development credentials saved there could be committed',\n reassurance: 'Nothing was changed',\n fix: `Add the file to a .gitignore that applies to ${path.dirname(file)}, then retry`,\n });\n}\n\nfunction unignoredEnvFileReferentError(envFile: string, referent: string) {\n return createDiagnosticMessage({\n whatHappened: `${envFile} links to ${referent}, which Git does not ignore`,\n why: 'development credentials saved there could be committed',\n reassurance: 'Nothing was changed',\n fix: `Add ${referent} to a .gitignore in its repository or set the development credentials manually, then retry`,\n });\n}\n\nfunction gitUnavailableError(file: string, error: unknown): string {\n return createDiagnosticMessage({\n whatHappened: `Could not run Git to verify that ${file} is untracked and ignored`,\n reassurance: 'Nothing was changed',\n fix: 'Install Git or make it available on PATH, then retry',\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nfunction gitOverrideError(file: string, names: string[]): string {\n return createDiagnosticMessage({\n whatHappened: `Git repository overrides are set in the environment: ${names.join(', ')}`,\n why: `they could point the untracked and ignore checks for ${file} at a different repository or index`,\n reassurance: 'Nothing was changed',\n fix: 'Unset them (for example, run outside a Git hook), then retry',\n });\n}\n\nfunction gitCheckFailedError(file: string, stderr: string): string {\n return createDiagnosticMessage({\n whatHappened: `Git could not check whether ${file} is untracked and ignored`,\n reassurance: 'Nothing was changed',\n fix: 'Fix the reported Git problem, then retry',\n details: stderr.trim(),\n });\n}\n\nexport type Credentials = { apiKey: string; projectId: string };\n\n// Include server-rendered frameworks with client-side development translation.\nconst FRAMEWORK_ENV_PREFIXES: Partial<\n Record<NonNullable<SupportedFrameworks>, string>\n> = {\n 'next-app': 'NEXT_PUBLIC_',\n 'next-pages': 'NEXT_PUBLIC_',\n vite: 'VITE_',\n gatsby: 'GATSBY_',\n react: 'REACT_APP_',\n redwood: 'REDWOOD_ENV_',\n 'tanstack-start': 'VITE_',\n};\n\n/** Names of the runtime variables init writes for this framework. */\nexport function getDevelopmentEnvNames(framework?: SupportedFrameworks) {\n const prefix = (framework && FRAMEWORK_ENV_PREFIXES[framework]) ?? '';\n return {\n projectId: `${prefix}GT_PROJECT_ID`,\n devApiKey: `${prefix}GT_DEV_API_KEY`,\n };\n}\n\n/**\n * Whether the project has the framework's development key, or an explicit\n * API key for a server-only runtime. A tooling key cannot enable client-side\n * hot reload, including in Next.js App Router. `settings.projectId` already\n * resolves every framework prefix. Login is checked separately.\n */\nexport function areCredentialsSet(\n settings: Pick<Settings, 'projectId' | 'apiKey'>,\n framework?: SupportedFrameworks\n): boolean {\n const { devApiKey } = getDevelopmentEnvNames(framework);\n const needsPublicKey = Boolean(\n framework && FRAMEWORK_ENV_PREFIXES[framework]\n );\n return Boolean(\n settings.projectId &&\n (process.env[devApiKey] || (!needsPublicKey && settings.apiKey))\n );\n}\n\nfunction assignedName(line: string): string | undefined {\n return /^\\s*(?:export\\s+)?([A-Za-z_][A-Za-z0-9_]*)\\s*=/.exec(line)?.[1];\n}\n\n/**\n * dotenv continues a quoted value onto later lines until its closing quote.\n * Replacing such a line would orphan the continuation, even when a later\n * duplicate hides the multiline value from dotenv's effective values.\n */\nfunction opensMultilineValue(line: string): boolean {\n const value = line.slice(line.indexOf('=') + 1).trim();\n const quote = value[0];\n return (\n ['\"', \"'\", '`'].includes(quote) &&\n !value.slice(1).replaceAll(`\\\\${quote}`, '').includes(quote)\n );\n}\n\nfunction upsertEnvAssignment(\n content: string,\n name: string,\n value: string\n): string {\n const assignsName = (line: string) => assignedName(line) === name;\n const lines = content.split('\\n');\n const first = lines.findIndex(assignsName);\n if (first === -1) {\n const separator = content && !content.endsWith('\\n') ? '\\n' : '';\n return `${content}${separator}${name}=${value}\\n`;\n }\n // Replace the first assignment in place and drop stale duplicates.\n return lines\n .map((line, index) => (index === first ? `${name}=${value}` : line))\n .filter((line, index) => index === first || !assignsName(line))\n .join('\\n');\n}\n\n/**\n * Where .env.local content lives and its mode. Follows an existing symlink so\n * its referent is replaced, never the link itself; anything but a regular\n * file (dangling link, directory) fails before any write.\n */\nasync function resolveEnvFile(\n envFile: string\n): Promise<{ target: string; mode: number } | undefined> {\n const entry = await fs.promises.lstat(envFile).catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (!entry) return undefined;\n // stat follows the link and fails on a dangling one.\n const stat = await fs.promises.stat(envFile).catch((error) => {\n if (error.code === 'ENOENT') return undefined;\n throw error;\n });\n if (!stat?.isFile()) throw new Error(unwritableEnvFileError(envFile));\n return {\n target: entry.isSymbolicLink()\n ? await fs.promises.realpath(envFile)\n : envFile,\n mode: stat.mode & 0o777,\n };\n}\n\ntype GitExposure = 'no-repository' | 'tracked' | 'ignored' | 'unignored';\n\n// Git honors these over discovering the repository from the working\n// directory, so an inherited value could select another repository, hide this\n// one, or substitute an empty index. Configuration variables stay in effect.\nconst GIT_LOCATION_OVERRIDES = [\n 'GIT_DIR',\n 'GIT_WORK_TREE',\n 'GIT_INDEX_FILE',\n 'GIT_COMMON_DIR',\n 'GIT_CEILING_DIRECTORIES',\n];\n\n/**\n * How Git in the file's own repository treats the path, using Git's real\n * index and effective ignore rules (comments, negations, nested .gitignore,\n * excludes). Only a Git-confirmed non-repository counts as no repository;\n * a missing binary, a repository override, or any other Git error fails\n * closed.\n */\nasync function inspectGitExposure(file: string): Promise<GitExposure> {\n const overrides = GIT_LOCATION_OVERRIDES.filter(\n (name) => process.env[name] !== undefined\n );\n if (overrides.length > 0) throw new Error(gitOverrideError(file, overrides));\n const cwd = path.dirname(file);\n const run = async (args: string[]) => {\n try {\n await execFileAsync('git', args, {\n cwd,\n encoding: 'utf8',\n windowsHide: true,\n // The no-repository check reads Git's untranslated message.\n env: { ...process.env, LC_ALL: 'C' },\n });\n return { code: 0, stderr: '' };\n } catch (error) {\n const { code, stderr } = error as { code?: unknown; stderr?: unknown };\n if (typeof code !== 'number')\n throw new Error(gitUnavailableError(file, error));\n return { code, stderr: typeof stderr === 'string' ? stderr : '' };\n }\n };\n\n const toplevel = await run(['rev-parse', '--show-toplevel']);\n if (toplevel.code === 128 && /not a git repository/i.test(toplevel.stderr)) {\n return 'no-repository';\n }\n if (toplevel.code !== 0) {\n throw new Error(gitCheckFailedError(file, toplevel.stderr));\n }\n // check-ignore ignores tracked files, so the index is consulted first.\n const tracked = await run(['ls-files', '--error-unmatch', '--', file]);\n if (tracked.code === 0) return 'tracked';\n if (tracked.code !== 1)\n throw new Error(gitCheckFailedError(file, tracked.stderr));\n const ignored = await run(['check-ignore', '-q', '--', file]);\n if (ignored.code === 0) return 'ignored';\n if (ignored.code === 1) return 'unignored';\n throw new Error(gitCheckFailedError(file, ignored.stderr));\n}\n\ntype CredentialsEnvFile = {\n envFile: string;\n existing: Awaited<ReturnType<typeof resolveEnvFile>>;\n exposure: GitExposure;\n};\n\n/**\n * Everything that must hold before credentials may be saved to .env.local,\n * so callers can fail before minting a key: the path is a regular file (or a\n * link to one) or absent, and neither it nor a link's referent is tracked by\n * Git. A referent inside any worktree must already be ignored there; only\n * .env.local itself gets an ignore rule added, by setCredentials.\n */\nexport async function inspectCredentialsEnvFile(\n cwd: string = process.cwd(),\n /** Also checks that the framework's credentials can be saved safely. */\n contentCheck?: { framework?: SupportedFrameworks }\n): Promise<CredentialsEnvFile> {\n const envFile = path.resolve(cwd, '.env.local');\n const existing = await resolveEnvFile(envFile);\n if (existing && contentCheck) {\n updateCredentialsEnvContent(\n await fs.promises.readFile(existing.target, 'utf8'),\n { projectId: 'gt-preflight', apiKey: 'gt-preflight' },\n contentCheck.framework\n );\n }\n const exposure = await inspectGitExposure(envFile);\n if (exposure === 'tracked') throw new Error(trackedEnvFileError(envFile));\n if (existing && existing.target !== envFile) {\n const referentExposure = await inspectGitExposure(existing.target);\n if (referentExposure === 'tracked') {\n throw new Error(trackedEnvFileError(existing.target));\n }\n if (referentExposure === 'unignored') {\n throw new Error(unignoredEnvFileReferentError(envFile, existing.target));\n }\n }\n return { envFile, existing, exposure };\n}\n\nasync function appendGitignoreRule(cwd: string): Promise<void> {\n const gitignoreFile = path.join(cwd, '.gitignore');\n const content = await fs.promises\n .readFile(gitignoreFile, 'utf8')\n .catch((error) => {\n if (error.code === 'ENOENT') return '';\n throw error;\n });\n const separator = content && !content.endsWith('\\n') ? '\\n' : '';\n await fs.promises.appendFile(\n gitignoreFile,\n `${separator}.env.local\\n`,\n 'utf8'\n );\n}\n\n// Same-directory temporary file and rename, as in auth/credentialStore.ts:\n// a failed write never truncates the existing file.\nasync function writeEnvFileAtomically(\n target: string,\n content: string,\n mode: number\n): Promise<void> {\n const temporaryPath = path.join(\n path.dirname(target),\n `.env.local.${randomUUID()}.tmp`\n );\n try {\n await fs.promises.writeFile(temporaryPath, content, {\n encoding: 'utf8',\n flag: 'wx',\n mode,\n });\n await fs.promises.chmod(temporaryPath, mode);\n await fs.promises.rename(temporaryPath, target);\n } catch (error) {\n await fs.promises.rm(temporaryPath, { force: true });\n throw error;\n }\n}\n\n/**\n * .env.local content with the runtime credentials set. Only the hot-reload\n * key: the CLI itself acts as the signed-in user, and CI keys are created\n * deliberately rather than dropped into .env.local. Other lines, comments,\n * and any GT_API_KEY are left untouched. Throws when the edit could corrupt\n * a multiline value.\n */\nfunction updateCredentialsEnvContent(\n envContent: string,\n credentials: Credentials,\n framework?: SupportedFrameworks\n): string {\n const names = getDevelopmentEnvNames(framework);\n const targetNames = Object.values(names);\n const targetOpensMultiline = envContent\n .split('\\n')\n .some(\n (line) =>\n targetNames.includes(assignedName(line) ?? '') &&\n opensMultilineValue(line)\n );\n const original = dotenv.parse(envContent);\n const expected = {\n ...original,\n [names.projectId]: credentials.projectId,\n [names.devApiKey]: credentials.apiKey,\n };\n let updatedContent = upsertEnvAssignment(\n envContent,\n names.projectId,\n credentials.projectId\n );\n updatedContent = upsertEnvAssignment(\n updatedContent,\n names.devApiKey,\n credentials.apiKey\n );\n\n const updated = dotenv.parse(updatedContent);\n if (\n targetOpensMultiline ||\n targetNames.some((name) => original[name]?.includes('\\n')) ||\n Object.keys(updated).length !== Object.keys(expected).length ||\n Object.entries(expected).some(([name, value]) => updated[name] !== value)\n ) {\n throw new Error(unsafeCredentialsEnvError);\n }\n return updatedContent;\n}\n\n// Sets the credentials in .env.local file\nexport async function setCredentials(\n credentials: Credentials,\n framework?: SupportedFrameworks,\n cwd: string = process.cwd()\n) {\n const {\n envFile,\n existing: existingEnvFile,\n exposure,\n } = await inspectCredentialsEnvFile(cwd);\n // Rechecked here: the file may have changed since the setup preflight.\n const envContent = updateCredentialsEnvContent(\n existingEnvFile\n ? await fs.promises.readFile(existingEnvFile.target, 'utf8')\n : '',\n credentials,\n framework\n );\n\n if (exposure === 'unignored') {\n // A rule appended to the same-directory .gitignore is the last match at\n // the deepest level, so it wins over earlier negations; verify anyway.\n await appendGitignoreRule(cwd);\n if ((await inspectGitExposure(envFile)) !== 'ignored') {\n throw new Error(unignoredEnvFileError(envFile));\n }\n } else if (exposure === 'no-repository') {\n // Without a repository there are no effective rules to consult, so this\n // is unverified: seed a .gitignore so a later `git init` ignores the file.\n const gitignoreFile = path.join(cwd, '.gitignore');\n if (\n !fs.existsSync(gitignoreFile) ||\n (await fs.promises.readFile(gitignoreFile, 'utf8'))\n .trimEnd()\n .split(/\\r?\\n/)\n .at(-1) !== '.env.local'\n ) {\n await appendGitignoreRule(cwd);\n }\n }\n\n await writeEnvFileAtomically(\n existingEnvFile?.target ?? envFile,\n envContent,\n existingEnvFile?.mode ?? 0o600\n );\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,gBAAgB,UAAU,SAAS;AAEzC,MAAM,4BAA4B,wBAAwB;CACxD,cAAc;CACd,aAAa;CACb,KAAK;CACN,CAAC;AAEF,SAAS,uBAAuB,SAAyB;AACvD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,QAAQ;EACzB,aAAa;EACb,KAAK;EACN,CAAC;;AAGJ,SAAS,oBAAoB,MAAsB;AACjD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,KAAK;EACtB,KAAK;EACL,aAAa;EACb,KAAK,yBAAyB,KAAK,SAAS,KAAK,CAAC,QAAQ,KAAK,QAAQ,KAAK,CAAC;EAC9E,CAAC;;AAGJ,SAAS,sBAAsB,MAAsB;AACnD,QAAO,wBAAwB;EAC7B,cAAc,GAAG,KAAK;EACtB,KAAK;EACL,aAAa;EACb,KAAK,gDAAgD,KAAK,QAAQ,KAAK,CAAC;EACzE,CAAC;;AAGJ,SAAS,8BAA8B,SAAiB,UAAkB;AACxE,QAAO,wBAAwB;EAC7B,cAAc,GAAG,QAAQ,YAAY,SAAS;EAC9C,KAAK;EACL,aAAa;EACb,KAAK,OAAO,SAAS;EACtB,CAAC;;AAGJ,SAAS,oBAAoB,MAAc,OAAwB;AACjE,QAAO,wBAAwB;EAC7B,c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SIONS: string[];
3
3
  export declare const INDEX_PAGE = "index";
4
+ /**
5
+ * Whether a URL points to a source page with no translation on disk, either at
6
+ * its mapped output path or at the localized URL. URLs with no source page,
7
+ * such as pages generated from an OpenAPI spec, are not missing a translation.
8
+ */
9
+ export declare function translationMissing(url: string, localizedUrl: string, localizedFiles: Record<string, string>): boolean;
4
10
  export type StaticUrlSettings = StaticLocalizationSettings;
5
11
  /**
6
12
  * Localizes static urls in content files.
@@ -381,6 +381,6 @@ function checkIfPathMatchesPattern(originalUrlArray, patternHeadArray) {
381
381
  return true;
382
382
  }
383
383
  //#endregion
384
- export { INDEX_PAGE, PAGE_EXTENSIONS, localizeStaticUrls as default, transformUrlPath };
384
+ export { INDEX_PAGE, PAGE_EXTENSIONS, localizeStaticUrls as default, transformUrlPath, translationMissing };
385
385
 
386
386
  //# sourceMappingURL=localizeStaticUrls.js.map