locadex 0.1.2 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/cli.d.ts +1 -0
  3. package/dist/cli.d.ts.map +1 -1
  4. package/dist/cli.js +14 -0
  5. package/dist/cli.js.map +1 -1
  6. package/dist/commands/fixErrors.d.ts +4 -0
  7. package/dist/commands/fixErrors.d.ts.map +1 -0
  8. package/dist/commands/fixErrors.js +41 -0
  9. package/dist/commands/fixErrors.js.map +1 -0
  10. package/dist/logging/logger.d.ts.map +1 -1
  11. package/dist/logging/logger.js.map +1 -1
  12. package/dist/mcp/getGuide.d.ts.map +1 -1
  13. package/dist/mcp/getGuide.js +2 -1
  14. package/dist/mcp/getGuide.js.map +1 -1
  15. package/dist/mcp/tools/guides.d.ts.map +1 -1
  16. package/dist/mcp/tools/guides.js +25 -55
  17. package/dist/mcp/tools/guides.js.map +1 -1
  18. package/dist/mcp.d.ts.map +1 -1
  19. package/dist/mcp.js +4 -2
  20. package/dist/mcp.js.map +1 -1
  21. package/dist/tasks/concurrency.d.ts.map +1 -1
  22. package/dist/tasks/concurrency.js +15 -23
  23. package/dist/tasks/concurrency.js.map +1 -1
  24. package/dist/tasks/fixErrors.d.ts +2 -0
  25. package/dist/tasks/fixErrors.d.ts.map +1 -0
  26. package/dist/tasks/fixErrors.js +82 -0
  27. package/dist/tasks/fixErrors.js.map +1 -0
  28. package/dist/tasks/i18n.d.ts.map +1 -1
  29. package/dist/tasks/i18n.js +25 -82
  30. package/dist/tasks/i18n.js.map +1 -1
  31. package/dist/tasks/setup.d.ts.map +1 -1
  32. package/dist/tasks/setup.js +21 -9
  33. package/dist/tasks/setup.js.map +1 -1
  34. package/dist/types/claude-sdk.d.ts +13 -9
  35. package/dist/types/claude-sdk.d.ts.map +1 -1
  36. package/dist/types/claude-sdk.js.map +1 -1
  37. package/dist/utils/claudeCode.d.ts +13 -1
  38. package/dist/utils/claudeCode.d.ts.map +1 -1
  39. package/dist/utils/claudeCode.js +173 -66
  40. package/dist/utils/claudeCode.js.map +1 -1
  41. package/dist/utils/errors.d.ts +20 -0
  42. package/dist/utils/errors.d.ts.map +1 -0
  43. package/dist/utils/errors.js +39 -0
  44. package/dist/utils/errors.js.map +1 -0
  45. package/dist/utils/packages/installPackage.d.ts +1 -2
  46. package/dist/utils/packages/installPackage.d.ts.map +1 -1
  47. package/dist/utils/packages/installPackage.js +19 -28
  48. package/dist/utils/packages/installPackage.js.map +1 -1
  49. package/dist/utils/shared.d.ts +1 -1
  50. package/dist/utils/shared.js +1 -1
  51. package/dist/utils/shared.js.map +1 -1
  52. package/dist/utils/shutdown.d.ts +1 -2
  53. package/dist/utils/shutdown.d.ts.map +1 -1
  54. package/dist/utils/shutdown.js +1 -5
  55. package/dist/utils/shutdown.js.map +1 -1
  56. package/guides/next/advanced/{ternary-operators.md → conditional-rendering.md} +97 -39
  57. package/guides/next/advanced/external-strings.md +346 -0
  58. package/guides/next/advanced/interpolated-strings.md +35 -115
  59. package/guides/next/advanced/{complicated-mapping-expressions.md → mapping-expressions.md} +58 -51
  60. package/guides/next/basic/branches.md +62 -45
  61. package/guides/next/basic/jsx.md +35 -33
  62. package/guides/next/basic/strings.md +43 -25
  63. package/guides/next/basic/variables.md +12 -12
  64. package/guides/next/important/functions.md +13 -11
  65. package/guides/next/{advanced → migration}/migrating.md +2 -3
  66. package/package.json +1 -1
  67. package/guides/next/advanced/var-outside-client-component.md +0 -446
  68. package/guides/next/advanced/var-outside-client-server-component.md +0 -550
  69. package/guides/next/advanced/var-outside-server-component.md +0 -545
  70. package/guides/next/basic/client-side-components.md +0 -221
  71. package/guides/next/basic/server-side-components.md +0 -165
