i18next-cli 1.34.0 → 1.34.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 (63) hide show
  1. package/README.md +1 -1
  2. package/dist/cjs/cli.js +271 -1
  3. package/dist/cjs/config.js +211 -1
  4. package/dist/cjs/extractor/core/ast-visitors.js +364 -1
  5. package/dist/cjs/extractor/core/extractor.js +245 -1
  6. package/dist/cjs/extractor/core/key-finder.js +132 -1
  7. package/dist/cjs/extractor/core/translation-manager.js +745 -1
  8. package/dist/cjs/extractor/parsers/ast-utils.js +85 -1
  9. package/dist/cjs/extractor/parsers/call-expression-handler.js +941 -1
  10. package/dist/cjs/extractor/parsers/comment-parser.js +375 -1
  11. package/dist/cjs/extractor/parsers/expression-resolver.js +362 -1
  12. package/dist/cjs/extractor/parsers/jsx-handler.js +492 -1
  13. package/dist/cjs/extractor/parsers/jsx-parser.js +355 -1
  14. package/dist/cjs/extractor/parsers/scope-manager.js +408 -1
  15. package/dist/cjs/extractor/plugin-manager.js +106 -1
  16. package/dist/cjs/heuristic-config.js +99 -1
  17. package/dist/cjs/index.js +28 -1
  18. package/dist/cjs/init.js +174 -1
  19. package/dist/cjs/linter.js +431 -1
  20. package/dist/cjs/locize.js +269 -1
  21. package/dist/cjs/migrator.js +196 -1
  22. package/dist/cjs/rename-key.js +354 -1
  23. package/dist/cjs/status.js +336 -1
  24. package/dist/cjs/syncer.js +120 -1
  25. package/dist/cjs/types-generator.js +165 -1
  26. package/dist/cjs/utils/default-value.js +43 -1
  27. package/dist/cjs/utils/file-utils.js +136 -1
  28. package/dist/cjs/utils/funnel-msg-tracker.js +75 -1
  29. package/dist/cjs/utils/logger.js +36 -1
  30. package/dist/cjs/utils/nested-object.js +124 -1
  31. package/dist/cjs/utils/validation.js +71 -1
  32. package/dist/esm/cli.js +269 -1
  33. package/dist/esm/config.js +206 -1
  34. package/dist/esm/extractor/core/ast-visitors.js +362 -1
  35. package/dist/esm/extractor/core/extractor.js +241 -1
  36. package/dist/esm/extractor/core/key-finder.js +130 -1
  37. package/dist/esm/extractor/core/translation-manager.js +743 -1
  38. package/dist/esm/extractor/parsers/ast-utils.js +80 -1
  39. package/dist/esm/extractor/parsers/call-expression-handler.js +939 -1
  40. package/dist/esm/extractor/parsers/comment-parser.js +373 -1
  41. package/dist/esm/extractor/parsers/expression-resolver.js +360 -1
  42. package/dist/esm/extractor/parsers/jsx-handler.js +490 -1
  43. package/dist/esm/extractor/parsers/jsx-parser.js +334 -1
  44. package/dist/esm/extractor/parsers/scope-manager.js +406 -1
  45. package/dist/esm/extractor/plugin-manager.js +103 -1
  46. package/dist/esm/heuristic-config.js +97 -1
  47. package/dist/esm/index.js +11 -1
  48. package/dist/esm/init.js +172 -1
  49. package/dist/esm/linter.js +425 -1
  50. package/dist/esm/locize.js +265 -1
  51. package/dist/esm/migrator.js +194 -1
  52. package/dist/esm/rename-key.js +352 -1
  53. package/dist/esm/status.js +334 -1
  54. package/dist/esm/syncer.js +118 -1
  55. package/dist/esm/types-generator.js +163 -1
  56. package/dist/esm/utils/default-value.js +41 -1
  57. package/dist/esm/utils/file-utils.js +131 -1
  58. package/dist/esm/utils/funnel-msg-tracker.js +72 -1
  59. package/dist/esm/utils/logger.js +34 -1
  60. package/dist/esm/utils/nested-object.js +120 -1
  61. package/dist/esm/utils/validation.js +68 -1
  62. package/package.json +2 -2
  63. package/types/locize.d.ts.map +1 -1
