gt 2.27.3 → 2.28.1

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 (37) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/dist/api/collectUserEditDiffs.js +77 -2
  3. package/dist/api/collectUserEditDiffs.js.map +1 -1
  4. package/dist/cli/base.d.ts +2 -0
  5. package/dist/cli/base.js +9 -5
  6. package/dist/cli/base.js.map +1 -1
  7. package/dist/cli/commands/setupProject.js +2 -0
  8. package/dist/cli/commands/setupProject.js.map +1 -1
  9. package/dist/cli/commands/stage.js +2 -0
  10. package/dist/cli/commands/stage.js.map +1 -1
  11. package/dist/cli/commands/upload.js +2 -0
  12. package/dist/cli/commands/upload.js.map +1 -1
  13. package/dist/generated/version.d.ts +1 -1
  14. package/dist/generated/version.js +1 -1
  15. package/dist/generated/version.js.map +1 -1
  16. package/dist/locadex/setupFlow.js +1 -1
  17. package/dist/locadex/setupFlow.js.map +1 -1
  18. package/dist/paraglide/collectParaglideContext.d.ts +5 -0
  19. package/dist/paraglide/collectParaglideContext.js +43 -0
  20. package/dist/paraglide/collectParaglideContext.js.map +1 -0
  21. package/dist/setup/developmentCredentials.d.ts +3 -1
  22. package/dist/setup/developmentCredentials.js +6 -2
  23. package/dist/setup/developmentCredentials.js.map +1 -1
  24. package/dist/setup/onboarding.d.ts +6 -2
  25. package/dist/setup/onboarding.js +8 -4
  26. package/dist/setup/onboarding.js.map +1 -1
  27. package/dist/setup/wizard.d.ts +8 -2
  28. package/dist/setup/wizard.js +26 -1
  29. package/dist/setup/wizard.js.map +1 -1
  30. package/dist/types/index.d.ts +2 -2
  31. package/dist/types/index.js.map +1 -1
  32. package/dist/types/parsing.d.ts +8 -1
  33. package/dist/types/parsing.js.map +1 -1
  34. package/dist/utils/resolveMintlifyRefs.d.ts +5 -0
  35. package/dist/utils/resolveMintlifyRefs.js +26 -8
  36. package/dist/utils/resolveMintlifyRefs.js.map +1 -1
  37. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"base.js","names":[],"sources":["../../src/cli/base.ts"],"sourcesContent":["import { Argument, Command, InvalidArgumentError, Option } from 'commander';\nimport {\n OrgApiKeyPermission,\n ProjectApiKeyPermission,\n} from 'generaltranslation/api';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport {\n applySetupConfig,\n mergeSetupConfig,\n type SetupConfigUpdate,\n} from '../fs/config/setupConfig.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport {\n displayHeader,\n promptText,\n logErrorAndExit,\n exitSync,\n promptConfirm,\n promptMultiSelect,\n promptSelect,\n promptGlobPatterns,\n} from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { lottieTranslateError } from '../console/index.js';\nimport { parseGlobPatterns } from '../console/promptParsing.js';\nimport path from 'node:path';\nimport {\n FilesOptions,\n Settings,\n SupportedFrameworks,\n SupportedLibraries,\n TranslateFlags,\n SharedFlags,\n} from '../types/index.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport chalk from 'chalk';\nimport {\n FILE_EXT_TO_EXT_LABEL,\n SETUP_FILE_FORMATS,\n SUPPORTED_FILE_EXTENSIONS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n executeReactSetup,\n resolveReactSetup,\n type ReactSetupPlan,\n} from '../setup/wizard.js';\nimport { formatInitNextSteps, getInitNextSteps } from '../setup/nextSteps.js';\nimport { getPackageManager } from '../utils/packageManager.js';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { getDesiredLocales } from '../setup/userInput.js';\nimport {\n areCredentialsSet,\n getDevelopmentEnvNames,\n inspectCredentialsEnvFile,\n} from '../utils/credentials.js';\nimport {\n checkDevelopmentProjectInputs,\n productionRuntimeKeyGuidance,\n provisionDevelopmentCredentials,\n resolveDevelopmentProject,\n signInForSetup,\n} from '../setup/developmentCredentials.js';\nimport {\n exitIfUnsupportedSetupTarget,\n reactNativeSetupError,\n} from '../setup/setupTarget.js';\nimport {\n asRecord,\n attachConfigureFlags,\n attachInitFlags,\n describeDefaults,\n displaySetupHeader,\n getConfiguredFramework,\n INIT_SOURCE_HELP,\n installWithProgress,\n OnboardingError,\n parseFilePatterns,\n readSetupConfig,\n reportJsonExitsBeforeOnboarding,\n resolvePackageManager,\n runOnboarding,\n setupConfigPath,\n validateSetupPattern,\n type ConfigureOptions,\n type InitOptions,\n type OnboardingSession,\n} from '../setup/onboarding.js';\nimport { upload } from './commands/upload.js';\nimport { attachSharedFlags, attachTranslateFlags } from './flags.js';\nimport { handleStage } from './commands/stage.js';\nimport { handleSetupProject } from './commands/setupProject.js';\nimport { handleDownload } from './commands/download.js';\nimport {\n handleTranslate,\n postProcessTranslations,\n} from './commands/translate.js';\nimport {\n getNeedsPostprocessing,\n clearDownloaded,\n} from '../state/recentDownloads.js';\nimport { clearWarnings } from '../state/translateWarnings.js';\nimport { displayTranslateSummary } from '../console/displayTranslateSummary.js';\nimport updateConfig from '../fs/config/updateConfig.js';\nimport {\n createLoadTranslationsFile,\n findLoadTranslationsFiles,\n} from '../fs/createLoadTranslationsFile.js';\nimport { saveLocalEdits } from '../api/saveLocalEdits.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './commands/utils/validation.js';\nimport processSharedStaticAssets, {\n mirrorAssetsToLocales,\n} from '../utils/sharedStaticAssets.js';\nimport { setupLocadex } from '../locadex/setupFlow.js';\nimport { detectFramework } from '../setup/detectFramework.js';\nimport { INLINE_LIBRARIES, Libraries } from '../types/libraries.js';\nimport { handleEnqueue } from './commands/enqueue.js';\nimport { splitMintlifyLanguageRefs } from '../utils/splitMintlifyLanguageRefs.js';\nimport { localizeMintlifyRedirects } from '../formats/files/postprocess/localizeMintlifyRedirects.js';\nimport {\n clearOrphanedFileNames,\n getOrphanedFileNames,\n} from '../state/orphanedFileNames.js';\nimport { runMergeDriver, type MergeDriverName } from '../git/mergeDrivers.js';\nimport { setupGitMergeDrivers } from '../git/setupMergeDrivers.js';\nimport { warnReactPackageCompatibility } from '../utils/reactPackageCompatibility.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { hasLogin, logout, whoAmI } from '../auth/oauth.js';\nimport { createUserAuthError, UserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { resolveConfig } from '../config/resolveConfig.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport {\n getBuildToolSetup,\n getSetupDocsUrl,\n type ManualAction,\n type SetupResult,\n} from '../setup/buildTools/index.js';\nimport { manifestDirectlyDeclaresGTVue } from '@generaltranslation/vue-extractor/integration';\nimport { api, configureApiClient } from '../utils/api.js';\nimport { handleApiCommand, type ApiCommandOptions } from './commands/api.js';\n\nconst ID_COMPATIBILITY_WARNING_COMMANDS = new Set([\n 'download',\n 'enqueue',\n 'generate',\n 'setup',\n 'stage',\n 'translate',\n 'validate',\n]);\nfunction createProjectCommandError(\n whatHappened: string,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened,\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst emptyApiKeyNameError = createDiagnosticMessage({\n whatHappened: 'The key name cannot be empty',\n fix: 'Pass a non-empty value with --name',\n});\n\nconst projectApiKeyPermissions = new Set<string>(\n Object.values(ProjectApiKeyPermission)\n);\n\nfunction isProjectApiKeyPermission(\n permission: OrgApiKeyPermission\n): permission is ProjectApiKeyPermission {\n return projectApiKeyPermissions.has(permission);\n}\n\nfunction parseApiKeyName(value: string): string {\n const name = value.trim();\n if (!name) throw new InvalidArgumentError(emptyApiKeyNameError);\n return name;\n}\n\n/** Credential failures keep their own diagnostic or get the setup context. */\nasync function withCredentialsError<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof OnboardingError) throw error;\n throw new Error(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError(\n 'Failed to set up the development credentials',\n error\n )\n );\n }\n}\n\nexport type UploadOptions = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n defaultLocale?: string;\n};\n\nexport type GitSetupOptions = {\n config?: string;\n dryRun?: boolean;\n omitConfigIds?: boolean;\n driverCommand?: string;\n};\n\ntype LocalTranslationGuidanceOptions = {\n generatedLoader: boolean;\n runtimeSetup: InlineRuntimeSetup;\n translationsDir: string;\n};\n\ntype InlineRuntimeSetup = {\n hasOtherInlineRuntime: boolean;\n hasVueRuntime: boolean;\n ranReactSetup: boolean;\n};\n\nexport class BaseCLI {\n protected library: SupportedLibraries;\n protected additionalModules: SupportedLibraries[];\n protected program: Command;\n // Constructor is shared amongst all CLI class types\n public constructor(\n program: Command,\n library: SupportedLibraries,\n additionalModules?: SupportedLibraries[]\n ) {\n this.program = program;\n this.library = library;\n this.additionalModules = additionalModules || [];\n\n this.program.option(\n '--skip-version-check',\n 'Skip the monorepo GT package version consistency check'\n );\n this.program.option(\n '--suppress-id-compatibility-warning',\n 'Suppress the React package ID compatibility warning'\n );\n this.program.option(\n '-q, --quiet',\n 'Suppress informational output; only warnings and errors are shown'\n );\n // Select console routing for this command before anything else logs:\n // root hooks run before subclass hooks (version checks) and the action's\n // settings resolution. `gt api-key create` prints the new secret on\n // stdout, so its diagnostics go to stderr, as do setup commands writing\n // JSON events; every other command gets the historical default back\n // (main() routes startup output to stderr).\n this.program.hook('preAction', (thisCommand, actionCommand) => {\n logger.setConsoleOutput(\n actionCommand.parent?.name() === 'api-key' || actionCommand.opts().json\n ? 'stderr'\n : 'stdout'\n );\n if (\n actionCommand.opts().json &&\n actionCommand.parent === thisCommand &&\n ['init', 'configure'].includes(actionCommand.name())\n ) {\n reportJsonExitsBeforeOnboarding(actionCommand.name());\n }\n });\n // Apply --quiet before any other hook or command action runs so the\n // singleton logger is muted for the rest of the invocation. The flag is a\n // global root option, so commander resolves it in any position and for\n // nested commands (e.g. `gt git setup --quiet`).\n this.program.hook('preAction', () => {\n logger.setQuiet(Boolean(this.program.opts().quiet));\n });\n this.program.hook('preAction', async (thisCommand, actionCommand) => {\n // Nested commands (e.g. `gt git setup`) can share leaf names with\n // translation commands; only direct children of the root qualify\n if (actionCommand.parent !== thisCommand) return;\n if (!ID_COMPATIBILITY_WARNING_COMMANDS.has(actionCommand.name())) return;\n await warnReactPackageCompatibility(\n Boolean(this.program.opts().suppressIdCompatibilityWarning)\n );\n });\n\n this.setupInitCommand();\n this.setupConfigureCommand();\n this.setupUploadCommand();\n this.setupUserAuthCommands();\n this.setupSendDiffsCommand();\n this.setupApiCommand();\n this.setupProjectCommands();\n this.setupApiKeyCommands();\n this.setupGitCommand();\n }\n // Init is never called in a child class\n public init() {\n this.setupSetupProjectCommand();\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n // Execute is called by the main program\n public execute() {\n // If no command is specified, run 'init'\n if (process.argv.length <= 2) {\n process.argv.push('init');\n }\n }\n\n protected setupSetupProjectCommand(): void {\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupStageCommand(): void {\n attachTranslateFlags(\n this.program\n .command('stage')\n .description(\n 'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupEnqueueCommand(): void {\n attachTranslateFlags(\n this.program\n .command('enqueue')\n .description('Enqueues translations for a given set of files')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Enqueuing translations...');\n await this.handleEnqueue(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupDownloadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('download')\n .description('Download translations that were originally staged')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Downloading translations...');\n await this.handleDownload(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachTranslateFlags(\n this.program\n .command('translate')\n .description('Translate your project using General Translation')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Starting translation...');\n await this.handleTranslate(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupSendDiffsCommand(): void {\n attachSharedFlags(\n this.program\n .command('save-local')\n .description(\n 'Save local edits for all configured files by sending diffs (no translation enqueued)'\n )\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .action(async (initOptions: SharedFlags) => {\n displayHeader('Saving local edits...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n await saveLocalEdits(settings);\n logger.endCommand('Saved local edits');\n });\n }\n\n protected setupApiCommand(): void {\n attachSharedFlags(\n this.program\n .command('api [endpoint]')\n .description('Make an authenticated request to the GT API')\n .option('-X, --method <method>', 'HTTP method', 'GET')\n .option('--input <file>', 'Request body file, or - for standard input')\n .option(\n '-H, --header <header>',\n 'Request header in \"Key: Value\" format',\n (header, headers: string[] | undefined) => [\n ...(headers ?? []),\n header,\n ]\n )\n .option('-i, --include', 'Include response status and headers')\n .option(\n '--spec',\n 'Print the bundled OpenAPI specification, or only the operations matching [endpoint] (path or operation ID) with references resolved'\n )\n .addOption(\n new Option(\n '--list',\n 'List the method, path, operation ID, and summary of every API operation'\n ).conflicts('spec')\n )\n ).action((endpoint, options: ApiCommandOptions) =>\n handleApiCommand(endpoint, options)\n );\n }\n\n protected setupProjectCommands(): void {\n const projectCommand = this.program\n .command('project')\n .description('Manage General Translation projects');\n\n attachSharedFlags(\n projectCommand\n .command('create')\n .description(\n 'Create a General Translation project using an organization API key'\n )\n .requiredOption('--org-id <orgId>', 'Organization ID')\n .requiredOption('--name <name>', 'Project name')\n .requiredOption('--default-locale <locale>', 'Project default locale')\n .option('--cdn-enabled', 'Enable CDN delivery', false)\n ).action(async (options) => {\n try {\n const settings = await generateSettings(options);\n // Project creation happens before a project ID exists.\n if (!hasValidServiceLocales(settings)) return exitSync(1);\n const { project } = await api.createProject(options.orgId, {\n name: options.name,\n defaultLocale: options.defaultLocale,\n cdnEnabled: options.cdnEnabled,\n });\n logger.info(`Created ${project.name} (${project.id})`);\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError('Failed to create the project', error)\n );\n }\n });\n\n attachSharedFlags(\n projectCommand\n .command('status')\n .description('Check the status of a project setup job')\n .argument('<job-id>', 'Setup job ID')\n ).action(async (jobId, options) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const [status] = await api.checkJobStatus([jobId]);\n logger.info(status?.status ?? 'unknown');\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError(\n 'Failed to check the project setup status',\n error\n )\n );\n }\n });\n }\n\n protected setupApiKeyCommands(): void {\n const apiKeyCommand = this.program\n .command('api-key')\n .description(\n 'Manage API keys for the configured project or an organization'\n );\n\n attachSharedFlags(\n apiKeyCommand\n .command('create')\n .description(\n 'Create a project API key, or an organization API key with --org-id, with the requested permissions and print it once'\n )\n .requiredOption('--name <name>', 'Key name', parseApiKeyName)\n .option(\n '--org-id <orgId>',\n 'Create an organization API key for this organization instead (requires gt login)'\n )\n // Validated before any request; the server grants the requested set\n // all-or-nothing, so omitting permissions would delegate everything.\n .addOption(\n new Option('--permission <permissions...>', 'Permissions to grant')\n .choices(Object.values(OrgApiKeyPermission))\n .makeOptionMandatory()\n )\n ).action(\n async (\n options: SharedFlags & {\n name: string;\n orgId?: string;\n permission: OrgApiKeyPermission[];\n }\n ) => {\n const projectPermissions = options.permission.filter(\n isProjectApiKeyPermission\n );\n const orgOnlyPermissions = options.permission.filter(\n (permission) => !isProjectApiKeyPermission(permission)\n );\n if (!options.orgId && orgOnlyPermissions.length > 0) {\n return logErrorAndExit(\n createDiagnosticMessage({\n whatHappened: `${orgOnlyPermissions.join(', ')} can only be granted to organization API keys`,\n fix: 'Pass --org-id, or remove those permissions',\n })\n );\n }\n try {\n const settings = await generateSettings(options);\n let key: string;\n if (options.orgId) {\n // No API key can create organization keys, so always send the\n // signed-in user's token, even when an API key is configured.\n configureApiClient({\n baseUrl: settings.baseUrl,\n userTokenProvider: settings.userTokenProvider,\n });\n const { apiKey } = await api.createOrgApiKey(options.orgId, {\n name: options.name,\n permissions: options.permission,\n });\n key = apiKey.key;\n } else {\n if (!hasValidCredentials(settings)) return exitSync(1);\n const { apiKey } = await api.createProjectApiKey(\n settings.projectId,\n { name: options.name, permissions: projectPermissions }\n );\n key = apiKey.key;\n }\n // Raw stdout: the secret is shown once and never reaches the log file.\n process.stdout.write(`${key}\\n`);\n } catch (error) {\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError('Failed to create the API key', error)\n );\n }\n }\n );\n }\n\n protected setupGitCommand(): void {\n const gitCommand = this.program\n .command('git')\n .description('Configure Git integrations for General Translation');\n\n gitCommand\n .command('setup')\n .description('Set up GT merge drivers for generated translation files')\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--dry-run', 'Print changes without writing files', false)\n .option(\n '--omit-config-ids',\n 'Persist omitConfigIds and remove generated config IDs'\n )\n .option(\n '--driver-command <command>',\n 'Command Git should use to invoke gt, e.g. \"pnpm exec gt\"'\n )\n .action(async (options: GitSetupOptions) => {\n displayHeader('Setting up GT Git merge drivers...');\n const settings = await generateSettings(options, undefined, {\n requireConfig: true,\n });\n const omitConfigIds = await this.resolveGitSetupOmitConfigIds(\n options,\n settings\n );\n const result = await setupGitMergeDrivers(settings, {\n dryRun: options.dryRun,\n omitConfigIds,\n driverCommand: options.driverCommand,\n });\n\n for (const line of result.addedAttributes) {\n logger.step(\n `${options.dryRun ? 'Would add' : 'Added'} ${chalk.cyan(\n line\n )} to ${chalk.cyan(result.gitattributesPath)}`\n );\n }\n if (result.addedAttributes.length === 0) {\n logger.info(`${chalk.cyan('.gitattributes')} is already configured.`);\n }\n\n for (const args of result.gitConfigCommands) {\n logger.step(\n `${options.dryRun ? 'Would run' : 'Configured'} ${chalk.cyan(\n `git config --local ${args.join(' ')}`\n )}`\n );\n }\n\n if (result.updatedConfig) {\n logger.step(\n `${options.dryRun ? 'Would persist' : 'Persisted'} ${chalk.cyan(\n 'omitConfigIds: true'\n )} in ${chalk.cyan(settings.config)}`\n );\n } else if (options.dryRun && !settings.omitConfigIds) {\n logger.info(\n `Run without ${chalk.cyan('--dry-run')} to be prompted to persist ${chalk.cyan(\n 'omitConfigIds: true'\n )}, or pass ${chalk.cyan('--omit-config-ids')}.`\n );\n }\n\n for (const warning of result.warnings) {\n logger.warn(chalk.yellow(warning));\n }\n\n logger.endCommand(\n options.dryRun\n ? 'Dry run complete.'\n : 'GT Git merge drivers configured.'\n );\n });\n\n gitCommand\n .command('merge-driver', { hidden: true })\n .addArgument(\n new Argument('<driver>', 'Merge driver name').choices([\n 'gt-lock',\n 'gtjson',\n ])\n )\n .argument('<base>', 'Common ancestor file')\n .argument('<ours>', 'Current branch file')\n .argument('<theirs>', 'Incoming branch file')\n .argument('[path]', 'Merged path')\n .action(\n (\n driver: MergeDriverName,\n base: string,\n ours: string,\n theirs: string\n ) => {\n const result = runMergeDriver(driver, base, ours, theirs);\n if (!result.ok) {\n logger.error(result.reason);\n exitSync(1);\n }\n }\n );\n }\n\n protected async resolveGitSetupOmitConfigIds(\n options: GitSetupOptions,\n settings: Settings\n ): Promise<boolean> {\n if (options.omitConfigIds) return true;\n // Already opted in: persist again so stale config IDs still get removed\n if (settings.omitConfigIds) return true;\n if (options.dryRun || !process.stdin.isTTY || !process.stdout.isTTY) {\n return false;\n }\n return promptConfirm({\n message:\n 'Also set omitConfigIds: true to reduce gt.config.json merge conflicts?',\n defaultValue: true,\n });\n }\n\n protected async handleSetupProject(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n await handleSetupProject(initOptions, settings, this.library);\n }\n\n protected async handleStage(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Update settings.stageTranslations to true\n settings.stageTranslations = true;\n await updateConfig(settings.config, {\n stageTranslations: true,\n });\n }\n await handleStage(initOptions, settings, this.library, true);\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleEnqueue(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleEnqueue(initOptions, settings, this.library);\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleDownload(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleDownload(initOptions, settings, this.library);\n await this.finalizeDownloadedTranslations(settings);\n }\n\n protected async handleTranslate(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Lottie translations finish asynchronously server-side (layout\n // refinement runs after the translation job completes), so the immediate\n // translate flow would try to download them before they're ready. Only\n // the stage + download flow supports them.\n if (settings.files?.resolvedPaths.lottie?.length) {\n return logErrorAndExit(lottieTranslateError);\n }\n const results = await handleStage(\n initOptions,\n settings,\n this.library,\n false\n );\n if (results) {\n await handleTranslate(\n initOptions,\n settings,\n results.fileVersionData,\n results.jobData,\n results.branchData,\n results.publishMap,\n results.inlineLibrary\n );\n }\n } else {\n await handleDownload(initOptions, settings, this.library);\n }\n await this.finalizeDownloadedTranslations(settings);\n }\n\n /**\n * Postprocesses the translations downloaded in this run and reports the\n * summary. Shared by translate and download so both write the same output.\n * @param settings - The settings for the command\n */\n protected async finalizeDownloadedTranslations(\n settings: Settings\n ): Promise<void> {\n // Only postprocess files downloaded in this run\n const include = getNeedsPostprocessing();\n if (include.size > 0) {\n await postProcessTranslations(settings, include);\n }\n // Split Mintlify language entries into $ref files to keep docs.json small\n await splitMintlifyLanguageRefs(settings);\n // Localize redirects for pages this run renamed or removed. Runs after the\n // split, which can rewrite $ref files such as redirects.json\n const orphanedFileNames = getOrphanedFileNames();\n if (orphanedFileNames) {\n const added = localizeMintlifyRedirects(settings, orphanedFileNames);\n if (added.length > 0) {\n logger.success(\n `Added ${added.length} localized redirect${added.length === 1 ? '' : 's'}`\n );\n }\n }\n clearOrphanedFileNames();\n // Mirror assets after translations are downloaded and locale dirs are populated\n await mirrorAssetsToLocales(settings);\n clearDownloaded();\n displayTranslateSummary();\n clearWarnings();\n }\n\n protected setupUploadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('upload')\n .description(\n 'Upload source files and translations to the General Translation platform'\n )\n ).action(async (initOptions: UploadOptions) => {\n displayHeader('Starting upload...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const options = { ...initOptions, ...settings };\n\n await this.handleUploadCommand(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupUserAuthCommands(): void {\n this.program\n .command('login')\n .description('Sign in to your General Translation account')\n .option(\n '--no-browser',\n 'Do not open a browser; show a sign-in URL to use on any device instead'\n )\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json'\n )\n .action(async (options: { browser: boolean; config?: string }) => {\n displayHeader('Signing in to General Translation...');\n try {\n // Tokens are bound to one API resource, so log in to the configured one.\n const baseUrl = (\n options.config\n ? loadConfig(withJsonExtension(options.config))\n : resolveConfig(process.cwd())?.config\n )?.baseUrl;\n await loginInteractively(\n typeof baseUrl === 'string' ? baseUrl : undefined,\n options.browser\n );\n logger.endCommand('You are now signed in.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign in failed', error));\n }\n });\n\n this.program\n .command('logout')\n .description('Sign out of your General Translation account')\n .action(async () => {\n try {\n await logout();\n logger.endCommand('Signed out successfully.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign out failed', error));\n }\n });\n\n this.program\n .command('whoami')\n .description('Show the signed-in General Translation account')\n .action(async () => {\n try {\n const user = await whoAmI();\n logger.message(user.email ?? user.name ?? user.sub);\n } catch (error) {\n logErrorAndExit(\n createUserAuthError('Could not load your account', error)\n );\n }\n });\n }\n\n protected setupInitCommand(): void {\n attachInitFlags(\n this.program\n .command('init')\n .description(\n 'Run the setup wizard to configure your project for General Translation. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: InitOptions) => this.handleInitWizard(options));\n }\n\n protected async handleInitWizard(options: InitOptions): Promise<void> {\n await runOnboarding('init', options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Running setup wizard...');\n\n const detected = await detectFramework();\n // Stop before any change rather than set React Native up as web React.\n if (detected.type === 'react-native') {\n throw new OnboardingError(reactNativeSetupError);\n }\n const reactDetected = detected.type === 'react' ? detected : undefined;\n if (options.framework && !reactDetected) {\n session.reject(\n '--framework applies only to projects detected as React applications'\n );\n }\n const configFilepath = setupConfigPath(options);\n const configured = getConfiguredFramework(\n readSetupConfig(configFilepath)\n );\n const configuredReact =\n configured !== 'mintlify' ? configured : undefined;\n // Explicit --defaults / --no-defaults also answer the Locadex gate.\n if (options.defaults !== undefined) session.defaults = options.defaults;\n const gateFramework = options.framework ?? configured ?? detected.name;\n if (gateFramework === 'mintlify' || gateFramework === 'next-app') {\n const useLocadex = await session.answer('--locadex', {\n explicit: options.locadex,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n gateFramework === 'mintlify'\n ? `Mintlify project detected. Would you like to connect to GitHub so that the Locadex AI Agent can translate your project automatically?`\n : `Next.js App Router detected. Would you like to connect to GitHub so that the Locadex AI Agent can set up your project automatically?`,\n defaultValue: false,\n }),\n });\n if (useLocadex) {\n session.assertResolved();\n const url = await setupLocadex(\n await generateSettings({ config: options.config }),\n { openBrowser: session.interactive }\n );\n session.emit({ type: 'handoff', url, reason: 'locadex' });\n logger.endCommand(\n 'Once installed, Locadex will open a PR to your repository. See the docs for more information: https://generaltranslation.com/docs/locadex'\n );\n return { outcome: 'needs_human_action', url };\n }\n } else if (options.locadex) {\n session.reject(\n '--locadex applies only to Mintlify and Next.js App Router projects'\n );\n }\n\n const shownFramework = reactDetected && {\n ...reactDetected,\n name: options.framework ?? configuredReact ?? reactDetected.name,\n };\n // Without --defaults, a noninteractive run uses no defaults.\n session.defaults =\n (await session.answer('--defaults', {\n explicit: options.defaults,\n fallback: false,\n ask: () =>\n promptConfirm({\n message: `Would you like to use the recommended General Translation defaults? ${chalk.dim(`(${describeDefaults(shownFramework)})`)}`,\n defaultValue: true,\n }),\n })) === true;\n\n const reactSetup = reactDetected\n ? await resolveReactSetup(\n session,\n options,\n reactDetected,\n configuredReact\n )\n : undefined;\n // flag > gt.config.json > detection, used for every later step.\n const framework =\n reactSetup?.framework ??\n options.framework ??\n configured ??\n detected.name;\n const nextSteps = await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n saveFramework: Boolean(reactSetup || options.framework),\n reactSetup,\n keepAppSource: !reactSetup,\n });\n\n if (nextSteps) {\n logger.endCommand(formatInitNextSteps(nextSteps));\n return { outcome: 'success', nextSteps };\n }\n logger.endCommand(\n 'Done! Check out our docs for more information on how to use General Translation: https://generaltranslation.com/docs'\n );\n return { outcome: 'success' };\n });\n }\n\n protected setupConfigureCommand(): void {\n attachConfigureFlags(\n this.program\n .command('configure')\n .description(\n 'Configure your project for General Translation. This will create a gt.config.json file in your codebase. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: ConfigureOptions) =>\n this.handleConfigureCommand(options)\n );\n }\n\n protected async handleConfigureCommand(\n options: ConfigureOptions,\n command: string = 'configure'\n ): Promise<void> {\n await runOnboarding(command, options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Configuring project...');\n\n logger.info(\n 'Welcome! This tool will help you configure your gt.config.json file. See the docs: https://generaltranslation.com/docs/cli/reference/config for more information.'\n );\n\n // Configure only offers the defaults when asked with --defaults.\n session.defaults = options.defaults ?? false;\n const detected = await detectFramework();\n const configFilepath = setupConfigPath(options);\n // Detection only picks env names here; it is not saved. React Native\n // keeps the generic React env names configure has always written.\n const framework =\n getConfiguredFramework(readSetupConfig(configFilepath)) ??\n (detected.type === 'react-native' ? 'react' : detected.name);\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n });\n\n logger.endCommand(\n 'Done! Make sure you have an API key and project ID to use General Translation. Get them on the dashboard: https://generaltranslation.com/dashboard'\n );\n return { outcome: 'success' };\n });\n }\n\n protected async handleUploadCommand(\n settings: Settings & UploadOptions\n ): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n // Process all file types at once with a single call\n await upload(settings);\n }\n\n /** Describes installed runtimes without changing historical package lookup. */\n protected getInlineRuntimeSetup(\n packageJson: Record<string, unknown>,\n ranReactSetup: boolean = false\n ): InlineRuntimeSetup {\n return {\n hasOtherInlineRuntime: INLINE_LIBRARIES.some(\n (lib) =>\n lib !== Libraries.GT_VUE && isPackageInstalled(lib, packageJson)\n ),\n hasVueRuntime: manifestDirectlyDeclaresGTVue(packageJson),\n ranReactSetup,\n };\n }\n\n /** Returns whether any inline runtime is installed for setup. */\n protected isInlineRuntimeInstalled(\n packageJson: Record<string, unknown>\n ): boolean {\n const { hasOtherInlineRuntime, hasVueRuntime } =\n this.getInlineRuntimeSetup(packageJson);\n return hasOtherInlineRuntime || hasVueRuntime;\n }\n\n /** Returns whether every installed runtime can consume CDN translations. */\n protected supportsCDNStorage(runtimeSetup: InlineRuntimeSetup): boolean {\n return !runtimeSetup.hasVueRuntime;\n }\n\n /** Returns whether setup should generate a local runtime loader. */\n protected shouldGenerateLocalTranslationLoader(\n buildToolOwnsLoader: boolean,\n runtimeSetup: InlineRuntimeSetup\n ): boolean {\n if (buildToolOwnsLoader) return false;\n if (!runtimeSetup.hasVueRuntime) return true;\n return runtimeSetup.hasOtherInlineRuntime || runtimeSetup.ranReactSetup;\n }\n\n /** Returns framework guidance after selecting local translation storage. */\n protected getLocalTranslationGuidance({\n generatedLoader,\n runtimeSetup,\n translationsDir,\n }: LocalTranslationGuidanceOptions): string | undefined {\n const guidance: string[] = [];\n if (generatedLoader) {\n guidance.push(`Created ${chalk.cyan('loadTranslations.js')} file for local translations.\nMake sure to add this function to your app configuration.\nSee https://generaltranslation.com/en/docs/next/guides/local-tx`);\n }\n if (runtimeSetup.hasVueRuntime) {\n guidance.push(`GT will write local translation files to ${translationsDir}.\nConfigure createGT({ loadTranslations }) to load files from that directory.\nSee https://www.npmjs.com/package/gt-vue`);\n }\n return guidance.length > 0 ? guidance.join('\\n') : undefined;\n }\n\n /**\n * Resolves every configuration answer and validates the resulting config,\n * checks the project and signs in before the first change, then applies\n * the React setup, gt.config.json, installs and development credentials.\n */\n protected async handleInitCommand(\n session: OnboardingSession,\n options: ConfigureOptions,\n setup: {\n /** Chosen once by the entry point from the detected framework. */\n configFilepath: string;\n /** Resolved framework; drives storage, env names and build-tool setup. */\n framework?: SupportedFrameworks;\n /** Write the framework even when no build-tool setup saves it. */\n saveFramework?: boolean;\n reactSetup?: ReactSetupPlan;\n /** Init without the React setup never changes application source. */\n keepAppSource?: boolean;\n }\n ): Promise<string[] | undefined> {\n const { configFilepath, reactSetup } = setup;\n const buildTool = getBuildToolSetup(setup.framework);\n const cwd = process.cwd();\n const existingConfig = readSetupConfig(configFilepath);\n const { defaultLocale, locales } = await getDesiredLocales(\n session,\n existingConfig,\n options\n );\n\n const packageJson =\n reactSetup?.packageJson ?? (await searchForPackageJson());\n const runtimeSetup: InlineRuntimeSetup = packageJson\n ? this.getInlineRuntimeSetup(packageJson, Boolean(reactSetup))\n : {\n hasOtherInlineRuntime: false,\n hasVueRuntime: false,\n ranReactSetup: false,\n };\n const isUsingGT =\n runtimeSetup.ranReactSetup ||\n runtimeSetup.hasOtherInlineRuntime ||\n runtimeSetup.hasVueRuntime;\n const supportsCDN = this.supportsCDNStorage(runtimeSetup);\n const existingFiles = asRecord(existingConfig.files) ?? {};\n const existingGtOutput = asRecord(existingFiles.gt)?.output;\n const configuredOutput =\n typeof existingGtOutput === 'string' ? existingGtOutput : undefined;\n const configuredStorage = configuredOutput\n ? 'local'\n : existingConfig.publish === true\n ? 'cdn'\n : undefined;\n\n if (isUsingGT && !supportsCDN && options.storage === 'cdn') {\n session.reject(\n 'gt-vue cannot load translations from the CDN; use --storage local'\n );\n }\n // Where GT translations are stored\n const storage = !isUsingGT\n ? undefined\n : !supportsCDN\n ? 'local'\n : await session.answer<'local' | 'cdn'>('--storage', {\n explicit: options.storage,\n configured: configuredStorage,\n recommended: 'local',\n ask: () =>\n promptSelect<'local' | 'cdn'>({\n message: `Would you like to save translation files locally or use the General Translation CDN to store them?`,\n options: [\n { value: 'local', label: 'Save locally' },\n { value: 'cdn', label: 'Use CDN' },\n ],\n defaultValue: 'local',\n }),\n });\n\n const defaultTranslationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n const outputMatch = configuredOutput?.match(\n /^(?:(.+)[\\\\/])?\\[locale\\]\\.json$/\n );\n const configuredTranslationsDir = outputMatch\n ? (outputMatch[1] ?? '.')\n : undefined;\n const translationsDir =\n storage === 'local'\n ? await session.answer('--translations-dir', {\n explicit: options.translationsDir?.trim() || undefined,\n configured: configuredTranslationsDir,\n recommended: defaultTranslationsDir,\n ask: async () =>\n (\n await promptText({\n message:\n 'What is the path to the directory where you would like to store your translation files?',\n defaultValue: defaultTranslationsDir,\n })\n ).trim() || defaultTranslationsDir,\n })\n : undefined;\n\n const filePatterns = parseFilePatterns(session, options.filePatterns);\n const selectedFormats = options.fileFormats?.filter(\n (format): format is SetupFileFormat => format !== 'none'\n );\n if (\n options.fileFormats?.includes('none') &&\n (selectedFormats?.length ?? 0) > 0\n ) {\n session.reject('--file-formats none cannot be combined with formats');\n }\n const configuredFormats = SETUP_FILE_FORMATS.filter(\n (format) => format in existingFiles\n );\n // Formats setup does not offer stay as configured and count as files.\n const otherFormats = SUPPORTED_FILE_EXTENSIONS.filter(\n (format) =>\n format in existingFiles &&\n !(SETUP_FILE_FORMATS as readonly string[]).includes(format)\n );\n const hasOtherFormats = otherFormats.length > 0;\n if (options.fileFormats && hasOtherFormats) {\n const kept = otherFormats.map((format) => `files.${format}`).join(', ');\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `${kept} stays in ${configFilepath}`,\n why: '--file-formats only changes the formats setup offers',\n fix: `Remove ${kept} from ${configFilepath} to stop translating those files`,\n })\n );\n }\n const fileFormats = await session.answer<SetupFileFormat[]>(\n '--file-formats',\n {\n explicit:\n selectedFormats ??\n (filePatterns.size > 0 ? [...filePatterns.keys()] : undefined),\n configured:\n configuredFormats.length > 0 || hasOtherFormats\n ? configuredFormats\n : undefined,\n // GT projects need no other files; others must choose a format.\n recommended: isUsingGT ? [] : undefined,\n ask: () =>\n promptMultiSelect({\n message: !isUsingGT\n ? 'What is the format of your language resource files? Select as many as applicable.\\nAdditionally, you can translate any other files you have in your project.'\n : `Do you have any additional files in this project to translate? For example, Markdown files for docs. ${chalk.dim(\n '(To continue without selecting press Enter)'\n )}`,\n options: SETUP_FILE_FORMATS.map((format) => ({\n value: format,\n label: FILE_EXT_TO_EXT_LABEL[format],\n })),\n required: !isUsingGT,\n }),\n }\n );\n if (\n fileFormats &&\n fileFormats.length === 0 &&\n !isUsingGT &&\n !hasOtherFormats\n ) {\n session.reject(\n 'No GT runtime is installed, so select at least one file format to translate'\n );\n }\n for (const format of filePatterns.keys()) {\n if (fileFormats && !fileFormats.includes(format)) {\n session.reject(\n `--file-patterns ${format}= needs ${format} in --file-formats`\n );\n }\n }\n\n const files: FilesOptions = {};\n for (const fileExtension of fileFormats ?? []) {\n const existingFormat = asRecord(existingFiles[fileExtension]);\n const configuredInclude = Array.isArray(existingFormat?.include)\n ? (existingFormat.include as string[])\n : undefined;\n const include = await session.answer(\n `--file-patterns ${fileExtension}=<glob>`,\n {\n explicit: filePatterns.get(fileExtension),\n configured: configuredInclude,\n recommended: [`./**/[locale]/*.${fileExtension}`],\n ask: async () =>\n parseGlobPatterns(\n await promptGlobPatterns({\n label: FILE_EXT_TO_EXT_LABEL[fileExtension],\n message: `${chalk.cyan(FILE_EXT_TO_EXT_LABEL[fileExtension])}: Enter a space-separated list of glob patterns matching the location of the ${FILE_EXT_TO_EXT_LABEL[fileExtension]} files you would like to translate.\\nMake sure to include [locale] in the patterns.\\nSee https://generaltranslation.com/docs/cli/reference/config#include for more information.`,\n defaultValue: `./**/[locale]/*.${fileExtension}`,\n validate: (value) =>\n parseGlobPatterns(value)\n .map(validateSetupPattern)\n .find((problem) => problem !== true) ?? true,\n })\n ),\n }\n );\n // Configured patterns stay untouched; new ones keep other entry options.\n if (include && include !== configuredInclude) {\n files[fileExtension] = { ...existingFormat, include };\n }\n }\n if (translationsDir && translationsDir !== configuredTranslationsDir) {\n files.gt = { output: path.join(translationsDir, `[locale].json`) };\n }\n\n const envFramework =\n setup.framework ?? getConfiguredFramework(existingConfig);\n // The effective project: an explicit ID replaces a configured one. The\n // framework's runtime project outranks a stale generic GT_PROJECT_ID.\n const projectId =\n options.projectId ||\n (typeof existingConfig.projectId === 'string'\n ? existingConfig.projectId\n : undefined) ||\n process.env[getDevelopmentEnvNames(envFramework).projectId];\n const configUpdate: SetupConfigUpdate = {\n defaultLocale,\n locales,\n src: options.src,\n files: Object.keys(files).length > 0 ? files : undefined,\n framework:\n (setup.saveFramework && setup.framework) || buildTool?.framework,\n publish: storage === 'cdn',\n // Selecting local storage drops stale CDN intent; a config that\n // already combines local files with publishing keeps it.\n clearPublish:\n storage === 'local' &&\n (options.storage === 'local' ||\n configuredStorage !== 'local' ||\n !supportsCDN),\n // An explicit switch to the CDN stops later runs inferring local files.\n clearGtOutput: storage === 'cdn' && configuredOutput !== undefined,\n // An explicit format list replaces the configured selection.\n removeFiles: selectedFormats\n ? configuredFormats.filter(\n (format) => !selectedFormats.includes(format)\n )\n : undefined,\n };\n session.assertResolved();\n\n // Validate what will be written, and use it for every later step.\n const { projectId: _writtenProjectId, ...effectiveConfig } =\n mergeSetupConfig(existingConfig, configUpdate);\n const settings = await generateSettings(\n { config: configFilepath, ...(projectId && { projectId }) },\n cwd,\n { resolvedConfig: effectiveConfig }\n );\n // Runtime credentials only count for the project this setup uses; the\n // framework's project variable is the one paired with its dev key.\n const runtimeProjectId =\n process.env[getDevelopmentEnvNames(envFramework).projectId] ??\n resolveProjectId();\n const runtimeProjectMatches =\n runtimeProjectId === undefined || runtimeProjectId === settings.projectId;\n const credentialsSet =\n runtimeProjectMatches && areCredentialsSet(settings, envFramework);\n const credentialsOption =\n (storage === 'local' && buildTool?.devCredentialsOption) ||\n '--dev-credentials';\n // Creating credentials talks to GT as the signed-in user unless an API\n // key is set. A development key in .env.local never stands in. An\n // obsolete stored login counts as signed out, so signing in replaces it.\n const canAuthenticate = async () =>\n Boolean(settings.apiKey) ||\n (await hasLogin({ baseUrl: settings.baseUrl }).catch((error) => {\n if (\n error instanceof UserAuthError &&\n error.code === 'obsolete_credentials'\n )\n return false;\n throw error;\n }));\n const provision =\n !credentialsSet &&\n (credentialsOption === '--live-translations'\n ? await session.answer('--live-translations', {\n explicit: options.liveTranslations ?? options.devCredentials,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n 'Would you like to set up live development translations? This requires signing in or an API key.',\n defaultValue: false,\n }),\n })\n : await session.answer('--dev-credentials or --no-dev-credentials', {\n explicit: options.devCredentials,\n // Creating a key is never a default, so --defaults leaves this open.\n // The prompt names the sign-in so its Yes default is informed.\n ask: async () =>\n promptConfirm({\n message: (await canAuthenticate())\n ? 'Would you like to set up a project ID and hot-reload key in .env.local?'\n : 'Would you like to sign in to General Translation and set up a project ID and hot-reload key in .env.local?',\n defaultValue: true,\n }),\n })) === true;\n if (!runtimeProjectMatches && !provision) {\n session.reject(\n `The runtime credentials in the environment belong to project ${runtimeProjectId}, not ${settings.projectId}; pass --dev-credentials to replace them in .env.local`\n );\n }\n // An explicit ID is saved to gt.config.json when it replaces a\n // configured one or no new credentials will record it in .env.local.\n if (options.projectId && (existingConfig.projectId || !provision)) {\n configUpdate.projectId = options.projectId;\n }\n if (provision) {\n checkDevelopmentProjectInputs(\n session,\n settings,\n options,\n options.projectId\n ? '--project-id'\n : // An empty configured ID falls through to the environment.\n typeof existingConfig.projectId === 'string' &&\n existingConfig.projectId\n ? configFilepath\n : 'the environment'\n );\n await withCredentialsError(() =>\n inspectCredentialsEnvFile(cwd, { framework: envFramework })\n );\n }\n\n if (reactSetup && buildTool) await buildTool.preflight(cwd);\n const installGT =\n packageJson !== null &&\n !isPackageInstalled('gt', packageJson, true, true) &&\n !buildTool?.skipsGTInstall(isUsingGT);\n const packageManager =\n reactSetup?.install || installGT\n ? await resolvePackageManager(session, options.packageManager)\n : undefined;\n\n session.assertResolved();\n\n if (provision && !(await canAuthenticate())) {\n await signInForSetup(session, settings.baseUrl);\n }\n const project = provision\n ? await withCredentialsError(() =>\n resolveDevelopmentProject(session, settings, options, cwd)\n )\n : undefined;\n session.assertResolved();\n\n // ----- Changes start here ----- //\n const resolvedLocales = locales as string[];\n\n if (reactSetup) {\n logger.info(`${chalk.yellow('[EXPERIMENTAL]')} Configuring project...`);\n if (reactSetup.install && packageManager) {\n await installWithProgress(\n session,\n reactSetup.install,\n packageManager,\n false\n );\n }\n await executeReactSetup(session, reactSetup, options);\n logger.step('Setting up project config...');\n }\n\n const reportManualAction = ({ whatHappened, fix }: ManualAction) => {\n session.humanActions.push(fix);\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened,\n fix,\n })\n );\n };\n const reportSetupResult = ({ steps, manualActions }: SetupResult) => {\n for (const step of steps) session.step(step);\n manualActions.forEach(reportManualAction);\n };\n const translationFilesError = (error: unknown) =>\n new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not create the translation files in ${translationsDir}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Choose another --translations-dir or fix the path, then rerun the command',\n })\n );\n const buildToolContext = {\n appDirectory: cwd,\n configFilepath,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n previousTranslationsDir: configuredTranslationsDir,\n };\n\n if (storage === 'local' && translationsDir) {\n if (buildTool && !reactSetup) {\n reportSetupResult(\n await buildTool\n .syncLoader({\n ...buildToolContext,\n translationsDir,\n keepAppSource: setup.keepAppSource,\n })\n .catch((error: unknown) => {\n throw translationFilesError(error);\n })\n );\n }\n const generatedLoader = this.shouldGenerateLocalTranslationLoader(\n buildTool?.ownsLoader ?? false,\n runtimeSetup\n );\n const loader = generatedLoader\n ? await createLoadTranslationsFile({\n appDirectory: cwd,\n translationsDir,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n previousTranslationsDir: configuredTranslationsDir,\n }).catch((error: unknown) => {\n throw translationFilesError(error);\n })\n : undefined;\n if (loader === 'created' || loader === 'updated') {\n session.step(`${loader} loadTranslations.js`);\n }\n // A loader left unchanged may not read the newly chosen directory.\n if (\n loader === 'custom' &&\n translationsDir !== configuredTranslationsDir\n ) {\n const loaderFile = path.relative(\n cwd,\n findLoadTranslationsFiles(cwd)[0] ?? 'loadTranslations.js'\n );\n reportManualAction({\n whatHappened: `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`,\n fix: `Update your custom ${loaderFile} to load translations from ${translationsDir}`,\n });\n }\n const guidance = this.getLocalTranslationGuidance({\n generatedLoader: generatedLoader && loader !== 'custom',\n runtimeSetup,\n translationsDir,\n });\n if (guidance) logger.message(guidance);\n } else if (\n storage === 'cdn' &&\n buildTool &&\n !reactSetup &&\n configuredTranslationsDir !== undefined\n ) {\n // Only the application setup rewrites the initializer; a loader passed\n // to it takes precedence over CDN loading.\n const action = await buildTool.getCDNStorageAction?.(buildToolContext);\n if (action !== null) {\n reportManualAction(\n action ?? {\n whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,\n fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`,\n }\n );\n }\n } else if (\n storage === 'cdn' &&\n !buildTool &&\n configuredTranslationsDir !== undefined\n ) {\n // gt-next uses a loadTranslations file whenever one exists, and a\n // loader passed to GTProvider takes precedence over the CDN. Name every\n // one: deleting only the first makes gt-next fall back to the next.\n const loaders = findLoadTranslationsFiles(cwd).map((loader) =>\n path.relative(cwd, loader)\n );\n if (loaders.length > 0) {\n const loaderFiles = loaders.join(', ');\n const [them, loads] =\n loaders.length === 1 ? ['it', 'loads'] : ['them', 'load'];\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${loaderFiles} still ${loads} them from ${configuredTranslationsDir}`,\n fix: `Delete ${loaderFiles}, and remove ${them} from your GT setup if you pass ${them} there, so translations load from the CDN`,\n });\n }\n }\n\n const configChange = await applySetupConfig(configFilepath, configUpdate);\n if (configChange !== 'unchanged') {\n session.step(`${configChange} ${configFilepath}`);\n }\n\n logger.success(\n `Edit ${chalk.cyan(\n configFilepath\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n if (reactSetup && buildTool) {\n reportSetupResult(await buildTool.apply(buildToolContext));\n }\n\n if (installGT && packageManager) {\n await installWithProgress(session, 'gt', packageManager, true);\n }\n\n if (project) {\n await withCredentialsError(() =>\n provisionDevelopmentCredentials(\n session,\n project,\n settings,\n envFramework,\n cwd\n )\n );\n logger.message(productionRuntimeKeyGuidance(settings.dashboardUrl));\n }\n\n if (!reactSetup) return undefined;\n // The React setup configures the app entry but never marks content for\n // translation, so what is left is reported as next steps.\n const devPackageManager =\n packageManager ??\n (await getPackageManager(cwd, options.packageManager, true).catch(\n () => undefined\n ));\n const scripts = asRecord(reactSetup.packageJson.scripts);\n return getInitNextSteps({\n framework: reactSetup.framework,\n configuredAppEntry:\n reactSetup.framework === 'next-app' || buildTool !== undefined,\n docsUrl: getSetupDocsUrl(reactSetup.framework),\n locales: resolvedLocales,\n configFilepath,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n devCommand:\n typeof scripts?.dev === 'string'\n ? `${devPackageManager?.runScriptCommand ?? 'npm run'} dev`\n : undefined,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAM,oCAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,SAAS,0BACP,cACA,OACQ;AACR,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV;EACA,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,uBAAuB,wBAAwB;CACnD,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAM,2BAA2B,IAAI,IACnC,OAAO,OAAO,wBAAwB,CACvC;AAED,SAAS,0BACP,YACuC;AACvC,QAAO,yBAAyB,IAAI,WAAW;;AAGjD,SAAS,gBAAgB,OAAuB;CAC9C,MAAM,OAAO,MAAM,MAAM;AACzB,KAAI,CAAC,KAAM,OAAM,IAAI,qBAAqB,qBAAqB;AAC/D,QAAO;;;AAIT,eAAe,qBAAwB,KAAmC;AACxE,KAAI;AACF,SAAO,MAAM,KAAK;UACX,OA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AAU,YAAY,eAAe,KAAK,kCAAkC,KAAK;KACvF,CAAC;;;EAIN,MAAM,eAAe,MAAM,iBAAiB,gBAAgB,aAAa;AACzE,MAAI,iBAAiB,YACnB,SAAQ,KAAK,GAAG,aAAa,GAAG,iBAAiB;AAGnD,SAAO,QACL,QAAQ,MAAM,KACZ,eACD,CAAC,sGACH;AAED,MAAI,cAAc,UAChB,mBAAkB,MAAM,UAAU,MAAM,iBAAiB,CAAC;AAG5D,MAAI,aAAa,eACf,OAAM,oBAAoB,SAAS,MAAM,gBAAgB,KAAK;AAGhE,MAAI,SAAS;AACX,SAAM,2BACJ,gCACE,SACA,SACA,UACA,cACA,IACD,CACF;AACD,UAAO,QAAQ,6BAA6B,SAAS,aAAa,CAAC;;AAGrE,MAAI,CAAC,WAAY,QAAO,KAAA;EAGxB,MAAM,oBACJ,kBACC,MAAM,kBAAkB,KAAK,QAAQ,gBAAgB,KAAK,CAAC,YACpD,KAAA,EACP;EACH,MAAM,UAAU,SAAS,WAAW,YAAY,QAAQ;AACxD,SAAO,iBAAiB;GACtB,WAAW,WAAW;GACtB,oBACE,WAAW,cAAc,cAAc,cAAc,KAAA;GACvD,SAAS,gBAAgB,WAAW,UAAU;GAC9C,SAAS;GACT;GACA,iBAAiB,YAAY,UAAU,kBAAkB,KAAA;GACzD,YACE,OAAO,SAAS,QAAQ,WACpB,GAAG,mBAAmB,oBAAoB,UAAU,QACpD,KAAA;GACP,CAAC"}