@@ -1 +1 @@
1
- {"version":3,"file":"concurrency.js","sourceRoot":"/","sources":["tasks/concurrency.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAA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,CACpD,CAAC;QACJ,CAAC;QACD,MAAM,UAAU,CAAC;IACnB,CAAC;IAED,IAAI,UAAU,EAAE,CAAC;QACf,MAAM,UAAU,CAAC;IACnB,CAAC;AACH,CAAC","sourcesContent":["import { LocadexManager } from '../utils/locadexManager.js';\nimport { logger } from '../logging/logger.js';\nimport { exit } from '../utils/shutdown.js';\n\n/**\n * Interface for defining how to process tasks in parallel.\n * Separates task preparation (preProcess) from result handling (postProcess).\n *\n * @template TTask - The type of individual tasks being processed\n * @template TContext - The type of shared context/configuration\n */\nexport interface TaskProcessor<TTask, TContext> {\n /**\n * Prepares tasks for processing and generates the prompt for the AI agent.\n * Called before each batch is sent to an agent.\n *\n * @param tasks - Batch of tasks to process\n * @param context - Shared context containing configuration and state\n * @returns Promise that resolves to the prompt string for the AI agent\n */\n preProcess: (tasks: TTask[], context: TContext) => Promise<string>;\n\n /**\n * Handles the results after the AI agent completes processing.\n * Called after each batch is successfully processed.\n *\n * @param tasks - The batch of tasks that were processed\n * @param context - Shared context containing configuration and state\n * @param agentReport - The report/output generated by the AI agent\n */\n postProcess: (\n tasks: TTask[],\n context: TContext,\n agentReport: string\n ) => Promise<void>;\n}\n\n/**\n * Configuration options for parallel processing behavior.\n */\nexport interface ParallelProcessingOptions {\n /** Number of concurrent agents to run in parallel */\n concurrency: number;\n /** Number of tasks to process in each batch */\n batchSize: number;\n}\n\n/**\n * Executes tasks in parallel using a pool of agents with proper concurrency control.\n *\n * This is a generic parallel processing framework that handles:\n * - Task queue management with thread-safe access\n * - Agent pool creation and lifecycle management\n * - Error handling and abort signal propagation\n * - Proper cleanup and resource management\n *\n * @template TTask - The type of tasks to process (e.g., string, object, etc.)\n * @template TContext - The type of context passed to the processor functions\n *\n * @param taskQueue - Array of tasks to process. Will be consumed (mutated) during processing.\n * @param processor - Object implementing preProcess and postProcess methods for task handling\n * @param context - Context object passed to processor methods, containing shared state/config\n * @param options - Configuration for parallel processing (concurrency level, batch size)\n *\n * @throws {Error} If processing fails or is aborted\n *\n * @example\n * ```typescript\n * const processor: TaskProcessor<string, { config: Config }> = {\n * preProcess: async (files, context) => generatePrompt(files, context.config),\n * postProcess: async (files, context, report) => handleResults(files, report)\n * };\n *\n * await runParallelProcessing(\n * ['file1.ts', 'file2.ts'],\n * processor,\n * { config: myConfig },\n * { concurrency: 3, batchSize: 2 }\n * );\n * ```\n */\nexport async function runParallelProcessing<TTask, TContext>(\n taskQueue: TTask[],\n processor: TaskProcessor<TTask, TContext>,\n context: TContext,\n options: ParallelProcessingOptions,\n maxRetries: number = 1\n): Promise<void> {\n const { concurrency, batchSize } = options;\n const manager = LocadexManager.getInstance();\n\n const agentAbortController = manager.getAgentAbortController();\n let firstError: Error | null = null;\n\n // Mutex for task queue access\n let taskQueueMutex = Promise.resolve();\n\n // Helper function to safely get tasks from queue\n const getNextTasks = async (batchSize: number): Promise<TTask[]> => {\n return new Promise((resolve) => {\n taskQueueMutex = taskQueueMutex.then(() => {\n const tasks = taskQueue.splice(0, batchSize);\n resolve(tasks);\n });\n });\n };\n\n const processTask = async (): Promise<void> => {\n while (taskQueue.length > 0 && !agentAbortController.signal.aborted) {\n // Check if we should abort early\n if (agentAbortController.signal.aborted) {\n return;\n }\n\n // Get an available agent atomically\n const agentInfo = await manager.getAvailableAgent();\n if (!agentInfo) {\n // No available agents, wait a bit (but check for abort)\n await new Promise((resolve) => {\n const timeout = global.setTimeout(resolve, 100);\n agentAbortController.signal.addEventListener('abort', () => {\n global.clearTimeout(timeout);\n resolve(undefined);\n });\n });\n continue;\n }\n\n const { id: agentId, agent } = agentInfo;\n\n // Get the next batch of tasks (thread-safe)\n const tasks = await getNextTasks(batchSize);\n if (tasks.length === 0) {\n manager.markAgentFree(agentId);\n break;\n }\n\n logger.debugMessage(`Using agent ${agentId} for ${tasks.length} tasks.`);\n\n // Process tasks using the provided processor\n try {\n // Pre-process: generate prompt\n const prompt = await processor.preProcess(tasks, context);\n\n // dynamic timeout based on the number of tasks\n const dynamicTimeoutSec = manager.getTimeoutFactor() * tasks.length;\n\n // Claude call with timeout and retry (handled inside agent.run)\n await agent.run(\n prompt,\n {\n timeoutSec: dynamicTimeoutSec,\n maxRetries: 1,\n },\n {}\n );\n\n const agentReport = agent.generateReport();\n manager.markAgentFree(agentId);\n\n // Post-process: handle reports, progress, etc.\n await processor.postProcess(tasks, context, agentReport);\n } catch (error) {\n // Check if this is an abort\n if (agentAbortController.signal.aborted) {\n return;\n }\n\n // Capture the first error and signal all other agents to abort\n if (!firstError) {\n firstError = new Error(\n `Error in claude parallel process (${agentId}): ${error}`\n );\n logger.debugMessage(firstError.message);\n }\n await exit(1); // Exit this agent's processing immediately\n return;\n }\n }\n };\n\n // Create agent pool with 100 (soft) turns cutoff\n manager.createAgentPool({ softTurnLimit: 100 });\n\n // Start parallel processing\n const processingPromises = Array.from({ length: concurrency }, () =>\n processTask()\n );\n\n try {\n await Promise.all(processingPromises);\n } catch (error) {\n // Check if this is an abort\n if (agentAbortController.signal.aborted) {\n throw new Error('Processing aborted');\n }\n\n // This shouldn't happen since we handle errors within processTask\n logger.debugMessage(`Unexpected error in parallel processing: ${error}`);\n if (!firstError) {\n firstError = new Error(\n `Unexpected error in parallel processing: ${error}`\n );\n }\n throw firstError;\n }\n\n if (firstError) {\n throw firstError;\n }\n}\n"]}
1
+ {"version":3,"file":"concurrency.js","sourceRoot":"/","sources":["tasks/concurrency.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAC5C,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AA6CvC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,MAAM,CAAC,KAAK,UAAU,qBAAqB,CACzC,SAAkB,EAClB,SAAyC,EAC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KAAK,CAAC;YACd,CAAC;QACH,CAAC;IACH,CAAC,CAAC;IAEF,iDAAiD;IACjD,OAAO,CAAC,eAAe,CAAC,EAAE,aAAa,EAAE,GAAG,EAAE,CAAC,CAAC;IAEhD,4BAA4B;IAC5B,MAAM,kBAAkB,GAAG,KAAK,CAAC,IAAI,CAAC,EAAE,MAAM,EAAE,WAAW,EAAE,EAAE,GAAG,EAAE,CAClE,WAAW,EAAE,CACd,CAAC;IAEF,IAAI,CAAC;QACH,MAAM,OAAO,CAAC,GAAG,CAAC,kBAAkB,CAAC,CAAC;IACxC,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,OAAO,CAAC,YAAY,EAAE,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;YAC3C,SAAS,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC;QACnC,CAAC,CAAC,CAAC;QACH,OAAO,CAAC,KAAK,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC,CAAC,iCAAiC;QAEvE,kCAAkC;QAClC,IAAI,oBAAoB,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACxC,OAAO;QACT,CAAC;QAED,KAAK,CACH,KAAK,CAAC,GAAG,CAAC,+BAA+B,GAAI,KAAe,CAAC,OAAO,CAAC,CACtE,CAAC;QACF,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC,mBAAmB;IACpC,CAAC;IACD,OAAO,CAAC,YAAY,EAAE,CAAC,OAAO,CAAC,CAAC,SAAS,EAAE,EAAE;QAC3C,SAAS,CAAC,KAAK,CAAC,cAAc,EAAE,CAAC;IACnC,CAAC,CAAC,CAAC;AACL,CAAC","sourcesContent":["import { LocadexManager } from '../utils/locadexManager.js';\nimport { logger } from '../logging/logger.js';\nimport { exit } from '../utils/shutdown.js';\nimport chalk from 'chalk';\nimport { outro } from '@clack/prompts';\n\n/**\n * Interface for defining how to process tasks in parallel.\n * Separates task preparation (preProcess) from result handling (postProcess).\n *\n * @template TTask - The type of individual tasks being processed\n * @template TContext - The type of shared context/configuration\n */\nexport interface TaskProcessor<TTask, TContext> {\n /**\n * Prepares tasks for processing and generates the prompt for the AI agent.\n * Called before each batch is sent to an agent.\n *\n * @param tasks - Batch of tasks to process\n * @param context - Shared context containing configuration and state\n * @returns Promise that resolves to the prompt string for the AI agent\n */\n preProcess: (tasks: TTask[], context: TContext) => Promise<string>;\n\n /**\n * Handles the results after the AI agent completes processing.\n * Called after each batch is successfully processed.\n *\n * @param tasks - The batch of tasks that were processed\n * @param context - Shared context containing configuration and state\n * @param agentReport - The report/output generated by the AI agent\n */\n postProcess: (\n tasks: TTask[],\n context: TContext,\n agentReport: string\n ) => Promise<void>;\n}\n\n/**\n * Configuration options for parallel processing behavior.\n */\nexport interface ParallelProcessingOptions {\n /** Number of concurrent agents to run in parallel */\n concurrency: number;\n /** Number of tasks to process in each batch */\n batchSize: number;\n}\n\n/**\n * Executes tasks in parallel using a pool of agents with proper concurrency control.\n *\n * This is a generic parallel processing framework that handles:\n * - Task queue management with thread-safe access\n * - Agent pool creation and lifecycle management\n * - Error handling and abort signal propagation\n * - Proper cleanup and resource management\n *\n * @template TTask - The type of tasks to process (e.g., string, object, etc.)\n * @template TContext - The type of context passed to the processor functions\n *\n * @param taskQueue - Array of tasks to process. Will be consumed (mutated) during processing.\n * @param processor - Object implementing preProcess and postProcess methods for task handling\n * @param context - Context object passed to processor methods, containing shared state/config\n * @param options - Configuration for parallel processing (concurrency level, batch size)\n *\n * @throws {Error} If processing fails or is aborted\n *\n * @example\n * ```typescript\n * const processor: TaskProcessor<string, { config: Config }> = {\n * preProcess: async (files, context) => generatePrompt(files, context.config),\n * postProcess: async (files, context, report) => handleResults(files, report)\n * };\n *\n * await runParallelProcessing(\n * ['file1.ts', 'file2.ts'],\n * processor,\n * { config: myConfig },\n * { concurrency: 3, batchSize: 2 }\n * );\n * ```\n */\nexport async function runParallelProcessing<TTask, TContext>(\n taskQueue: TTask[],\n processor: TaskProcessor<TTask, TContext>,\n context: TContext,\n options: ParallelProcessingOptions,\n maxRetries: number = 1\n): Promise<void> {\n const { concurrency, batchSize } = options;\n const manager = LocadexManager.getInstance();\n const agentAbortController = manager.getAgentAbortController();\n\n // Mutex for task queue access\n let taskQueueMutex = Promise.resolve();\n\n // Helper function to safely get tasks from queue\n const getNextTasks = async (batchSize: number): Promise<TTask[]> => {\n return new Promise((resolve) => {\n taskQueueMutex = taskQueueMutex.then(() => {\n const tasks = taskQueue.splice(0, batchSize);\n resolve(tasks);\n });\n });\n };\n\n const processTask = async (): Promise<void> => {\n while (taskQueue.length > 0 && !agentAbortController.signal.aborted) {\n // Check if we should abort early\n if (agentAbortController.signal.aborted) {\n return;\n }\n\n // Get an available agent atomically\n const agentInfo = await manager.getAvailableAgent();\n if (!agentInfo) {\n // No available agents, wait a bit (but check for abort)\n await new Promise((resolve) => {\n const timeout = global.setTimeout(resolve, 100);\n agentAbortController.signal.addEventListener('abort', () => {\n global.clearTimeout(timeout);\n resolve(undefined);\n });\n });\n continue;\n }\n\n const { id: agentId, agent } = agentInfo;\n\n // Get the next batch of tasks (thread-safe)\n const tasks = await getNextTasks(batchSize);\n if (tasks.length === 0) {\n manager.markAgentFree(agentId);\n break;\n }\n\n logger.debugMessage(`Using agent ${agentId} for ${tasks.length} tasks.`);\n\n // Process tasks using the provided processor\n try {\n // Pre-process: generate prompt\n const prompt = await processor.preProcess(tasks, context);\n\n // dynamic timeout based on the number of tasks\n const dynamicTimeoutSec = manager.getTimeoutFactor() * tasks.length;\n\n // Claude call with timeout and retry (handled inside agent.run)\n await agent.run(\n prompt,\n {\n timeoutSec: dynamicTimeoutSec,\n maxRetries: 1,\n },\n {}\n );\n\n const agentReport = agent.generateReport();\n manager.markAgentFree(agentId);\n\n // Post-process: handle reports, progress, etc.\n await processor.postProcess(tasks, context, agentReport);\n } catch (error) {\n logger.debugMessage(`[${agentId}] error: ${error}`);\n throw error;\n }\n }\n };\n\n // Create agent pool with 100 (soft) turns cutoff\n manager.createAgentPool({ softTurnLimit: 100 });\n\n // Start parallel processing\n const processingPromises = Array.from({ length: concurrency }, () =>\n processTask()\n );\n\n try {\n await Promise.all(processingPromises);\n } catch (error) {\n manager.getAgentPool().forEach((agentInfo) => {\n agentInfo.agent.aggregateStats();\n });\n manager.stats.recordTelemetry(false); // do this after aggregateStats()\n\n // Check if this is a manual abort\n if (agentAbortController.signal.aborted) {\n return;\n }\n\n outro(\n chalk.red('❌ Locadex failed with error: ' + (error as Error).message)\n );\n await exit(1); // Exit the process\n }\n manager.getAgentPool().forEach((agentInfo) => {\n agentInfo.agent.aggregateStats();\n });\n}\n"]}
@@ -0,0 +1,2 @@
1
+ export declare function fixErrorsTask(): Promise<string[] | undefined>;
2
+ //# sourceMappingURL=fixErrors.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fixErrors.d.ts","sourceRoot":"/","sources":["tasks/fixErrors.ts"],"names":[],"mappings":"AASA,wBAAsB,aAAa,kCAoClC"}
@@ -0,0 +1,82 @@
1
+ import { allMcpPrompt } from '../prompts/system.js';
2
+ import { exit } from '../utils/shutdown.js';
3
+ import { logger } from '../logging/logger.js';
4
+ import { LocadexManager } from '../utils/locadexManager.js';
5
+ import { outro } from '@clack/prompts';
6
+ import chalk from 'chalk';
7
+ import { CLAUDE_CODE_VERSION } from '../utils/shared.js';
8
+ import { installGlobalPackage } from '../utils/packages/installPackage.js';
9
+ export async function fixErrorsTask() {
10
+ const manager = LocadexManager.getInstance();
11
+ const reports = [];
12
+ // Install claude-code if not installed
13
+ await installGlobalPackage('@anthropic-ai/claude-code', CLAUDE_CODE_VERSION);
14
+ // Create a clean agent for cleanup
15
+ const cleanupAgent = manager.createSingleAgent('claude_cleanup_agent', {});
16
+ logger.initializeSpinner();
17
+ logger.spinner.start('Fixing errors...');
18
+ const fixPrompt = getFixPrompt(manager.appDirectory);
19
+ try {
20
+ await cleanupAgent.run(fixPrompt, {
21
+ maxTurns: 200,
22
+ timeoutSec: 300,
23
+ maxRetries: 1,
24
+ }, {});
25
+ reports.push(`## Fixed errors\n${cleanupAgent.generateReport()}`);
26
+ }
27
+ catch (error) {
28
+ cleanupAgent.aggregateStats();
29
+ logger.debugMessage(`[claude_cleanup_agent] Fixing errors failed: ${error}`);
30
+ manager.stats.recordTelemetry(false);
31
+ outro(chalk.red('❌ Locadex i18n failed!'));
32
+ await exit(1);
33
+ return;
34
+ }
35
+ cleanupAgent.aggregateStats();
36
+ logger.spinner.stop('Fixed errors');
37
+ return reports;
38
+ }
39
+ // check (dry run and ts check) should be at the end
40
+ function getFixPrompt(appDirectory) {
41
+ const prompt = `# Task: Fix internationalization errors in the project.
42
+
43
+ ## INSTRUCTIONS
44
+
45
+ Previously, you helped me internationalize a set of files in this project.
46
+ Your new task is to fix any errors that were introduced by your previous implementation.
47
+
48
+ ## Steps:
49
+ 1. Run the gt-next validator.
50
+ 2. Fix all errors output by the gt-next validator.
51
+ 3. Repeat steps 1-2 until there are no more errors, or until you believe that you have fixed all errors.
52
+
53
+ ## RULES:
54
+ - ONLY modify files that are relevant to the internationalization of the project.
55
+ - ONLY fix errors that result from your current or previous implementation.
56
+ - Resolve unused imports from 'gt-next'.
57
+ - In particular, if a file contains user-facing content that should be internationalized and is not, you should internationalize it.
58
+ - Resolve missing imports from 'gt-next'. If a file is missing an import from 'gt-next', add it.
59
+ - ALWAYS adhere to the guides provided via the 'mcp__locadex__' tools.
60
+ - These guides provide additional knowledge about how to internationalize the content.
61
+ - NEVER move content to a different file. All content MUST remain in the same file where it came from.
62
+ - NEVER CREATE OR DELETE ANY FILES (especially .bak files)
63
+
64
+ To run the gt-next validator, run the following command from the app root:
65
+ 'locadex validate' (global command)
66
+ The app root is: "${appDirectory}"
67
+
68
+ ## MCP TOOLS
69
+
70
+ ${allMcpPrompt}
71
+
72
+ ## Final output
73
+ - When you are done, please return a brief summary of the files you modified, following this format.
74
+ - **DO NOT** include any other text in your response.
75
+ - If there were issues with some files, please include the issues in the list of changes for that file.
76
+
77
+ [file 1 path]
78
+ - List of changes to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AC,cAAc,EAAE,EAAE,CAAC,CAAC;IACpE,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,YAAY,CAAC,cAAc,EAAE,CAAC;QAC9B,MAAM,CAAC,YAAY,CACjB,gDAAgD,KAAK,EAAE,CACxD,CAAC;QACF,OAAO,CAAC,KAAK,CAAC,eAAe,CAAC,KAAK,CAAC,CAAC;QACrC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,wBAAwB,CAAC,CAAC,CAAC;QAC3C,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC;QACd,OAAO;IACT,CAAC;IACD,YAAY,CAAC,cAAc,EAAE,CAAC;IAC9B,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,cAAc,CAAC,CAAC;IACpC,OAAO,OAAO,CAAC;AACjB,CAAC;AAED,oDAAoD;AAEpD,SAAS,YAAY,CAAC,YAAoB;IACxC,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;oBAyBG,YAAY;;;;EAI9B,YAAY;;;;;;;;;CASb,CAAC;IAEA,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { allMcpPrompt } from '../prompts/system.js';\nimport { exit } from '../utils/shutdown.js';\nimport { logger } from '../logging/logger.js';\nimport { LocadexManager } from '../utils/locadexManager.js';\nimport { outro } from '@clack/prompts';\nimport chalk from 'chalk';\nimport { CLAUDE_CODE_VERSION } from '../utils/shared.js';\nimport { installGlobalPackage } from '../utils/packages/installPackage.js';\n\nexport async function fixErrorsTask() {\n const manager = LocadexManager.getInstance();\n const reports: string[] = [];\n // Install claude-code if not installed\n await installGlobalPackage('@anthropic-ai/claude-code', CLAUDE_CODE_VERSION);\n\n // Create a clean agent for cleanup\n const cleanupAgent = manager.createSingleAgent('claude_cleanup_agent', {});\n\n logger.initializeSpinner();\n logger.spinner.start('Fixing errors...');\n const fixPrompt = getFixPrompt(manager.appDirectory);\n try {\n await cleanupAgent.run(\n fixPrompt,\n {\n maxTurns: 200,\n timeoutSec: 300,\n maxRetries: 1,\n },\n {}\n );\n reports.push(`## Fixed errors\\n${cleanupAgent.generateReport()}`);\n } catch (error) {\n cleanupAgent.aggregateStats();\n logger.debugMessage(\n `[claude_cleanup_agent] Fixing errors failed: ${error}`\n );\n manager.stats.recordTelemetry(false);\n outro(chalk.red('❌ Locadex i18n failed!'));\n await exit(1);\n return;\n }\n cleanupAgent.aggregateStats();\n logger.spinner.stop('Fixed errors');\n return reports;\n}\n\n// check (dry run and ts check) should be at the end\n\nfunction getFixPrompt(appDirectory: string) {\n const prompt = `# Task: Fix internationalization errors in the project.\n\n## INSTRUCTIONS\n\nPreviously, you helped me internationalize a set of files in this project.\nYour new task is to fix any errors that were introduced by your previous implementation.\n\n## Steps:\n1. Run the gt-next validator.\n2. Fix all errors output by the gt-next validator.\n3. Repeat steps 1-2 until there are no more errors, or until you believe that you have fixed all errors.\n\n## RULES:\n- ONLY modify files that are relevant to the internationalization of the project.\n- ONLY fix errors that result from your current or previous implementation.\n- Resolve unused imports from 'gt-next'. \n - In particular, if a file contains user-facing content that should be internationalized and is not, you should internationalize it.\n- Resolve missing imports from 'gt-next'. If a file is missing an import from 'gt-next', add it.\n- ALWAYS adhere to the guides provided via the 'mcp__locadex__' tools.\n - These guides provide additional knowledge about how to internationalize the content.\n- NEVER move content to a different file. All content MUST remain in the same file where it came from.\n- NEVER CREATE OR DELETE ANY FILES (especially .bak files)\n\nTo run the gt-next validator, run the following command from the app root:\n'locadex validate' (global command)\nThe app root is: \"${appDirectory}\"\n\n## MCP TOOLS\n\n${allMcpPrompt}\n\n## Final output\n- When you are done, please return a brief summary of the files you modified, following this format.\n- **DO NOT** include any other text in your response. \n- If there were issues with some files, please include the issues in the list of changes for that file.\n\n[file 1 path]\n- List of changes to file 1\n`;\n\n return prompt;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"i18n.d.ts","sourceRoot":"/","sources":["tasks/i18n.ts"],"names":[],"mappings":"AAuBA,wBAAsB,QAAQ,kBAiO7B"}
1
+ {"version":3,"file":"i18n.d.ts","sourceRoot":"/","sources":["tasks/i18n.ts"],"names":[],"mappings":"AA0BA,wBAAsB,QAAQ,kBAwM7B"}
@@ -11,10 +11,13 @@ import { appendFileSync } from 'node:fs';
11
11
  import { detectFormatter, formatFiles } from 'gtx-cli/hooks/postProcess';
12
12
  import path from 'node:path';
13
13
  import { updateLockfile, cleanupLockfile } from '../utils/lockfile.js';
14
- import { installClaudeCode } from '../utils/packages/installPackage.js';
15
14
  import { extractFiles } from '../utils/dag/extractFiles.js';
16
15
  import { getPackageJson, isPackageInstalled } from 'gtx-cli/utils/packageJson';
17
16
  import { deleteAddedFiles } from '../utils/fs/git.js';
17
+ import { CLAUDE_CODE_VERSION } from '../utils/shared.js';
18
+ import { installGlobalPackage } from '../utils/packages/installPackage.js';
19
+ import { fixErrorsTask } from './fixErrors.js';
20
+ import { getLocadexVersion } from 'src/utils/getPaths.js';
18
21
  export async function i18nTask() {
19
22
  const manager = LocadexManager.getInstance();
20
23
  // have to use the package.json from the appDir
@@ -27,7 +30,9 @@ export async function i18nTask() {
27
30
  await exit(1);
28
31
  }
29
32
  // Install claude-code if not installed
30
- await installClaudeCode();
33
+ await installGlobalPackage('@anthropic-ai/claude-code', CLAUDE_CODE_VERSION);
34
+ // Install locadex if not installed
35
+ await installGlobalPackage('locadex', getLocadexVersion());
31
36
  logger.debugMessage('App directory: ' + manager.appDirectory);
32
37
  logger.debugMessage('Root directory: ' + manager.rootDirectory);
33
38
  // Init message
@@ -78,18 +83,18 @@ export async function i18nTask() {
78
83
  dependentFiles: dependents,
79
84
  });
80
85
  },
81
- postProcess: async (files, context, agentReport) => {
86
+ postProcess: async (processedFiles, context, agentReport) => {
82
87
  const { filesStateFilePath } = context;
83
88
  // Mark tasks as complete
84
- await Promise.all(files.map((task) => markFileAsEdited(task, filesStateFilePath)));
89
+ await Promise.all(processedFiles.map((file) => markFileAsEdited(file, filesStateFilePath)));
85
90
  // Add agent report
86
91
  reports.push(agentReport);
87
- // Update progress bar
88
- logger.progressBar.advance(files.length, `Processed ${Number(((reports.length * files.length) / files.length) * 100).toFixed(2)}% of files`);
89
92
  // Update stats
90
93
  manager.stats.updateStats({
91
- newProcessedFiles: files.length,
94
+ newProcessedFiles: processedFiles.length,
92
95
  });
96
+ // Update progress bar
97
+ logger.progressBar.advance(processedFiles.length, `Processed ${Number((manager.stats.getStats().processedFiles / files.length) * 100).toFixed(2)}% of files`);
93
98
  },
94
99
  };
95
100
  // Run parallel processing
@@ -101,30 +106,10 @@ export async function i18nTask() {
101
106
  return;
102
107
  }
103
108
  logger.progressBar.stop(`Processed ${files.length} files [${Math.round((Date.now() - fileProcessingStartTime) / 1000)}s]`);
104
- // TODO: uncomment
105
- // // Always clean up the file list when done, regardless of success or failure
106
- // cleanUp(stateFilePath);
107
- // Create a clean agent for cleanup
108
- const cleanupAgent = manager.createSingleAgent('claude_cleanup_agent', {});
109
- logger.initializeSpinner();
110
- logger.spinner.start('Fixing errors...');
111
- const fixPrompt = getFixPrompt(manager.appDirectory);
112
- try {
113
- await cleanupAgent.run(fixPrompt, {
114
- maxTurns: 200,
115
- timeoutSec: 300,
116
- maxRetries: 1,
117
- }, {});
118
- reports.push(`## Fixed errors\n${cleanupAgent.generateReport()}`);
109
+ const cleanupReports = await fixErrorsTask();
110
+ if (cleanupReports) {
111
+ reports.push(...cleanupReports);
119
112
  }
120
- catch (error) {
121
- logger.debugMessage(`[claude_cleanup_agent] Fixing errors failed: ${error}`);
122
- manager.stats.recordTelemetry(false);
123
- outro(chalk.red('❌ Locadex i18n failed!'));
124
- await exit(1);
125
- return;
126
- }
127
- logger.spinner.stop('Fixed errors');
128
113
  // Generate report
129
114
  const reportSummary = `# Summary of locadex i18n changes
130
115
  ${reports.join('\n')}`;
@@ -172,28 +157,25 @@ function getPrompt({ targetFile, dependencyFiles, dependentFiles, }) {
172
157
  - If the target files have no relevant content, are already internationalized, or contain build-time code (e.g. nextjs plugins) they should never be internationalized.
173
158
  **IMPORTANT**: IF NONE OF THE TARGET FILES NEED TO BE INTERNATIONALIZED, YOUR TASK IS COMPLETE AND YOU MAY RETURN.
174
159
  3. **Identify the tools to use** Given the contents of the files, ask yourself which tools and guides you need to use to get the necessary knowledge to internationalize the target files. Here are some helpful questions to evaluate for tool selection:
175
- - 3.a. Does this file contain a component? If so, is it a server-side component or a client-side component?
176
- - 3.b. Is the content that needs to be i18ned being used in this same file, or is it being used in another file?
177
- - 3.c. Is there any string interpolation that needs to be i18ned?
178
- - 3.d. Is there any conditional logic or rendering that needs to be i18ned?
179
- - 3.e. Is the content that needs to be i18ned HTML/JSX or a string?
160
+ - 3.a. Is the content that needs to be i18ned being used in this same file, or is it being used in another file?
161
+ - 3.b. Is there any string interpolation that needs to be i18ned?
162
+ - 3.c. Is there any conditional logic or rendering that needs to be i18ned?
163
+ - 3.d. Is the content that needs to be i18ned HTML/JSX or a string?
180
164
  4. **Internationalize** You now have the necessary knowledge. Internationalize the files using the information from the tools provided to you.
181
- - 4.a. Do not worry about running tsc. We will do that later.
165
+ - 4.a. Do not run validation checks such as tsc. We will do that later.
182
166
 
183
167
  ## RULES:
184
168
  - ALWAYS use the <T> component to internationalize HTML/JSX content.
185
- - ALWAYS use getGT() or useGT() and getDict() or useDict() to internationalize string content (strings created with '', "", or \`\`).
186
- - When possible, avoid using getDict() or useDict(); getGT() and useGT() are preferred.
169
+ - ALWAYS use useGT() or useTranslations() to internationalize string content (strings created with '', "", or \`\`).
170
+ - When possible, avoid using useTranslations(); useGT() is always preferred.
187
171
  - DO NOT internationalize non-user facing content or content that is functional, such as ids, class names, error strings, logical strings, etc.
188
172
  - Do not add i18n middleware to the app.
189
- - When adding 'useGT()' or 'useDict()' to a client component, you must add 'use client' to the top of the file.
190
- - Always adhere to the guides provided via the 'mcp__locadex__' tools.
173
+ - ALWAYS adhere to the guides provided via the 'mcp__locadex__' tools.
191
174
  - These guides provide additional knowledge about how to internationalize the content.
192
175
  - Minimize the footprint of your changes.
193
- - Focus on internationalizing the content of the target files.
194
- - NEVER move internationalized content to a different file. All content MUST remain in the same file where it came from.
176
+ - Focus on internationalizing all user facing content in the target files.
177
+ - NEVER move content to a different file. All content MUST remain in the same file where it came from.
195
178
  - NEVER CREATE OR DELETE ANY FILES (especially .bak files)
196
- - Internationalize all user facing content in the target files.
197
179
  - NEVER EDIT FILES THAT ARE NOT GIVEN TO YOU.
198
180
 
199
181
  ## TARGET FILE INFORMATION
@@ -219,45 +201,6 @@ ${allMcpPrompt}
219
201
  - **DO NOT** include any other text in your response.
220
202
  - If there were issues with some files, please include the issues in the list of changes for that file.
221
203
 
222
- [file 1 path]
223
- - List of changes to file 1
224
- `;
225
- return prompt;
226
- }
227
- // check (dry run and ts check) should be at the end
228
- function getFixPrompt(appDirectory) {
229
- const prompt = `# Task: Fix internationalization errors in the project.
230
-
231
- ## INSTRUCTIONS
232
-
233
- Previously, you helped me internationalize a set of files in this project.
234
- Your new task is as follows:
235
-
236
- 1. Run the gt-next validator.
237
- 2. Fix all errors output by the gt-next validator.
238
- 3. Whenever you are finished with your changes, run the gt-next validator.
239
- 4. Repeat steps 1-3 until there are no more errors, or until you believe that you have fixed all errors.
240
-
241
- ## RULES:
242
- - ONLY modify files that are relevant to the internationalization of the project.
243
- - ONLY fix errors that result from your current or previous implementation.
244
- - Resolve unused imports from 'gt-next'.
245
- - In particular, if a file contains user-facing content that should be internationalized and is not, you should internationalize it.
246
- - Resolve missing imports from 'gt-next'. If a file is missing an import from 'gt-next', add it.
247
-
248
- To run the gt-next validator, run the following command from the app root:
249
- 'npx locadex translate --dry-run'
250
- The app root is: "${appDirectory}"
251
-
252
- ## MCP TOOLS
253
-
254
- ${allMcpPrompt}
255
-
256
- ## Final output
257
- - When you are done, please return a brief summary of the files you modified, following this format.
258
- - **DO NOT** include any other text in your response.
259
- - If there were issues with some files, please include the issues in the list of changes for that file.
260
-
261
204
  [file 1 path]
262
205
  - List of changes to file 1
263
206
  `;
@@ -1 +1 @@
1
- {"version":3,"file":"i18n.js","sourceR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;;;;;;;;;;;;;oBAqBG,YAAY;;;;EAI9B,YAAY;;;;;;;;;CASb,CAAC;IAEA,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { createSpinner } from '../logging/console.js';\nimport { allMcpPrompt } from '../prompts/system.js';\nimport { exit } from '../utils/shutdown.js';\nimport { logger } from '../logging/logger.js';\nimport { LocadexManager } from '../utils/locadexManager.js';\nimport {\n addFilesToManager,\n markFileAsEdited,\n markFileAsInProgress,\n} from '../utils/dag/getFiles.js';\nimport { runParallelProcessing, TaskProcessor } from './concurrency.js';\nimport { outro } from '@clack/prompts';\nimport chalk from 'chalk';\nimport { appendFileSync } from 'node:fs';\nimport { detectFormatter, formatFiles } from 'gtx-cli/hooks/postProcess';\nimport path from 'node:path';\nimport { updateLockfile, cleanupLockfile } from '../utils/lockfile.js';\nimport { installClaudeCode } from '../utils/packages/installPackage.js';\nimport { extractFiles } from '../utils/dag/extractFiles.js';\nimport { Dag } from '../utils/dag/createDag.js';\nimport { getPackageJson, isPackageInstalled } from 'gtx-cli/utils/packageJson';\nimport { deleteAddedFiles } from '../utils/fs/git.js';\n\nexport async function i18nTask() {\n const manager = LocadexManager.getInstance();\n // have to use the package.json from the appDir\n const packageJson = await getPackageJson(manager.appDirectory);\n const isUsingGTNext = packageJson\n ? isPackageInstalled('gt-next', packageJson)\n : false;\n if (!isUsingGTNext) {\n logger.error(\n `gt-next not detected in ${manager.appDirectory}. Please specify the correct app directory with the --app-dir flag, or ensure that gt-next is correctly installed in the project.`\n );\n await exit(1);\n }\n\n // Install claude-code if not installed\n await installClaudeCode();\n\n logger.debugMessage('App directory: ' + manager.appDirectory);\n logger.debugMessage('Root directory: ' + manager.rootDirectory);\n\n // Init message\n const spinner = createSpinner();\n spinner.start('Initializing Locadex...');\n\n const { files, dag } = extractFiles(manager);\n\n if (files.length === 0) {\n spinner.stop('No files have changed since last run');\n outro(chalk.green('✅ Locadex i18n complete - no changes detected!'));\n await exit(0);\n }\n\n const filesStateFilePath = manager.getFilesStateFilePath();\n const concurrency = manager.getMaxConcurrency();\n const batchSize = manager.getBatchSize();\n\n // Create the list of files (aka tasks) to process\n const taskQueue = Array.from(files);\n\n // Add files to manager\n const stateFilePath = addFilesToManager(filesStateFilePath, taskQueue);\n spinner.stop('Locadex initialized');\n\n logger.verboseMessage(`Processing ${files.length} modified files`);\n logger.debugMessage(`Track progress here: ${stateFilePath}`);\n logger.debugMessage(`Order:\\n${taskQueue.join('\\n')}`);\n\n logger.message(`Using ${concurrency} concurrent agents`);\n logger.initializeProgressBar(taskQueue.length);\n\n const fileProcessingStartTime = Date.now();\n logger.progressBar.start(`Processing ${taskQueue.length} files...`);\n\n // Shared reports array for collecting results\n const reports: string[] = [];\n\n // Create i18n task processor\n const i18nProcessor: TaskProcessor<\n string,\n {\n dag: Dag;\n files: string[];\n filesStateFilePath: string;\n }\n > = {\n preProcess: async (files, context) => {\n const { dag, filesStateFilePath } = context;\n logger.debugMessage(`Files: ${files.join(', ')}`);\n // Mark tasks as in progress\n await Promise.all(\n files.map((file) => markFileAsInProgress(file, filesStateFilePath))\n );\n\n // Construct prompt\n const dependencies = Object.fromEntries(\n files.map((file) => [\n file,\n Array.from(new Set(dag.getDependencies(file))).map(String),\n ])\n );\n const dependents = Object.fromEntries(\n files.map((file) => [\n file,\n Array.from(new Set(dag.getDependents(file))).map(String),\n ])\n );\n\n return getPrompt({\n targetFile: files,\n dependencyFiles: dependencies,\n dependentFiles: dependents,\n });\n },\n postProcess: async (files, context, agentReport) => {\n const { filesStateFilePath } = context;\n\n // Mark tasks as complete\n await Promise.all(\n files.map((task) => markFileAsEdited(task, filesStateFilePath))\n );\n\n // Add agent report\n reports.push(agentReport);\n\n // Update progress bar\n logger.progressBar.advance(\n files.length,\n `Processed ${Number(((reports.length * files.length) / files.length) * 100).toFixed(2)}% of files`\n );\n\n // Update stats\n manager.stats.updateStats({\n newProcessedFiles: files.length,\n });\n },\n };\n\n // Run parallel processing\n await runParallelProcessing(\n Array.from(taskQueue),\n i18nProcessor,\n { dag, files, filesStateFilePath },\n {\n concurrency,\n batchSize,\n },\n 1\n );\n\n if (manager.isAborted()) {\n return;\n }\n\n logger.progressBar.stop(\n `Processed ${files.length} files [${Math.round(\n (Date.now() - fileProcessingStartTime) / 1000\n )}s]`\n );\n\n // TODO: uncomment\n // // Always clean up the file list when done, regardless of success or failure\n // cleanUp(stateFilePath);\n\n // Create a clean agent for cleanup\n const cleanupAgent = manager.createSingleAgent('claude_cleanup_agent', {});\n\n logger.initializeSpinner();\n logger.spinner.start('Fixing errors...');\n const fixPrompt = getFixPrompt(manager.appDirectory);\n try {\n await cleanupAgent.run(\n fixPrompt,\n {\n maxTurns: 200,\n timeoutSec: 300,\n maxRetries: 1,\n },\n {}\n );\n reports.push(`## Fixed errors\\n${cleanupAgent.generateReport()}`);\n } catch (error) {\n logger.debugMessage(\n `[claude_cleanup_agent] Fixing errors failed: ${error}`\n );\n manager.stats.recordTelemetry(false);\n outro(chalk.red('❌ Locadex i18n failed!'));\n await exit(1);\n return;\n }\n logger.spinner.stop('Fixed errors');\n\n // Generate report\n const reportSummary = `# Summary of locadex i18n changes\n${reports.join('\\n')}`;\n const summaryFilePath = path.join(\n manager.getLogDirectory(),\n 'locadex-report.md'\n );\n appendFileSync(summaryFilePath, reportSummary);\n logger.step(`Saved summary of changes to: ${summaryFilePath}`);\n\n // cleanup\n const formatter = await detectFormatter();\n if (formatter) {\n await formatFiles(files, formatter);\n }\n\n const lockfilePath = manager.getLockFilePath();\n\n // Update lockfile with processed files\n updateLockfile(files, lockfilePath, manager.rootDirectory);\n\n // Clean up stale entries from lockfile\n cleanupLockfile(lockfilePath, manager.rootDirectory);\n\n logger.message(chalk.dim(`Updated lockfile with ${files.length} files`));\n\n deleteAddedFiles([\n path.relative(manager.rootDirectory, manager.locadexDirectory),\n ]);\n\n logger.info(\n chalk.dim(\n `Total Cost: $${manager.stats.getStats().totalCost.toFixed(2)}\nTotal wall time: ${Math.round(\n (Date.now() - manager.stats.getStats().startTime) / 1000\n )}s\nTotal files processed: ${manager.stats.getStats().processedFiles}`\n )\n );\n\n const finalStats = manager.stats.getStats();\n\n // Record telemetry for final stats\n manager.stats.recordTelemetry(true);\n\n logger.verboseMessage(\n `Total input tokens: ${finalStats.inputTokens}\nTotal cached input tokens: ${finalStats.cachedInputTokens}\nTotal output tokens: ${finalStats.outputTokens}\nTotal turns: ${finalStats.turns}`\n );\n\n outro(chalk.green('✅ Locadex i18n complete!'));\n await exit(0);\n}\n\nfunction getPrompt({\n targetFile,\n dependencyFiles,\n dependentFiles,\n}: {\n targetFile: string[];\n dependencyFiles: Record<string, string[]>;\n dependentFiles: Record<string, string[]>;\n}) {\n const prompt = `# Task: Internationalize the target file(s) using gt-next.\n\n## INSTRUCTIONS\n\n- You are given a list of target files and their corresponding dependency/dependent files.\n- The project is already setup for internationalization. Do not try to setup the project again for i18n.\n\n## Workflow:\n1. **Gather context** Read the target files closely (you should not have to read the dependency/dependent files).\n2. **Evaluate if i18n is necessary** Evaluate if the target files need to be internationalized using gt-next \n - If the target files have no relevant content, are already internationalized, or contain build-time code (e.g. nextjs plugins) they should never be internationalized.\n**IMPORTANT**: IF NONE OF THE TARGET FILES NEED TO BE INTERNATIONALIZED, YOUR TASK IS COMPLETE AND YOU MAY RETURN.\n3. **Identify the tools to use** Given the contents of the files, ask yourself which tools and guides you need to use to get the necessary knowledge to internationalize the target files. Here are some helpful questions to evaluate for tool selection:\n - 3.a. Does this file contain a component? If so, is it a server-side component or a client-side component?\n - 3.b. Is the content that needs to be i18ned being used in this same file, or is it being used in another file?\n - 3.c. Is there any string interpolation that needs to be i18ned?\n - 3.d. Is there any conditional logic or rendering that needs to be i18ned?\n - 3.e. Is the content that needs to be i18ned HTML/JSX or a string?\n4. **Internationalize** You now have the necessary knowledge. Internationalize the files using the information from the tools provided to you.\n - 4.a. Do not worry about running tsc. We will do that later.\n\n## RULES:\n- ALWAYS use the <T> component to internationalize HTML/JSX content.\n- ALWAYS use getGT() or useGT() and getDict() or useDict() to internationalize string content (strings created with '', \"\", or \\`\\`).\n - When possible, avoid using getDict() or useDict(); getGT() and useGT() are preferred.\n- DO NOT internationalize non-user facing content or content that is functional, such as ids, class names, error strings, logical strings, etc.\n- Do not add i18n middleware to the app.\n- When adding 'useGT()' or 'useDict()' to a client component, you must add 'use client' to the top of the file.\n- Always adhere to the guides provided via the 'mcp__locadex__' tools.\n - These guides provide additional knowledge about how to internationalize the content.\n- Minimize the footprint of your changes.\n- Focus on internationalizing the content of the target files.\n- NEVER move internationalized content to a different file. All content MUST remain in the same file where it came from.\n- NEVER CREATE OR DELETE ANY FILES (especially .bak files)\n- Internationalize all user facing content in the target files. \n- NEVER EDIT FILES THAT ARE NOT GIVEN TO YOU.\n\n## TARGET FILE INFORMATION\n${targetFile.map(\n (file, index) => `\nTARGET FILE ${index + 1}:\n${file}\n\nDEPENDENCY FILES (files imported by target file ${index + 1}):\n${dependencyFiles[file].length > 0 ? ` ${dependencyFiles[file].join(', ')}` : 'none'}\n\nDEPENDENT FILES (files that import target file ${index + 1}):\n${dependentFiles[file].length > 0 ? ` ${dependentFiles[file].join(', ')}` : 'none'}\n`\n)}\n\n---\n\n## MCP TOOLS\n\n${allMcpPrompt}\n\n## Final output\n- When you are done, please return a brief summary of the files you modified, following this format.\n- **DO NOT** include any other text in your response. \n- If there were issues with some files, please include the issues in the list of changes for that file.\n\n[file 1 path]\n- List of changes to file 1\n`;\n\n return prompt;\n}\n\n// check (dry run and ts check) should be at the end\n\nfunction getFixPrompt(appDirectory: string) {\n const prompt = `# Task: Fix internationalization errors in the project.\n\n## INSTRUCTIONS\n\nPreviously, you helped me internationalize a set of files in this project.\nYour new task is as follows:\n\n1. Run the gt-next validator.\n2. Fix all errors output by the gt-next validator.\n3. Whenever you are finished with your changes, run the gt-next validator.\n4. Repeat steps 1-3 until there are no more errors, or until you believe that you have fixed all errors.\n\n## RULES:\n- ONLY modify files that are relevant to the internationalization of the project.\n- ONLY fix errors that result from your current or previous implementation.\n- Resolve unused imports from 'gt-next'. \n - In particular, if a file contains user-facing content that should be internationalized and is not, you should internationalize it.\n- Resolve missing imports from 'gt-next'. If a file is missing an import from 'gt-next', add it.\n\nTo run the gt-next validator, run the following command from the app root:\n'npx locadex translate --dry-run'\nThe app root is: \"${appDirectory}\"\n\n## MCP TOOLS\n\n${allMcpPrompt}\n\n## Final output\n- When you are done, please return a brief summary of the files you modified, following this format.\n- **DO NOT** include any other text in your response. \n- If there were issues with some files, please include the issues in the list of changes for that file.\n\n[file 1 path]\n- List of changes to file 1\n`;\n\n return prompt;\n}\n"]}
1
+ {"version":3,"file":"i18n.js","sourceRoot":"/","sources":["tasks/i18n.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACtD,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,IAAI,EAAE,MAAM,sBAAsB,CAAC;AAC5C,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EACL,iBAAiB,EACjB,gBAAgB,EAChB,oBAAoB,GACrB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAE,qBAAqB,EAAiB,MAAM,kBAAkB,CAAC;AACxE,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvE,OAAO,EAAE,YAAY,EAAE,MAAM,8BAA8B,CAAC;AAE5D,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAA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mC;IACnC,OAAO,CAAC,KAAK,CAAC,eAAe,CAAC,IAAI,CAAC,CAAC;IAEpC,MAAM,CAAC,cAAc,CACnB,uBAAuB,UAAU,CAAC,WAAW;6BACpB,UAAU,CAAC,iBAAiB;uBAClC,UAAU,CAAC,YAAY;eAC/B,UAAU,CAAC,KAAK,EAAE,CAC9B,CAAC;IAEF,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,0BAA0B,CAAC,CAAC,CAAC;IAC/C,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC;AAChB,CAAC;AAED,SAAS,SAAS,CAAC,EACjB,UAAU,EACV,eAAe,EACf,cAAc,GAKf;IACC,MAAM,MAAM,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAmCf,UAAU,CAAC,GAAG,CACd,CAAC,IAAI,EAAE,KAAK,EAAE,EAAE,CAAC;cACL,KAAK,GAAG,CAAC;EACrB,IAAI;;kDAE4C,KAAK,GAAG,CAAC;EACzD,eAAe,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,eAAe,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM;;iDAEnC,KAAK,GAAG,CAAC;EACxD,cAAc,CAAC,IAAI,CAAC,CAAC,MAAM,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,cAAc,CAAC,IAAI,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,CAAC,MAAM;CACjF,CACA;;;;;;EAMC,YAAY;;;;;;;;;CASb,CAAC;IAEA,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { createSpinner } from '../logging/console.js';\nimport { allMcpPrompt } from '../prompts/system.js';\nimport { exit } from '../utils/shutdown.js';\nimport { logger } from '../logging/logger.js';\nimport { LocadexManager } from '../utils/locadexManager.js';\nimport {\n addFilesToManager,\n markFileAsEdited,\n markFileAsInProgress,\n} from '../utils/dag/getFiles.js';\nimport { runParallelProcessing, TaskProcessor } from './concurrency.js';\nimport { outro } from '@clack/prompts';\nimport chalk from 'chalk';\nimport { appendFileSync } from 'node:fs';\nimport { detectFormatter, formatFiles } from 'gtx-cli/hooks/postProcess';\nimport path from 'node:path';\nimport { updateLockfile, cleanupLockfile } from '../utils/lockfile.js';\nimport { extractFiles } from '../utils/dag/extractFiles.js';\nimport { Dag } from '../utils/dag/createDag.js';\nimport { getPackageJson, isPackageInstalled } from 'gtx-cli/utils/packageJson';\nimport { deleteAddedFiles } from '../utils/fs/git.js';\nimport { CLAUDE_CODE_VERSION } from '../utils/shared.js';\nimport { installGlobalPackage } from '../utils/packages/installPackage.js';\nimport { fixErrorsTask } from './fixErrors.js';\nimport { getLocadexVersion } from 'src/utils/getPaths.js';\n\nexport async function i18nTask() {\n const manager = LocadexManager.getInstance();\n // have to use the package.json from the appDir\n const packageJson = await getPackageJson(manager.appDirectory);\n const isUsingGTNext = packageJson\n ? isPackageInstalled('gt-next', packageJson)\n : false;\n if (!isUsingGTNext) {\n logger.error(\n `gt-next not detected in ${manager.appDirectory}. Please specify the correct app directory with the --app-dir flag, or ensure that gt-next is correctly installed in the project.`\n );\n await exit(1);\n }\n\n // Install claude-code if not installed\n await installGlobalPackage('@anthropic-ai/claude-code', CLAUDE_CODE_VERSION);\n // Install locadex if not installed\n await installGlobalPackage('locadex', getLocadexVersion());\n\n logger.debugMessage('App directory: ' + manager.appDirectory);\n logger.debugMessage('Root directory: ' + manager.rootDirectory);\n\n // Init message\n const spinner = createSpinner();\n spinner.start('Initializing Locadex...');\n\n const { files, dag } = extractFiles(manager);\n\n if (files.length === 0) {\n spinner.stop('No files have changed since last run');\n outro(chalk.green('✅ Locadex i18n complete - no changes detected!'));\n await exit(0);\n }\n\n const filesStateFilePath = manager.getFilesStateFilePath();\n const concurrency = manager.getMaxConcurrency();\n const batchSize = manager.getBatchSize();\n\n // Create the list of files (aka tasks) to process\n const taskQueue = Array.from(files);\n\n // Add files to manager\n const stateFilePath = addFilesToManager(filesStateFilePath, taskQueue);\n spinner.stop('Locadex initialized');\n\n logger.verboseMessage(`Processing ${files.length} modified files`);\n logger.debugMessage(`Track progress here: ${stateFilePath}`);\n logger.debugMessage(`Order:\\n${taskQueue.join('\\n')}`);\n\n logger.message(`Using ${concurrency} concurrent agents`);\n logger.initializeProgressBar(taskQueue.length);\n\n const fileProcessingStartTime = Date.now();\n logger.progressBar.start(`Processing ${taskQueue.length} files...`);\n\n // Shared reports array for collecting results\n const reports: string[] = [];\n\n // Create i18n task processor\n const i18nProcessor: TaskProcessor<\n string,\n {\n dag: Dag;\n files: string[];\n filesStateFilePath: string;\n }\n > = {\n preProcess: async (files, context) => {\n const { dag, filesStateFilePath } = context;\n logger.debugMessage(`Files: ${files.join(', ')}`);\n // Mark tasks as in progress\n await Promise.all(\n files.map((file) => markFileAsInProgress(file, filesStateFilePath))\n );\n\n // Construct prompt\n const dependencies = Object.fromEntries(\n files.map((file) => [\n file,\n Array.from(new Set(dag.getDependencies(file))).map(String),\n ])\n );\n const dependents = Object.fromEntries(\n files.map((file) => [\n file,\n Array.from(new Set(dag.getDependents(file))).map(String),\n ])\n );\n\n return getPrompt({\n targetFile: files,\n dependencyFiles: dependencies,\n dependentFiles: dependents,\n });\n },\n postProcess: async (processedFiles, context, agentReport) => {\n const { filesStateFilePath } = context;\n\n // Mark tasks as complete\n await Promise.all(\n processedFiles.map((file) => markFileAsEdited(file, filesStateFilePath))\n );\n\n // Add agent report\n reports.push(agentReport);\n\n // Update stats\n manager.stats.updateStats({\n newProcessedFiles: processedFiles.length,\n });\n\n // Update progress bar\n logger.progressBar.advance(\n processedFiles.length,\n `Processed ${Number((manager.stats.getStats().processedFiles / files.length) * 100).toFixed(2)}% of files`\n );\n },\n };\n\n // Run parallel processing\n await runParallelProcessing(\n Array.from(taskQueue),\n i18nProcessor,\n { dag, files, filesStateFilePath },\n {\n concurrency,\n batchSize,\n },\n 1\n );\n\n if (manager.isAborted()) {\n return;\n }\n\n logger.progressBar.stop(\n `Processed ${files.length} files [${Math.round(\n (Date.now() - fileProcessingStartTime) / 1000\n )}s]`\n );\n\n const cleanupReports = await fixErrorsTask();\n if (cleanupReports) {\n reports.push(...cleanupReports);\n }\n\n // Generate report\n const reportSummary = `# Summary of locadex i18n changes\n${reports.join('\\n')}`;\n const summaryFilePath = path.join(\n manager.getLogDirectory(),\n 'locadex-report.md'\n );\n appendFileSync(summaryFilePath, reportSummary);\n logger.step(`Saved summary of changes to: ${summaryFilePath}`);\n\n // cleanup\n const formatter = await detectFormatter();\n if (formatter) {\n await formatFiles(files, formatter);\n }\n\n const lockfilePath = manager.getLockFilePath();\n\n // Update lockfile with processed files\n updateLockfile(files, lockfilePath, manager.rootDirectory);\n\n // Clean up stale entries from lockfile\n cleanupLockfile(lockfilePath, manager.rootDirectory);\n\n logger.message(chalk.dim(`Updated lockfile with ${files.length} files`));\n\n deleteAddedFiles([\n path.relative(manager.rootDirectory, manager.locadexDirectory),\n ]);\n\n logger.info(\n chalk.dim(\n `Total Cost: $${manager.stats.getStats().totalCost.toFixed(2)}\nTotal wall time: ${Math.round(\n (Date.now() - manager.stats.getStats().startTime) / 1000\n )}s\nTotal files processed: ${manager.stats.getStats().processedFiles}`\n )\n );\n\n const finalStats = manager.stats.getStats();\n\n // Record telemetry for final stats\n manager.stats.recordTelemetry(true);\n\n logger.verboseMessage(\n `Total input tokens: ${finalStats.inputTokens}\nTotal cached input tokens: ${finalStats.cachedInputTokens}\nTotal output tokens: ${finalStats.outputTokens}\nTotal turns: ${finalStats.turns}`\n );\n\n outro(chalk.green('✅ Locadex i18n complete!'));\n await exit(0);\n}\n\nfunction getPrompt({\n targetFile,\n dependencyFiles,\n dependentFiles,\n}: {\n targetFile: string[];\n dependencyFiles: Record<string, string[]>;\n dependentFiles: Record<string, string[]>;\n}) {\n const prompt = `# Task: Internationalize the target file(s) using gt-next.\n\n## INSTRUCTIONS\n\n- You are given a list of target files and their corresponding dependency/dependent files.\n- The project is already setup for internationalization. Do not try to setup the project again for i18n.\n\n## Workflow:\n1. **Gather context** Read the target files closely (you should not have to read the dependency/dependent files).\n2. **Evaluate if i18n is necessary** Evaluate if the target files need to be internationalized using gt-next \n - If the target files have no relevant content, are already internationalized, or contain build-time code (e.g. nextjs plugins) they should never be internationalized.\n**IMPORTANT**: IF NONE OF THE TARGET FILES NEED TO BE INTERNATIONALIZED, YOUR TASK IS COMPLETE AND YOU MAY RETURN.\n3. **Identify the tools to use** Given the contents of the files, ask yourself which tools and guides you need to use to get the necessary knowledge to internationalize the target files. Here are some helpful questions to evaluate for tool selection:\n - 3.a. Is the content that needs to be i18ned being used in this same file, or is it being used in another file?\n - 3.b. Is there any string interpolation that needs to be i18ned?\n - 3.c. Is there any conditional logic or rendering that needs to be i18ned?\n - 3.d. Is the content that needs to be i18ned HTML/JSX or a string?\n4. **Internationalize** You now have the necessary knowledge. Internationalize the files using the information from the tools provided to you.\n - 4.a. Do not run validation checks such as tsc. We will do that later.\n\n## RULES:\n- ALWAYS use the <T> component to internationalize HTML/JSX content.\n- ALWAYS use useGT() or useTranslations() to internationalize string content (strings created with '', \"\", or \\`\\`).\n - When possible, avoid using useTranslations(); useGT() is always preferred.\n- DO NOT internationalize non-user facing content or content that is functional, such as ids, class names, error strings, logical strings, etc.\n- Do not add i18n middleware to the app.\n- ALWAYS adhere to the guides provided via the 'mcp__locadex__' tools.\n - These guides provide additional knowledge about how to internationalize the content.\n- Minimize the footprint of your changes.\n- Focus on internationalizing all user facing content in the target files. \n- NEVER move content to a different file. All content MUST remain in the same file where it came from.\n- NEVER CREATE OR DELETE ANY FILES (especially .bak files)\n- NEVER EDIT FILES THAT ARE NOT GIVEN TO YOU.\n\n## TARGET FILE INFORMATION\n${targetFile.map(\n (file, index) => `\nTARGET FILE ${index + 1}:\n${file}\n\nDEPENDENCY FILES (files imported by target file ${index + 1}):\n${dependencyFiles[file].length > 0 ? ` ${dependencyFiles[file].join(', ')}` : 'none'}\n\nDEPENDENT FILES (files that import target file ${index + 1}):\n${dependentFiles[file].length > 0 ? ` ${dependentFiles[file].join(', ')}` : 'none'}\n`\n)}\n\n---\n\n## MCP TOOLS\n\n${allMcpPrompt}\n\n## Final output\n- When you are done, please return a brief summary of the files you modified, following this format.\n- **DO NOT** include any other text in your response. \n- If there were issues with some files, please include the issues in the list of changes for that file.\n\n[file 1 path]\n- List of changes to file 1\n`;\n\n return prompt;\n}\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"setup.d.ts","sourceRoot":"/","sources":["tasks/setup.ts"],"names":[],"mappings":"AA4BA,wBAAsB,SAAS,CAC7B,aAAa,EAAE,OAAO,EACtB,uBAAuB,CAAC,EAAE,MAAM,iBA4HjC"}
1
+ {"version":3,"file":"setup.d.ts","sourceRoot":"/","sources":["tasks/setup.ts"],"names":[],"mappings":"AAyBA,wBAAsB,SAAS,CAC7B,aAAa,EAAE,OAAO,EACtB,uBAAuB,CAAC,EAAE,MAAM,iBAyHjC"}
@@ -1,5 +1,5 @@
1
1
  import { createSpinner, promptConfirm } from '../logging/console.js';
2
- import { getPackageJson, isPackageInstalled, } from 'gtx-cli/utils/packageJson';
2
+ import { getPackageJson, isPackageInstalled } from 'gtx-cli/utils/packageJson';
3
3
  import { getPackageManager } from 'gtx-cli/utils/packageManager';
4
4
  import { installPackage } from 'gtx-cli/utils/installPackage';
5
5
  import chalk from 'chalk';
@@ -13,10 +13,12 @@ import { i18nTask } from '../tasks/i18n.js';
13
13
  import { getNextDirectories } from '../utils/fs/getFiles.js';
14
14
  import { LocadexManager } from '../utils/locadexManager.js';
15
15
  import { outro } from '@clack/prompts';
16
- import { appendFileSync } from 'node:fs';
16
+ import { appendFileSync, existsSync, writeFileSync } from 'node:fs';
17
17
  import path from 'node:path';
18
18
  import { exit } from '../utils/shutdown.js';
19
- import { addTranslateScript, installClaudeCode, installLocadex, } from '../utils/packages/installPackage.js';
19
+ import { addTranslateScript, installGlobalPackage, } from '../utils/packages/installPackage.js';
20
+ import { CLAUDE_CODE_VERSION } from '../utils/shared.js';
21
+ import { getLocadexVersion } from '../utils/getPaths.js';
20
22
  export async function setupTask(bypassPrompts, specifiedPackageManager) {
21
23
  if (!bypassPrompts) {
22
24
  await promptConfirm({
@@ -79,15 +81,13 @@ export async function setupTask(bypassPrompts, specifiedPackageManager) {
79
81
  await addTranslateScript(manager, appPackageJson, packageManager);
80
82
  }
81
83
  // Install claude-code if not installed
82
- await installClaudeCode();
84
+ await installGlobalPackage('@anthropic-ai/claude-code', CLAUDE_CODE_VERSION);
83
85
  // Install locadex if not installed
84
- const rootPackageJson = await getPackageJson(manager.rootDirectory);
85
- if (rootPackageJson &&
86
- !isPackageInstalled('locadex', rootPackageJson, true, true)) {
87
- await installLocadex(manager);
88
- }
86
+ await installGlobalPackage('locadex', getLocadexVersion());
89
87
  // Set up locale selector
90
88
  await setupLocaleSelector();
89
+ // Create dictionary.json file if not exists
90
+ setupDictionary(manager);
91
91
  const formatter = await detectFormatter();
92
92
  if (formatter && filesUpdated.length > 0) {
93
93
  await formatFiles(filesUpdated, formatter);
@@ -95,6 +95,16 @@ export async function setupTask(bypassPrompts, specifiedPackageManager) {
95
95
  // Run i18n command
96
96
  await i18nTask();
97
97
  }
98
+ function setupDictionary(manager) {
99
+ const usingSrcDirectory = existsSync(path.join(manager.appDirectory, 'src'));
100
+ const dictionaryPath = usingSrcDirectory
101
+ ? path.join(manager.appDirectory, 'src', 'dictionary.json')
102
+ : path.join(manager.appDirectory, 'dictionary.json');
103
+ if (!existsSync(dictionaryPath)) {
104
+ writeFileSync(dictionaryPath, '{}');
105
+ logger.step(`Created ${chalk.cyan('dictionary.json')} file at ${chalk.cyan(dictionaryPath)}.`);
106
+ }
107
+ }
98
108
  async function setupLocaleSelector() {
99
109
  logger.initializeSpinner();
100
110
  logger.spinner.start('Creating locale selector...');
@@ -117,6 +127,7 @@ ${report}`;
117
127
  appendFileSync(summaryFilePath, reportSummary);
118
128
  }
119
129
  catch (error) {
130
+ agent.aggregateStats();
120
131
  // Check if this is an abort
121
132
  if (manager.getAgentAbortController().signal.aborted) {
122
133
  return;
@@ -125,6 +136,7 @@ ${report}`;
125
136
  outro(chalk.red('❌ Locadex setup failed!'));
126
137
  await exit(1);
127
138
  }
139
+ agent.aggregateStats();
128
140
  logger.spinner.stop('Locale selector setup complete');
129
141
  }
130
142
  function getLocaleSelectorPrompt(appDirectory) {
@@ -1 +1 @@
1
- {"version":3,"file":"setup.js","sourceRoot":"/","sources":["tasks/setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EACL,cAAc,EACd,kBAAkB,GAEnB,MAAM,2BAA2B,CAAC;AACnC,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAAE,MAAM,gCAAgC,CAAC;AACjE,OAAO,EAAE,YAAY,EAAE,MAAM,iCAAiC,CAAC;AAC/D,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,MAAM,2BAA2B,CAAC;AACzE,OAAO,EAAE,oBAAoB,EAAE,MAAM,+BAA+B,CAAC;AACrE,OAAO,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAC5C,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAC5D,OAAO,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACvC,OAAO,EAAE,cAAc,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,IAAI,EAAE,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YACf,UAAU,EAAE,CAAC;SACd,EACD,EAAE,CACH,CAAC;QAEF,kBAAkB;QAClB,MAAM,MAAM,GAAG,KAAK,CAAC,cAAc,EAAE,CAAC;QACtC,MAAM,aAAa,GAAG;EACxB,MAAM,EAAE,CAAC;QACP,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAC/B,OAAO,CAAC,eAAe,EAAE,EACzB,mBAAmB,CACpB,CAAC;QACF,cAAc,CAAC,eAAe,EAAE,aAAa,CAAC,CAAC;IACjD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,4BAA4B;QAC5B,IAAI,OAAO,CAAC,uBAAuB,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACrD,OAAO;QACT,CAAC;QACD,MAAM,CAAC,YAAY,CAAC,0CAA0C,KAAK,EAAE,CAAC,CAAC;QACvE,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC;QAC5C,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC;IAChB,CAAC;IAED,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;AACxD,CAAC;AAED,SAAS,uBAAuB,CAAC,YAAoB;IACnD,MAAM,MAAM,GAAG;;;;sBAIK,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BjC,CAAC;IACA,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { createSpinner, promptConfirm } from '../logging/console.js';\nimport {\n getPackageJson,\n isPackageInstalled,\n updatePackageJson,\n} from 'gtx-cli/utils/packageJson';\nimport { getPackageManager } from 'gtx-cli/utils/packageManager';\nimport { installPackage } from 'gtx-cli/utils/installPackage';\nimport chalk from 'chalk';\nimport { logger } from '../logging/logger.js';\nimport { findFilepaths } from '../utils/fs/findConfigs.js';\nimport { wrapContentNext } from 'gtx-cli/next/parse/wrapContent';\nimport { handleInitGT } from 'gtx-cli/next/parse/handleInitGT';\nimport { detectFormatter, formatFiles } from 'gtx-cli/hooks/postProcess';\nimport { createOrUpdateConfig } from 'gtx-cli/fs/config/setupConfig';\nimport { i18nTask } from '../tasks/i18n.js';\nimport { getNextDirectories } from '../utils/fs/getFiles.js';\nimport { LocadexManager } from '../utils/locadexManager.js';\nimport { outro } from '@clack/prompts';\nimport { appendFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { exit } from '../utils/shutdown.js';\nimport {\n addTranslateScript,\n installClaudeCode,\n installLocadex,\n} from '../utils/packages/installPackage.js';\n\nexport async function setupTask(\n bypassPrompts: boolean,\n specifiedPackageManager?: string\n) {\n if (!bypassPrompts) {\n await promptConfirm({\n message: chalk.yellow(\n `Locadex will modify files! Make sure you have committed or stashed any changes. Do you want to continue?`\n ),\n defaultValue: true,\n cancelMessage: 'Operation cancelled.',\n });\n }\n\n const manager = LocadexManager.getInstance();\n\n const packageManager = await getPackageManager(\n manager.rootDirectory,\n specifiedPackageManager\n );\n let appPackageJson = await getPackageJson(manager.appDirectory);\n\n if (appPackageJson) {\n if (!isPackageInstalled('gt-next', appPackageJson)) {\n const spinner = createSpinner('timer');\n spinner.start(`Installing gt-next with ${packageManager.name}...`);\n await installPackage(\n 'gt-next',\n packageManager,\n false,\n manager.appDirectory\n );\n spinner.stop('Automatically installed gt-next.');\n }\n }\n\n const nextConfigPath = findFilepaths(\n [\n './next.config.js',\n './next.config.ts',\n './next.config.mjs',\n './next.config.mts',\n ],\n manager.appDirectory\n )[0];\n\n if (!nextConfigPath) {\n logger.error('No next.config.[js|ts|mjs|mts] file found.');\n await exit(1);\n }\n\n const errors: string[] = [];\n const warnings: string[] = [];\n let filesUpdated: string[] = [];\n\n const babel = createSpinner();\n\n babel.start('Wrapping <GTProvider> tags...');\n\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated: filesUpdatedNext } = await wrapContentNext(\n {\n src: getNextDirectories(manager.appDirectory),\n config: nextConfigPath,\n disableIds: true,\n disableFormatting: true,\n skipTs: true,\n addGTProvider: true,\n },\n 'gt-next',\n errors,\n warnings\n );\n filesUpdated = [...filesUpdated, ...filesUpdatedNext];\n\n babel.stop(`Modified ${filesUpdated.length} files.`);\n\n // Add the withGTConfig() function to the next.config.js file\n await handleInitGT(nextConfigPath, errors, warnings, filesUpdated);\n logger.step(`Added withGTConfig() to your ${nextConfigPath} file.`);\n\n // Create gt.config.json\n await createOrUpdateConfig(\n path.resolve(manager.appDirectory, 'gt.config.json'),\n {\n defaultLocale: 'en',\n locales: ['es', 'fr', 'de', 'ja', 'zh'],\n framework: 'next-app',\n }\n );\n\n logger.success(\n `Feel free to edit ${chalk.cyan(\n 'gt.config.json'\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n // Add translate to scripts\n // Re-get the package.json to make sure it's updated\n appPackageJson = await getPackageJson(manager.appDirectory);\n if (appPackageJson) {\n await addTranslateScript(manager, appPackageJson, packageManager);\n }\n\n // Install claude-code if not installed\n await installClaudeCode();\n\n // Install locadex if not installed\n const rootPackageJson = await getPackageJson(manager.rootDirectory);\n if (\n rootPackageJson &&\n !isPackageInstalled('locadex', rootPackageJson, true, true)\n ) {\n await installLocadex(manager);\n }\n\n // Set up locale selector\n await setupLocaleSelector();\n\n const formatter = await detectFormatter();\n if (formatter && filesUpdated.length > 0) {\n await formatFiles(filesUpdated, formatter);\n }\n\n // Run i18n command\n await i18nTask();\n}\n\nasync function setupLocaleSelector() {\n logger.initializeSpinner();\n logger.spinner.start('Creating locale selector...');\n\n // Create agent\n const manager = LocadexManager.getInstance();\n\n const agent = manager.createSingleAgent('claude_setup_agent', {});\n\n // Fix prompt\n const localeSelectorPrompt = getLocaleSelectorPrompt(manager.appDirectory);\n try {\n await agent.run(\n localeSelectorPrompt,\n {\n maxTurns: 50,\n timeoutSec: 120,\n maxRetries: 1,\n },\n {}\n );\n\n // Generate report\n const report = agent.generateReport();\n const reportSummary = `# Summary of locadex setup changes\n${report}`;\n const summaryFilePath = path.join(\n manager.getLogDirectory(),\n 'locadex-report.md'\n );\n appendFileSync(summaryFilePath, reportSummary);\n } catch (error) {\n // Check if this is an abort\n if (manager.getAgentAbortController().signal.aborted) {\n return;\n }\n logger.debugMessage(`[setup] Adding locale selector failed: ${error}`);\n outro(chalk.red('❌ Locadex setup failed!'));\n await exit(1);\n }\n\n logger.spinner.stop('Locale selector setup complete');\n}\n\nfunction getLocaleSelectorPrompt(appDirectory: string) {\n const prompt = `# Task: Add a locale selector to the app\n\n## Instructions\n- The locale selector should be a dropdown that allows the user to select the locale.\n- The app root is: \"${appDirectory}\"\n\n## LOCALE SELECTOR USAGE\n(1) Import the locale selector component from 'gt-next/client'\n(2) Add the locale selector to the app\n\nFor example:\nimport { LocaleSelector } from 'gt-next/client';\n\nfunction MyComponent() {\n return (\n <div>\n <LocaleSelector />\n <p>Hello, world!</p>\n </div>\n );\n}\n\n## RULES\n- The locale selector should be added to a header or footer or some other very obvious place in the app.\n- Scan across files to find the best place to add the locale selector.\n- **DO NOT** create new files. You may only modify existing files.\n- You do not need to mark the component containing the LocaleSelector with 'use client'. The LocaleSelector component is already internally marked with 'use client'.\n\n## Final output\n- When you are done, please return a **brief summary** of the files you modified.\n- **DO NOT** include any other text in your response.\n`;\n return prompt;\n}\n"]}
1
+ {"version":3,"file":"setup.js","sourceRoot":"/","sources":["tasks/setup.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,uBAAuB,CAAC;AACrE,OAAO,EAAE,cAAc,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAC/E,OAAO,EAAE,iBAAiB,EAAE,MAAM,8BAA8B,CAAC;AACjE,OAAO,EAAE,cAAc,EAAE,MAAM,8BAA8B,CAAC;AAC9D,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAC9C,OAAO,EAAE,aAAa,EAAE,MAAM,4BAA4B,CAAC;AAC3D,OAAO,EAAE,eAAe,EAA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kB;QAClB,MAAM,MAAM,GAAG,KAAK,CAAC,cAAc,EAAE,CAAC;QACtC,MAAM,aAAa,GAAG;EACxB,MAAM,EAAE,CAAC;QACP,MAAM,eAAe,GAAG,IAAI,CAAC,IAAI,CAC/B,OAAO,CAAC,eAAe,EAAE,EACzB,mBAAmB,CACpB,CAAC;QACF,cAAc,CAAC,eAAe,EAAE,aAAa,CAAC,CAAC;IACjD,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,KAAK,CAAC,cAAc,EAAE,CAAC;QACvB,4BAA4B;QAC5B,IAAI,OAAO,CAAC,uBAAuB,EAAE,CAAC,MAAM,CAAC,OAAO,EAAE,CAAC;YACrD,OAAO;QACT,CAAC;QACD,MAAM,CAAC,YAAY,CAAC,0CAA0C,KAAK,EAAE,CAAC,CAAC;QACvE,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,yBAAyB,CAAC,CAAC,CAAC;QAC5C,MAAM,IAAI,CAAC,CAAC,CAAC,CAAC;IAChB,CAAC;IACD,KAAK,CAAC,cAAc,EAAE,CAAC;IAEvB,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,gCAAgC,CAAC,CAAC;AACxD,CAAC;AAED,SAAS,uBAAuB,CAAC,YAAoB;IACnD,MAAM,MAAM,GAAG;;;;sBAIK,YAAY;;;;;;;;;;;;;;;;;;;;;;;;;;;CA2BjC,CAAC;IACA,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import { createSpinner, promptConfirm } from '../logging/console.js';\nimport { getPackageJson, isPackageInstalled } from 'gtx-cli/utils/packageJson';\nimport { getPackageManager } from 'gtx-cli/utils/packageManager';\nimport { installPackage } from 'gtx-cli/utils/installPackage';\nimport chalk from 'chalk';\nimport { logger } from '../logging/logger.js';\nimport { findFilepaths } from '../utils/fs/findConfigs.js';\nimport { wrapContentNext } from 'gtx-cli/next/parse/wrapContent';\nimport { handleInitGT } from 'gtx-cli/next/parse/handleInitGT';\nimport { detectFormatter, formatFiles } from 'gtx-cli/hooks/postProcess';\nimport { createOrUpdateConfig } from 'gtx-cli/fs/config/setupConfig';\nimport { i18nTask } from '../tasks/i18n.js';\nimport { getNextDirectories } from '../utils/fs/getFiles.js';\nimport { LocadexManager } from '../utils/locadexManager.js';\nimport { outro } from '@clack/prompts';\nimport { appendFileSync, existsSync, writeFileSync } from 'node:fs';\nimport path from 'node:path';\nimport { exit } from '../utils/shutdown.js';\nimport {\n addTranslateScript,\n installGlobalPackage,\n} from '../utils/packages/installPackage.js';\nimport { CLAUDE_CODE_VERSION } from '../utils/shared.js';\nimport { getLocadexVersion } from '../utils/getPaths.js';\n\nexport async function setupTask(\n bypassPrompts: boolean,\n specifiedPackageManager?: string\n) {\n if (!bypassPrompts) {\n await promptConfirm({\n message: chalk.yellow(\n `Locadex will modify files! Make sure you have committed or stashed any changes. Do you want to continue?`\n ),\n defaultValue: true,\n cancelMessage: 'Operation cancelled.',\n });\n }\n\n const manager = LocadexManager.getInstance();\n\n const packageManager = await getPackageManager(\n manager.rootDirectory,\n specifiedPackageManager\n );\n let appPackageJson = await getPackageJson(manager.appDirectory);\n\n if (appPackageJson) {\n if (!isPackageInstalled('gt-next', appPackageJson)) {\n const spinner = createSpinner('timer');\n spinner.start(`Installing gt-next with ${packageManager.name}...`);\n await installPackage(\n 'gt-next',\n packageManager,\n false,\n manager.appDirectory\n );\n spinner.stop('Automatically installed gt-next.');\n }\n }\n\n const nextConfigPath = findFilepaths(\n [\n './next.config.js',\n './next.config.ts',\n './next.config.mjs',\n './next.config.mts',\n ],\n manager.appDirectory\n )[0];\n\n if (!nextConfigPath) {\n logger.error('No next.config.[js|ts|mjs|mts] file found.');\n await exit(1);\n }\n\n const errors: string[] = [];\n const warnings: string[] = [];\n let filesUpdated: string[] = [];\n\n const babel = createSpinner();\n\n babel.start('Wrapping <GTProvider> tags...');\n\n // Wrap all JSX elements in the src directory with a <T> tag, with unique ids\n const { filesUpdated: filesUpdatedNext } = await wrapContentNext(\n {\n src: getNextDirectories(manager.appDirectory),\n config: nextConfigPath,\n disableIds: true,\n disableFormatting: true,\n skipTs: true,\n addGTProvider: true,\n },\n 'gt-next',\n errors,\n warnings\n );\n filesUpdated = [...filesUpdated, ...filesUpdatedNext];\n\n babel.stop(`Modified ${filesUpdated.length} files.`);\n\n // Add the withGTConfig() function to the next.config.js file\n await handleInitGT(nextConfigPath, errors, warnings, filesUpdated);\n logger.step(`Added withGTConfig() to your ${nextConfigPath} file.`);\n\n // Create gt.config.json\n await createOrUpdateConfig(\n path.resolve(manager.appDirectory, 'gt.config.json'),\n {\n defaultLocale: 'en',\n locales: ['es', 'fr', 'de', 'ja', 'zh'],\n framework: 'next-app',\n }\n );\n\n logger.success(\n `Feel free to edit ${chalk.cyan(\n 'gt.config.json'\n )} to customize your translation setup. Docs: https://generaltranslation.com/docs/cli/reference/config`\n );\n\n // Add translate to scripts\n // Re-get the package.json to make sure it's updated\n appPackageJson = await getPackageJson(manager.appDirectory);\n if (appPackageJson) {\n await addTranslateScript(manager, appPackageJson, packageManager);\n }\n\n // Install claude-code if not installed\n await installGlobalPackage('@anthropic-ai/claude-code', CLAUDE_CODE_VERSION);\n\n // Install locadex if not installed\n await installGlobalPackage('locadex', getLocadexVersion());\n\n // Set up locale selector\n await setupLocaleSelector();\n\n // Create dictionary.json file if not exists\n setupDictionary(manager);\n\n const formatter = await detectFormatter();\n if (formatter && filesUpdated.length > 0) {\n await formatFiles(filesUpdated, formatter);\n }\n\n // Run i18n command\n await i18nTask();\n}\n\nfunction setupDictionary(manager: LocadexManager) {\n const usingSrcDirectory = existsSync(path.join(manager.appDirectory, 'src'));\n const dictionaryPath = usingSrcDirectory\n ? path.join(manager.appDirectory, 'src', 'dictionary.json')\n : path.join(manager.appDirectory, 'dictionary.json');\n if (!existsSync(dictionaryPath)) {\n writeFileSync(dictionaryPath, '{}');\n logger.step(\n `Created ${chalk.cyan(\n 'dictionary.json'\n )} file at ${chalk.cyan(dictionaryPath)}.`\n );\n }\n}\n\nasync function setupLocaleSelector() {\n logger.initializeSpinner();\n logger.spinner.start('Creating locale selector...');\n\n // Create agent\n const manager = LocadexManager.getInstance();\n\n const agent = manager.createSingleAgent('claude_setup_agent', {});\n\n // Fix prompt\n const localeSelectorPrompt = getLocaleSelectorPrompt(manager.appDirectory);\n try {\n await agent.run(\n localeSelectorPrompt,\n {\n maxTurns: 50,\n timeoutSec: 120,\n maxRetries: 1,\n },\n {}\n );\n\n // Generate report\n const report = agent.generateReport();\n const reportSummary = `# Summary of locadex setup changes\n${report}`;\n const summaryFilePath = path.join(\n manager.getLogDirectory(),\n 'locadex-report.md'\n );\n appendFileSync(summaryFilePath, reportSummary);\n } catch (error) {\n agent.aggregateStats();\n // Check if this is an abort\n if (manager.getAgentAbortController().signal.aborted) {\n return;\n }\n logger.debugMessage(`[setup] Adding locale selector failed: ${error}`);\n outro(chalk.red('❌ Locadex setup failed!'));\n await exit(1);\n }\n agent.aggregateStats();\n\n logger.spinner.stop('Locale selector setup complete');\n}\n\nfunction getLocaleSelectorPrompt(appDirectory: string) {\n const prompt = `# Task: Add a locale selector to the app\n\n## Instructions\n- The locale selector should be a dropdown that allows the user to select the locale.\n- The app root is: \"${appDirectory}\"\n\n## LOCALE SELECTOR USAGE\n(1) Import the locale selector component from 'gt-next/client'\n(2) Add the locale selector to the app\n\nFor example:\nimport { LocaleSelector } from 'gt-next/client';\n\nfunction MyComponent() {\n return (\n <div>\n <LocaleSelector />\n <p>Hello, world!</p>\n </div>\n );\n}\n\n## RULES\n- The locale selector should be added to a header or footer or some other very obvious place in the app.\n- Scan across files to find the best place to add the locale selector.\n- **DO NOT** create new files. You may only modify existing files.\n- You do not need to mark the component containing the LocaleSelector with 'use client'. The LocaleSelector component is already internally marked with 'use client'.\n\n## Final output\n- When you are done, please return a **brief summary** of the files you modified.\n- **DO NOT** include any other text in your response.\n`;\n return prompt;\n}\n"]}
@@ -10,30 +10,34 @@ export type ClaudeSDKMessage = {
10
10
  } | {
11
11
  type: 'result';
12
12
  subtype: 'success';
13
- cost_usd: Number;
14
- duration_ms: Number;
15
- duration_api_ms: Number;
13
+ duration_ms: number;
14
+ duration_api_ms: number;
16
15
  is_error: boolean;
17
- num_turns: Number;
16
+ num_turns: number;
18
17
  result: string;
19
18
  session_id: string;
19
+ total_cost_usd: number;
20
20
  } | {
21
21
  type: 'result';
22
- subtype: 'error_max_turns';
23
- cost_usd: Number;
24
- duration_ms: Number;
25
- duration_api_ms: Number;
22
+ subtype: 'error_max_turns' | 'error_during_execution';
23
+ duration_ms: number;
24
+ duration_api_ms: number;
26
25
  is_error: boolean;
27
- num_turns: Number;
26
+ num_turns: number;
28
27
  session_id: string;
28
+ total_cost_usd: number;
29
29
  } | {
30
30
  type: 'system';
31
31
  subtype: 'init';
32
+ apiKeySource: string;
33
+ cwd: string;
32
34
  session_id: string;
33
35
  tools: string[];
34
36
  mcp_servers: {
35
37
  name: string;
36
38
  status: string;
37
39
  }[];
40
+ model: string;
41
+ permissionMode: 'default' | 'acceptEdits' | 'bypassPermissions' | 'plan';
38
42
  };
39
43
  //# sourceMappingURL=claude-sdk.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"claude-sdk.d.ts","sourceRoot":"/","sources":["types/claude-sdk.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,OAAO,EAAE,KAAK,YAAY,EAAE,MAAM,6BAA6B,CAAC;AAE9E,MAAM,MAAM,gBAAgB,GAExB;IACE,IAAI,EAAE,WAAW,CAAC;IAClB,OAAO,EAAE,OAAO,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;CACpB,GAGD;IACE,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,EAAE,YAAY,CAAC;IACtB,UAAU,EAAE,MAAM,CAAC;CACpB,GAGD;IACE,IAAI,EAAE,QAAQ,CAAC;IACf,OAAO,EAAE,SAAS,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,WAAW,EAAE,MAAM,CAAC;IACpB,eAAe,EAAE,MAAM,CAAC;IACxB,QAA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