package/dist/esm/cli.js CHANGED
@@ -1,2 +1,270 @@
1
1
  #!/usr/bin/env node
2
- import{Command as o}from"commander";import e from"chokidar";import{glob as t}from"glob";import{minimatch as n}from"minimatch";import i from"chalk";import{ensureConfig as r,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as s}from"./extractor/core/extractor.js";import"react";import"react-i18next";import"node:path";import"node:fs/promises";import"jiti";import"@croct/json5-parser";import{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as d}from"./migrator.js";import{runInit as f}from"./init.js";import{runLinterCli as m}from"./linter.js";import{runStatus as u}from"./status.js";import{runLocizeSync as y,runLocizeDownload as g,runLocizeMigrate as h}from"./locize.js";import{runRenameKey as w}from"./rename-key.js";const x=new o;x.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.34.0"),x.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),x.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").option("--sync-all","Sync primary language values with default values from code AND clear synced keys in all other locales.").action(async o=>{try{const t=x.opts().config,i=await r(t),a=async()=>{const e=!!o.syncPrimary||!!o.syncAll,t=await s(i,{isWatchMode:!!o.watch,isDryRun:!!o.dryRun,syncPrimaryWithDefaults:e,syncAll:!!o.syncAll});return o.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):o.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await a(),o.watch){console.log("\nWatching for changes...");const o=await z(i.extract.input),t=j(i.extract.ignore),r=v(i.extract.output),c=[...t,...r].filter(Boolean),s=o.filter(o=>!c.some(e=>n(o,e,{dot:!0})));e.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),a()})}}catch(o){console.error("Error running extractor:",o),process.exit(1)}}),x.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(o,e)=>{const t=x.opts().config;let n=await a(t);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),n=o}await u(n,{detail:o,namespace:e.namespace})}),x.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async o=>{const t=x.opts().config,i=await r(t),a=()=>l(i);if(await a(),o.watch){console.log("\nWatching for changes...");const o=await z(i.types?.input||[]),t=[...j(i.extract?.ignore)].filter(Boolean),r=o.filter(o=>!t.some(e=>n(o,e,{dot:!0})));e.watch(r,{persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),a()})}}),x.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const o=x.opts().config,e=await r(o);await p(e)}),x.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async o=>{await d(o)}),x.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(f),x.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async o=>{const t=x.opts().config,r=async()=>{let o=await a(t);if(!o){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await c();e||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),o=e}await m(o)};if(await r(),o.watch){console.log("\nWatching for changes...");const o=await a(t);if(o?.extract?.input){const t=await z(o.extract.input),i=[...j(o.extract.ignore),...v(o.extract.output)].filter(Boolean),a=t.filter(o=>!i.some(e=>n(o,e,{dot:!0})));e.watch(a,{ignored:/node_modules/,persistent:!0}).on("change",o=>{console.log(`\nFile changed: ${o}`),r()})}}}),x.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").option("--cdn-type <standard|pro>","Specify the cdn endpoint that should be used (depends on which cdn type you've in your locize project)").action(async o=>{const e=x.opts().config,t=await r(e);await y(t,o)}),x.command("locize-download").description("Download all translations from your locize project.").option("--cdn-type <standard|pro>","Specify the cdn endpoint that should be used (depends on which cdn type you've in your locize project)").action(async o=>{const e=x.opts().config,t=await r(e);await g(t,o)}),x.command("locize-migrate").description("Migrate local translation files to a new locize project.").option("--cdn-type <standard|pro>","Specify the cdn endpoint that should be used (depends on which cdn type you've in your locize project)").action(async o=>{const e=x.opts().config,t=await r(e);await h(t,o)}),x.command("rename-key <oldKey> <newKey>").description("Rename a translation key across all source files and translation files.").option("--dry-run","Preview changes without modifying files").action(async(o,e,t)=>{try{const n=x.opts().config,a=await r(n),c=await w(a,o,e,t);c.success||(c.conflicts&&(console.error(i.red("\n❌ Conflicts detected:")),c.conflicts.forEach(o=>console.error(` - ${o}`))),c.error&&console.error(i.red(`\n❌ ${c.error}`)),process.exit(1));0===c.sourceFiles.reduce((o,e)=>o+e.changes,0)&&console.log(i.yellow(`\n⚠️ No usages found for "${o}"`))}catch(o){console.error(i.red("Error renaming key:"),o),process.exit(1)}}),x.parse(process.argv);const j=o=>Array.isArray(o)?o:o?[o]:[],v=o=>o&&"string"==typeof o?[o.replace(/\{\{[^}]+\}\}/g,"*")]:[],z=async(o=[])=>{const e=j(o),n=await Promise.all(e.map(o=>t(o||"",{nodir:!0})));return Array.from(new Set(n.flat()))};export{x as program};
2
+ import { Command } from 'commander';
3
+ import chokidar from 'chokidar';
4
+ import { glob } from 'glob';
5
+ import { minimatch } from 'minimatch';
6
+ import chalk from 'chalk';
7
+ import { ensureConfig, loadConfig } from './config.js';
8
+ import { detectConfig } from './heuristic-config.js';
9
+ import { runExtractor } from './extractor/core/extractor.js';
10
+ import 'react';
11
+ import 'react-i18next';
12
+ import 'node:path';
13
+ import 'node:fs/promises';
14
+ import 'jiti';
15
+ import '@croct/json5-parser';
16
+ import { runTypesGenerator } from './types-generator.js';
17
+ import { runSyncer } from './syncer.js';
18
+ import { runMigrator } from './migrator.js';
19
+ import { runInit } from './init.js';
20
+ import { runLinterCli } from './linter.js';
21
+ import { runStatus } from './status.js';
22
+ import { runLocizeSync, runLocizeDownload, runLocizeMigrate } from './locize.js';
23
+ import { runRenameKey } from './rename-key.js';
24
+
25
+ const program = new Command();
26
+ program
27
+ .name('i18next-cli')
28
+ .description('A unified, high-performance i18next CLI.')
29
+ .version('1.34.1'); // This string is replaced with the actual version at build time by rollup
30
+ // new: global config override option
31
+ program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)');
32
+ program
33
+ .command('extract')
34
+ .description('Extract translation keys from source files and update resource files.')
35
+ .option('-w, --watch', 'Watch for file changes and re-run the extractor.')
36
+ .option('--ci', 'Exit with a non-zero status code if any files are updated.')
37
+ .option('--dry-run', 'Run the extractor without writing any files to disk.')
38
+ .option('--sync-primary', 'Sync primary language values with default values from code.')
39
+ .option('--sync-all', 'Sync primary language values with default values from code AND clear synced keys in all other locales.')
40
+ .action(async (options) => {
41
+ try {
42
+ const cfgPath = program.opts().config;
43
+ const config = await ensureConfig(cfgPath);
44
+ const runExtract = async () => {
45
+ // --sync-all implies sync-primary behavior
46
+ const syncPrimary = !!options.syncPrimary || !!options.syncAll;
47
+ const success = await runExtractor(config, {
48
+ isWatchMode: !!options.watch,
49
+ isDryRun: !!options.dryRun,
50
+ syncPrimaryWithDefaults: syncPrimary,
51
+ syncAll: !!options.syncAll
52
+ });
53
+ if (options.ci && !success) {
54
+ console.log('✅ No files were updated.');
55
+ process.exit(0);
56
+ }
57
+ else if (options.ci && success) {
58
+ console.error('❌ Some files were updated. This should not happen in CI mode.');
59
+ process.exit(1);
60
+ }
61
+ return success;
62
+ };
63
+ // Run the extractor once initially
64
+ await runExtract();
65
+ // If in watch mode, set up the chokidar watcher
66
+ if (options.watch) {
67
+ console.log('\nWatching for changes...');
68
+ // expand configured input globs (keep original behavior for detection)
69
+ const expanded = await expandGlobs(config.extract.input);
70
+ // build ignore list (configured + derived from output template)
71
+ const configuredIgnore = toArray(config.extract.ignore);
72
+ const derivedIgnore = deriveOutputIgnore(config.extract.output);
73
+ const ignoreGlobs = [...configuredIgnore, ...derivedIgnore].filter(Boolean);
74
+ // filter expanded files by ignore globs
75
+ const watchFiles = expanded.filter(f => !ignoreGlobs.some(g => minimatch(f, g, { dot: true })));
76
+ const watcher = chokidar.watch(watchFiles, {
77
+ ignored: /node_modules/,
78
+ persistent: true,
79
+ });
80
+ watcher.on('change', path => {
81
+ console.log(`\nFile changed: ${path}`);
82
+ runExtract();
83
+ });
84
+ }
85
+ }
86
+ catch (error) {
87
+ console.error('Error running extractor:', error);
88
+ process.exit(1);
89
+ }
90
+ });
91
+ program
92
+ .command('status [locale]')
93
+ .description('Display translation status. Provide a locale for a detailed key-by-key view.')
94
+ .option('-n, --namespace <ns>', 'Filter the status report by a specific namespace')
95
+ .action(async (locale, options) => {
96
+ const cfgPath = program.opts().config;
97
+ let config = await loadConfig(cfgPath);
98
+ if (!config) {
99
+ console.log(chalk.blue('No config file found. Attempting to detect project structure...'));
100
+ const detected = await detectConfig();
101
+ if (!detected) {
102
+ console.error(chalk.red('Could not automatically detect your project structure.'));
103
+ console.log(`Please create a config file first by running: ${chalk.cyan('npx i18next-cli init')}`);
104
+ process.exit(1);
105
+ }
106
+ console.log(chalk.green('Project structure detected successfully!'));
107
+ config = detected;
108
+ }
109
+ await runStatus(config, { detail: locale, namespace: options.namespace });
110
+ });
111
+ program
112
+ .command('types')
113
+ .description('Generate TypeScript definitions from translation resource files.')
114
+ .option('-w, --watch', 'Watch for file changes and re-run the type generator.')
115
+ .action(async (options) => {
116
+ const cfgPath = program.opts().config;
117
+ const config = await ensureConfig(cfgPath);
118
+ const run = () => runTypesGenerator(config);
119
+ await run();
120
+ if (options.watch) {
121
+ console.log('\nWatching for changes...');
122
+ const expandedTypes = await expandGlobs(config.types?.input || []);
123
+ const ignoredTypes = [...toArray(config.extract?.ignore)].filter(Boolean);
124
+ const watchTypes = expandedTypes.filter(f => !ignoredTypes.some(g => minimatch(f, g, { dot: true })));
125
+ const watcher = chokidar.watch(watchTypes, { persistent: true });
126
+ watcher.on('change', path => {
127
+ console.log(`\nFile changed: ${path}`);
128
+ run();
129
+ });
130
+ }
131
+ });
132
+ program
133
+ .command('sync')
134
+ .description('Synchronize secondary language files with the primary language file.')
135
+ .action(async () => {
136
+ const cfgPath = program.opts().config;
137
+ const config = await ensureConfig(cfgPath);
138
+ await runSyncer(config);
139
+ });
140
+ program
141
+ .command('migrate-config [configPath]')
142
+ .description('Migrate a legacy i18next-parser.config.js to the new format.')
143
+ .action(async (configPath) => {
144
+ await runMigrator(configPath);
145
+ });
146
+ program
147
+ .command('init')
148
+ .description('Create a new i18next.config.ts/js file with an interactive setup wizard.')
149
+ .action(runInit);
150
+ program
151
+ .command('lint')
152
+ .description('Find potential issues like hardcoded strings in your codebase.')
153
+ .option('-w, --watch', 'Watch for file changes and re-run the linter.')
154
+ .action(async (options) => {
155
+ const cfgPath = program.opts().config;
156
+ const loadAndRunLinter = async () => {
157
+ // The existing logic for loading the config or detecting it is now inside this function
158
+ let config = await loadConfig(cfgPath);
159
+ if (!config) {
160
+ console.log(chalk.blue('No config file found. Attempting to detect project structure...'));
161
+ const detected = await detectConfig();
162
+ if (!detected) {
163
+ console.error(chalk.red('Could not automatically detect your project structure.'));
164
+ console.log(`Please create a config file first by running: ${chalk.cyan('npx i18next-cli init')}`);
165
+ process.exit(1);
166
+ }
167
+ console.log(chalk.green('Project structure detected successfully!'));
168
+ config = detected;
169
+ }
170
+ await runLinterCli(config);
171
+ };
172
+ // Run the linter once initially
173
+ await loadAndRunLinter();
174
+ // If in watch mode, set up the chokidar watcher
175
+ if (options.watch) {
176
+ console.log('\nWatching for changes...');
177
+ // Re-load the config to get the correct input paths for the watcher
178
+ const config = await loadConfig(cfgPath);
179
+ if (config?.extract?.input) {
180
+ const expandedLint = await expandGlobs(config.extract.input);
181
+ const configuredIgnore2 = toArray(config.extract.ignore);
182
+ const derivedIgnore2 = deriveOutputIgnore(config.extract.output);
183
+ const ignoredLint = [...configuredIgnore2, ...derivedIgnore2].filter(Boolean);
184
+ const watchLint = expandedLint.filter(f => !ignoredLint.some(g => minimatch(f, g, { dot: true })));
185
+ const watcher = chokidar.watch(watchLint, {
186
+ ignored: /node_modules/,
187
+ persistent: true,
188
+ });
189
+ watcher.on('change', path => {
190
+ console.log(`\nFile changed: ${path}`);
191
+ loadAndRunLinter(); // Re-run on change
192
+ });
193
+ }
194
+ }
195
+ });
196
+ program
197
+ .command('locize-sync')
198
+ .description('Synchronize local translations with your locize project.')
199
+ .option('--update-values', 'Update values of existing translations on locize.')
200
+ .option('--src-lng-only', 'Check for changes in source language only.')
201
+ .option('--compare-mtime', 'Compare modification times when syncing.')
202
+ .option('--dry-run', 'Run the command without making any changes.')
203
+ .option('--cdn-type <standard|pro>', 'Specify the cdn endpoint that should be used (depends on which cdn type you\'ve in your locize project)')
204
+ .action(async (options) => {
205
+ const cfgPath = program.opts().config;
206
+ const config = await ensureConfig(cfgPath);
207
+ await runLocizeSync(config, options);
208
+ });
209
+ program
210
+ .command('locize-download')
211
+ .description('Download all translations from your locize project.')
212
+ .option('--cdn-type <standard|pro>', 'Specify the cdn endpoint that should be used (depends on which cdn type you\'ve in your locize project)')
213
+ .action(async (options) => {
214
+ const cfgPath = program.opts().config;
215
+ const config = await ensureConfig(cfgPath);
216
+ await runLocizeDownload(config, options);
217
+ });
218
+ program
219
+ .command('locize-migrate')
220
+ .description('Migrate local translation files to a new locize project.')
221
+ .option('--cdn-type <standard|pro>', 'Specify the cdn endpoint that should be used (depends on which cdn type you\'ve in your locize project)')
222
+ .action(async (options) => {
223
+ const cfgPath = program.opts().config;
224
+ const config = await ensureConfig(cfgPath);
225
+ await runLocizeMigrate(config, options);
226
+ });
227
+ program
228
+ .command('rename-key <oldKey> <newKey>')
229
+ .description('Rename a translation key across all source files and translation files.')
230
+ .option('--dry-run', 'Preview changes without modifying files')
231
+ .action(async (oldKey, newKey, options) => {
232
+ try {
233
+ const cfgPath = program.opts().config;
234
+ const config = await ensureConfig(cfgPath);
235
+ const result = await runRenameKey(config, oldKey, newKey, options);
236
+ if (!result.success) {
237
+ if (result.conflicts) {
238
+ console.error(chalk.red('\n❌ Conflicts detected:'));
239
+ result.conflicts.forEach(c => console.error(` - ${c}`));
240
+ }
241
+ if (result.error) {
242
+ console.error(chalk.red(`\n❌ ${result.error}`));
243
+ }
244
+ process.exit(1);
245
+ }
246
+ const totalChanges = result.sourceFiles.reduce((sum, f) => sum + f.changes, 0);
247
+ if (totalChanges === 0) {
248
+ console.log(chalk.yellow(`\n⚠️ No usages found for "${oldKey}"`));
249
+ }
250
+ }
251
+ catch (error) {
252
+ console.error(chalk.red('Error renaming key:'), error);
253
+ process.exit(1);
254
+ }
255
+ });
256
+ program.parse(process.argv);
257
+ const toArray = (v) => Array.isArray(v) ? v : (v ? [v] : []);
258
+ const deriveOutputIgnore = (output) => {
259
+ if (!output || typeof output !== 'string')
260
+ return [];
261
+ return [output.replace(/\{\{[^}]+\}\}/g, '*')];
262
+ };
263
+ // helper to expand one or many glob patterns
264
+ const expandGlobs = async (patterns = []) => {
265
+ const arr = toArray(patterns);
266
+ const sets = await Promise.all(arr.map(p => glob(p || '', { nodir: true })));
267
+ return Array.from(new Set(sets.flat()));
268
+ };
269
+
270
+ export { program };
@@ -1 +1,206 @@
1
- import{resolve as r,join as t,dirname as o}from"node:path";import{pathToFileURL as n}from"node:url";import{access as e,readFile as i}from"node:fs/promises";import{createJiti as a}from"jiti";import{parse as c}from"jsonc-parser";import s from"inquirer";import f from"chalk";import{runInit as l}from"./init.js";import{ConsoleLogger as u}from"./utils/logger.js";const p=["i18next.config.ts","i18next.config.js","i18next.config.mjs","i18next.config.cjs"];function m(r){return r}async function d(t,o=new u){const i=await async function(t){if(t){const o=r(process.cwd(),t);try{return await e(o),o}catch{return null}}for(const t of p){const o=r(process.cwd(),t);try{return await e(o),o}catch{}}return null}(t);if(!i)return t&&o.error(`Error: Config file not found at "${t}"`),null;try{let r;if(i.endsWith(".ts")){const t=await w(),o=a(process.cwd(),{alias:t,interopDefault:!1}),n=await o.import(i,{default:!0});r=n}else{const t=n(i).href,o=await import(`${t}?t=${Date.now()}`);r=o.default}return r?(r.extract||={},r.extract.primaryLanguage||=r.locales[0]||"en",r.extract.secondaryLanguages||=r.locales.filter(t=>t!==r.extract.primaryLanguage),r):(o.error(`Error: No default export found in ${i}`),null)}catch(r){return o.error(`Error loading configuration from ${i}`),o.error(r),null}}async function g(r,t=new u){let o=await d(r,t);if(o)return o;const{shouldInit:n}=await s.prompt([{type:"confirm",name:"shouldInit",message:f.yellow("Configuration file not found. Would you like to create one now?"),default:!0}]);if(n){if(await l(),t.info(f.green("Configuration created. Resuming command...")),o=await d(r,t),o)return o;t.error(f.red("Error: Failed to load configuration after creation. Please try running the command again.")),process.exit(1)}else t.info("Operation cancelled. Please create a configuration file to proceed."),process.exit(0)}async function w(){try{const n=await async function(){let r=process.cwd();for(;;){const n=t(r,"tsconfig.json");try{return await e(n),n}catch{const t=o(r);if(t===r)return null;r=t}}}();if(!n)return{};const a=await i(n,"utf-8"),s=c(a),f=s.compilerOptions?.paths,l=s.compilerOptions?.baseUrl||".";if(!f)return{};const u={};for(const[t,o]of Object.entries(f))if(Array.isArray(o)&&o.length>0){const n=t.replace("/*",""),e=r(process.cwd(),l,o[0].replace("/*",""));u[n]=e}return u}catch(r){return{}}}export{m as defineConfig,g as ensureConfig,w as getTsConfigAliases,d as loadConfig};
1
+ import { resolve, join, dirname } from 'node:path';
2
+ import { pathToFileURL } from 'node:url';
3
+ import { access, readFile } from 'node:fs/promises';
4
+ import { createJiti } from 'jiti';
5
+ import { parse } from 'jsonc-parser';
6
+ import inquirer from 'inquirer';
7
+ import chalk from 'chalk';
8
+ import { runInit } from './init.js';
9
+ import { ConsoleLogger } from './utils/logger.js';
10
+
11
+ /**
12
+ * List of supported configuration file names in order of precedence
13
+ */
14
+ const CONFIG_FILES = [
15
+ 'i18next.config.ts',
16
+ 'i18next.config.js',
17
+ 'i18next.config.mjs',
18
+ 'i18next.config.cjs',
19
+ ];
20
+ /**
21
+ * A helper function for defining the i18next-cli config with type-safety.
22
+ *
23
+ * @param config - The configuration object to define
24
+ * @returns The same configuration object with type safety
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * export default defineConfig({
29
+ * locales: ['en', 'de'],
30
+ * extract: {
31
+ * input: 'src',
32
+ * output: 'locales/{{language}}/{{namespace}}.json'
33
+ * }
34
+ * })
35
+ * ```
36
+ */
37
+ function defineConfig(config) {
38
+ return config;
39
+ }
40
+ /**
41
+ * Helper function to find the first existing config file in the current working directory.
42
+ * Searches for files in the order defined by CONFIG_FILES.
43
+ *
44
+ * @returns Promise that resolves to the full path of the found config file, or null if none found
45
+ */
46
+ async function findConfigFile(configPath) {
47
+ if (configPath) {
48
+ // Allow relative or absolute path provided by the user
49
+ const resolved = resolve(process.cwd(), configPath);
50
+ try {
51
+ await access(resolved);
52
+ return resolved;
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ }
58
+ for (const file of CONFIG_FILES) {
59
+ const fullPath = resolve(process.cwd(), file);
60
+ try {
61
+ await access(fullPath);
62
+ return fullPath;
63
+ }
64
+ catch {
65
+ // File doesn't exist, continue to the next one
66
+ }
67
+ }
68
+ return null;
69
+ }
70
+ /**
71
+ * Loads and validates the i18next toolkit configuration from the project root or a provided path.
72
+ *
73
+ * @param configPath - Optional explicit path to a config file (relative to cwd or absolute)
74
+ * @param logger - Optional logger instance
75
+ */
76
+ async function loadConfig(configPath, logger = new ConsoleLogger()) {
77
+ const configPathFound = await findConfigFile(configPath);
78
+ if (!configPathFound) {
79
+ if (configPath) {
80
+ logger.error(`Error: Config file not found at "${configPath}"`);
81
+ }
82
+ // QUIETLY RETURN NULL: The caller will handle the "not found" case.
83
+ return null;
84
+ }
85
+ try {
86
+ let config;
87
+ // Use jiti for TypeScript files, native import for JavaScript
88
+ if (configPathFound.endsWith('.ts')) {
89
+ const aliases = await getTsConfigAliases();
90
+ const jiti = createJiti(process.cwd(), {
91
+ alias: aliases,
92
+ interopDefault: false,
93
+ });
94
+ const configModule = await jiti.import(configPathFound, { default: true });
95
+ config = configModule;
96
+ }
97
+ else {
98
+ const configUrl = pathToFileURL(configPathFound).href;
99
+ const configModule = await import(`${configUrl}?t=${Date.now()}`);
100
+ config = configModule.default;
101
+ }
102
+ if (!config) {
103
+ logger.error(`Error: No default export found in ${configPathFound}`);
104
+ return null;
105
+ }
106
+ // Set default sync options
107
+ config.extract ||= {};
108
+ config.extract.primaryLanguage ||= config.locales[0] || 'en';
109
+ config.extract.secondaryLanguages ||= config.locales.filter((l) => l !== config.extract.primaryLanguage);
110
+ return config;
111
+ }
112
+ catch (error) {
113
+ logger.error(`Error loading configuration from ${configPathFound}`);
114
+ logger.error(error);
115
+ return null;
116
+ }
117
+ }
118
+ /**
119
+ * Ensures a configuration exists, prompting the user to create one if necessary.
120
+ * Accepts an optional configPath which will be used when loading the config.
121
+ */
122
+ async function ensureConfig(configPath, logger = new ConsoleLogger()) {
123
+ let config = await loadConfig(configPath, logger);
124
+ if (config) {
125
+ return config;
126
+ }
127
+ // No config found, so we prompt the user.
128
+ const { shouldInit } = await inquirer.prompt([{
129
+ type: 'confirm',
130
+ name: 'shouldInit',
131
+ message: chalk.yellow('Configuration file not found. Would you like to create one now?'),
132
+ default: true,
133
+ }]);
134
+ if (shouldInit) {
135
+ await runInit(); // Run the interactive setup wizard (keeps existing behavior)
136
+ logger.info(chalk.green('Configuration created. Resuming command...'));
137
+ config = await loadConfig(configPath, logger); // Try loading the newly created config
138
+ if (config) {
139
+ return config;
140
+ }
141
+ else {
142
+ logger.error(chalk.red('Error: Failed to load configuration after creation. Please try running the command again.'));
143
+ process.exit(1);
144
+ }
145
+ }
146
+ else {
147
+ logger.info('Operation cancelled. Please create a configuration file to proceed.');
148
+ process.exit(0);
149
+ }
150
+ }
151
+ /**
152
+ * Searches upwards from the current directory to find the tsconfig.json file.
153
+ * @returns The full path to the tsconfig.json file, or null if not found.
154
+ */
155
+ async function findTsConfigFile() {
156
+ let currentDir = process.cwd();
157
+ while (true) {
158
+ const tsConfigPath = join(currentDir, 'tsconfig.json');
159
+ try {
160
+ await access(tsConfigPath);
161
+ return tsConfigPath;
162
+ }
163
+ catch {
164
+ // File not found, move to parent directory
165
+ const parentDir = dirname(currentDir);
166
+ if (parentDir === currentDir) {
167
+ // Reached the root of the file system
168
+ return null;
169
+ }
170
+ currentDir = parentDir;
171
+ }
172
+ }
173
+ }
174
+ /**
175
+ * Parses the project's tsconfig.json to extract path aliases for jiti.
176
+ * @returns A record of aliases for jiti's configuration.
177
+ */
178
+ async function getTsConfigAliases() {
179
+ try {
180
+ const tsConfigPath = await findTsConfigFile();
181
+ if (!tsConfigPath)
182
+ return {};
183
+ const tsConfigStr = await readFile(tsConfigPath, 'utf-8');
184
+ const tsConfig = parse(tsConfigStr);
185
+ const paths = tsConfig.compilerOptions?.paths;
186
+ const baseUrl = tsConfig.compilerOptions?.baseUrl || '.';
187
+ if (!paths)
188
+ return {};
189
+ const aliases = {};
190
+ for (const [alias, aliasPaths] of Object.entries(paths)) {
191
+ if (Array.isArray(aliasPaths) && aliasPaths.length > 0) {
192
+ // Convert "@/*": ["./src/*"] to "@": "./src"
193
+ const key = alias.replace('/*', '');
194
+ const value = resolve(process.cwd(), baseUrl, aliasPaths[0].replace('/*', ''));
195
+ aliases[key] = value;
196
+ }
197
+ }
198
+ return aliases;
199
+ }
200
+ catch (e) {
201
+ // Return empty if tsconfig doesn't exist or fails to parse
202
+ return {};
203
+ }
204
+ }
205
+
206
+ export { defineConfig, ensureConfig, getTsConfigAliases, loadConfig };