1
+ {"version":3,"file":"base.js","names":[],"sources":["../../src/cli/base.ts"],"sourcesContent":["import { Argument, Command, InvalidArgumentError, Option } from 'commander';\nimport {\n OrgApiKeyPermission,\n ProjectApiKeyPermission,\n} from 'generaltranslation/api';\nimport { DEFAULT_TRANSLATIONS_DIR } from '../utils/constants.js';\nimport {\n applySetupConfig,\n mergeSetupConfig,\n type SetupConfigUpdate,\n} from '../fs/config/setupConfig.js';\nimport findFilepath from '../fs/findFilepath.js';\nimport {\n displayHeader,\n promptText,\n logErrorAndExit,\n exitSync,\n promptConfirm,\n promptMultiSelect,\n promptSelect,\n promptGlobPatterns,\n} from '../console/logging.js';\nimport { logger } from '../console/logger.js';\nimport { lottieTranslateError } from '../console/index.js';\nimport { parseGlobPatterns } from '../console/promptParsing.js';\nimport path from 'node:path';\nimport {\n FilesOptions,\n Settings,\n SupportedFrameworks,\n SupportedLibraries,\n TranslateFlags,\n SharedFlags,\n} from '../types/index.js';\nimport { generateSettings } from '../config/generateSettings.js';\nimport chalk from 'chalk';\nimport {\n FILE_EXT_TO_EXT_LABEL,\n SETUP_FILE_FORMATS,\n SUPPORTED_FILE_EXTENSIONS,\n type SetupFileFormat,\n} from '../formats/files/supportedFiles.js';\nimport {\n executeReactSetup,\n resolveReactSetup,\n type ReactSetupPlan,\n} from '../setup/wizard.js';\nimport { formatInitNextSteps, getInitNextSteps } from '../setup/nextSteps.js';\nimport { getPackageManager } from '../utils/packageManager.js';\nimport {\n isPackageInstalled,\n searchForPackageJson,\n} from '../utils/packageJson.js';\nimport { getDesiredLocales } from '../setup/userInput.js';\nimport {\n areCredentialsSet,\n getDevelopmentEnvNames,\n inspectCredentialsEnvFile,\n} from '../utils/credentials.js';\nimport {\n checkDevelopmentProjectInputs,\n productionRuntimeKeyGuidance,\n provisionDevelopmentCredentials,\n resolveDevelopmentProject,\n signInForSetup,\n} from '../setup/developmentCredentials.js';\nimport {\n exitIfUnsupportedSetupTarget,\n reactNativeSetupError,\n} from '../setup/setupTarget.js';\nimport {\n asRecord,\n attachConfigureFlags,\n attachInitFlags,\n describeDefaults,\n displaySetupHeader,\n getConfiguredFramework,\n INIT_SOURCE_HELP,\n installWithProgress,\n OnboardingError,\n parseFilePatterns,\n readSetupConfig,\n reportJsonExitsBeforeOnboarding,\n resolvePackageManager,\n runOnboarding,\n setupConfigPath,\n validateSetupPattern,\n type ConfigureOptions,\n type InitOptions,\n type OnboardingSession,\n} from '../setup/onboarding.js';\nimport { upload } from './commands/upload.js';\nimport { attachSharedFlags, attachTranslateFlags } from './flags.js';\nimport { handleStage } from './commands/stage.js';\nimport { handleSetupProject } from './commands/setupProject.js';\nimport { handleDownload } from './commands/download.js';\nimport {\n handleTranslate,\n postProcessTranslations,\n} from './commands/translate.js';\nimport {\n getNeedsPostprocessing,\n clearDownloaded,\n} from '../state/recentDownloads.js';\nimport { clearWarnings } from '../state/translateWarnings.js';\nimport { displayTranslateSummary } from '../console/displayTranslateSummary.js';\nimport updateConfig from '../fs/config/updateConfig.js';\nimport {\n createLoadTranslationsFile,\n findLoadTranslationsFiles,\n} from '../fs/createLoadTranslationsFile.js';\nimport { saveLocalEdits } from '../api/saveLocalEdits.js';\nimport { resolveProjectId } from '../fs/utils.js';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './commands/utils/validation.js';\nimport processSharedStaticAssets, {\n mirrorAssetsToLocales,\n} from '../utils/sharedStaticAssets.js';\nimport { setupLocadex } from '../locadex/setupFlow.js';\nimport { detectFramework } from '../setup/detectFramework.js';\nimport { INLINE_LIBRARIES, Libraries } from '../types/libraries.js';\nimport { handleEnqueue } from './commands/enqueue.js';\nimport { splitMintlifyLanguageRefs } from '../utils/splitMintlifyLanguageRefs.js';\nimport { localizeMintlifyRedirects } from '../formats/files/postprocess/localizeMintlifyRedirects.js';\nimport {\n clearOrphanedFileNames,\n getOrphanedFileNames,\n} from '../state/orphanedFileNames.js';\nimport { runMergeDriver, type MergeDriverName } from '../git/mergeDrivers.js';\nimport { setupGitMergeDrivers } from '../git/setupMergeDrivers.js';\nimport { warnReactPackageCompatibility } from '../utils/reactPackageCompatibility.js';\nimport {\n createDiagnosticMessage,\n formatDiagnosticErrorDetails,\n} from 'generaltranslation/diagnostics';\nimport { hasLogin, logout, whoAmI } from '../auth/oauth.js';\nimport { createUserAuthError, UserAuthError } from '../auth/errors.js';\nimport { loginInteractively } from '../auth/interactiveLogin.js';\nimport { resolveConfig } from '../config/resolveConfig.js';\nimport { loadConfig, withJsonExtension } from '../fs/config/loadConfig.js';\nimport {\n getBuildToolSetup,\n getSetupDocsUrl,\n type ManualAction,\n type SetupResult,\n} from '../setup/buildTools/index.js';\nimport { manifestDirectlyDeclaresGTVue } from '@generaltranslation/vue-extractor/integration';\nimport { api, configureApiClient } from '../utils/api.js';\nimport { handleApiCommand, type ApiCommandOptions } from './commands/api.js';\n\nconst ID_COMPATIBILITY_WARNING_COMMANDS = new Set([\n 'download',\n 'enqueue',\n 'generate',\n 'setup',\n 'stage',\n 'translate',\n 'validate',\n]);\nfunction createProjectCommandError(\n whatHappened: string,\n error: unknown\n): string {\n return createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened,\n details: formatDiagnosticErrorDetails(error),\n });\n}\n\nconst emptyApiKeyNameError = createDiagnosticMessage({\n whatHappened: 'The key name cannot be empty',\n fix: 'Pass a non-empty value with --name',\n});\n\nconst projectApiKeyPermissions = new Set<string>(\n Object.values(ProjectApiKeyPermission)\n);\n\nfunction isProjectApiKeyPermission(\n permission: OrgApiKeyPermission\n): permission is ProjectApiKeyPermission {\n return projectApiKeyPermissions.has(permission);\n}\n\nfunction parseApiKeyName(value: string): string {\n const name = value.trim();\n if (!name) throw new InvalidArgumentError(emptyApiKeyNameError);\n return name;\n}\n\n/** Credential failures keep their own diagnostic or get the setup context. */\nasync function withCredentialsError<T>(run: () => Promise<T>): Promise<T> {\n try {\n return await run();\n } catch (error) {\n if (error instanceof OnboardingError) throw error;\n throw new Error(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError(\n 'Failed to set up the development credentials',\n error\n )\n );\n }\n}\n\nexport type UploadOptions = {\n config?: string;\n apiKey?: string;\n projectId?: string;\n defaultLocale?: string;\n};\n\nexport type GitSetupOptions = {\n config?: string;\n dryRun?: boolean;\n omitConfigIds?: boolean;\n driverCommand?: string;\n};\n\ntype LocalTranslationGuidanceOptions = {\n generatedLoader: boolean;\n runtimeSetup: InlineRuntimeSetup;\n translationsDir: string;\n};\n\ntype InlineRuntimeSetup = {\n hasOtherInlineRuntime: boolean;\n hasVueRuntime: boolean;\n ranReactSetup: boolean;\n};\n\nexport class BaseCLI {\n protected library: SupportedLibraries;\n protected additionalModules: SupportedLibraries[];\n protected program: Command;\n // Constructor is shared amongst all CLI class types\n public constructor(\n program: Command,\n library: SupportedLibraries,\n additionalModules?: SupportedLibraries[]\n ) {\n this.program = program;\n this.library = library;\n this.additionalModules = additionalModules || [];\n\n this.program.option(\n '--skip-version-check',\n 'Skip the monorepo GT package version consistency check'\n );\n this.program.option(\n '--suppress-id-compatibility-warning',\n 'Suppress the React package ID compatibility warning'\n );\n this.program.option(\n '-q, --quiet',\n 'Suppress informational output; only warnings and errors are shown'\n );\n // Select console routing for this command before anything else logs:\n // root hooks run before subclass hooks (version checks) and the action's\n // settings resolution. `gt api-key create` prints the new secret on\n // stdout, so its diagnostics go to stderr, as do setup commands writing\n // JSON events; every other command gets the historical default back\n // (main() routes startup output to stderr).\n this.program.hook('preAction', (thisCommand, actionCommand) => {\n logger.setConsoleOutput(\n actionCommand.parent?.name() === 'api-key' || actionCommand.opts().json\n ? 'stderr'\n : 'stdout'\n );\n if (\n actionCommand.opts().json &&\n actionCommand.parent === thisCommand &&\n ['init', 'configure'].includes(actionCommand.name())\n ) {\n reportJsonExitsBeforeOnboarding(actionCommand.name());\n }\n });\n // Apply --quiet before any other hook or command action runs so the\n // singleton logger is muted for the rest of the invocation. The flag is a\n // global root option, so commander resolves it in any position and for\n // nested commands (e.g. `gt git setup --quiet`).\n this.program.hook('preAction', () => {\n logger.setQuiet(Boolean(this.program.opts().quiet));\n });\n this.program.hook('preAction', async (thisCommand, actionCommand) => {\n // Nested commands (e.g. `gt git setup`) can share leaf names with\n // translation commands; only direct children of the root qualify\n if (actionCommand.parent !== thisCommand) return;\n if (!ID_COMPATIBILITY_WARNING_COMMANDS.has(actionCommand.name())) return;\n await warnReactPackageCompatibility(\n Boolean(this.program.opts().suppressIdCompatibilityWarning)\n );\n });\n\n this.setupInitCommand();\n this.setupConfigureCommand();\n this.setupUploadCommand();\n this.setupUserAuthCommands();\n this.setupSendDiffsCommand();\n this.setupApiCommand();\n this.setupProjectCommands();\n this.setupApiKeyCommands();\n this.setupGitCommand();\n }\n // Init is never called in a child class\n public init() {\n this.setupSetupProjectCommand();\n this.setupStageCommand();\n this.setupTranslateCommand();\n this.setupDownloadCommand();\n this.setupEnqueueCommand();\n }\n // Execute is called by the main program\n public execute() {\n // If no command is specified, run 'init'\n if (process.argv.length <= 2) {\n process.argv.push('init');\n }\n }\n\n protected setupSetupProjectCommand(): void {\n attachTranslateFlags(\n this.program\n .command('setup')\n .description(\n 'Upload source files and setup the project for translation'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Uploading source files and setting up project...');\n await this.handleSetupProject(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupStageCommand(): void {\n attachTranslateFlags(\n this.program\n .command('stage')\n .description(\n 'Submits the project to the General Translation API for translation. Translations created using this command will require human approval.'\n )\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader(\n 'Staging project for translation with approval required...'\n );\n await this.handleStage(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupEnqueueCommand(): void {\n attachTranslateFlags(\n this.program\n .command('enqueue')\n .description('Enqueues translations for a given set of files')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Enqueuing translations...');\n await this.handleEnqueue(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected setupDownloadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('download')\n .description('Download translations that were originally staged')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Downloading translations...');\n await this.handleDownload(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupTranslateCommand(): void {\n attachTranslateFlags(\n this.program\n .command('translate')\n .description('Translate your project using General Translation')\n ).action(async (initOptions: TranslateFlags) => {\n displayHeader('Starting translation...');\n await this.handleTranslate(initOptions);\n logger.endCommand('Done!');\n });\n }\n\n protected setupSendDiffsCommand(): void {\n attachSharedFlags(\n this.program\n .command('save-local')\n .description(\n 'Save local edits for all configured files by sending diffs (no translation enqueued)'\n )\n )\n .option('--publish', 'Publish translations to the CDN', false)\n .action(async (initOptions: SharedFlags) => {\n displayHeader('Saving local edits...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n await saveLocalEdits(settings);\n logger.endCommand('Saved local edits');\n });\n }\n\n protected setupApiCommand(): void {\n attachSharedFlags(\n this.program\n .command('api [endpoint]')\n .description('Make an authenticated request to the GT API')\n .option('-X, --method <method>', 'HTTP method', 'GET')\n .option('--input <file>', 'Request body file, or - for standard input')\n .option(\n '-H, --header <header>',\n 'Request header in \"Key: Value\" format',\n (header, headers: string[] | undefined) => [\n ...(headers ?? []),\n header,\n ]\n )\n .option('-i, --include', 'Include response status and headers')\n .option(\n '--spec',\n 'Print the bundled OpenAPI specification, or only the operations matching [endpoint] (path or operation ID) with references resolved'\n )\n .addOption(\n new Option(\n '--list',\n 'List the method, path, operation ID, and summary of every API operation'\n ).conflicts('spec')\n )\n ).action((endpoint, options: ApiCommandOptions) =>\n handleApiCommand(endpoint, options)\n );\n }\n\n protected setupProjectCommands(): void {\n const projectCommand = this.program\n .command('project')\n .description('Manage General Translation projects');\n\n attachSharedFlags(\n projectCommand\n .command('create')\n .description(\n 'Create a General Translation project using an organization API key'\n )\n .requiredOption('--org-id <orgId>', 'Organization ID')\n .requiredOption('--name <name>', 'Project name')\n .requiredOption('--default-locale <locale>', 'Project default locale')\n .option('--cdn-enabled', 'Enable CDN delivery', false)\n ).action(async (options) => {\n try {\n const settings = await generateSettings(options);\n // Project creation happens before a project ID exists.\n if (!hasValidServiceLocales(settings)) return exitSync(1);\n const { project } = await api.createProject(options.orgId, {\n name: options.name,\n defaultLocale: options.defaultLocale,\n cdnEnabled: options.cdnEnabled,\n });\n logger.info(`Created ${project.name} (${project.id})`);\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError('Failed to create the project', error)\n );\n }\n });\n\n attachSharedFlags(\n projectCommand\n .command('status')\n .description('Check the status of a project setup job')\n .argument('<job-id>', 'Setup job ID')\n ).action(async (jobId, options) => {\n try {\n const settings = await generateSettings(options);\n if (!hasValidCredentials(settings)) return exitSync(1);\n const [status] = await api.checkJobStatus([jobId]);\n logger.info(status?.status ?? 'unknown');\n } catch (error) {\n return logErrorAndExit(\n createProjectCommandError(\n 'Failed to check the project setup status',\n error\n )\n );\n }\n });\n }\n\n protected setupApiKeyCommands(): void {\n const apiKeyCommand = this.program\n .command('api-key')\n .description(\n 'Manage API keys for the configured project or an organization'\n );\n\n attachSharedFlags(\n apiKeyCommand\n .command('create')\n .description(\n 'Create a project API key, or an organization API key with --org-id, with the requested permissions and print it once'\n )\n .requiredOption('--name <name>', 'Key name', parseApiKeyName)\n .option(\n '--org-id <orgId>',\n 'Create an organization API key for this organization instead (requires gt login)'\n )\n // Validated before any request; the server grants the requested set\n // all-or-nothing, so omitting permissions would delegate everything.\n .addOption(\n new Option('--permission <permissions...>', 'Permissions to grant')\n .choices(Object.values(OrgApiKeyPermission))\n .makeOptionMandatory()\n )\n ).action(\n async (\n options: SharedFlags & {\n name: string;\n orgId?: string;\n permission: OrgApiKeyPermission[];\n }\n ) => {\n const projectPermissions = options.permission.filter(\n isProjectApiKeyPermission\n );\n const orgOnlyPermissions = options.permission.filter(\n (permission) => !isProjectApiKeyPermission(permission)\n );\n if (!options.orgId && orgOnlyPermissions.length > 0) {\n return logErrorAndExit(\n createDiagnosticMessage({\n whatHappened: `${orgOnlyPermissions.join(', ')} can only be granted to organization API keys`,\n fix: 'Pass --org-id, or remove those permissions',\n })\n );\n }\n try {\n const settings = await generateSettings(options);\n let key: string;\n if (options.orgId) {\n // No API key can create organization keys, so always send the\n // signed-in user's token, even when an API key is configured.\n configureApiClient({\n baseUrl: settings.baseUrl,\n userTokenProvider: settings.userTokenProvider,\n });\n const { apiKey } = await api.createOrgApiKey(options.orgId, {\n name: options.name,\n permissions: options.permission,\n });\n key = apiKey.key;\n } else {\n if (!hasValidCredentials(settings)) return exitSync(1);\n const { apiKey } = await api.createProjectApiKey(\n settings.projectId,\n { name: options.name, permissions: projectPermissions }\n );\n key = apiKey.key;\n }\n // Raw stdout: the secret is shown once and never reaches the log file.\n process.stdout.write(`${key}\\n`);\n } catch (error) {\n return logErrorAndExit(\n error instanceof UserAuthError\n ? error.message\n : createProjectCommandError('Failed to create the API key', error)\n );\n }\n }\n );\n }\n\n protected setupGitCommand(): void {\n const gitCommand = this.program\n .command('git')\n .description('Configure Git integrations for General Translation');\n\n gitCommand\n .command('setup')\n .description('Set up GT merge drivers for generated translation files')\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json',\n findFilepath(['gt.config.json'])\n )\n .option('--dry-run', 'Print changes without writing files', false)\n .option(\n '--omit-config-ids',\n 'Persist omitConfigIds and remove generated config IDs'\n )\n .option(\n '--driver-command <command>',\n 'Command Git should use to invoke gt, e.g. \"pnpm exec gt\"'\n )\n .action(async (options: GitSetupOptions) => {\n displayHeader('Setting up GT Git merge drivers...');\n const settings = await generateSettings(options, undefined, {\n requireConfig: true,\n });\n const omitConfigIds = await this.resolveGitSetupOmitConfigIds(\n options,\n settings\n );\n const result = await setupGitMergeDrivers(settings, {\n dryRun: options.dryRun,\n omitConfigIds,\n driverCommand: options.driverCommand,\n });\n\n for (const line of result.addedAttributes) {\n logger.step(\n `${options.dryRun ? 'Would add' : 'Added'} ${chalk.cyan(\n line\n )} to ${chalk.cyan(result.gitattributesPath)}`\n );\n }\n if (result.addedAttributes.length === 0) {\n logger.info(`${chalk.cyan('.gitattributes')} is already configured.`);\n }\n\n for (const args of result.gitConfigCommands) {\n logger.step(\n `${options.dryRun ? 'Would run' : 'Configured'} ${chalk.cyan(\n `git config --local ${args.join(' ')}`\n )}`\n );\n }\n\n if (result.updatedConfig) {\n logger.step(\n `${options.dryRun ? 'Would persist' : 'Persisted'} ${chalk.cyan(\n 'omitConfigIds: true'\n )} in ${chalk.cyan(settings.config)}`\n );\n } else if (options.dryRun && !settings.omitConfigIds) {\n logger.info(\n `Run without ${chalk.cyan('--dry-run')} to be prompted to persist ${chalk.cyan(\n 'omitConfigIds: true'\n )}, or pass ${chalk.cyan('--omit-config-ids')}.`\n );\n }\n\n for (const warning of result.warnings) {\n logger.warn(chalk.yellow(warning));\n }\n\n logger.endCommand(\n options.dryRun\n ? 'Dry run complete.'\n : 'GT Git merge drivers configured.'\n );\n });\n\n gitCommand\n .command('merge-driver', { hidden: true })\n .addArgument(\n new Argument('<driver>', 'Merge driver name').choices([\n 'gt-lock',\n 'gtjson',\n ])\n )\n .argument('<base>', 'Common ancestor file')\n .argument('<ours>', 'Current branch file')\n .argument('<theirs>', 'Incoming branch file')\n .argument('[path]', 'Merged path')\n .action(\n (\n driver: MergeDriverName,\n base: string,\n ours: string,\n theirs: string\n ) => {\n const result = runMergeDriver(driver, base, ours, theirs);\n if (!result.ok) {\n logger.error(result.reason);\n exitSync(1);\n }\n }\n );\n }\n\n protected async resolveGitSetupOmitConfigIds(\n options: GitSetupOptions,\n settings: Settings\n ): Promise<boolean> {\n if (options.omitConfigIds) return true;\n // Already opted in: persist again so stale config IDs still get removed\n if (settings.omitConfigIds) return true;\n if (options.dryRun || !process.stdin.isTTY || !process.stdout.isTTY) {\n return false;\n }\n return promptConfirm({\n message:\n 'Also set omitConfigIds: true to reduce gt.config.json merge conflicts?',\n defaultValue: true,\n });\n }\n\n protected async handleSetupProject(\n initOptions: TranslateFlags\n ): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n await handleSetupProject(initOptions, settings, this.library);\n }\n\n protected async handleStage(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Update settings.stageTranslations to true\n settings.stageTranslations = true;\n await updateConfig(settings.config, {\n stageTranslations: true,\n });\n }\n await handleStage(initOptions, settings, this.library, true);\n }\n\n /**\n * Enqueues translations for a given set of files\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleEnqueue(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleEnqueue(initOptions, settings, this.library);\n }\n\n /**\n * Downloads translations that were originally staged\n * @param initOptions - The options for the command\n * @returns The results of the command\n */\n protected async handleDownload(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n await handleDownload(initOptions, settings, this.library);\n await this.finalizeDownloadedTranslations(settings);\n }\n\n protected async handleTranslate(initOptions: TranslateFlags): Promise<void> {\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n // Preprocess shared static assets if configured (move + rewrite sources)\n await processSharedStaticAssets(settings);\n\n if (!settings.stageTranslations) {\n // Lottie translations finish asynchronously server-side (layout\n // refinement runs after the translation job completes), so the immediate\n // translate flow would try to download them before they're ready. Only\n // the stage + download flow supports them.\n if (settings.files?.resolvedPaths.lottie?.length) {\n return logErrorAndExit(lottieTranslateError);\n }\n const results = await handleStage(\n initOptions,\n settings,\n this.library,\n false\n );\n if (results) {\n await handleTranslate(\n initOptions,\n settings,\n results.fileVersionData,\n results.jobData,\n results.branchData,\n results.publishMap,\n results.inlineLibrary\n );\n }\n } else {\n await handleDownload(initOptions, settings, this.library);\n }\n await this.finalizeDownloadedTranslations(settings);\n }\n\n /**\n * Postprocesses the translations downloaded in this run and reports the\n * summary. Shared by translate and download so both write the same output.\n * @param settings - The settings for the command\n */\n protected async finalizeDownloadedTranslations(\n settings: Settings\n ): Promise<void> {\n // Only postprocess files downloaded in this run\n const include = getNeedsPostprocessing();\n if (include.size > 0) {\n await postProcessTranslations(settings, include);\n }\n // Split Mintlify language entries into $ref files to keep docs.json small\n await splitMintlifyLanguageRefs(settings);\n // Localize redirects for pages this run renamed or removed. Runs after the\n // split, which can rewrite $ref files such as redirects.json\n const orphanedFileNames = getOrphanedFileNames();\n if (orphanedFileNames) {\n const added = localizeMintlifyRedirects(settings, orphanedFileNames);\n if (added.length > 0) {\n logger.success(\n `Added ${added.length} localized redirect${added.length === 1 ? '' : 's'}`\n );\n }\n }\n clearOrphanedFileNames();\n // Mirror assets after translations are downloaded and locale dirs are populated\n await mirrorAssetsToLocales(settings);\n clearDownloaded();\n displayTranslateSummary();\n clearWarnings();\n }\n\n protected setupUploadCommand(): void {\n attachTranslateFlags(\n this.program\n .command('upload')\n .description(\n 'Upload source files and translations to the General Translation platform'\n )\n ).action(async (initOptions: UploadOptions) => {\n displayHeader('Starting upload...');\n const settings = await generateSettings(initOptions, undefined, {\n requireConfig: true,\n });\n\n const options = { ...initOptions, ...settings };\n\n await this.handleUploadCommand(options);\n logger.endCommand('Done!');\n });\n }\n\n protected setupUserAuthCommands(): void {\n this.program\n .command('login')\n .description('Sign in to your General Translation account')\n .option(\n '--no-browser',\n 'Do not open a browser; show a sign-in URL to use on any device instead'\n )\n .option(\n '-c, --config <path>',\n 'Filepath to config file, by default gt.config.json'\n )\n .action(async (options: { browser: boolean; config?: string }) => {\n displayHeader('Signing in to General Translation...');\n try {\n // Tokens are bound to one API resource, so log in to the configured one.\n const baseUrl = (\n options.config\n ? loadConfig(withJsonExtension(options.config))\n : resolveConfig(process.cwd())?.config\n )?.baseUrl;\n await loginInteractively(\n typeof baseUrl === 'string' ? baseUrl : undefined,\n options.browser\n );\n logger.endCommand('You are now signed in.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign in failed', error));\n }\n });\n\n this.program\n .command('logout')\n .description('Sign out of your General Translation account')\n .action(async () => {\n try {\n await logout();\n logger.endCommand('Signed out successfully.');\n } catch (error) {\n logErrorAndExit(createUserAuthError('Sign out failed', error));\n }\n });\n\n this.program\n .command('whoami')\n .description('Show the signed-in General Translation account')\n .action(async () => {\n try {\n const user = await whoAmI();\n logger.message(user.email ?? user.name ?? user.sub);\n } catch (error) {\n logErrorAndExit(\n createUserAuthError('Could not load your account', error)\n );\n }\n });\n }\n\n protected setupInitCommand(): void {\n attachInitFlags(\n this.program\n .command('init')\n .description(\n 'Run the setup wizard to configure your project for General Translation. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: InitOptions) => this.handleInitWizard(options));\n }\n\n protected async handleInitWizard(options: InitOptions): Promise<void> {\n await runOnboarding('init', options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Running setup wizard...');\n\n const detected = await detectFramework();\n // Stop before any change rather than set React Native up as web React.\n if (detected.type === 'react-native') {\n throw new OnboardingError(reactNativeSetupError);\n }\n const reactDetected = detected.type === 'react' ? detected : undefined;\n if (options.framework && !reactDetected) {\n session.reject(\n '--framework applies only to projects detected as React applications'\n );\n }\n const configFilepath = setupConfigPath(options);\n const configured = getConfiguredFramework(\n readSetupConfig(configFilepath)\n );\n const configuredReact =\n configured !== 'mintlify' ? configured : undefined;\n // Explicit --defaults / --no-defaults also answer the Locadex gate.\n if (options.defaults !== undefined) session.defaults = options.defaults;\n const gateFramework = options.framework ?? configured ?? detected.name;\n if (gateFramework === 'mintlify' || gateFramework === 'next-app') {\n const useLocadex = await session.answer('--locadex', {\n explicit: options.locadex,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n gateFramework === 'mintlify'\n ? `Mintlify project detected. Would you like to connect to GitHub so that the Locadex AI Agent can translate your project automatically?`\n : `Next.js App Router detected. Would you like to connect to GitHub so that the Locadex AI Agent can set up your project automatically?`,\n defaultValue: false,\n }),\n });\n if (useLocadex) {\n session.assertResolved();\n const url = await setupLocadex(\n await generateSettings({ config: options.config }),\n { openBrowser: session.interactive }\n );\n session.emit({ type: 'handoff', url, reason: 'locadex' });\n logger.endCommand(\n 'Once installed, Locadex will open a PR to your repository. See the docs for more information: https://generaltranslation.com/docs/locadex'\n );\n return { outcome: 'needs_human_action', url };\n }\n } else if (options.locadex) {\n session.reject(\n '--locadex applies only to Mintlify and Next.js App Router projects'\n );\n }\n\n const shownFramework = reactDetected && {\n ...reactDetected,\n name: options.framework ?? configuredReact ?? reactDetected.name,\n };\n // Without --defaults, a noninteractive run uses no defaults.\n session.defaults =\n (await session.answer('--defaults', {\n explicit: options.defaults,\n fallback: false,\n ask: () =>\n promptConfirm({\n message: `Would you like to use the recommended General Translation defaults? ${chalk.dim(`(${describeDefaults(shownFramework)})`)}`,\n defaultValue: true,\n }),\n })) === true;\n\n const resolvedSetup = reactDetected\n ? await resolveReactSetup(\n session,\n options,\n reactDetected,\n configuredReact\n )\n : undefined;\n // A skipped setup only names the framework; the app is left unchanged.\n const reactSetup =\n resolvedSetup && !('skipped' in resolvedSetup)\n ? resolvedSetup\n : undefined;\n // flag > gt.config.json > detection, used for every later step.\n const framework =\n resolvedSetup?.framework ??\n options.framework ??\n configured ??\n detected.name;\n const nextSteps = await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n saveFramework: Boolean(resolvedSetup || options.framework),\n reactSetup,\n skippedReactSetup: Boolean(resolvedSetup && !reactSetup),\n keepAppSource: !reactSetup,\n });\n\n if (nextSteps) {\n logger.endCommand(formatInitNextSteps(nextSteps));\n return { outcome: 'success', nextSteps };\n }\n logger.endCommand(\n 'Done! Check out our docs for more information on how to use General Translation: https://generaltranslation.com/docs'\n );\n return { outcome: 'success' };\n });\n }\n\n protected setupConfigureCommand(): void {\n attachConfigureFlags(\n this.program\n .command('configure')\n .description(\n 'Configure your project for General Translation. This will create a gt.config.json file in your codebase. Flags answer its questions; unanswered ones are asked, or listed as missing with --no-interactive'\n ),\n INIT_SOURCE_HELP\n ).action((options: ConfigureOptions) =>\n this.handleConfigureCommand(options)\n );\n }\n\n protected async handleConfigureCommand(\n options: ConfigureOptions,\n command: string = 'configure'\n ): Promise<void> {\n await runOnboarding(command, options, async (session) => {\n await exitIfUnsupportedSetupTarget();\n displaySetupHeader(session, 'Configuring project...');\n\n logger.info(\n 'Welcome! This tool will help you configure your gt.config.json file. See the docs: https://generaltranslation.com/docs/cli/reference/config for more information.'\n );\n\n // Configure only offers the defaults when asked with --defaults.\n session.defaults = options.defaults ?? false;\n const detected = await detectFramework();\n const configFilepath = setupConfigPath(options);\n // Detection only picks env names here; it is not saved. React Native\n // keeps the generic React env names configure has always written.\n const framework =\n getConfiguredFramework(readSetupConfig(configFilepath)) ??\n (detected.type === 'react-native' ? 'react' : detected.name);\n await this.handleInitCommand(session, options, {\n configFilepath,\n framework,\n });\n\n logger.endCommand(\n 'Done! Make sure you have an API key and project ID to use General Translation. Get them on the dashboard: https://generaltranslation.com/dashboard'\n );\n return { outcome: 'success' };\n });\n }\n\n protected async handleUploadCommand(\n settings: Settings & UploadOptions\n ): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n // Process all file types at once with a single call\n await upload(settings);\n }\n\n /** Describes installed runtimes without changing historical package lookup. */\n protected getInlineRuntimeSetup(\n packageJson: Record<string, unknown>,\n ranReactSetup: boolean = false\n ): InlineRuntimeSetup {\n return {\n hasOtherInlineRuntime: INLINE_LIBRARIES.some(\n (lib) =>\n lib !== Libraries.GT_VUE && isPackageInstalled(lib, packageJson)\n ),\n hasVueRuntime: manifestDirectlyDeclaresGTVue(packageJson),\n ranReactSetup,\n };\n }\n\n /** Returns whether any inline runtime is installed for setup. */\n protected isInlineRuntimeInstalled(\n packageJson: Record<string, unknown>\n ): boolean {\n const { hasOtherInlineRuntime, hasVueRuntime } =\n this.getInlineRuntimeSetup(packageJson);\n return hasOtherInlineRuntime || hasVueRuntime;\n }\n\n /** Returns whether every installed runtime can consume CDN translations. */\n protected supportsCDNStorage(runtimeSetup: InlineRuntimeSetup): boolean {\n return !runtimeSetup.hasVueRuntime;\n }\n\n /** Returns whether setup should generate a local runtime loader. */\n protected shouldGenerateLocalTranslationLoader(\n buildToolOwnsLoader: boolean,\n runtimeSetup: InlineRuntimeSetup\n ): boolean {\n if (buildToolOwnsLoader) return false;\n if (!runtimeSetup.hasVueRuntime) return true;\n return runtimeSetup.hasOtherInlineRuntime || runtimeSetup.ranReactSetup;\n }\n\n /** Returns framework guidance after selecting local translation storage. */\n protected getLocalTranslationGuidance({\n generatedLoader,\n runtimeSetup,\n translationsDir,\n }: LocalTranslationGuidanceOptions): string | undefined {\n const guidance: string[] = [];\n if (generatedLoader) {\n guidance.push(`Created ${chalk.cyan('loadTranslations.js')} file for local translations.\nMake sure to add this function to your app configuration.\nSee https://generaltranslation.com/en/docs/next/guides/local-tx`);\n }\n if (runtimeSetup.hasVueRuntime) {\n guidance.push(`GT will write local translation files to ${translationsDir}.\nConfigure createGT({ loadTranslations }) to load files from that directory.\nSee https://www.npmjs.com/package/gt-vue`);\n }\n return guidance.length > 0 ? guidance.join('\\n') : undefined;\n }\n\n /**\n * Resolves every configuration answer and validates the resulting config,\n * checks the project and signs in before the first change, then applies\n * the React setup, gt.config.json, installs and development credentials.\n */\n protected async handleInitCommand(\n session: OnboardingSession,\n options: ConfigureOptions,\n setup: {\n /** Chosen once by the entry point from the detected framework. */\n configFilepath: string;\n /** Resolved framework; drives storage, env names and build-tool setup. */\n framework?: SupportedFrameworks;\n /** Write the framework even when no build-tool setup saves it. */\n saveFramework?: boolean;\n reactSetup?: ReactSetupPlan;\n /** The app still needs a GT runtime the wizard could not set up. */\n skippedReactSetup?: boolean;\n /** Init without the React setup never changes application source. */\n keepAppSource?: boolean;\n }\n ): Promise<string[] | undefined> {\n const { configFilepath, reactSetup } = setup;\n const buildTool = getBuildToolSetup(setup.framework);\n const cwd = process.cwd();\n const existingConfig = readSetupConfig(configFilepath);\n const desiredLocales = await getDesiredLocales(\n session,\n existingConfig,\n options\n );\n const { defaultLocale } = desiredLocales;\n // Next.js i18n routing requires its default locale in locales, and the\n // Pages Router quickstart passes the gt.config.json locales to it.\n const locales =\n setup.framework === 'next-pages' &&\n defaultLocale &&\n desiredLocales.locales &&\n !desiredLocales.locales.includes(defaultLocale)\n ? [defaultLocale, ...desiredLocales.locales]\n : desiredLocales.locales;\n\n const packageJson =\n reactSetup?.packageJson ?? (await searchForPackageJson());\n const runtimeSetup: InlineRuntimeSetup = packageJson\n ? this.getInlineRuntimeSetup(\n packageJson,\n Boolean(reactSetup || setup.skippedReactSetup)\n )\n : {\n hasOtherInlineRuntime: false,\n hasVueRuntime: false,\n ranReactSetup: false,\n };\n const isUsingGT =\n runtimeSetup.ranReactSetup ||\n runtimeSetup.hasOtherInlineRuntime ||\n runtimeSetup.hasVueRuntime;\n const supportsCDN = this.supportsCDNStorage(runtimeSetup);\n const existingFiles = asRecord(existingConfig.files) ?? {};\n const existingGtOutput = asRecord(existingFiles.gt)?.output;\n const configuredOutput =\n typeof existingGtOutput === 'string' ? existingGtOutput : undefined;\n const configuredStorage = configuredOutput\n ? 'local'\n : existingConfig.publish === true\n ? 'cdn'\n : undefined;\n\n if (isUsingGT && !supportsCDN && options.storage === 'cdn') {\n session.reject(\n 'gt-vue cannot load translations from the CDN; use --storage local'\n );\n }\n // Where GT translations are stored\n const storage = !isUsingGT\n ? undefined\n : !supportsCDN\n ? 'local'\n : await session.answer<'local' | 'cdn'>('--storage', {\n explicit: options.storage,\n configured: configuredStorage,\n recommended: 'local',\n ask: () =>\n promptSelect<'local' | 'cdn'>({\n message: `Would you like to save translation files locally or use the General Translation CDN to store them?`,\n options: [\n { value: 'local', label: 'Save locally' },\n { value: 'cdn', label: 'Use CDN' },\n ],\n defaultValue: 'local',\n }),\n });\n\n const defaultTranslationsDir =\n buildTool?.defaultTranslationsDir ?? DEFAULT_TRANSLATIONS_DIR;\n const outputMatch = configuredOutput?.match(\n /^(?:(.+)[\\\\/])?\\[locale\\]\\.json$/\n );\n const configuredTranslationsDir = outputMatch\n ? (outputMatch[1] ?? '.')\n : undefined;\n const translationsDir =\n storage === 'local'\n ? await session.answer('--translations-dir', {\n explicit: options.translationsDir?.trim() || undefined,\n configured: configuredTranslationsDir,\n recommended: defaultTranslationsDir,\n ask: async () =>\n (\n await promptText({\n message:\n 'What is the path to the directory where you would like to store your translation files?',\n defaultValue: defaultTranslationsDir,\n })\n ).trim() || defaultTranslationsDir,\n })\n : undefined;\n\n const filePatterns = parseFilePatterns(session, options.filePatterns);\n const selectedFormats = options.fileFormats?.filter(\n (format): format is SetupFileFormat => format !== 'none'\n );\n if (\n options.fileFormats?.includes('none') &&\n (selectedFormats?.length ?? 0) > 0\n ) {\n session.reject('--file-formats none cannot be combined with formats');\n }\n const configuredFormats = SETUP_FILE_FORMATS.filter(\n (format) => format in existingFiles\n );\n // Formats setup does not offer stay as configured and count as files.\n const otherFormats = SUPPORTED_FILE_EXTENSIONS.filter(\n (format) =>\n format in existingFiles &&\n !(SETUP_FILE_FORMATS as readonly string[]).includes(format)\n );\n const hasOtherFormats = otherFormats.length > 0;\n if (options.fileFormats && hasOtherFormats) {\n const kept = otherFormats.map((format) => `files.${format}`).join(', ');\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened: `${kept} stays in ${configFilepath}`,\n why: '--file-formats only changes the formats setup offers',\n fix: `Remove ${kept} from ${configFilepath} to stop translating those files`,\n })\n );\n }\n const fileFormats = await session.answer<SetupFileFormat[]>(\n '--file-formats',\n {\n explicit:\n selectedFormats ??\n (filePatterns.size > 0 ? [...filePatterns.keys()] : undefined),\n configured:\n configuredFormats.length > 0 || hasOtherFormats\n ? configuredFormats\n : undefined,\n // GT projects need no other files; others must choose a format.\n recommended: isUsingGT ? [] : undefined,\n ask: () =>\n promptMultiSelect({\n message: !isUsingGT\n ? 'What is the format of your language resource files? Select as many as applicable.\\nAdditionally, you can translate any other files you have in your project.'\n : `Do you have any additional files in this project to translate? For example, Markdown files for docs. ${chalk.dim(\n '(To continue without selecting press Enter)'\n )}`,\n options: SETUP_FILE_FORMATS.map((format) => ({\n value: format,\n label: FILE_EXT_TO_EXT_LABEL[format],\n })),\n required: !isUsingGT,\n }),\n }\n );\n if (\n fileFormats &&\n fileFormats.length === 0 &&\n !isUsingGT &&\n !hasOtherFormats\n ) {\n session.reject(\n 'No GT runtime is installed, so select at least one file format to translate'\n );\n }\n for (const format of filePatterns.keys()) {\n if (fileFormats && !fileFormats.includes(format)) {\n session.reject(\n `--file-patterns ${format}= needs ${format} in --file-formats`\n );\n }\n }\n\n const files: FilesOptions = {};\n for (const fileExtension of fileFormats ?? []) {\n const existingFormat = asRecord(existingFiles[fileExtension]);\n const configuredInclude = Array.isArray(existingFormat?.include)\n ? (existingFormat.include as string[])\n : undefined;\n const include = await session.answer(\n `--file-patterns ${fileExtension}=<glob>`,\n {\n explicit: filePatterns.get(fileExtension),\n configured: configuredInclude,\n recommended: [`./**/[locale]/*.${fileExtension}`],\n ask: async () =>\n parseGlobPatterns(\n await promptGlobPatterns({\n label: FILE_EXT_TO_EXT_LABEL[fileExtension],\n message: `${chalk.cyan(FILE_EXT_TO_EXT_LABEL[fileExtension])}: Enter a space-separated list of glob patterns matching the location of the ${FILE_EXT_TO_EXT_LABEL[fileExtension]} files you would like to translate.\\nMake sure to include [locale] in the patterns.\\nSee https://generaltranslation.com/docs/cli/reference/config#include for more information.`,\n defaultValue: `./**/[locale]/*.${fileExtension}`,\n validate: (value) =>\n parseGlobPatterns(value)\n .map(validateSetupPattern)\n .find((problem) => problem !== true) ?? true,\n })\n ),\n }\n );\n // Configured patterns stay untouched; new ones keep other entry options.\n if (include && include !== configuredInclude) {\n files[fileExtension] = { ...existingFormat, include };\n }\n }\n if (translationsDir && translationsDir !== configuredTranslationsDir) {\n files.gt = { output: path.join(translationsDir, `[locale].json`) };\n }\n\n const envFramework =\n setup.framework ?? getConfiguredFramework(existingConfig);\n // The effective project: an explicit ID replaces a configured one. The\n // framework's runtime project outranks a stale generic GT_PROJECT_ID.\n const projectId =\n options.projectId ||\n (typeof existingConfig.projectId === 'string'\n ? existingConfig.projectId\n : undefined) ||\n process.env[getDevelopmentEnvNames(envFramework).projectId];\n const configUpdate: SetupConfigUpdate = {\n defaultLocale,\n locales,\n src: options.src,\n files: Object.keys(files).length > 0 ? files : undefined,\n framework:\n (setup.saveFramework && setup.framework) || buildTool?.framework,\n publish: storage === 'cdn',\n // Selecting local storage drops stale CDN intent; a config that\n // already combines local files with publishing keeps it.\n clearPublish:\n storage === 'local' &&\n (options.storage === 'local' ||\n configuredStorage !== 'local' ||\n !supportsCDN),\n // An explicit switch to the CDN stops later runs inferring local files.\n clearGtOutput: storage === 'cdn' && configuredOutput !== undefined,\n // An explicit format list replaces the configured selection.\n removeFiles: selectedFormats\n ? configuredFormats.filter(\n (format) => !selectedFormats.includes(format)\n )\n : undefined,\n };\n session.assertResolved();\n\n // Validate what will be written, and use it for every later step.\n const { projectId: _writtenProjectId, ...effectiveConfig } =\n mergeSetupConfig(existingConfig, configUpdate);\n const settings = await generateSettings(\n { config: configFilepath, ...(projectId && { projectId }) },\n cwd,\n { resolvedConfig: effectiveConfig }\n );\n // Runtime credentials only count for the project this setup uses; the\n // framework's project variable is the one paired with its dev key.\n const runtimeProjectId =\n process.env[getDevelopmentEnvNames(envFramework).projectId] ??\n resolveProjectId();\n const runtimeProjectMatches =\n runtimeProjectId === undefined || runtimeProjectId === settings.projectId;\n const credentialsSet =\n runtimeProjectMatches && areCredentialsSet(settings, envFramework);\n const credentialsOption =\n (storage === 'local' && buildTool?.devCredentialsOption) ||\n '--dev-credentials';\n // Creating credentials talks to GT as the signed-in user unless an API\n // key is set. A development key in .env.local never stands in. An\n // obsolete stored login counts as signed out, so signing in replaces it.\n const canAuthenticate = async () =>\n Boolean(settings.apiKey) ||\n (await hasLogin({ baseUrl: settings.baseUrl }).catch((error) => {\n if (\n error instanceof UserAuthError &&\n error.code === 'obsolete_credentials'\n )\n return false;\n throw error;\n }));\n const provision =\n !credentialsSet &&\n (credentialsOption === '--live-translations'\n ? await session.answer('--live-translations', {\n explicit: options.liveTranslations ?? options.devCredentials,\n recommended: false,\n ask: () =>\n promptConfirm({\n message:\n 'Would you like to set up live development translations? This requires signing in or an API key.',\n defaultValue: false,\n }),\n })\n : await session.answer('--dev-credentials or --no-dev-credentials', {\n explicit: options.devCredentials,\n // Creating a key is never a default, so --defaults leaves this open.\n // The prompt names the sign-in so its Yes default is informed.\n ask: async () =>\n promptConfirm({\n message: (await canAuthenticate())\n ? 'Would you like to set up a project ID and hot-reload key in .env.local?'\n : 'Would you like to sign in to General Translation and set up a project ID and hot-reload key in .env.local?',\n defaultValue: true,\n }),\n })) === true;\n if (!runtimeProjectMatches && !provision) {\n session.reject(\n `The runtime credentials in the environment belong to project ${runtimeProjectId}, not ${settings.projectId}; pass --dev-credentials to replace them in .env.local`\n );\n }\n // An explicit ID is saved to gt.config.json when it replaces a\n // configured one or no new credentials will record it in .env.local.\n if (options.projectId && (existingConfig.projectId || !provision)) {\n configUpdate.projectId = options.projectId;\n }\n if (provision) {\n checkDevelopmentProjectInputs(\n session,\n settings,\n options,\n options.projectId\n ? '--project-id'\n : // An empty configured ID falls through to the environment.\n typeof existingConfig.projectId === 'string' &&\n existingConfig.projectId\n ? configFilepath\n : 'the environment'\n );\n await withCredentialsError(() =>\n inspectCredentialsEnvFile(cwd, { framework: envFramework })\n );\n }\n\n if (reactSetup && buildTool) await buildTool.preflight(cwd);\n const installGT =\n packageJson !== null &&\n !isPackageInstalled('gt', packageJson, true, true) &&\n !buildTool?.skipsGTInstall(isUsingGT);\n const packageManager =\n reactSetup?.install || installGT\n ? await resolvePackageManager(session, options.packageManager)\n : undefined;\n\n session.assertResolved();\n\n if (provision && !(await canAuthenticate())) {\n await signInForSetup(session, settings.baseUrl);\n }\n const project = provision\n ? await withCredentialsError(() =>\n resolveDevelopmentProject(session, settings, options, cwd)\n )\n : undefined;\n session.assertResolved();\n\n // ----- Changes start here ----- //\n const resolvedLocales = locales as string[];\n\n if (reactSetup) {\n logger.info(`${chalk.yellow('[EXPERIMENTAL]')} Configuring project...`);\n if (reactSetup.install && packageManager) {\n await installWithProgress(\n session,\n reactSetup.install,\n packageManager,\n false\n );\n }\n await executeReactSetup(session, reactSetup, options);\n logger.step('Setting up project config...');\n }\n\n const reportManualAction = ({ whatHappened, fix }: ManualAction) => {\n session.humanActions.push(fix);\n logger.warn(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Warning',\n whatHappened,\n fix,\n })\n );\n };\n const reportSetupResult = ({ steps, manualActions }: SetupResult) => {\n for (const step of steps) session.step(step);\n manualActions.forEach(reportManualAction);\n };\n const translationFilesError = (error: unknown) =>\n new Error(\n createDiagnosticMessage({\n source: 'gt',\n severity: 'Error',\n whatHappened: `Could not create the translation files in ${translationsDir}`,\n details: formatDiagnosticErrorDetails(error),\n fix: 'Choose another --translations-dir or fix the path, then rerun the command',\n })\n );\n const buildToolContext = {\n appDirectory: cwd,\n configFilepath,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n previousTranslationsDir: configuredTranslationsDir,\n };\n\n if (storage === 'local' && translationsDir) {\n if (buildTool && !reactSetup) {\n reportSetupResult(\n await buildTool\n .syncLoader({\n ...buildToolContext,\n translationsDir,\n keepAppSource: setup.keepAppSource,\n })\n .catch((error: unknown) => {\n throw translationFilesError(error);\n })\n );\n }\n const generatedLoader = this.shouldGenerateLocalTranslationLoader(\n buildTool?.ownsLoader ?? false,\n runtimeSetup\n );\n const loader = generatedLoader\n ? await createLoadTranslationsFile({\n appDirectory: cwd,\n translationsDir,\n defaultLocale: settings.defaultLocale,\n locales: resolvedLocales,\n previousTranslationsDir: configuredTranslationsDir,\n }).catch((error: unknown) => {\n throw translationFilesError(error);\n })\n : undefined;\n if (loader === 'created' || loader === 'updated') {\n session.step(`${loader} loadTranslations.js`);\n }\n // A loader left unchanged may not read the newly chosen directory.\n if (\n loader === 'custom' &&\n translationsDir !== configuredTranslationsDir\n ) {\n const loaderFile = path.relative(\n cwd,\n findLoadTranslationsFiles(cwd)[0] ?? 'loadTranslations.js'\n );\n reportManualAction({\n whatHappened: `Your custom ${loaderFile} was left unchanged, but translations now go to ${translationsDir}`,\n fix: `Update your custom ${loaderFile} to load translations from ${translationsDir}`,\n });\n }\n const guidance = this.getLocalTranslationGuidance({\n generatedLoader: generatedLoader && loader !== 'custom',\n runtimeSetup,\n translationsDir,\n });\n if (guidance) logger.message(guidance);\n } else if (\n storage === 'cdn' &&\n buildTool &&\n !reactSetup &&\n configuredTranslationsDir !== undefined\n ) {\n // Only the application setup rewrites the initializer; a loader passed\n // to it takes precedence over CDN loading.\n const action = await buildTool.getCDNStorageAction?.(buildToolContext);\n if (action !== null) {\n reportManualAction(\n action ?? {\n whatHappened: `Translations now load from the CDN, but ${buildTool.initializer} may still receive the local loader for ${configuredTranslationsDir}`,\n fix: `Remove the loadTranslations option and its import from the ${buildTool.initializer}() call so translations load from the CDN`,\n }\n );\n }\n } else if (\n storage === 'cdn' &&\n !buildTool &&\n configuredTranslationsDir !== undefined\n ) {\n // gt-next uses a loadTranslations file whenever one exists, and a\n // loader passed to GTProvider takes precedence over the CDN. Name every\n // one: deleting only the first makes gt-next fall back to the next.\n const loaders = findLoadTranslationsFiles(cwd).map((loader) =>\n path.relative(cwd, loader)\n );\n if (loaders.length > 0) {\n const loaderFiles = loaders.join(', ');\n const [them, loads] =\n loaders.length === 1 ? ['it', 'loads'] : ['them', 'load'];\n reportManualAction({\n whatHappened: `Translations now load from the CDN, but ${loaderFiles} still ${loads} them from ${configuredTranslationsDir}`,\n fix: `Delete ${loaderFiles}, and remove ${them} from your GT setup if you pass ${them} there, so translations load from the CDN`,\n });\n }\n }\n\n const configChange = await applySetupConfig(configFilepath, configUpdate);\n if (configChange !== 'unchanged') {\n session.step(`${configChange} ${configFilepath}`);\n }\n\n logger.success(\n `Edit ${chalk.cyan(\n configFilepath\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n if (reactSetup && buildTool) {\n reportSetupResult(await buildTool.apply(buildToolContext));\n }\n\n if (installGT && packageManager) {\n await installWithProgress(session, 'gt', packageManager, true);\n }\n\n if (project) {\n await withCredentialsError(() =>\n provisionDevelopmentCredentials(\n session,\n project,\n settings,\n envFramework,\n cwd\n )\n );\n logger.message(productionRuntimeKeyGuidance(settings.dashboardUrl));\n }\n\n if (!reactSetup) return undefined;\n // The React setup configures the app entry but never marks content for\n // translation, so what is left is reported as next steps.\n const devPackageManager =\n packageManager ??\n (await getPackageManager(cwd, options.packageManager, true).catch(\n () => undefined\n ));\n const scripts = asRecord(reactSetup.packageJson.scripts);\n return getInitNextSteps({\n framework: reactSetup.framework,\n configuredAppEntry:\n reactSetup.framework === 'next-app' || buildTool !== undefined,\n docsUrl: getSetupDocsUrl(reactSetup.framework),\n locales: resolvedLocales,\n configFilepath,\n translationsDir: storage === 'local' ? translationsDir : undefined,\n devCommand:\n typeof scripts?.dev === 'string'\n ? `${devPackageManager?.runScriptCommand ?? 'npm run'} dev`\n : undefined,\n });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwJA,MAAM,oCAAoC,IAAI,IAAI;CAChD;CACA;CACA;CACA;CACA;CACA;CACA;CACD,CAAC;AACF,SAAS,0BACP,cACA,OACQ;AACR,QAAO,wBAAwB;EAC7B,QAAQ;EACR,UAAU;EACV;EACA,SAAS,6BAA6B,MAAM;EAC7C,CAAC;;AAGJ,MAAM,uBAAuB,wBAAwB;CACnD,cAAc;CACd,KAAK;CACN,CAAC;AAEF,MAAM,2BAA2B,IAAI,IACnC,OAAO,OAAO,wBAAwB,CACvC;AAED,SAAS,0BACP,YACuC;AACvC,QAAO,yBAAyB,IAAI,WAAW;;AAGjD,SAAS,gBAAgB,OAAuB;CAC9C,MAAM,OAAO,MAAM,MAAM;AACzB,KAAI,CAAC,KAAM,OAAM,IAAI,qBAAqB,qBAAqB;AAC/D,QAAO;;;AAIT,eAAe,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-1,12 +1,14 @@
1
1
  import { logger } from "../../console/logger.js";
2
2
  import { exitSync, logCollectedFiles } from "../../console/logging.js";
3
3
  import { hasValidCredentials, hasValidLocales } from "./utils/validation.js";
4
+ import { collectParaglideContext } from "../../paraglide/collectParaglideContext.js";
4
5
  import { collectFiles } from "../../formats/files/collectFiles.js";
5
6
  import { runSetupProjectWorkflow } from "../../workflows/setupProject.js";
6
7
  //#region src/cli/commands/setupProject.ts
7
8
  async function handleSetupProject(options, settings, library) {
8
9
  if (!hasValidLocales(settings, { forApi: !options.dryRun })) return exitSync(1);
9
10
  if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);
11
+ if (settings.files?.parsingFlags?.json?.includeSourceCodeContext) await collectParaglideContext();
10
12
  const { files: allFiles, reactComponents, inlineLibrary } = await collectFiles(options, settings, library);
11
13
  if (options.dryRun) {
12
14
  logger.success(`Dry run: No files were uploaded to General Translation.`);
@@ -1 +1 @@
1
- {"version":3,"file":"setupProject.js","names":[],"sources":["../../../src/cli/commands/setupProject.ts"],"sourcesContent":["import { logger } from '../../console/logger.js';\nimport { exitSync, logCollectedFiles } from '../../console/logging.js';\nimport {\n Settings,\n SupportedLibraries,\n TranslateFlags,\n} from '../../types/index.js';\nimport { FileTranslationData } from '../../workflows/download.js';\nimport { BranchData } from '../../types/branch.js';\nimport { collectFiles } from '../../formats/files/collectFiles.js';\nimport { runSetupProjectWorkflow } from '../../workflows/setupProject.js';\nimport { hasValidCredentials, hasValidLocales } from './utils/validation.js';\n\nexport async function handleSetupProject(\n options: TranslateFlags,\n settings: Settings,\n library: SupportedLibraries\n): Promise<{\n fileVersionData: FileTranslationData | undefined;\n branchData: BranchData | undefined;\n} | null> {\n if (!hasValidLocales(settings, { forApi: !options.dryRun }))\n return exitSync(1);\n // Validate credentials if not in dry run\n if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);\n\n const {\n files: allFiles,\n reactComponents,\n inlineLibrary,\n } = await collectFiles(options, settings, library);\n\n // Dry run\n if (options.dryRun) {\n logger.success(`Dry run: No files were uploaded to General Translation.`);\n logCollectedFiles(allFiles, reactComponents, inlineLibrary);\n return null;\n }\n\n if (allFiles.length === 0) {\n logger.error(\n 'No files to upload were found. Check your configuration and try again.'\n );\n }\n\n // Upload files and run setup step\n let fileVersionData: FileTranslationData | undefined;\n let branchData: BranchData | undefined;\n if (allFiles.length > 0) {\n const { branchData: branchDataResult } = await runSetupProjectWorkflow(\n allFiles,\n options,\n settings,\n inlineLibrary\n );\n branchData = branchDataResult;\n\n fileVersionData = Object.fromEntries(\n allFiles.map((file) => [\n file.fileId,\n {\n fileName: file.fileName,\n versionId: file.versionId,\n },\n ])\n );\n }\n return {\n fileVersionData,\n branchData,\n };\n}\n"],"mappings":";;;;;;AAaA,eAAsB,mBACpB,SACA,UACA,SAIQ;AACR,KAAI,CAAC,gBAAgB,UAAU,EAAE,QAAQ,CAAC,QAAQ,QAAQ,CAAC,CACzD,QAAO,SAAS,EAAE;AAEpB,KAAI,CAAC,QAAQ,UAAU,CAAC,oBAAoB,SAAS,CAAE,QAAO,SAAS,EAAE;CAEzE,MAAM,EACJ,OAAO,UACP,iBACA,kBACE,MAAM,aAAa,SAAS,UAAU,QAAQ;AAGlD,KAAI,QAAQ,QAAQ;AAClB,SAAO,QAAQ,0DAA0D;AACzE,oBAAkB,UAAU,iBAAiB,cAAc;AAC3D,SAAO;;AAGT,KAAI,SAAS,WAAW,EACtB,QAAO,MACL,yEACD;CAIH,IAAI;CACJ,IAAI;AACJ,KAAI,SAAS,SAAS,GAAG;EACvB,MAAM,EAAE,YAAY,qBAAqB,MAAM,wBAC7C,UACA,SACA,UACA,cACD;AACD,eAAa;AAEb,oBAAkB,OAAO,YACvB,SAAS,KAAK,SAAS,CACrB,KAAK,QACL;GACE,UAAU,KAAK;GACf,WAAW,KAAK;GACjB,CACF,CAAC,CACH;;AAEH,QAAO;EACL;EACA;EACD"}
1
+ {"version":3,"file":"setupProject.js","names":[],"sources":["../../../src/cli/commands/setupProject.ts"],"sourcesContent":["import { logger } from '../../console/logger.js';\nimport { exitSync, logCollectedFiles } from '../../console/logging.js';\nimport {\n Settings,\n SupportedLibraries,\n TranslateFlags,\n} from '../../types/index.js';\nimport { FileTranslationData } from '../../workflows/download.js';\nimport { BranchData } from '../../types/branch.js';\nimport { collectFiles } from '../../formats/files/collectFiles.js';\nimport { runSetupProjectWorkflow } from '../../workflows/setupProject.js';\nimport { hasValidCredentials, hasValidLocales } from './utils/validation.js';\nimport { collectParaglideContext } from '../../paraglide/collectParaglideContext.js';\n\nexport async function handleSetupProject(\n options: TranslateFlags,\n settings: Settings,\n library: SupportedLibraries\n): Promise<{\n fileVersionData: FileTranslationData | undefined;\n branchData: BranchData | undefined;\n} | null> {\n if (!hasValidLocales(settings, { forApi: !options.dryRun }))\n return exitSync(1);\n // Validate credentials if not in dry run\n if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);\n\n if (settings.files?.parsingFlags?.json?.includeSourceCodeContext) {\n await collectParaglideContext();\n }\n\n const {\n files: allFiles,\n reactComponents,\n inlineLibrary,\n } = await collectFiles(options, settings, library);\n\n // Dry run\n if (options.dryRun) {\n logger.success(`Dry run: No files were uploaded to General Translation.`);\n logCollectedFiles(allFiles, reactComponents, inlineLibrary);\n return null;\n }\n\n if (allFiles.length === 0) {\n logger.error(\n 'No files to upload were found. Check your configuration and try again.'\n );\n }\n\n // Upload files and run setup step\n let fileVersionData: FileTranslationData | undefined;\n let branchData: BranchData | undefined;\n if (allFiles.length > 0) {\n const { branchData: branchDataResult } = await runSetupProjectWorkflow(\n allFiles,\n options,\n settings,\n inlineLibrary\n );\n branchData = branchDataResult;\n\n fileVersionData = Object.fromEntries(\n allFiles.map((file) => [\n file.fileId,\n {\n fileName: file.fileName,\n versionId: file.versionId,\n },\n ])\n );\n }\n return {\n fileVersionData,\n branchData,\n };\n}\n"],"mappings":";;;;;;;AAcA,eAAsB,mBACpB,SACA,UACA,SAIQ;AACR,KAAI,CAAC,gBAAgB,UAAU,EAAE,QAAQ,CAAC,QAAQ,QAAQ,CAAC,CACzD,QAAO,SAAS,EAAE;AAEpB,KAAI,CAAC,QAAQ,UAAU,CAAC,oBAAoB,SAAS,CAAE,QAAO,SAAS,EAAE;AAEzE,KAAI,SAAS,OAAO,cAAc,MAAM,yBACtC,OAAM,yBAAyB;CAGjC,MAAM,EACJ,OAAO,UACP,iBACA,kBACE,MAAM,aAAa,SAAS,UAAU,QAAQ;AAGlD,KAAI,QAAQ,QAAQ;AAClB,SAAO,QAAQ,0DAA0D;AACzE,oBAAkB,UAAU,iBAAiB,cAAc;AAC3D,SAAO;;AAGT,KAAI,SAAS,WAAW,EACtB,QAAO,MACL,yEACD;CAIH,IAAI;CACJ,IAAI;AACJ,KAAI,SAAS,SAAS,GAAG;EACvB,MAAM,EAAE,YAAY,qBAAqB,MAAM,wBAC7C,UACA,SACA,UACA,cACD;AACD,eAAa;AAEb,oBAAkB,OAAO,YACvB,SAAS,KAAK,SAAS,CACrB,KAAK,QACL;GACE,UAAU,KAAK;GACf,WAAW,KAAK;GACjB,CACF,CAAC,CACH;;AAEH,QAAO;EACL;EACA;EACD"}
@@ -3,6 +3,7 @@ import { TEMPLATE_FILE_ID } from "../../utils/constants.js";
3
3
  import { exitSync, logCollectedFiles } from "../../console/logging.js";
4
4
  import { writeStagedEntries } from "../../fs/config/downloadedVersions.js";
5
5
  import { hasValidCredentials, hasValidLocales } from "./utils/validation.js";
6
+ import { collectParaglideContext } from "../../paraglide/collectParaglideContext.js";
6
7
  import { runStageFilesWorkflow } from "../../workflows/stage.js";
7
8
  import updateConfig from "../../fs/config/updateConfig.js";
8
9
  import { collectFiles } from "../../formats/files/collectFiles.js";
@@ -12,6 +13,7 @@ import { warnManualReviewSetup } from "../../translation/reviewSetupWarning.js";
12
13
  async function handleStage(options, settings, library, stage) {
13
14
  if (!hasValidLocales(settings, { forApi: !options.dryRun })) return exitSync(1);
14
15
  if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);
16
+ if (settings.files?.parsingFlags?.json?.includeSourceCodeContext) await collectParaglideContext();
15
17
  const { files: allFiles, reactComponents, inlineLibrary, publishMap } = await collectFiles(options, settings, library);
16
18
  await warnManualReviewSetup(settings, allFiles);
17
19
  if (options.dryRun) {
@@ -1 +1 @@
1
- {"version":3,"file":"stage.js","names":[],"sources":["../../../src/cli/commands/stage.ts"],"sourcesContent":["import { logger } from '../../console/logger.js';\nimport { exitSync, logCollectedFiles } from '../../console/logging.js';\nimport {\n Settings,\n SupportedLibraries,\n TranslateFlags,\n} from '../../types/index.js';\nimport { runStageFilesWorkflow } from '../../workflows/stage.js';\nimport { writeStagedEntries } from '../../fs/config/downloadedVersions.js';\nimport type { EnqueueFilesResult } from 'generaltranslation/types';\nimport updateConfig from '../../fs/config/updateConfig.js';\nimport { FileTranslationData } from '../../workflows/download.js';\nimport { BranchData } from '../../types/branch.js';\nimport { TEMPLATE_FILE_ID } from '../../utils/constants.js';\nimport { collectFiles } from '../../formats/files/collectFiles.js';\nimport { convertToFileTranslationData } from '../../formats/files/convertToFileTranslationData.js';\nimport { hasValidCredentials, hasValidLocales } from './utils/validation.js';\nimport { warnManualReviewSetup } from '../../translation/reviewSetupWarning.js';\nimport type { InlineLibrary } from '../../types/libraries.js';\n\nexport async function handleStage(\n options: TranslateFlags,\n settings: Settings,\n library: SupportedLibraries,\n stage: boolean\n): Promise<{\n fileVersionData: FileTranslationData | undefined;\n jobData: EnqueueFilesResult | undefined;\n branchData: BranchData | undefined;\n publishMap: Map<string, boolean>;\n inlineLibrary?: InlineLibrary;\n} | null> {\n if (!hasValidLocales(settings, { forApi: !options.dryRun }))\n return exitSync(1);\n // Validate credentials if not in dry run\n if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);\n\n const {\n files: allFiles,\n reactComponents,\n inlineLibrary,\n publishMap,\n } = await collectFiles(options, settings, library);\n\n // Point at dashboard review setup when uploading review-gated content\n await warnManualReviewSetup(settings, allFiles);\n\n // Dry run\n if (options.dryRun) {\n logger.success(`Dry run: No files were sent to General Translation.`);\n logCollectedFiles(allFiles, reactComponents, inlineLibrary);\n return null;\n }\n\n if (allFiles.length === 0 && !settings.publish) {\n logger.error(\n 'No files to translate were found. Check your configuration and try again.'\n );\n }\n\n // Send translations to General Translation\n let fileVersionData: FileTranslationData | undefined;\n let jobData: EnqueueFilesResult | undefined;\n let branchData: BranchData | undefined;\n if (allFiles.length > 0) {\n const { branchData: branchDataResult, enqueueResult } =\n await runStageFilesWorkflow({\n files: allFiles,\n options,\n settings,\n inlineLibrary,\n });\n jobData = enqueueResult;\n branchData = branchDataResult;\n\n fileVersionData = convertToFileTranslationData(allFiles);\n\n // Write staged entries to the lockfile\n if (stage) {\n const stagedFiles = Object.entries(fileVersionData).map(\n ([fileId, data]) => ({\n fileId,\n versionId: data.versionId,\n fileName: data.fileName,\n })\n );\n writeStagedEntries(settings, stagedFiles, branchData.currentBranch.id);\n }\n const templateData = allFiles.find(\n (file) => file.fileId === TEMPLATE_FILE_ID\n );\n if (settings.omitConfigIds) {\n // Remove persisted config IDs only after staging has succeeded, so\n // failed and empty runs keep the previous pinned version/branch state\n await updateConfig(settings.config, {\n _versionId: null,\n _branchId: null,\n });\n } else if (templateData?.versionId) {\n await updateConfig(settings.config, {\n _versionId: templateData.versionId,\n _branchId: branchData.currentBranch.id,\n });\n }\n }\n\n // Always delete branch id from config if branching is disabled\n // Avoids incorrect CDN queries at runtime\n if (!settings.branchOptions.enabled && !settings.omitConfigIds) {\n await updateConfig(settings.config, {\n _branchId: null,\n });\n }\n\n return {\n fileVersionData,\n jobData,\n branchData,\n publishMap,\n inlineLibrary,\n };\n}\n"],"mappings":";;;;;;;;;;;AAoBA,eAAsB,YACpB,SACA,UACA,SACA,OAOQ;AACR,KAAI,CAAC,gBAAgB,UAAU,EAAE,QAAQ,CAAC,QAAQ,QAAQ,CAAC,CACzD,QAAO,SAAS,EAAE;AAEpB,KAAI,CAAC,QAAQ,UAAU,CAAC,oBAAoB,SAAS,CAAE,QAAO,SAAS,EAAE;CAEzE,MAAM,EACJ,OAAO,UACP,iBACA,eACA,eACE,MAAM,aAAa,SAAS,UAAU,QAAQ;AAGlD,OAAM,sBAAsB,UAAU,SAAS;AAG/C,KAAI,QAAQ,QAAQ;AAClB,SAAO,QAAQ,sDAAsD;AACrE,oBAAkB,UAAU,iBAAiB,cAAc;AAC3D,SAAO;;AAGT,KAAI,SAAS,WAAW,KAAK,CAAC,SAAS,QACrC,QAAO,MACL,4EACD;CAIH,IAAI;CACJ,IAAI;CACJ,IAAI;AACJ,KAAI,SAAS,SAAS,GAAG;EACvB,MAAM,EAAE,YAAY,kBAAkB,kBACpC,MAAM,sBAAsB;GAC1B,OAAO;GACP;GACA;GACA;GACD,CAAC;AACJ,YAAU;AACV,eAAa;AAEb,oBAAkB,6BAA6B,SAAS;AAGxD,MAAI,MAQF,oBAAmB,UAPC,OAAO,QAAQ,gBAAgB,CAAC,KACjD,CAAC,QAAQ,WAAW;GACnB;GACA,WAAW,KAAK;GAChB,UAAU,KAAK;GAChB,EAEqC,EAAE,WAAW,cAAc,GAAG;EAExE,MAAM,eAAe,SAAS,MAC3B,SAAS,KAAK,WAAW,iBAC3B;AACD,MAAI,SAAS,cAGX,OAAM,aAAa,SAAS,QAAQ;GAClC,YAAY;GACZ,WAAW;GACZ,CAAC;WACO,cAAc,UACvB,OAAM,aAAa,SAAS,QAAQ;GAClC,YAAY,aAAa;GACzB,WAAW,WAAW,cAAc;GACrC,CAAC;;AAMN,KAAI,CAAC,SAAS,cAAc,WAAW,CAAC,SAAS,cAC/C,OAAM,aAAa,SAAS,QAAQ,EAClC,WAAW,MACZ,CAAC;AAGJ,QAAO;EACL;EACA;EACA;EACA;EACA;EACD"}
1
+ {"version":3,"file":"stage.js","names":[],"sources":["../../../src/cli/commands/stage.ts"],"sourcesContent":["import { logger } from '../../console/logger.js';\nimport { exitSync, logCollectedFiles } from '../../console/logging.js';\nimport {\n Settings,\n SupportedLibraries,\n TranslateFlags,\n} from '../../types/index.js';\nimport { runStageFilesWorkflow } from '../../workflows/stage.js';\nimport { writeStagedEntries } from '../../fs/config/downloadedVersions.js';\nimport type { EnqueueFilesResult } from 'generaltranslation/types';\nimport updateConfig from '../../fs/config/updateConfig.js';\nimport { FileTranslationData } from '../../workflows/download.js';\nimport { BranchData } from '../../types/branch.js';\nimport { TEMPLATE_FILE_ID } from '../../utils/constants.js';\nimport { collectFiles } from '../../formats/files/collectFiles.js';\nimport { convertToFileTranslationData } from '../../formats/files/convertToFileTranslationData.js';\nimport { hasValidCredentials, hasValidLocales } from './utils/validation.js';\nimport { warnManualReviewSetup } from '../../translation/reviewSetupWarning.js';\nimport type { InlineLibrary } from '../../types/libraries.js';\nimport { collectParaglideContext } from '../../paraglide/collectParaglideContext.js';\n\nexport async function handleStage(\n options: TranslateFlags,\n settings: Settings,\n library: SupportedLibraries,\n stage: boolean\n): Promise<{\n fileVersionData: FileTranslationData | undefined;\n jobData: EnqueueFilesResult | undefined;\n branchData: BranchData | undefined;\n publishMap: Map<string, boolean>;\n inlineLibrary?: InlineLibrary;\n} | null> {\n if (!hasValidLocales(settings, { forApi: !options.dryRun }))\n return exitSync(1);\n // Validate credentials if not in dry run\n if (!options.dryRun && !hasValidCredentials(settings)) return exitSync(1);\n\n if (settings.files?.parsingFlags?.json?.includeSourceCodeContext) {\n await collectParaglideContext();\n }\n\n const {\n files: allFiles,\n reactComponents,\n inlineLibrary,\n publishMap,\n } = await collectFiles(options, settings, library);\n\n // Point at dashboard review setup when uploading review-gated content\n await warnManualReviewSetup(settings, allFiles);\n\n // Dry run\n if (options.dryRun) {\n logger.success(`Dry run: No files were sent to General Translation.`);\n logCollectedFiles(allFiles, reactComponents, inlineLibrary);\n return null;\n }\n\n if (allFiles.length === 0 && !settings.publish) {\n logger.error(\n 'No files to translate were found. Check your configuration and try again.'\n );\n }\n\n // Send translations to General Translation\n let fileVersionData: FileTranslationData | undefined;\n let jobData: EnqueueFilesResult | undefined;\n let branchData: BranchData | undefined;\n if (allFiles.length > 0) {\n const { branchData: branchDataResult, enqueueResult } =\n await runStageFilesWorkflow({\n files: allFiles,\n options,\n settings,\n inlineLibrary,\n });\n jobData = enqueueResult;\n branchData = branchDataResult;\n\n fileVersionData = convertToFileTranslationData(allFiles);\n\n // Write staged entries to the lockfile\n if (stage) {\n const stagedFiles = Object.entries(fileVersionData).map(\n ([fileId, data]) => ({\n fileId,\n versionId: data.versionId,\n fileName: data.fileName,\n })\n );\n writeStagedEntries(settings, stagedFiles, branchData.currentBranch.id);\n }\n const templateData = allFiles.find(\n (file) => file.fileId === TEMPLATE_FILE_ID\n );\n if (settings.omitConfigIds) {\n // Remove persisted config IDs only after staging has succeeded, so\n // failed and empty runs keep the previous pinned version/branch state\n await updateConfig(settings.config, {\n _versionId: null,\n _branchId: null,\n });\n } else if (templateData?.versionId) {\n await updateConfig(settings.config, {\n _versionId: templateData.versionId,\n _branchId: branchData.currentBranch.id,\n });\n }\n }\n\n // Always delete branch id from config if branching is disabled\n // Avoids incorrect CDN queries at runtime\n if (!settings.branchOptions.enabled && !settings.omitConfigIds) {\n await updateConfig(settings.config, {\n _branchId: null,\n });\n }\n\n return {\n fileVersionData,\n jobData,\n branchData,\n publishMap,\n inlineLibrary,\n };\n}\n"],"mappings":";;;;;;;;;;;;AAqBA,eAAsB,YACpB,SACA,UACA,SACA,OAOQ;AACR,KAAI,CAAC,gBAAgB,UAAU,EAAE,QAAQ,CAAC,QAAQ,QAAQ,CAAC,CACzD,QAAO,SAAS,EAAE;AAEpB,KAAI,CAAC,QAAQ,UAAU,CAAC,oBAAoB,SAAS,CAAE,QAAO,SAAS,EAAE;AAEzE,KAAI,SAAS,OAAO,cAAc,MAAM,yBACtC,OAAM,yBAAyB;CAGjC,MAAM,EACJ,OAAO,UACP,iBACA,eACA,eACE,MAAM,aAAa,SAAS,UAAU,QAAQ;AAGlD,OAAM,sBAAsB,UAAU,SAAS;AAG/C,KAAI,QAAQ,QAAQ;AAClB,SAAO,QAAQ,sDAAsD;AACrE,oBAAkB,UAAU,iBAAiB,cAAc;AAC3D,SAAO;;AAGT,KAAI,SAAS,WAAW,KAAK,CAAC,SAAS,QACrC,QAAO,MACL,4EACD;CAIH,IAAI;CACJ,IAAI;CACJ,IAAI;AACJ,KAAI,SAAS,SAAS,GAAG;EACvB,MAAM,EAAE,YAAY,kBAAkB,kBACpC,MAAM,sBAAsB;GAC1B,OAAO;GACP;GACA;GACA;GACD,CAAC;AACJ,YAAU;AACV,eAAa;AAEb,oBAAkB,6BAA6B,SAAS;AAGxD,MAAI,MAQF,oBAAmB,UAPC,OAAO,QAAQ,gBAAgB,CAAC,KACjD,CAAC,QAAQ,WAAW;GACnB;GACA,WAAW,KAAK;GAChB,UAAU,KAAK;GAChB,EAEqC,EAAE,WAAW,cAAc,GAAG;EAExE,MAAM,eAAe,SAAS,MAC3B,SAAS,KAAK,WAAW,iBAC3B;AACD,MAAI,SAAS,cAGX,OAAM,aAAa,SAAS,QAAQ;GAClC,YAAY;GACZ,WAAW;GACZ,CAAC;WACO,cAAc,UACvB,OAAM,aAAa,SAAS,QAAQ;GAClC,YAAY,aAAa;GACzB,WAAW,WAAW,cAAc;GACrC,CAAC;;AAMN,KAAI,CAAC,SAAS,cAAc,WAAW,CAAC,SAAS,cAC/C,OAAM,aAAa,SAAS,QAAQ,EAClC,WAAW,MACZ,CAAC;AAGJ,QAAO;EACL;EACA;EACA;EACA;EACA;EACD"}
@@ -13,6 +13,7 @@ import { hasValidCredentials, hasValidServiceLocales } from "./utils/validation.
13
13
  import { runPublishWorkflow } from "../../workflows/publish.js";
14
14
  import { parseXcstringsCatalog, serializeXcstringsSlice, sliceTranslationCatalog } from "../../formats/xcstrings/parseXcstrings.js";
15
15
  import { aggregateFiles, isUnparsableFile } from "../../formats/files/aggregateFiles.js";
16
+ import { collectParaglideContext } from "../../paraglide/collectParaglideContext.js";
16
17
  import { existsSync } from "node:fs";
17
18
  //#region src/cli/commands/upload.ts
18
19
  /**
@@ -24,6 +25,7 @@ async function upload(settings) {
24
25
  if (!settings.files) return;
25
26
  const additionalOptions = settings.options || {};
26
27
  const { resolvedPaths: filePaths, placeholderPaths, transformPaths, transformFormats } = settings.files;
28
+ if (settings.files?.parsingFlags?.json?.includeSourceCodeContext) await collectParaglideContext();
27
29
  const { files: allFiles, publishMap } = await aggregateFiles(settings);
28
30
  const sourceFileNames = new Set(allFiles.map((file) => file.fileName));
29
31
  const compositeJsonFiles = /* @__PURE__ */ new Map();
@@ -1 +1 @@
1
- {"version":3,"file":"upload.js","names":[],"sources":["../../../src/cli/commands/upload.ts"],"sourcesContent":["import {\n fileEncodingSkipReason,\n noDefaultLocaleError,\n} from '../../console/index.js';\nimport { exitSync, logErrorAndExit } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\nimport { getRelative, readFile } from '../../fs/findFilepath.js';\nimport { readFileContent } from '../../fs/fileContent.js';\nimport { Settings } from '../../types/index.js';\nimport { UploadOptions } from '../base.js';\nimport { extractJson } from '../../formats/json/extractJson.js';\nimport { validateJsonSchema } from '../../formats/json/utils.js';\nimport { runUploadFilesWorkflow } from '../../workflows/upload.js';\nimport { existsSync } from 'node:fs';\nimport { createFileMapping } from '../../formats/files/fileMapping.js';\nimport type { FileToUpload } from 'generaltranslation/types';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './utils/validation.js';\nimport { runPublishWorkflow } from '../../workflows/publish.js';\nimport {\n aggregateFiles,\n isUnparsableFile,\n} from '../../formats/files/aggregateFiles.js';\nimport { recordWarning } from '../../state/translateWarnings.js';\nimport {\n parseXcstringsCatalog,\n serializeXcstringsSlice,\n sliceTranslationCatalog,\n type XcstringsCatalog,\n} from '../../formats/xcstrings/parseXcstrings.js';\nimport { api } from '../../utils/api.js';\n\n/**\n * Sends multiple files to the API for translation\n * @param settings - Translation options including API settings\n * @returns Promise that resolves when translation is complete\n */\nexport async function upload(\n settings: Settings & UploadOptions\n): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n const additionalOptions = settings.options || {};\n const {\n resolvedPaths: filePaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n } = settings.files;\n\n // Reuse the same source aggregation path as translate/stage so source\n // parsing behavior stays consistent across commands.\n const { files: allFiles, publishMap } = await aggregateFiles(settings);\n const sourceFileNames = new Set(allFiles.map((file) => file.fileName));\n const compositeJsonFiles = new Map<\n string,\n { filePath: string; content: string }\n >();\n\n if (filePaths.json) {\n for (const filePath of filePaths.json) {\n const relativePath = getRelative(filePath);\n if (!sourceFileNames.has(relativePath)) continue;\n\n const jsonSchema = validateJsonSchema(additionalOptions, filePath);\n if (jsonSchema?.composite) {\n compositeJsonFiles.set(relativePath, {\n filePath,\n content: readFile(filePath),\n });\n }\n }\n }\n\n // Translation files are validated like their sources in aggregateFiles.\n const skipValidation = additionalOptions.skipFileValidation;\n const translationParseFormats = new Map<string, 'JSON' | 'YAML'>();\n if (!skipValidation?.json) {\n for (const filePath of [\n ...(filePaths.json ?? []),\n ...(filePaths.twilioContentJson ?? []),\n ]) {\n translationParseFormats.set(getRelative(filePath), 'JSON');\n }\n }\n if (!skipValidation?.yaml) {\n for (const filePath of filePaths.yaml ?? []) {\n translationParseFormats.set(getRelative(filePath), 'YAML');\n }\n }\n\n // An .xcstrings catalog carries its own translations, so each locale's\n // upload is a slice of the same file rather than a separate translation\n // file. Catalogs aggregateFiles could not parse are already reported.\n const xcstringsCatalogs = new Map<string, XcstringsCatalog>();\n if (filePaths.xcstrings) {\n for (const filePath of filePaths.xcstrings) {\n const relativePath = getRelative(filePath);\n if (!sourceFileNames.has(relativePath)) continue;\n xcstringsCatalogs.set(\n relativePath,\n parseXcstringsCatalog(readFile(filePath))\n );\n }\n }\n\n if (allFiles.length === 0) {\n logger.error(\n 'No files to upload were found. Check your configuration and try again.'\n );\n return;\n }\n\n if (!settings.defaultLocale) {\n return logErrorAndExit(noDefaultLocaleError);\n }\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n\n const locales = settings.locales || [];\n // Create file mapping for all file types\n const fileMapping = createFileMapping(\n filePaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n locales,\n settings.defaultLocale\n );\n\n // construct object\n const uploadData = allFiles.map((file) => {\n const sourceFile: FileToUpload = { ...file };\n\n const translations: FileToUpload[] = [];\n const compositeInfo = compositeJsonFiles.get(file.fileName);\n const xcstringsCatalog = xcstringsCatalogs.get(file.fileName);\n\n for (const locale of locales) {\n if (xcstringsCatalog) {\n // Catalog keys are canonical tags; the configured locale may be an alias.\n const slice = sliceTranslationCatalog(\n xcstringsCatalog,\n api.resolveCanonicalLocale(locale)\n );\n // A locale the catalog does not carry has nothing to upload\n if (!slice) continue;\n translations.push({\n content: serializeXcstringsSlice(slice),\n fileName: file.fileName,\n fileFormat: file.transformFormat ?? file.fileFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n } else if (compositeInfo) {\n // Composite JSON: extract translations from the same source file\n const extracted = extractJson(\n compositeInfo.content,\n compositeInfo.filePath,\n additionalOptions,\n locale,\n settings.defaultLocale\n );\n if (extracted) {\n translations.push({\n content: extracted,\n fileName: file.fileName,\n fileFormat: file.transformFormat ?? file.fileFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n }\n } else {\n // Non-composite: look for separate translation files\n const translatedFileName = fileMapping[locale]?.[file.fileName];\n if (translatedFileName && existsSync(translatedFileName)) {\n const translationFormat = file.transformFormat ?? file.fileFormat;\n let translatedContent: string;\n try {\n translatedContent = readFileContent(\n translatedFileName,\n translationFormat\n );\n } catch (error) {\n // One undecodable locale should not block the others: skip it and\n // report it in the summary.\n const relativePath = getRelative(translatedFileName);\n const reason = fileEncodingSkipReason(error);\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n const parseFormat = translationParseFormats.get(file.fileName);\n if (\n parseFormat &&\n isUnparsableFile(\n translatedContent,\n getRelative(translatedFileName),\n parseFormat\n )\n ) {\n continue;\n }\n translations.push({\n content: translatedContent,\n fileName: translatedFileName,\n fileFormat: translationFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n }\n }\n }\n return {\n source: sourceFile,\n translations,\n };\n });\n\n try {\n // Send all files in a single API call\n const { branchData } = await runUploadFilesWorkflow({\n files: uploadData,\n options: settings,\n });\n\n // Publish files to CDN if publish config exists\n await runPublishWorkflow(\n allFiles,\n publishMap,\n branchData.currentBranch.id,\n settings\n );\n } catch (error) {\n logErrorAndExit(`Error uploading files: ${error}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAuCA,eAAsB,OACpB,UACe;AACf,KAAI,CAAC,SAAS,MACZ;CAGF,MAAM,oBAAoB,SAAS,WAAW,EAAE;CAChD,MAAM,EACJ,eAAe,WACf,kBACA,gBACA,qBACE,SAAS;CAIb,MAAM,EAAE,OAAO,UAAU,eAAe,MAAM,eAAe,SAAS;CACtE,MAAM,kBAAkB,IAAI,IAAI,SAAS,KAAK,SAAS,KAAK,SAAS,CAAC;CACtE,MAAM,qCAAqB,IAAI,KAG5B;AAEH,KAAI,UAAU,KACZ,MAAK,MAAM,YAAY,UAAU,MAAM;EACrC,MAAM,eAAe,YAAY,SAAS;AAC1C,MAAI,CAAC,gBAAgB,IAAI,aAAa,CAAE;AAGxC,MADmB,mBAAmB,mBAAmB,SAC3C,EAAE,UACd,oBAAmB,IAAI,cAAc;GACnC;GACA,SAAS,SAAS,SAAS;GAC5B,CAAC;;CAMR,MAAM,iBAAiB,kBAAkB;CACzC,MAAM,0CAA0B,IAAI,KAA8B;AAClE,KAAI,CAAC,gBAAgB,KACnB,MAAK,MAAM,YAAY,CACrB,GAAI,UAAU,QAAQ,EAAE,EACxB,GAAI,UAAU,qBAAqB,EAAE,CACtC,CACC,yBAAwB,IAAI,YAAY,SAAS,EAAE,OAAO;AAG9D,KAAI,CAAC,gBAAgB,KACnB,MAAK,MAAM,YAAY,UAAU,QA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AAK;IACzC,YAAY,KAAK;IACjB;IACA,QAAQ,KAAK;IACb,WAAW,KAAK;IACjB,CAAC;SAEC;GAEL,MAAM,qBAAqB,YAAY,UAAU,KAAK;AACtD,OAAI,sBAAsB,WAAW,mBAAmB,EAAE;IACxD,MAAM,oBAAoB,KAAK,mBAAmB,KAAK;IACvD,IAAI;AACJ,QAAI;AACF,yBAAoB,gBAClB,oBACA,kBACD;aACM,OAAO;KAGd,MAAM,eAAe,YAAY,mBAAmB;KACpD,MAAM,SAAS,uBAAuB,MAAM;AAC5C,YAAO,KAAK,YAAY,aAAa,IAAI,SAAS;AAClD,mBAAc,gBAAgB,cAAc,OAAO;AACnD;;IAEF,MAAM,cAAc,wBAAwB,IAAI,KAAK,SAAS;AAC9D,QACE,eACA,iBACE,mBACA,YAAY,mBAAmB,EAC/B,YACD,CAED;AAEF,iBAAa,KAAK;KAChB,SAAS;KACT,UAAU;KACV,YAAY;KACZ,YAAY,KAAK;KACjB;KACA,QAAQ,KAAK;KACb,WAAW,KAAK;KACjB,CAAC;;;AAIR,SAAO;GACL,QAAQ;GACR;GACD;GACD;AAEF,KAAI;EAEF,MAAM,EAAE,eAAe,MAAM,uBAAuB;GAClD,OAAO;GACP,SAAS;GACV,CAAC;AAGF,QAAM,mBACJ,UACA,YACA,WAAW,cAAc,IACzB,SACD;UACM,OAAO;AACd,kBAAgB,0BAA0B,QAAQ"}
1
+ {"version":3,"file":"upload.js","names":[],"sources":["../../../src/cli/commands/upload.ts"],"sourcesContent":["import {\n fileEncodingSkipReason,\n noDefaultLocaleError,\n} from '../../console/index.js';\nimport { exitSync, logErrorAndExit } from '../../console/logging.js';\nimport { logger } from '../../console/logger.js';\nimport { getRelative, readFile } from '../../fs/findFilepath.js';\nimport { readFileContent } from '../../fs/fileContent.js';\nimport { Settings } from '../../types/index.js';\nimport { UploadOptions } from '../base.js';\nimport { extractJson } from '../../formats/json/extractJson.js';\nimport { validateJsonSchema } from '../../formats/json/utils.js';\nimport { runUploadFilesWorkflow } from '../../workflows/upload.js';\nimport { existsSync } from 'node:fs';\nimport { createFileMapping } from '../../formats/files/fileMapping.js';\nimport type { FileToUpload } from 'generaltranslation/types';\nimport {\n hasValidCredentials,\n hasValidServiceLocales,\n} from './utils/validation.js';\nimport { runPublishWorkflow } from '../../workflows/publish.js';\nimport {\n aggregateFiles,\n isUnparsableFile,\n} from '../../formats/files/aggregateFiles.js';\nimport { recordWarning } from '../../state/translateWarnings.js';\nimport {\n parseXcstringsCatalog,\n serializeXcstringsSlice,\n sliceTranslationCatalog,\n type XcstringsCatalog,\n} from '../../formats/xcstrings/parseXcstrings.js';\nimport { api } from '../../utils/api.js';\nimport { collectParaglideContext } from '../../paraglide/collectParaglideContext.js';\n\n/**\n * Sends multiple files to the API for translation\n * @param settings - Translation options including API settings\n * @returns Promise that resolves when translation is complete\n */\nexport async function upload(\n settings: Settings & UploadOptions\n): Promise<void> {\n if (!settings.files) {\n return;\n }\n\n const additionalOptions = settings.options || {};\n const {\n resolvedPaths: filePaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n } = settings.files;\n\n if (settings.files?.parsingFlags?.json?.includeSourceCodeContext) {\n await collectParaglideContext();\n }\n\n // Reuse the same source aggregation path as translate/stage so source\n // parsing behavior stays consistent across commands.\n const { files: allFiles, publishMap } = await aggregateFiles(settings);\n const sourceFileNames = new Set(allFiles.map((file) => file.fileName));\n const compositeJsonFiles = new Map<\n string,\n { filePath: string; content: string }\n >();\n\n if (filePaths.json) {\n for (const filePath of filePaths.json) {\n const relativePath = getRelative(filePath);\n if (!sourceFileNames.has(relativePath)) continue;\n\n const jsonSchema = validateJsonSchema(additionalOptions, filePath);\n if (jsonSchema?.composite) {\n compositeJsonFiles.set(relativePath, {\n filePath,\n content: readFile(filePath),\n });\n }\n }\n }\n\n // Translation files are validated like their sources in aggregateFiles.\n const skipValidation = additionalOptions.skipFileValidation;\n const translationParseFormats = new Map<string, 'JSON' | 'YAML'>();\n if (!skipValidation?.json) {\n for (const filePath of [\n ...(filePaths.json ?? []),\n ...(filePaths.twilioContentJson ?? []),\n ]) {\n translationParseFormats.set(getRelative(filePath), 'JSON');\n }\n }\n if (!skipValidation?.yaml) {\n for (const filePath of filePaths.yaml ?? []) {\n translationParseFormats.set(getRelative(filePath), 'YAML');\n }\n }\n\n // An .xcstrings catalog carries its own translations, so each locale's\n // upload is a slice of the same file rather than a separate translation\n // file. Catalogs aggregateFiles could not parse are already reported.\n const xcstringsCatalogs = new Map<string, XcstringsCatalog>();\n if (filePaths.xcstrings) {\n for (const filePath of filePaths.xcstrings) {\n const relativePath = getRelative(filePath);\n if (!sourceFileNames.has(relativePath)) continue;\n xcstringsCatalogs.set(\n relativePath,\n parseXcstringsCatalog(readFile(filePath))\n );\n }\n }\n\n if (allFiles.length === 0) {\n logger.error(\n 'No files to upload were found. Check your configuration and try again.'\n );\n return;\n }\n\n if (!settings.defaultLocale) {\n return logErrorAndExit(noDefaultLocaleError);\n }\n if (!hasValidCredentials(settings) || !hasValidServiceLocales(settings))\n return exitSync(1);\n\n const locales = settings.locales || [];\n // Create file mapping for all file types\n const fileMapping = createFileMapping(\n filePaths,\n placeholderPaths,\n transformPaths,\n transformFormats,\n locales,\n settings.defaultLocale\n );\n\n // construct object\n const uploadData = allFiles.map((file) => {\n const sourceFile: FileToUpload = { ...file };\n\n const translations: FileToUpload[] = [];\n const compositeInfo = compositeJsonFiles.get(file.fileName);\n const xcstringsCatalog = xcstringsCatalogs.get(file.fileName);\n\n for (const locale of locales) {\n if (xcstringsCatalog) {\n // Catalog keys are canonical tags; the configured locale may be an alias.\n const slice = sliceTranslationCatalog(\n xcstringsCatalog,\n api.resolveCanonicalLocale(locale)\n );\n // A locale the catalog does not carry has nothing to upload\n if (!slice) continue;\n translations.push({\n content: serializeXcstringsSlice(slice),\n fileName: file.fileName,\n fileFormat: file.transformFormat ?? file.fileFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n } else if (compositeInfo) {\n // Composite JSON: extract translations from the same source file\n const extracted = extractJson(\n compositeInfo.content,\n compositeInfo.filePath,\n additionalOptions,\n locale,\n settings.defaultLocale\n );\n if (extracted) {\n translations.push({\n content: extracted,\n fileName: file.fileName,\n fileFormat: file.transformFormat ?? file.fileFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n }\n } else {\n // Non-composite: look for separate translation files\n const translatedFileName = fileMapping[locale]?.[file.fileName];\n if (translatedFileName && existsSync(translatedFileName)) {\n const translationFormat = file.transformFormat ?? file.fileFormat;\n let translatedContent: string;\n try {\n translatedContent = readFileContent(\n translatedFileName,\n translationFormat\n );\n } catch (error) {\n // One undecodable locale should not block the others: skip it and\n // report it in the summary.\n const relativePath = getRelative(translatedFileName);\n const reason = fileEncodingSkipReason(error);\n logger.warn(`Skipping ${relativePath}: ${reason}`);\n recordWarning('skipped_file', relativePath, reason);\n continue;\n }\n const parseFormat = translationParseFormats.get(file.fileName);\n if (\n parseFormat &&\n isUnparsableFile(\n translatedContent,\n getRelative(translatedFileName),\n parseFormat\n )\n ) {\n continue;\n }\n translations.push({\n content: translatedContent,\n fileName: translatedFileName,\n fileFormat: translationFormat,\n dataFormat: file.dataFormat,\n locale,\n fileId: file.fileId,\n versionId: file.versionId,\n });\n }\n }\n }\n return {\n source: sourceFile,\n translations,\n };\n });\n\n try {\n // Send all files in a single API call\n const { branchData } = await runUploadFilesWorkflow({\n files: uploadData,\n options: settings,\n });\n\n // Publish files to CDN if publish config exists\n await runPublishWorkflow(\n allFiles,\n publishMap,\n branchData.currentBranch.id,\n settings\n );\n } catch (error) {\n logErrorAndExit(`Error uploading files: ${error}`);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAwCA,eAAsB,OACpB,UACe;AACf,KAAI,CAAC,SAAS,MACZ;CAGF,MAAM,oBAAoB,SAAS,WAAW,EAAE;CAChD,MAAM,EACJ,eAAe,WACf,kBACA,gBACA,qBACE,SAAS;AAEb,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AY,mBAAmB,EAC/B,YACD,CAED;AAEF,iBAAa,KAAK;KAChB,SAAS;KACT,UAAU;KACV,YAAY;KACZ,YAAY,KAAK;KACjB;KACA,QAAQ,KAAK;KACb,WAAW,KAAK;KACjB,CAAC;;;AAIR,SAAO;GACL,QAAQ;GACR;GACD;GACD;AAEF,KAAI;EAEF,MAAM,EAAE,eAAe,MAAM,uBAAuB;GAClD,OAAO;GACP,SAAS;GACV,CAAC;AAGF,QAAM,mBACJ,UACA,YACA,WAAW,cAAc,IACzB,SACD;UACM,OAAO;AACd,kBAAgB,0BAA0B,QAAQ"}
@@ -1 +1 @@
1
- export declare const PACKAGE_VERSION = "2.27.3";
1
+ export declare const PACKAGE_VERSION = "2.28.1";
@@ -1,5 +1,5 @@
1
1
  //#region src/generated/version.ts
2
- const PACKAGE_VERSION = "2.27.3";
2
+ const PACKAGE_VERSION = "2.28.1";
3
3
  //#endregion
4
4
  export { PACKAGE_VERSION };
5
5
 
@@ -1 +1 @@
1
- {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.27.3';\n"],"mappings":";AACA,MAAa,kBAAkB"}
1
+ {"version":3,"file":"version.js","names":[],"sources":["../../src/generated/version.ts"],"sourcesContent":["// This file is auto-generated. Do not edit manually.\nexport const PACKAGE_VERSION = '2.28.1';\n"],"mappings":";AACA,MAAa,kBAAkB"}