i18next-cli 1.19.2 → 1.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.20.0](https://github.com/i18next/i18next-cli/compare/v1.19.3...v1.20.0) - 2025-11-03
9
+
10
+ - feat(extractor): statically extract keys referenced via TypeScript enums (e.g. `t(ERROR_CODE.UNKNOWN_ERROR)` → `'UNKNOWN_ERROR'`). Resolves only string-initialized enum members; conservative, non-breaking. [#87](https://github.com/i18next/i18next-cli/issues/87)
11
+
12
+ ## [1.19.3](https://github.com/i18next/i18next-cli/compare/v1.19.2...v1.19.3) - 2025-11-02
13
+
14
+ - fix(extractor): improving preserve flat JSON output when extract.defaultNS is false during re-extraction. [#73](https://github.com/i18next/i18next-cli/issues/73)
15
+
8
16
  ## [1.19.2](https://github.com/i18next/i18next-cli/compare/v1.19.1...v1.19.2) - 2025-11-02
9
17
 
10
18
  - fix(extractor): preserve flat output when extract.defaultNS is false on re-extracttion. [#73](https://github.com/i18next/i18next-cli/issues/73)
package/dist/cjs/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=require("commander"),t=require("chokidar"),o=require("glob"),n=require("minimatch"),i=require("chalk"),a=require("./config.js"),r=require("./heuristic-config.js"),c=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var s=require("./types-generator.js"),l=require("./syncer.js"),u=require("./migrator.js"),g=require("./init.js"),d=require("./linter.js"),p=require("./status.js"),f=require("./locize.js");const m=new e.Command;m.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.19.2"),m.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),m.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.").action(async e=>{try{const o=m.opts().config,i=await a.ensureConfig(o),r=async()=>{const t=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.extract.input),o=y(i.extract.ignore),a=h(i.extract.output),c=[...o,...a].filter(Boolean),s=e.filter(e=>!c.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}catch(e){console.error("Error running extractor:",e),process.exit(1)}}),m.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(e,t)=>{const o=m.opts().config;let n=await a.loadConfig(o);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await r.detectConfig();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!")),n=e}await p.runStatus(n,{detail:e,namespace:t.namespace})}),m.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 e=>{const o=m.opts().config,i=await a.ensureConfig(o),r=()=>s.runTypesGenerator(i);if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.types?.input||[]),o=[...y(i.extract?.ignore)].filter(Boolean),a=e.filter(e=>!o.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}),m.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=m.opts().config,t=await a.ensureConfig(e);await l.runSyncer(t)}),m.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),m.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(g.runInit),m.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 e=>{const o=m.opts().config,c=async()=>{let e=await a.loadConfig(o);if(!e){console.log(i.blue("No config file found. Attempting to detect project structure..."));const t=await r.detectConfig();t||(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!")),e=t}await d.runLinterCli(e)};if(await c(),e.watch){console.log("\nWatching for changes...");const e=await a.loadConfig(o);if(e?.extract?.input){const o=await w(e.extract.input),i=[...y(e.extract.ignore),...h(e.extract.output)].filter(Boolean),a=o.filter(e=>!i.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}}),m.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.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeSync(o,e)}),m.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeDownload(o,e)}),m.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeMigrate(o,e)}),m.parse(process.argv);const y=e=>Array.isArray(e)?e:e?[e]:[],h=e=>e&&"string"==typeof e?[e.replace(/\{\{[^}]+\}\}/g,"*")]:[],w=async(e=[])=>{const t=y(e),n=await Promise.all(t.map(e=>o.glob(e||"",{nodir:!0})));return Array.from(new Set(n.flat()))};
2
+ "use strict";var e=require("commander"),t=require("chokidar"),o=require("glob"),n=require("minimatch"),i=require("chalk"),a=require("./config.js"),r=require("./heuristic-config.js"),c=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var s=require("./types-generator.js"),l=require("./syncer.js"),u=require("./migrator.js"),g=require("./init.js"),d=require("./linter.js"),p=require("./status.js"),f=require("./locize.js");const m=new e.Command;m.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.20.0"),m.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),m.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.").action(async e=>{try{const o=m.opts().config,i=await a.ensureConfig(o),r=async()=>{const t=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.extract.input),o=y(i.extract.ignore),a=h(i.extract.output),c=[...o,...a].filter(Boolean),s=e.filter(e=>!c.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}catch(e){console.error("Error running extractor:",e),process.exit(1)}}),m.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(e,t)=>{const o=m.opts().config;let n=await a.loadConfig(o);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await r.detectConfig();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!")),n=e}await p.runStatus(n,{detail:e,namespace:t.namespace})}),m.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 e=>{const o=m.opts().config,i=await a.ensureConfig(o),r=()=>s.runTypesGenerator(i);if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.types?.input||[]),o=[...y(i.extract?.ignore)].filter(Boolean),a=e.filter(e=>!o.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}),m.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=m.opts().config,t=await a.ensureConfig(e);await l.runSyncer(t)}),m.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),m.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(g.runInit),m.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 e=>{const o=m.opts().config,c=async()=>{let e=await a.loadConfig(o);if(!e){console.log(i.blue("No config file found. Attempting to detect project structure..."));const t=await r.detectConfig();t||(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!")),e=t}await d.runLinterCli(e)};if(await c(),e.watch){console.log("\nWatching for changes...");const e=await a.loadConfig(o);if(e?.extract?.input){const o=await w(e.extract.input),i=[...y(e.extract.ignore),...h(e.extract.output)].filter(Boolean),a=o.filter(e=>!i.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}}),m.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.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeSync(o,e)}),m.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeDownload(o,e)}),m.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeMigrate(o,e)}),m.parse(process.argv);const y=e=>Array.isArray(e)?e:e?[e]:[],h=e=>e&&"string"==typeof e?[e.replace(/\{\{[^}]+\}\}/g,"*")]:[],w=async(e=[])=>{const t=y(e),n=await Promise.all(t.map(e=>o.glob(e||"",{nodir:!0})));return Array.from(new Set(n.flat()))};
@@ -1 +1 @@
1
- "use strict";var e=require("../parsers/scope-manager.js"),s=require("../parsers/expression-resolver.js"),r=require("../parsers/call-expression-handler.js"),o=require("../parsers/jsx-handler.js");exports.ASTVisitors=class{pluginContext;config;logger;hooks;get objectKeys(){return this.callExpressionHandler.objectKeys}scopeManager;expressionResolver;callExpressionHandler;jsxHandler;constructor(a,t,i,n){this.pluginContext=t,this.config=a,this.logger=i,this.hooks={onBeforeVisitNode:n?.onBeforeVisitNode,onAfterVisitNode:n?.onAfterVisitNode,resolvePossibleKeyStringValues:n?.resolvePossibleKeyStringValues,resolvePossibleContextStringValues:n?.resolvePossibleContextStringValues},this.scopeManager=new e.ScopeManager(a),this.expressionResolver=new s.ExpressionResolver(this.hooks),this.callExpressionHandler=new r.CallExpressionHandler(a,t,i,this.expressionResolver),this.jsxHandler=new o.JSXHandler(a,t,this.expressionResolver)}visit(e){this.scopeManager.reset(),this.scopeManager.enterScope(),this.walk(e),this.scopeManager.exitScope()}walk(e){if(!e)return;let s=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.scopeManager.enterScope(),s=!0),this.hooks.onBeforeVisitNode?.(e),e.type){case"VariableDeclarator":this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);break;case"CallExpression":this.callExpressionHandler.handleCallExpression(e,this.scopeManager.getVarFromScope.bind(this.scopeManager));break;case"JSXElement":this.jsxHandler.handleJSXElement(e,this.scopeManager.getVarFromScope.bind(this.scopeManager))}this.hooks.onAfterVisitNode?.(e);for(const s in e){if("span"===s)continue;const r=e[s];if(Array.isArray(r)){for(const e of r)if(e&&"object"==typeof e)if("VariableDeclarator"!==e.type){if("VariableDeclaration"===e.type&&Array.isArray(e.declarations))for(const s of e.declarations)s&&"object"==typeof s&&"VariableDeclarator"===s.type&&(this.scopeManager.handleVariableDeclarator(s),this.expressionResolver.captureVariableDeclarator(s))}else this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);for(const e of r)e&&"object"==typeof e&&this.walk(e)}else r&&"object"==typeof r&&this.walk(r)}s&&this.scopeManager.exitScope()}getVarFromScope(e){return this.scopeManager.getVarFromScope(e)}};
1
+ "use strict";var e=require("../parsers/scope-manager.js"),s=require("../parsers/expression-resolver.js"),r=require("../parsers/call-expression-handler.js"),a=require("../parsers/jsx-handler.js");exports.ASTVisitors=class{pluginContext;config;logger;hooks;get objectKeys(){return this.callExpressionHandler.objectKeys}scopeManager;expressionResolver;callExpressionHandler;jsxHandler;constructor(o,t,i,n,l){this.pluginContext=t,this.config=o,this.logger=i,this.hooks={onBeforeVisitNode:n?.onBeforeVisitNode,onAfterVisitNode:n?.onAfterVisitNode,resolvePossibleKeyStringValues:n?.resolvePossibleKeyStringValues,resolvePossibleContextStringValues:n?.resolvePossibleContextStringValues},this.scopeManager=new e.ScopeManager(o),this.expressionResolver=l??new s.ExpressionResolver(this.hooks),this.callExpressionHandler=new r.CallExpressionHandler(o,t,i,this.expressionResolver),this.jsxHandler=new a.JSXHandler(o,t,this.expressionResolver)}visit(e){this.scopeManager.reset(),this.scopeManager.enterScope(),this.walk(e),this.scopeManager.exitScope()}walk(e){if(!e)return;let s=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.scopeManager.enterScope(),s=!0),this.hooks.onBeforeVisitNode?.(e),e.type){case"VariableDeclarator":this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);break;case"TSEnumDeclaration":case"TsEnumDeclaration":case"TsEnumDecl":this.expressionResolver.captureEnumDeclaration(e);break;case"CallExpression":this.callExpressionHandler.handleCallExpression(e,this.scopeManager.getVarFromScope.bind(this.scopeManager));break;case"JSXElement":this.jsxHandler.handleJSXElement(e,this.scopeManager.getVarFromScope.bind(this.scopeManager))}this.hooks.onAfterVisitNode?.(e);for(const s in e){if("span"===s)continue;const r=e[s];if(Array.isArray(r)){for(const e of r)if(e&&"object"==typeof e)if("VariableDeclarator"!==e.type){if(e&&e.id&&Array.isArray(e.members)&&this.expressionResolver.captureEnumDeclaration(e),"VariableDeclaration"===e.type&&Array.isArray(e.declarations))for(const s of e.declarations)s&&"object"==typeof s&&"VariableDeclarator"===s.type&&(this.scopeManager.handleVariableDeclarator(s),this.expressionResolver.captureVariableDeclarator(s))}else this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);for(const e of r)e&&"object"==typeof e&&this.walk(e)}else r&&"object"==typeof r&&this.walk(r)}s&&this.scopeManager.exitScope()}getVarFromScope(e){return this.scopeManager.getVarFromScope(e)}};
@@ -1 +1 @@
1
- "use strict";var e=require("glob"),r=require("./extractor.js"),t=require("../../utils/logger.js"),n=require("../plugin-manager.js"),o=require("./ast-visitors.js");exports.findKeys=async function(i,s=new t.ConsoleLogger){const{plugins:a,...c}=i,l=a||[],u=await async function(r){const t=["node_modules/**"],n=Array.isArray(r.extract.ignore)?r.extract.ignore:r.extract.ignore?[r.extract.ignore]:[];return await e.glob(r.extract.input,{ignore:[...t,...n],cwd:process.cwd()})}(i),g=new Map,x=n.createPluginContext(g,l,c,s),p={onBeforeVisitNode:e=>{for(const r of l)try{r.onVisitNode?.(e,x)}catch(e){s.warn(`Plugin ${r.name} onVisitNode failed:`,e)}},resolvePossibleKeyStringValues:e=>l.flatMap(r=>{try{return r.extractKeysFromExpression?.(e,i,s)??[]}catch(e){return s.warn(`Plugin ${r.name} extractKeysFromExpression failed:`,e),[]}}),resolvePossibleContextStringValues:e=>l.flatMap(r=>{try{return r.extractContextFromExpression?.(e,i,s)??[]}catch(e){return s.warn(`Plugin ${r.name} extractContextFromExpression failed:`,e),[]}})},d=new o.ASTVisitors(c,x,s,p);x.getVarFromScope=d.getVarFromScope.bind(d),await n.initializePlugins(l);for(const e of u)await r.processFile(e,l,d,x,c,s);for(const e of l)await(e.onEnd?.(g));const f=c.extract?.pluralSeparator??"_",y=["zero","one","two","few","many","other"];for(const e of g.values()){const r=String(e.key).split(f),t=r[r.length-1],n=r.length>=3&&"ordinal"===r[r.length-2];(y.includes(t)||n&&y.includes(t))&&(e.isExpandedPlural=!0)}return{allKeys:g,objectKeys:d.objectKeys}};
1
+ "use strict";var e=require("glob"),r=require("./extractor.js"),t=require("../../utils/logger.js"),o=require("../plugin-manager.js"),n=require("./ast-visitors.js"),s=require("../parsers/expression-resolver.js");exports.findKeys=async function(i,a=new t.ConsoleLogger){const{plugins:l,...c}=i,u=l||[],g=await async function(r){const t=["node_modules/**"],o=Array.isArray(r.extract.ignore)?r.extract.ignore:r.extract.ignore?[r.extract.ignore]:[];return await e.glob(r.extract.input,{ignore:[...t,...o],cwd:process.cwd()})}(i),x=new Map,p=o.createPluginContext(x,u,c,a),d={onBeforeVisitNode:e=>{for(const r of u)try{r.onVisitNode?.(e,p)}catch(e){a.warn(`Plugin ${r.name} onVisitNode failed:`,e)}},resolvePossibleKeyStringValues:e=>u.flatMap(r=>{try{return r.extractKeysFromExpression?.(e,i,a)??[]}catch(e){return a.warn(`Plugin ${r.name} extractKeysFromExpression failed:`,e),[]}}),resolvePossibleContextStringValues:e=>u.flatMap(r=>{try{return r.extractContextFromExpression?.(e,i,a)??[]}catch(e){return a.warn(`Plugin ${r.name} extractContextFromExpression failed:`,e),[]}})},f=new s.ExpressionResolver(d),w=new n.ASTVisitors(c,p,a,d,f);p.getVarFromScope=w.getVarFromScope.bind(w),await o.initializePlugins(u);for(const e of g)await r.processFile(e,u,w,p,c,a);for(const e of u)await(e.onEnd?.(x));const y=c.extract?.pluralSeparator??"_",m=["zero","one","two","few","many","other"];for(const e of x.values()){const r=String(e.key).split(y),t=r[r.length-1],o=r.length>=3&&"ordinal"===r[r.length-2];(m.includes(t)||o&&m.includes(t))&&(e.isExpandedPlural=!0)}return{allKeys:x,objectKeys:w.objectKeys}};
@@ -1 +1 @@
1
- "use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),n=require("../../utils/file-utils.js"),a=require("../../utils/default-value.js");function r(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function o(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const s={},n=t?.extract?.pluralSeparator??"_",a=["zero","one","two","few","many","other"],r=a.map(e=>`ordinal${n}${e}`),l=Object.keys(e).sort((e,t)=>{const s=e=>{for(const t of r)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of a)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},o=s(e),l=s(t);if(o.isPlural&&l.isPlural){const e=o.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(o.isOrdinal!==l.isOrdinal)return o.isOrdinal?1:-1;const t=o.isOrdinal?r:a,s=t.indexOf(o.form),n=t.indexOf(l.form);return-1!==s&&-1!==n?s-n:o.form.localeCompare(l.form)}const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t,void 0,{sensitivity:"case"}):i});for(const n of l)s[n]=o(e[n],t);return s}function l(e,t,n,r,l,i=[],c=new Set,u=!1){const{keySeparator:f=".",sort:d=!0,removeUnusedKeys:p=!0,primaryLanguage:g,defaultValue:y="",pluralSeparator:h="_",contextSeparator:x="_"}=n.extract,m=(...e)=>{console.log("[i18next-debug]",...e)};m("buildNewTranslationsForNs start",{locale:r,namespace:l,keySeparator:f,pluralSeparator:h,primaryLanguage:g}),m("nsKeys (count):",e.length);try{m("existingTranslations keys:",s.getNestedKeys(t,f??".").slice(0,50))}catch(e){m("could not list existing keys",e)}const v=new Set;let O=[],S=[];try{const e=new Intl.PluralRules(r,{type:"cardinal"}),t=new Intl.PluralRules(r,{type:"ordinal"});O=e.resolvedOptions().pluralCategories,S=t.resolvedOptions().pluralCategories,O.forEach(e=>v.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}catch(e){const t=g||"en",s=new Intl.PluralRules(t,{type:"cardinal"}),n=new Intl.PluralRules(t,{type:"ordinal"});O=s.resolvedOptions().pluralCategories,S=n.resolvedOptions().pluralCategories,O.forEach(e=>v.add(e)),n.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}const N=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if(i.some(t=>t.test(e)))return!1;if(!t)return!0;const n=e.split(h);if(t&&1===n.length)return!0;if(1===O.length&&"other"===O[0]&&1===n.length)return!0;if(s&&n.includes("ordinal")){const e=n[n.length-1];return v.has(`ordinal_${e}`)}if(t){const e=n[n.length-1];return v.has(e)}return!0}),b=new Set;for(const e of N)if(e.isExpandedPlural){const t=String(e.key).split(h);t.length>=3&&"ordinal"===t[t.length-2]?b.add(t.slice(0,-2).join(h)):b.add(t.slice(0,-1).join(h))}let w=p?{}:JSON.parse(JSON.stringify(t));const V=s.getNestedKeys(t,f??".");for(const e of V)if(i.some(t=>t.test(e))){const n=s.getNestedValue(t,e,f??".");s.setNestedValue(w,e,n,f??".")}if(p){const e=s.getNestedKeys(t,f??".");for(const n of e){const e=n.split(h);if("zero"===e[e.length-1]){const a=e.slice(0,-1).join(h);if(N.some(({key:e})=>e.split(h).slice(0,-1).join(h)===a)){const e=s.getNestedValue(t,n,f??".");s.setNestedValue(w,n,e,f??".")}}}}for(const{key:e,defaultValue:o,explicitDefault:i,hasCount:d,isExpandedPlural:p,isOrdinal:v}of N){if(d&&!p){const t=String(e).split(h);let s=e;if(t.length>=3&&"ordinal"===t[t.length-2]?s=t.slice(0,-2).join(h):t.length>=2&&(s=t.slice(0,-1).join(h)),b.has(s))continue}if(d&&!p){if(1===String(e).split(h).length&&r!==g){const i=e;if(b.has(i));else{const e=v?S:O;for(const c of e){const e=v?`${i}${h}ordinal${h}${c}`:`${i}${h}${c}`,u=s.getNestedValue(t,e,f??".");if(void 0===u){let t;t="string"==typeof o?o:a.resolveDefaultValue(y,String(i),l||n?.extract?.defaultNS||"translation",r,o),m("expanding plural variant",{finalKey:e,existingVariantValue:u,resolvedValue:t}),s.setNestedValue(w,e,t,f??".")}else m("keeping existing plural variant",{finalKey:e,existingVariantValue:u}),s.setNestedValue(w,e,u,f??".")}}continue}}const V=s.getNestedValue(t,e,f??"."),k=!1===f||!N.some(t=>t.key!==e&&t.key.startsWith(`${e}${f}`)),$="object"==typeof V&&null!==V&&(c.has(e)||!o||o===e),j="object"==typeof V&&null!==V&&k&&!c.has(e)&&!$;if(m("processing key",{key:e,existingValueType:typeof V,isLeafInNewKeys:k,shouldPreserveObject:$,isStaleObject:j,defaultValue:o}),$){s.setNestedValue(w,e,V,f??".");continue}let P;if(void 0===V||j)if(r===g)if(u){const t=o&&(o===e||e!==o&&(e.startsWith(o+h)||e.startsWith(o+x)));P=o&&!t?o:a.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",r,o)}else P=o||e;else P=a.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",r,o);else if(r===g&&u){const t=o&&(o===e||e!==o&&(e.startsWith(o+h)||e.startsWith(o+x)));P=(e.includes(h)||e.includes(x))&&!i?V:o&&!t?o:V}else P=V;m("final decision for key",{key:e,existingValue:V,valueToSet:P,typeofExisting:typeof V,typeofValueToSet:typeof P}),s.setNestedValue(w,e,P,f??".")}if(!0===d)return o(w,n);if("function"==typeof d){const e={},t=Object.keys(w),s=new Map;for(const e of N){const t=!1===f?e.key:e.key.split(f)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof d){const n=s.get(e),a=s.get(t);if(n&&a)return d(n,a)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=o(w[s],n);w=e}return w}exports.getTranslations=async function(s,a,o,{syncPrimaryWithDefaults:i=!1}={}){o.extract.primaryLanguage||=o.locales[0]||"en",o.extract.secondaryLanguages||=o.locales.filter(e=>e!==o?.extract?.primaryLanguage);const c=[...o.extract.preservePatterns||[]],u=o.extract.indentation??2;for(const e of a)c.push(`${e}.*`);const f=c.map(r),d="__no_namespace__",p=new Map;for(const e of s.values()){const t=e.nsIsImplicit&&!1===o.extract.defaultNS?d:String(e.ns??o.extract.defaultNS??"translation");p.has(t)||p.set(t,[]),p.get(t).push(e)}const g=[],y=Array.isArray(o.extract.ignore)?o.extract.ignore:o.extract.ignore?[o.extract.ignore]:[];for(const s of o.locales){if(o.extract.mergeNamespaces||"string"==typeof o.extract.output&&!o.extract.output.includes("{{namespace}}")){const t={},r=n.getOutputPath(o.extract.output,s),c=e.resolve(process.cwd(),r),y=await n.loadTranslationFile(c)||{},h=Object.keys(y),x=h.some(e=>{const t=y[e];return"object"==typeof t&&null!==t&&!Array.isArray(t)})?new Set([...p.keys(),...h]):new Set([...p.keys(),d]);for(const e of x){const n=p.get(e)||[];if(e===d){const e=l(n,y,o,s,void 0,f,a,i);Object.assign(t,e)}else{const r=y[e]||{};t[e]=l(n,r,o,s,e,f,a,i)}}const m=JSON.stringify(y,null,u),v=JSON.stringify(t,null,u);g.push({path:c,updated:v!==m,newTranslations:t,existingTranslations:y})}else{const r=new Set(p.keys()),c=n.getOutputPath(o.extract.output,s,"*").replace(/\\/g,"/"),d=await t.glob(c,{ignore:y});for(const t of d)r.add(e.basename(t,e.extname(t)));for(const t of r){const r=p.get(t)||[],c=n.getOutputPath(o.extract.output,s,t),d=e.resolve(process.cwd(),c),y=await n.loadTranslationFile(d)||{},h=l(r,y,o,s,t,f,a,i),x=JSON.stringify(y,null,u),m=JSON.stringify(h,null,u);g.push({path:d,updated:m!==x,newTranslations:h,existingTranslations:y})}}}return g};
1
+ "use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),n=require("../../utils/file-utils.js"),r=require("../../utils/default-value.js");function a(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function o(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const s={},n=t?.extract?.pluralSeparator??"_",r=["zero","one","two","few","many","other"],a=r.map(e=>`ordinal${n}${e}`),l=Object.keys(e).sort((e,t)=>{const s=e=>{for(const t of a)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of r)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},o=s(e),l=s(t);if(o.isPlural&&l.isPlural){const e=o.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(o.isOrdinal!==l.isOrdinal)return o.isOrdinal?1:-1;const t=o.isOrdinal?a:r,s=t.indexOf(o.form),n=t.indexOf(l.form);return-1!==s&&-1!==n?s-n:o.form.localeCompare(l.form)}const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t,void 0,{sensitivity:"case"}):i});for(const n of l)s[n]=o(e[n],t);return s}function l(e,t,n,a,l,i=[],c=new Set,u=!1){const{keySeparator:f=".",sort:d=!0,removeUnusedKeys:p=!0,primaryLanguage:g,defaultValue:y="",pluralSeparator:h="_",contextSeparator:x="_"}=n.extract,m=new Set;let O=[],v=[];try{const e=new Intl.PluralRules(a,{type:"cardinal"}),t=new Intl.PluralRules(a,{type:"ordinal"});O=e.resolvedOptions().pluralCategories,v=t.resolvedOptions().pluralCategories,O.forEach(e=>m.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>m.add(`ordinal_${e}`))}catch(e){const t=g||"en",s=new Intl.PluralRules(t,{type:"cardinal"}),n=new Intl.PluralRules(t,{type:"ordinal"});O=s.resolvedOptions().pluralCategories,v=n.resolvedOptions().pluralCategories,O.forEach(e=>m.add(e)),n.resolvedOptions().pluralCategories.forEach(e=>m.add(`ordinal_${e}`))}const S=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if(i.some(t=>t.test(e)))return!1;if(!t)return!0;const n=e.split(h);if(t&&1===n.length)return!0;if(1===O.length&&"other"===O[0]&&1===n.length)return!0;if(s&&n.includes("ordinal")){const e=n[n.length-1];return m.has(`ordinal_${e}`)}if(t){const e=n[n.length-1];return m.has(e)}return!0}),N=new Set;for(const e of S)if(e.isExpandedPlural){const t=String(e.key).split(h);t.length>=3&&"ordinal"===t[t.length-2]?N.add(t.slice(0,-2).join(h)):N.add(t.slice(0,-1).join(h))}let $=p?{}:JSON.parse(JSON.stringify(t));const w=s.getNestedKeys(t,f??".");for(const e of w)if(i.some(t=>t.test(e))){const n=s.getNestedValue(t,e,f??".");s.setNestedValue($,e,n,f??".")}if(p){const e=s.getNestedKeys(t,f??".");for(const n of e){const e=n.split(h);if("zero"===e[e.length-1]){const r=e.slice(0,-1).join(h);if(S.some(({key:e})=>e.split(h).slice(0,-1).join(h)===r)){const e=s.getNestedValue(t,n,f??".");s.setNestedValue($,n,e,f??".")}}}}for(const{key:e,defaultValue:o,explicitDefault:i,hasCount:d,isExpandedPlural:p,isOrdinal:m}of S){if(d&&!p){const t=String(e).split(h);let s=e;if(t.length>=3&&"ordinal"===t[t.length-2]?s=t.slice(0,-2).join(h):t.length>=2&&(s=t.slice(0,-1).join(h)),N.has(s))continue}if(d&&!p){if(1===String(e).split(h).length&&a!==g){const i=e;if(N.has(i));else{const e=m?v:O;for(const c of e){const e=m?`${i}${h}ordinal${h}${c}`:`${i}${h}${c}`,u=s.getNestedValue(t,e,f??".");if(void 0===u){let t;t="string"==typeof o?o:r.resolveDefaultValue(y,String(i),l||n?.extract?.defaultNS||"translation",a,o),s.setNestedValue($,e,t,f??".")}else s.setNestedValue($,e,u,f??".")}}continue}}const w=s.getNestedValue(t,e,f??"."),b=!1===f||!S.some(t=>t.key!==e&&t.key.startsWith(`${e}${f}`)),j="object"==typeof w&&null!==w&&(c.has(e)||!o||o===e),P="object"==typeof w&&null!==w&&b&&!c.has(e)&&!j;if(j){s.setNestedValue($,e,w,f??".");continue}let k;if(void 0===w||P)if(a===g)if(u){const t=o&&(o===e||e!==o&&(e.startsWith(o+h)||e.startsWith(o+x)));k=o&&!t?o:r.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",a,o)}else k=o||e;else k=r.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",a,o);else if(a===g&&u){const t=o&&(o===e||e!==o&&(e.startsWith(o+h)||e.startsWith(o+x)));k=(e.includes(h)||e.includes(x))&&!i?w:o&&!t?o:w}else k=w;s.setNestedValue($,e,k,f??".")}if(!0===d)return o($,n);if("function"==typeof d){const e={},t=Object.keys($),s=new Map;for(const e of S){const t=!1===f?e.key:e.key.split(f)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof d){const n=s.get(e),r=s.get(t);if(n&&r)return d(n,r)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=o($[s],n);$=e}return $}exports.getTranslations=async function(s,r,o,{syncPrimaryWithDefaults:i=!1}={}){o.extract.primaryLanguage||=o.locales[0]||"en",o.extract.secondaryLanguages||=o.locales.filter(e=>e!==o?.extract?.primaryLanguage);const c=[...o.extract.preservePatterns||[]],u=o.extract.indentation??2;for(const e of r)c.push(`${e}.*`);const f=c.map(a),d="__no_namespace__",p=new Map;for(const e of s.values()){const t=e.nsIsImplicit&&!1===o.extract.defaultNS?d:String(e.ns??o.extract.defaultNS??"translation");p.has(t)||p.set(t,[]),p.get(t).push(e)}const g=[],y=Array.isArray(o.extract.ignore)?o.extract.ignore:o.extract.ignore?[o.extract.ignore]:[];for(const s of o.locales){if(o.extract.mergeNamespaces||"string"==typeof o.extract.output&&!o.extract.output.includes("{{namespace}}")){const t={},a=n.getOutputPath(o.extract.output,s),c=e.resolve(process.cwd(),a),y=await n.loadTranslationFile(c)||{},h=Object.keys(y),x=!1!==o.extract.defaultNS&&h.some(e=>{const t=y[e];return"object"==typeof t&&null!==t&&!Array.isArray(t)})?new Set([...p.keys(),...h]):new Set([...p.keys(),d]);for(const e of x){const n=p.get(e)||[];if(e===d){const e=l(n,y,o,s,void 0,f,r,i);Object.assign(t,e)}else{const a=y[e]||{};t[e]=l(n,a,o,s,e,f,r,i)}}const m=JSON.stringify(y,null,u),O=JSON.stringify(t,null,u);g.push({path:c,updated:O!==m,newTranslations:t,existingTranslations:y})}else{const a=new Set(p.keys()),c=n.getOutputPath(o.extract.output,s,"*").replace(/\\/g,"/"),d=await t.glob(c,{ignore:y});for(const t of d)a.add(e.basename(t,e.extname(t)));for(const t of a){const a=p.get(t)||[],c=n.getOutputPath(o.extract.output,s,t),d=e.resolve(process.cwd(),c),y=await n.loadTranslationFile(d)||{},h=l(a,y,o,s,t,f,r,i),x=JSON.stringify(y,null,u),m=JSON.stringify(h,null,u);g.push({path:d,updated:m!==x,newTranslations:h,existingTranslations:y})}}}return g};
@@ -1 +1 @@
1
- "use strict";exports.ExpressionResolver=class{hooks;symbolTable=new Map;constructor(e){this.hooks=e}captureVariableDeclarator(e){try{if(!e||!e.id||!e.init)return;if("Identifier"!==e.id.type)return;const s=e.id.value,t=e.init;if("ObjectExpression"===t.type&&Array.isArray(t.properties)){const e={};for(const s of t.properties){if(!s||"KeyValueProperty"!==s.type)continue;const t=s.key,r="Identifier"===t?.type||"StringLiteral"===t?.type?t.value:void 0;if(!r)continue;const i=s.value,o=this.resolvePossibleStringValuesFromExpression(i);1===o.length&&(e[r]=o[0])}if(Object.keys(e).length>0)return void this.symbolTable.set(s,e)}const r=this.resolvePossibleStringValuesFromExpression(t);r.length>0&&this.symbolTable.set(s,r)}catch{}}resolvePossibleContextStringValues(e){return[...this.hooks.resolvePossibleContextStringValues?.(e)??[],...this.resolvePossibleStringValuesFromExpression(e)]}resolvePossibleKeyStringValues(e){return[...this.hooks.resolvePossibleKeyStringValues?.(e)??[],...this.resolvePossibleStringValuesFromExpression(e)]}resolvePossibleStringValuesFromExpression(e,s=!1){if("StringLiteral"===e.type)return e.value||s?[e.value]:[];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValuesFromExpression(e.consequent,s),...this.resolvePossibleStringValuesFromExpression(e.alternate,s)]}if("Identifier"===e.type&&"undefined"===e.value)return[];if("TemplateLiteral"===e.type)return this.resolvePossibleStringValuesFromTemplateString(e);if("MemberExpression"===e.type)try{const s=e.object,t=e.property;if("Identifier"===s.type){const e=this.symbolTable.get(s.value);if(e&&"string"!=typeof e&&!Array.isArray(e)){let s;if("Identifier"===t.type?s=t.value:"Computed"===t.type&&"StringLiteral"===t.expression?.type&&(s=t.expression.value),s&&void 0!==e[s])return[e[s]]}}}catch{}if(e.left&&e.right)try{const t=this.resolvePossibleStringValuesFromExpression(e.left,s),r=this.resolvePossibleStringValuesFromExpression(e.right,s);if(t.length>0&&r.length>0){const e=[];for(const s of t)for(const t of r)e.push(`${s}${t}`);return e}}catch{}if("NumericLiteral"===e.type||"BooleanLiteral"===e.type)return[`${e.value}`];if("TsSatisfiesExpression"===e.type||"TsAsExpression"===e.type){const t=e.typeAnnotation;return this.resolvePossibleStringValuesFromType(t,s)}if("Identifier"===e.type){const s=this.symbolTable.get(e.value);return s&&Array.isArray(s)?s:[]}return[]}resolvePossibleStringValuesFromType(e,s=!1){if("TsUnionType"===e.type)return e.types.flatMap(e=>this.resolvePossibleStringValuesFromType(e,s));if("TsLiteralType"===e.type){if("StringLiteral"===e.literal.type)return e.literal.value||s?[e.literal.value]:[];if("TemplateLiteral"===e.literal.type)return this.resolvePossibleStringValuesFromTemplateLiteralType(e.literal);if("NumericLiteral"===e.literal.type||"BooleanLiteral"===e.literal.type)return[`${e.literal.value}`]}return[]}resolvePossibleStringValuesFromTemplateString(e){if(1===e.quasis.length&&0===e.expressions.length)return[e.quasis[0].cooked||""];const[s,...t]=e.quasis;return e.expressions.reduce((e,s,r)=>e.flatMap(e=>{const i=t[r]?.cooked??"";return this.resolvePossibleStringValuesFromExpression(s,!0).map(s=>`${e}${s}${i}`)}),[s.cooked??""])}resolvePossibleStringValuesFromTemplateLiteralType(e){if(1===e.quasis.length&&0===e.types.length)return[e.quasis[0].cooked||""];const[s,...t]=e.quasis;return e.types.reduce((e,s,r)=>e.flatMap(e=>{const i=t[r]?.cooked??"";return this.resolvePossibleStringValuesFromType(s,!0).map(s=>`${e}${s}${i}`)}),[s.cooked??""])}};
1
+ "use strict";exports.ExpressionResolver=class{hooks;symbolTable=new Map;constructor(e){this.hooks=e}captureVariableDeclarator(e){try{if(!e||!e.id||!e.init)return;if("Identifier"!==e.id.type)return;const t=e.id.value,r=e.init;if("ObjectExpression"===r.type&&Array.isArray(r.properties)){const e={};for(const t of r.properties){if(!t||"KeyValueProperty"!==t.type)continue;const r=t.key,s="Identifier"===r?.type||"StringLiteral"===r?.type?r.value:void 0;if(!s)continue;const i=t.value,o=this.resolvePossibleStringValuesFromExpression(i);1===o.length&&(e[s]=o[0])}if(Object.keys(e).length>0)return void this.symbolTable.set(t,e)}const s=this.resolvePossibleStringValuesFromExpression(r);s.length>0&&this.symbolTable.set(t,s)}catch{}}captureEnumDeclaration(e){try{if(!e||!e.id||!Array.isArray(e.members))return;const t="Identifier"===e.id.type?e.id.value:void 0;if(!t)return;const r={};for(const t of e.members){if(!t||!t.id)continue;const e=t.id,s="Identifier"===e.type||"StringLiteral"===e.type?e.value:void 0;if(!s)continue;const i=t.init??t.initializer;i&&"StringLiteral"===i.type&&(r[s]=i.value)}Object.keys(r).length>0&&this.symbolTable.set(t,r)}catch{}}resolvePossibleContextStringValues(e){return[...this.hooks.resolvePossibleContextStringValues?.(e)??[],...this.resolvePossibleStringValuesFromExpression(e)]}resolvePossibleKeyStringValues(e){return[...this.hooks.resolvePossibleKeyStringValues?.(e)??[],...this.resolvePossibleStringValuesFromExpression(e)]}resolvePossibleStringValuesFromExpression(e,t=!1){if("StringLiteral"===e.type)return e.value||t?[e.value]:[];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValuesFromExpression(e.consequent,t),...this.resolvePossibleStringValuesFromExpression(e.alternate,t)]}if("Identifier"===e.type&&"undefined"===e.value)return[];if("TemplateLiteral"===e.type)return this.resolvePossibleStringValuesFromTemplateString(e);if("MemberExpression"===e.type)try{const t=e.object,r=e.property;if("Identifier"===t.type){const e=this.symbolTable.get(t.value);if(e&&"string"!=typeof e&&!Array.isArray(e)){let t;if("Identifier"===r.type?t=r.value:"Computed"===r.type&&"StringLiteral"===r.expression?.type&&(t=r.expression.value),t&&void 0!==e[t])return[e[t]]}}}catch{}if(e.left&&e.right)try{const r=this.resolvePossibleStringValuesFromExpression(e.left,t),s=this.resolvePossibleStringValuesFromExpression(e.right,t);if(r.length>0&&s.length>0){const e=[];for(const t of r)for(const r of s)e.push(`${t}${r}`);return e}}catch{}if("NumericLiteral"===e.type||"BooleanLiteral"===e.type)return[`${e.value}`];if("TsSatisfiesExpression"===e.type||"TsAsExpression"===e.type){const r=e.typeAnnotation;return this.resolvePossibleStringValuesFromType(r,t)}if("Identifier"===e.type){const t=this.symbolTable.get(e.value);return t&&Array.isArray(t)?t:[]}return[]}resolvePossibleStringValuesFromType(e,t=!1){if("TsUnionType"===e.type)return e.types.flatMap(e=>this.resolvePossibleStringValuesFromType(e,t));if("TsLiteralType"===e.type){if("StringLiteral"===e.literal.type)return e.literal.value||t?[e.literal.value]:[];if("TemplateLiteral"===e.literal.type)return this.resolvePossibleStringValuesFromTemplateLiteralType(e.literal);if("NumericLiteral"===e.literal.type||"BooleanLiteral"===e.literal.type)return[`${e.literal.value}`]}return[]}resolvePossibleStringValuesFromTemplateString(e){if(1===e.quasis.length&&0===e.expressions.length)return[e.quasis[0].cooked||""];const[t,...r]=e.quasis;return e.expressions.reduce((e,t,s)=>e.flatMap(e=>{const i=r[s]?.cooked??"";return this.resolvePossibleStringValuesFromExpression(t,!0).map(t=>`${e}${t}${i}`)}),[t.cooked??""])}resolvePossibleStringValuesFromTemplateLiteralType(e){if(1===e.quasis.length&&0===e.types.length)return[e.quasis[0].cooked||""];const[t,...r]=e.quasis;return e.types.reduce((e,t,s)=>e.flatMap(e=>{const i=r[s]?.cooked??"";return this.resolvePossibleStringValuesFromType(t,!0).map(t=>`${e}${t}${i}`)}),[t.cooked??""])}};
package/dist/esm/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import{minimatch as i}from"minimatch";import n from"chalk";import{ensureConfig as a,loadConfig as r}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as s}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as f}from"./init.js";import{runLinterCli as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as u,runLocizeDownload as y,runLocizeMigrate as h}from"./locize.js";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.19.2"),w.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),w.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.").action(async t=>{try{const e=w.opts().config,n=await a(e),r=async()=>{const o=await s(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!o?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&o&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),o};if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.extract.input),e=x(n.extract.ignore),a=j(n.extract.output),c=[...e,...a].filter(Boolean),s=t.filter(t=>!c.some(o=>i(t,o,{dot:!0})));o.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),w.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(t,o)=>{const e=w.opts().config;let i=await r(e);if(!i){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),i=t}await g(i,{detail:t,namespace:o.namespace})}),w.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 t=>{const e=w.opts().config,n=await a(e),r=()=>l(n);if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.types?.input||[]),e=[...x(n.extract?.ignore)].filter(Boolean),a=t.filter(t=>!e.some(o=>i(t,o,{dot:!0})));o.watch(a,{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=w.opts().config,o=await a(t);await p(o)}),w.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await m(t)}),w.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(f),w.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 t=>{const e=w.opts().config,a=async()=>{let t=await r(e);if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=o}await d(t)};if(await a(),t.watch){console.log("\nWatching for changes...");const t=await r(e);if(t?.extract?.input){const e=await z(t.extract.input),n=[...x(t.extract.ignore),...j(t.extract.output)].filter(Boolean),r=e.filter(t=>!n.some(o=>i(t,o,{dot:!0})));o.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}}),w.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.").action(async t=>{const o=w.opts().config,e=await a(o);await u(e,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await y(e,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await h(e,t)}),w.parse(process.argv);const x=t=>Array.isArray(t)?t:t?[t]:[],j=t=>t&&"string"==typeof t?[t.replace(/\{\{[^}]+\}\}/g,"*")]:[],z=async(t=[])=>{const o=x(t),i=await Promise.all(o.map(t=>e(t||"",{nodir:!0})));return Array.from(new Set(i.flat()))};
2
+ import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import{minimatch as i}from"minimatch";import n from"chalk";import{ensureConfig as a,loadConfig as r}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as s}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as f}from"./init.js";import{runLinterCli as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as u,runLocizeDownload as y,runLocizeMigrate as h}from"./locize.js";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.20.0"),w.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),w.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.").action(async t=>{try{const e=w.opts().config,n=await a(e),r=async()=>{const o=await s(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!o?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&o&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),o};if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.extract.input),e=x(n.extract.ignore),a=j(n.extract.output),c=[...e,...a].filter(Boolean),s=t.filter(t=>!c.some(o=>i(t,o,{dot:!0})));o.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),w.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(t,o)=>{const e=w.opts().config;let i=await r(e);if(!i){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),i=t}await g(i,{detail:t,namespace:o.namespace})}),w.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 t=>{const e=w.opts().config,n=await a(e),r=()=>l(n);if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.types?.input||[]),e=[...x(n.extract?.ignore)].filter(Boolean),a=t.filter(t=>!e.some(o=>i(t,o,{dot:!0})));o.watch(a,{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=w.opts().config,o=await a(t);await p(o)}),w.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await m(t)}),w.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(f),w.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 t=>{const e=w.opts().config,a=async()=>{let t=await r(e);if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=o}await d(t)};if(await a(),t.watch){console.log("\nWatching for changes...");const t=await r(e);if(t?.extract?.input){const e=await z(t.extract.input),n=[...x(t.extract.ignore),...j(t.extract.output)].filter(Boolean),r=e.filter(t=>!n.some(o=>i(t,o,{dot:!0})));o.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}}),w.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.").action(async t=>{const o=w.opts().config,e=await a(o);await u(e,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await y(e,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await h(e,t)}),w.parse(process.argv);const x=t=>Array.isArray(t)?t:t?[t]:[],j=t=>t&&"string"==typeof t?[t.replace(/\{\{[^}]+\}\}/g,"*")]:[],z=async(t=[])=>{const o=x(t),i=await Promise.all(o.map(t=>e(t||"",{nodir:!0})));return Array.from(new Set(i.flat()))};
@@ -1 +1 @@
1
- import{ScopeManager as e}from"../parsers/scope-manager.js";import{ExpressionResolver as s}from"../parsers/expression-resolver.js";import{CallExpressionHandler as r}from"../parsers/call-expression-handler.js";import{JSXHandler as o}from"../parsers/jsx-handler.js";class a{pluginContext;config;logger;hooks;get objectKeys(){return this.callExpressionHandler.objectKeys}scopeManager;expressionResolver;callExpressionHandler;jsxHandler;constructor(a,t,i,n){this.pluginContext=t,this.config=a,this.logger=i,this.hooks={onBeforeVisitNode:n?.onBeforeVisitNode,onAfterVisitNode:n?.onAfterVisitNode,resolvePossibleKeyStringValues:n?.resolvePossibleKeyStringValues,resolvePossibleContextStringValues:n?.resolvePossibleContextStringValues},this.scopeManager=new e(a),this.expressionResolver=new s(this.hooks),this.callExpressionHandler=new r(a,t,i,this.expressionResolver),this.jsxHandler=new o(a,t,this.expressionResolver)}visit(e){this.scopeManager.reset(),this.scopeManager.enterScope(),this.walk(e),this.scopeManager.exitScope()}walk(e){if(!e)return;let s=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.scopeManager.enterScope(),s=!0),this.hooks.onBeforeVisitNode?.(e),e.type){case"VariableDeclarator":this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);break;case"CallExpression":this.callExpressionHandler.handleCallExpression(e,this.scopeManager.getVarFromScope.bind(this.scopeManager));break;case"JSXElement":this.jsxHandler.handleJSXElement(e,this.scopeManager.getVarFromScope.bind(this.scopeManager))}this.hooks.onAfterVisitNode?.(e);for(const s in e){if("span"===s)continue;const r=e[s];if(Array.isArray(r)){for(const e of r)if(e&&"object"==typeof e)if("VariableDeclarator"!==e.type){if("VariableDeclaration"===e.type&&Array.isArray(e.declarations))for(const s of e.declarations)s&&"object"==typeof s&&"VariableDeclarator"===s.type&&(this.scopeManager.handleVariableDeclarator(s),this.expressionResolver.captureVariableDeclarator(s))}else this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);for(const e of r)e&&"object"==typeof e&&this.walk(e)}else r&&"object"==typeof r&&this.walk(r)}s&&this.scopeManager.exitScope()}getVarFromScope(e){return this.scopeManager.getVarFromScope(e)}}export{a as ASTVisitors};
1
+ import{ScopeManager as e}from"../parsers/scope-manager.js";import{ExpressionResolver as s}from"../parsers/expression-resolver.js";import{CallExpressionHandler as r}from"../parsers/call-expression-handler.js";import{JSXHandler as o}from"../parsers/jsx-handler.js";class a{pluginContext;config;logger;hooks;get objectKeys(){return this.callExpressionHandler.objectKeys}scopeManager;expressionResolver;callExpressionHandler;jsxHandler;constructor(a,t,i,n,l){this.pluginContext=t,this.config=a,this.logger=i,this.hooks={onBeforeVisitNode:n?.onBeforeVisitNode,onAfterVisitNode:n?.onAfterVisitNode,resolvePossibleKeyStringValues:n?.resolvePossibleKeyStringValues,resolvePossibleContextStringValues:n?.resolvePossibleContextStringValues},this.scopeManager=new e(a),this.expressionResolver=l??new s(this.hooks),this.callExpressionHandler=new r(a,t,i,this.expressionResolver),this.jsxHandler=new o(a,t,this.expressionResolver)}visit(e){this.scopeManager.reset(),this.scopeManager.enterScope(),this.walk(e),this.scopeManager.exitScope()}walk(e){if(!e)return;let s=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.scopeManager.enterScope(),s=!0),this.hooks.onBeforeVisitNode?.(e),e.type){case"VariableDeclarator":this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);break;case"TSEnumDeclaration":case"TsEnumDeclaration":case"TsEnumDecl":this.expressionResolver.captureEnumDeclaration(e);break;case"CallExpression":this.callExpressionHandler.handleCallExpression(e,this.scopeManager.getVarFromScope.bind(this.scopeManager));break;case"JSXElement":this.jsxHandler.handleJSXElement(e,this.scopeManager.getVarFromScope.bind(this.scopeManager))}this.hooks.onAfterVisitNode?.(e);for(const s in e){if("span"===s)continue;const r=e[s];if(Array.isArray(r)){for(const e of r)if(e&&"object"==typeof e)if("VariableDeclarator"!==e.type){if(e&&e.id&&Array.isArray(e.members)&&this.expressionResolver.captureEnumDeclaration(e),"VariableDeclaration"===e.type&&Array.isArray(e.declarations))for(const s of e.declarations)s&&"object"==typeof s&&"VariableDeclarator"===s.type&&(this.scopeManager.handleVariableDeclarator(s),this.expressionResolver.captureVariableDeclarator(s))}else this.scopeManager.handleVariableDeclarator(e),this.expressionResolver.captureVariableDeclarator(e);for(const e of r)e&&"object"==typeof e&&this.walk(e)}else r&&"object"==typeof r&&this.walk(r)}s&&this.scopeManager.exitScope()}getVarFromScope(e){return this.scopeManager.getVarFromScope(e)}}export{a as ASTVisitors};
@@ -1 +1 @@
1
- import{glob as t}from"glob";import{processFile as r}from"./extractor.js";import{ConsoleLogger as e}from"../../utils/logger.js";import{createPluginContext as o,initializePlugins as n}from"../plugin-manager.js";import{ASTVisitors as a}from"./ast-visitors.js";async function s(s,i=new e){const{plugins:c,...l}=s,p=c||[],u=await async function(r){const e=["node_modules/**"],o=Array.isArray(r.extract.ignore)?r.extract.ignore:r.extract.ignore?[r.extract.ignore]:[];return await t(r.extract.input,{ignore:[...e,...o],cwd:process.cwd()})}(s),f=new Map,g=o(f,p,l,i),m={onBeforeVisitNode:t=>{for(const r of p)try{r.onVisitNode?.(t,g)}catch(t){i.warn(`Plugin ${r.name} onVisitNode failed:`,t)}},resolvePossibleKeyStringValues:t=>p.flatMap(r=>{try{return r.extractKeysFromExpression?.(t,s,i)??[]}catch(t){return i.warn(`Plugin ${r.name} extractKeysFromExpression failed:`,t),[]}}),resolvePossibleContextStringValues:t=>p.flatMap(r=>{try{return r.extractContextFromExpression?.(t,s,i)??[]}catch(t){return i.warn(`Plugin ${r.name} extractContextFromExpression failed:`,t),[]}})},x=new a(l,g,i,m);g.getVarFromScope=x.getVarFromScope.bind(x),await n(p);for(const t of u)await r(t,p,x,g,l,i);for(const t of p)await(t.onEnd?.(f));const d=l.extract?.pluralSeparator??"_",w=["zero","one","two","few","many","other"];for(const t of f.values()){const r=String(t.key).split(d),e=r[r.length-1],o=r.length>=3&&"ordinal"===r[r.length-2];(w.includes(e)||o&&w.includes(e))&&(t.isExpandedPlural=!0)}return{allKeys:f,objectKeys:x.objectKeys}}export{s as findKeys};
1
+ import{glob as r}from"glob";import{processFile as e}from"./extractor.js";import{ConsoleLogger as t}from"../../utils/logger.js";import{createPluginContext as o,initializePlugins as n}from"../plugin-manager.js";import{ASTVisitors as a}from"./ast-visitors.js";import{ExpressionResolver as s}from"../parsers/expression-resolver.js";async function i(i,c=new t){const{plugins:l,...p}=i,m=l||[],f=await async function(e){const t=["node_modules/**"],o=Array.isArray(e.extract.ignore)?e.extract.ignore:e.extract.ignore?[e.extract.ignore]:[];return await r(e.extract.input,{ignore:[...t,...o],cwd:process.cwd()})}(i),u=new Map,g=o(u,m,p,c),x={onBeforeVisitNode:r=>{for(const e of m)try{e.onVisitNode?.(r,g)}catch(r){c.warn(`Plugin ${e.name} onVisitNode failed:`,r)}},resolvePossibleKeyStringValues:r=>m.flatMap(e=>{try{return e.extractKeysFromExpression?.(r,i,c)??[]}catch(r){return c.warn(`Plugin ${e.name} extractKeysFromExpression failed:`,r),[]}}),resolvePossibleContextStringValues:r=>m.flatMap(e=>{try{return e.extractContextFromExpression?.(r,i,c)??[]}catch(r){return c.warn(`Plugin ${e.name} extractContextFromExpression failed:`,r),[]}})},d=new s(x),w=new a(p,g,c,x,d);g.getVarFromScope=w.getVarFromScope.bind(w),await n(m);for(const r of f)await e(r,m,w,g,p,c);for(const r of m)await(r.onEnd?.(u));const y=p.extract?.pluralSeparator??"_",h=["zero","one","two","few","many","other"];for(const r of u.values()){const e=String(r.key).split(y),t=e[e.length-1],o=e.length>=3&&"ordinal"===e[e.length-2];(h.includes(t)||o&&h.includes(t))&&(r.isExpandedPlural=!0)}return{allKeys:u,objectKeys:w.objectKeys}}export{i as findKeys};
@@ -1 +1 @@
1
- import{resolve as e,basename as t,extname as n}from"node:path";import{glob as s}from"glob";import{getNestedKeys as r,getNestedValue as o,setNestedValue as a}from"../../utils/nested-object.js";import{getOutputPath as i,loadTranslationFile as l}from"../../utils/file-utils.js";import{resolveDefaultValue as c}from"../../utils/default-value.js";function f(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function u(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const n={},s=t?.extract?.pluralSeparator??"_",r=["zero","one","two","few","many","other"],o=r.map(e=>`ordinal${s}${e}`),a=Object.keys(e).sort((e,t)=>{const n=e=>{for(const t of o)if(e.endsWith(`${s}${t}`)){return{base:e.slice(0,-(s.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of r)if(e.endsWith(`${s}${t}`)){return{base:e.slice(0,-(s.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},a=n(e),i=n(t);if(a.isPlural&&i.isPlural){const e=a.base.localeCompare(i.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(a.isOrdinal!==i.isOrdinal)return a.isOrdinal?1:-1;const t=a.isOrdinal?o:r,n=t.indexOf(a.form),s=t.indexOf(i.form);return-1!==n&&-1!==s?n-s:a.form.localeCompare(i.form)}const l=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===l?e.localeCompare(t,void 0,{sensitivity:"case"}):l});for(const s of a)n[s]=u(e[s],t);return n}function p(e,t,n,s,i,l=[],f=new Set,p=!1){const{keySeparator:d=".",sort:g=!0,removeUnusedKeys:y=!0,primaryLanguage:h,defaultValue:m="",pluralSeparator:x="_",contextSeparator:S="_"}=n.extract,O=(...e)=>{console.log("[i18next-debug]",...e)};O("buildNewTranslationsForNs start",{locale:s,namespace:i,keySeparator:d,pluralSeparator:x,primaryLanguage:h}),O("nsKeys (count):",e.length);try{O("existingTranslations keys:",r(t,d??".").slice(0,50))}catch(e){O("could not list existing keys",e)}const v=new Set;let w=[],k=[];try{const e=new Intl.PluralRules(s,{type:"cardinal"}),t=new Intl.PluralRules(s,{type:"ordinal"});w=e.resolvedOptions().pluralCategories,k=t.resolvedOptions().pluralCategories,w.forEach(e=>v.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}catch(e){const t=h||"en",n=new Intl.PluralRules(t,{type:"cardinal"}),s=new Intl.PluralRules(t,{type:"ordinal"});w=n.resolvedOptions().pluralCategories,k=s.resolvedOptions().pluralCategories,w.forEach(e=>v.add(e)),s.resolvedOptions().pluralCategories.forEach(e=>v.add(`ordinal_${e}`))}const $=e.filter(({key:e,hasCount:t,isOrdinal:n})=>{if(l.some(t=>t.test(e)))return!1;if(!t)return!0;const s=e.split(x);if(t&&1===s.length)return!0;if(1===w.length&&"other"===w[0]&&1===s.length)return!0;if(n&&s.includes("ordinal")){const e=s[s.length-1];return v.has(`ordinal_${e}`)}if(t){const e=s[s.length-1];return v.has(e)}return!0}),b=new Set;for(const e of $)if(e.isExpandedPlural){const t=String(e.key).split(x);t.length>=3&&"ordinal"===t[t.length-2]?b.add(t.slice(0,-2).join(x)):b.add(t.slice(0,-1).join(x))}let j=y?{}:JSON.parse(JSON.stringify(t));const N=r(t,d??".");for(const e of N)if(l.some(t=>t.test(e))){const n=o(t,e,d??".");a(j,e,n,d??".")}if(y){const e=r(t,d??".");for(const n of e){const e=n.split(x);if("zero"===e[e.length-1]){const s=e.slice(0,-1).join(x);if($.some(({key:e})=>e.split(x).slice(0,-1).join(x)===s)){const e=o(t,n,d??".");a(j,n,e,d??".")}}}}for(const{key:e,defaultValue:r,explicitDefault:l,hasCount:u,isExpandedPlural:g,isOrdinal:y}of $){if(u&&!g){const t=String(e).split(x);let n=e;if(t.length>=3&&"ordinal"===t[t.length-2]?n=t.slice(0,-2).join(x):t.length>=2&&(n=t.slice(0,-1).join(x)),b.has(n))continue}if(u&&!g){if(1===String(e).split(x).length&&s!==h){const l=e;if(b.has(l));else{const e=y?k:w;for(const f of e){const e=y?`${l}${x}ordinal${x}${f}`:`${l}${x}${f}`,u=o(t,e,d??".");if(void 0===u){let t;t="string"==typeof r?r:c(m,String(l),i||n?.extract?.defaultNS||"translation",s,r),O("expanding plural variant",{finalKey:e,existingVariantValue:u,resolvedValue:t}),a(j,e,t,d??".")}else O("keeping existing plural variant",{finalKey:e,existingVariantValue:u}),a(j,e,u,d??".")}}continue}}const v=o(t,e,d??"."),N=!1===d||!$.some(t=>t.key!==e&&t.key.startsWith(`${e}${d}`)),P="object"==typeof v&&null!==v&&(f.has(e)||!r||r===e),C="object"==typeof v&&null!==v&&N&&!f.has(e)&&!P;if(O("processing key",{key:e,existingValueType:typeof v,isLeafInNewKeys:N,shouldPreserveObject:P,isStaleObject:C,defaultValue:r}),P){a(j,e,v,d??".");continue}let V;if(void 0===v||C)if(s===h)if(p){const t=r&&(r===e||e!==r&&(e.startsWith(r+x)||e.startsWith(r+S)));V=r&&!t?r:c(m,e,i||n?.extract?.defaultNS||"translation",s,r)}else V=r||e;else V=c(m,e,i||n?.extract?.defaultNS||"translation",s,r);else if(s===h&&p){const t=r&&(r===e||e!==r&&(e.startsWith(r+x)||e.startsWith(r+S)));V=(e.includes(x)||e.includes(S))&&!l?v:r&&!t?r:v}else V=v;O("final decision for key",{key:e,existingValue:v,valueToSet:V,typeofExisting:typeof v,typeofValueToSet:typeof V}),a(j,e,V,d??".")}if(!0===g)return u(j,n);if("function"==typeof g){const e={},t=Object.keys(j),s=new Map;for(const e of $){const t=!1===d?e.key:e.key.split(d)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof g){const n=s.get(e),r=s.get(t);if(n&&r)return g(n,r)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=u(j[s],n);j=e}return j}async function d(r,o,a,{syncPrimaryWithDefaults:c=!1}={}){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(e=>e!==a?.extract?.primaryLanguage);const u=[...a.extract.preservePatterns||[]],d=a.extract.indentation??2;for(const e of o)u.push(`${e}.*`);const g=u.map(f),y="__no_namespace__",h=new Map;for(const e of r.values()){const t=e.nsIsImplicit&&!1===a.extract.defaultNS?y:String(e.ns??a.extract.defaultNS??"translation");h.has(t)||h.set(t,[]),h.get(t).push(e)}const m=[],x=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const r of a.locales){if(a.extract.mergeNamespaces||"string"==typeof a.extract.output&&!a.extract.output.includes("{{namespace}}")){const t={},n=i(a.extract.output,r),s=e(process.cwd(),n),f=await l(s)||{},u=Object.keys(f),x=u.some(e=>{const t=f[e];return"object"==typeof t&&null!==t&&!Array.isArray(t)})?new Set([...h.keys(),...u]):new Set([...h.keys(),y]);for(const e of x){const n=h.get(e)||[];if(e===y){const e=p(n,f,a,r,void 0,g,o,c);Object.assign(t,e)}else{const s=f[e]||{};t[e]=p(n,s,a,r,e,g,o,c)}}const S=JSON.stringify(f,null,d),O=JSON.stringify(t,null,d);m.push({path:s,updated:O!==S,newTranslations:t,existingTranslations:f})}else{const f=new Set(h.keys()),u=i(a.extract.output,r,"*").replace(/\\/g,"/"),y=await s(u,{ignore:x});for(const e of y)f.add(t(e,n(e)));for(const t of f){const n=h.get(t)||[],s=i(a.extract.output,r,t),f=e(process.cwd(),s),u=await l(f)||{},y=p(n,u,a,r,t,g,o,c),x=JSON.stringify(u,null,d),S=JSON.stringify(y,null,d);m.push({path:f,updated:S!==x,newTranslations:y,existingTranslations:u})}}}return m}export{d as getTranslations};
1
+ import{resolve as t,basename as e,extname as n}from"node:path";import{glob as r}from"glob";import{getNestedKeys as s,getNestedValue as o,setNestedValue as a}from"../../utils/nested-object.js";import{getOutputPath as i,loadTranslationFile as l}from"../../utils/file-utils.js";import{resolveDefaultValue as c}from"../../utils/default-value.js";function f(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}function u(t,e){if("object"!=typeof t||null===t||Array.isArray(t))return t;const n={},r=e?.extract?.pluralSeparator??"_",s=["zero","one","two","few","many","other"],o=s.map(t=>`ordinal${r}${t}`),a=Object.keys(t).sort((t,e)=>{const n=t=>{for(const e of o)if(t.endsWith(`${r}${e}`)){return{base:t.slice(0,-(r.length+e.length)),form:e,isOrdinal:!0,isPlural:!0,fullKey:t}}for(const e of s)if(t.endsWith(`${r}${e}`)){return{base:t.slice(0,-(r.length+e.length)),form:e,isOrdinal:!1,isPlural:!0,fullKey:t}}return{base:t,form:"",isOrdinal:!1,isPlural:!1,fullKey:t}},a=n(t),i=n(e);if(a.isPlural&&i.isPlural){const t=a.base.localeCompare(i.base,void 0,{sensitivity:"base"});if(0!==t)return t;if(a.isOrdinal!==i.isOrdinal)return a.isOrdinal?1:-1;const e=a.isOrdinal?o:s,n=e.indexOf(a.form),r=e.indexOf(i.form);return-1!==n&&-1!==r?n-r:a.form.localeCompare(i.form)}const l=t.localeCompare(e,void 0,{sensitivity:"base"});return 0===l?t.localeCompare(e,void 0,{sensitivity:"case"}):l});for(const r of a)n[r]=u(t[r],e);return n}function p(t,e,n,r,i,l=[],f=new Set,p=!1){const{keySeparator:d=".",sort:g=!0,removeUnusedKeys:y=!0,primaryLanguage:h,defaultValue:m="",pluralSeparator:x="_",contextSeparator:O="_"}=n.extract,S=new Set;let $=[],w=[];try{const t=new Intl.PluralRules(r,{type:"cardinal"}),e=new Intl.PluralRules(r,{type:"ordinal"});$=t.resolvedOptions().pluralCategories,w=e.resolvedOptions().pluralCategories,$.forEach(t=>S.add(t)),e.resolvedOptions().pluralCategories.forEach(t=>S.add(`ordinal_${t}`))}catch(t){const e=h||"en",n=new Intl.PluralRules(e,{type:"cardinal"}),r=new Intl.PluralRules(e,{type:"ordinal"});$=n.resolvedOptions().pluralCategories,w=r.resolvedOptions().pluralCategories,$.forEach(t=>S.add(t)),r.resolvedOptions().pluralCategories.forEach(t=>S.add(`ordinal_${t}`))}const v=t.filter(({key:t,hasCount:e,isOrdinal:n})=>{if(l.some(e=>e.test(t)))return!1;if(!e)return!0;const r=t.split(x);if(e&&1===r.length)return!0;if(1===$.length&&"other"===$[0]&&1===r.length)return!0;if(n&&r.includes("ordinal")){const t=r[r.length-1];return S.has(`ordinal_${t}`)}if(e){const t=r[r.length-1];return S.has(t)}return!0}),b=new Set;for(const t of v)if(t.isExpandedPlural){const e=String(t.key).split(x);e.length>=3&&"ordinal"===e[e.length-2]?b.add(e.slice(0,-2).join(x)):b.add(e.slice(0,-1).join(x))}let j=y?{}:JSON.parse(JSON.stringify(e));const k=s(e,d??".");for(const t of k)if(l.some(e=>e.test(t))){const n=o(e,t,d??".");a(j,t,n,d??".")}if(y){const t=s(e,d??".");for(const n of t){const t=n.split(x);if("zero"===t[t.length-1]){const r=t.slice(0,-1).join(x);if(v.some(({key:t})=>t.split(x).slice(0,-1).join(x)===r)){const t=o(e,n,d??".");a(j,n,t,d??".")}}}}for(const{key:t,defaultValue:s,explicitDefault:l,hasCount:u,isExpandedPlural:g,isOrdinal:y}of v){if(u&&!g){const e=String(t).split(x);let n=t;if(e.length>=3&&"ordinal"===e[e.length-2]?n=e.slice(0,-2).join(x):e.length>=2&&(n=e.slice(0,-1).join(x)),b.has(n))continue}if(u&&!g){if(1===String(t).split(x).length&&r!==h){const l=t;if(b.has(l));else{const t=y?w:$;for(const f of t){const t=y?`${l}${x}ordinal${x}${f}`:`${l}${x}${f}`,u=o(e,t,d??".");if(void 0===u){let e;e="string"==typeof s?s:c(m,String(l),i||n?.extract?.defaultNS||"translation",r,s),a(j,t,e,d??".")}else a(j,t,u,d??".")}}continue}}const S=o(e,t,d??"."),k=!1===d||!v.some(e=>e.key!==t&&e.key.startsWith(`${t}${d}`)),C="object"==typeof S&&null!==S&&(f.has(t)||!s||s===t),N="object"==typeof S&&null!==S&&k&&!f.has(t)&&!C;if(C){a(j,t,S,d??".");continue}let P;if(void 0===S||N)if(r===h)if(p){const e=s&&(s===t||t!==s&&(t.startsWith(s+x)||t.startsWith(s+O)));P=s&&!e?s:c(m,t,i||n?.extract?.defaultNS||"translation",r,s)}else P=s||t;else P=c(m,t,i||n?.extract?.defaultNS||"translation",r,s);else if(r===h&&p){const e=s&&(s===t||t!==s&&(t.startsWith(s+x)||t.startsWith(s+O)));P=(t.includes(x)||t.includes(O))&&!l?S:s&&!e?s:S}else P=S;a(j,t,P,d??".")}if(!0===g)return u(j,n);if("function"==typeof g){const t={},e=Object.keys(j),r=new Map;for(const t of v){const e=!1===d?t.key:t.key.split(d)[0];r.has(e)||r.set(e,t)}e.sort((t,e)=>{if("function"==typeof g){const n=r.get(t),s=r.get(e);if(n&&s)return g(n,s)}return t.localeCompare(e,void 0,{sensitivity:"base"})});for(const r of e)t[r]=u(j[r],n);j=t}return j}async function d(s,o,a,{syncPrimaryWithDefaults:c=!1}={}){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(t=>t!==a?.extract?.primaryLanguage);const u=[...a.extract.preservePatterns||[]],d=a.extract.indentation??2;for(const t of o)u.push(`${t}.*`);const g=u.map(f),y="__no_namespace__",h=new Map;for(const t of s.values()){const e=t.nsIsImplicit&&!1===a.extract.defaultNS?y:String(t.ns??a.extract.defaultNS??"translation");h.has(e)||h.set(e,[]),h.get(e).push(t)}const m=[],x=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const s of a.locales){if(a.extract.mergeNamespaces||"string"==typeof a.extract.output&&!a.extract.output.includes("{{namespace}}")){const e={},n=i(a.extract.output,s),r=t(process.cwd(),n),f=await l(r)||{},u=Object.keys(f),x=!1!==a.extract.defaultNS&&u.some(t=>{const e=f[t];return"object"==typeof e&&null!==e&&!Array.isArray(e)})?new Set([...h.keys(),...u]):new Set([...h.keys(),y]);for(const t of x){const n=h.get(t)||[];if(t===y){const t=p(n,f,a,s,void 0,g,o,c);Object.assign(e,t)}else{const r=f[t]||{};e[t]=p(n,r,a,s,t,g,o,c)}}const O=JSON.stringify(f,null,d),S=JSON.stringify(e,null,d);m.push({path:r,updated:S!==O,newTranslations:e,existingTranslations:f})}else{const f=new Set(h.keys()),u=i(a.extract.output,s,"*").replace(/\\/g,"/"),y=await r(u,{ignore:x});for(const t of y)f.add(e(t,n(t)));for(const e of f){const n=h.get(e)||[],r=i(a.extract.output,s,e),f=t(process.cwd(),r),u=await l(f)||{},y=p(n,u,a,s,e,g,o,c),x=JSON.stringify(u,null,d),O=JSON.stringify(y,null,d);m.push({path:f,updated:O!==x,newTranslations:y,existingTranslations:u})}}}return m}export{d as getTranslations};
@@ -1 +1 @@
1
- class e{hooks;symbolTable=new Map;constructor(e){this.hooks=e}captureVariableDeclarator(e){try{if(!e||!e.id||!e.init)return;if("Identifier"!==e.id.type)return;const s=e.id.value,t=e.init;if("ObjectExpression"===t.type&&Array.isArray(t.properties)){const e={};for(const s of t.properties){if(!s||"KeyValueProperty"!==s.type)continue;const t=s.key,r="Identifier"===t?.type||"StringLiteral"===t?.type?t.value:void 0;if(!r)continue;const i=s.value,o=this.resolvePossibleStringValuesFromExpression(i);1===o.length&&(e[r]=o[0])}if(Object.keys(e).length>0)return void this.symbolTable.set(s,e)}const r=this.resolvePossibleStringValuesFromExpression(t);r.length>0&&this.symbolTable.set(s,r)}catch{}}resolvePossibleContextStringValues(e){return[...this.hooks.resolvePossibleContextStringValues?.(e)??[],...this.resolvePossibleStringValuesFromExpression(e)]}resolvePossibleKeyStringValues(e){return[...this.hooks.resolvePossibleKeyStringValues?.(e)??[],...this.resolvePossibleStringValuesFromExpression(e)]}resolvePossibleStringValuesFromExpression(e,s=!1){if("StringLiteral"===e.type)return e.value||s?[e.value]:[];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValuesFromExpression(e.consequent,s),...this.resolvePossibleStringValuesFromExpression(e.alternate,s)]}if("Identifier"===e.type&&"undefined"===e.value)return[];if("TemplateLiteral"===e.type)return this.resolvePossibleStringValuesFromTemplateString(e);if("MemberExpression"===e.type)try{const s=e.object,t=e.property;if("Identifier"===s.type){const e=this.symbolTable.get(s.value);if(e&&"string"!=typeof e&&!Array.isArray(e)){let s;if("Identifier"===t.type?s=t.value:"Computed"===t.type&&"StringLiteral"===t.expression?.type&&(s=t.expression.value),s&&void 0!==e[s])return[e[s]]}}}catch{}if(e.left&&e.right)try{const t=this.resolvePossibleStringValuesFromExpression(e.left,s),r=this.resolvePossibleStringValuesFromExpression(e.right,s);if(t.length>0&&r.length>0){const e=[];for(const s of t)for(const t of r)e.push(`${s}${t}`);return e}}catch{}if("NumericLiteral"===e.type||"BooleanLiteral"===e.type)return[`${e.value}`];if("TsSatisfiesExpression"===e.type||"TsAsExpression"===e.type){const t=e.typeAnnotation;return this.resolvePossibleStringValuesFromType(t,s)}if("Identifier"===e.type){const s=this.symbolTable.get(e.value);return s&&Array.isArray(s)?s:[]}return[]}resolvePossibleStringValuesFromType(e,s=!1){if("TsUnionType"===e.type)return e.types.flatMap(e=>this.resolvePossibleStringValuesFromType(e,s));if("TsLiteralType"===e.type){if("StringLiteral"===e.literal.type)return e.literal.value||s?[e.literal.value]:[];if("TemplateLiteral"===e.literal.type)return this.resolvePossibleStringValuesFromTemplateLiteralType(e.literal);if("NumericLiteral"===e.literal.type||"BooleanLiteral"===e.literal.type)return[`${e.literal.value}`]}return[]}resolvePossibleStringValuesFromTemplateString(e){if(1===e.quasis.length&&0===e.expressions.length)return[e.quasis[0].cooked||""];const[s,...t]=e.quasis;return e.expressions.reduce((e,s,r)=>e.flatMap(e=>{const i=t[r]?.cooked??"";return this.resolvePossibleStringValuesFromExpression(s,!0).map(s=>`${e}${s}${i}`)}),[s.cooked??""])}resolvePossibleStringValuesFromTemplateLiteralType(e){if(1===e.quasis.length&&0===e.types.length)return[e.quasis[0].cooked||""];const[s,...t]=e.quasis;return e.types.reduce((e,s,r)=>e.flatMap(e=>{const i=t[r]?.cooked??"";return this.resolvePossibleStringValuesFromType(s,!0).map(s=>`${e}${s}${i}`)}),[s.cooked??""])}}export{e as ExpressionResolver};
1
+ class e{hooks;symbolTable=new Map;constructor(e){this.hooks=e}captureVariableDeclarator(e){try{if(!e||!e.id||!e.init)return;if("Identifier"!==e.id.type)return;const t=e.id.value,r=e.init;if("ObjectExpression"===r.type&&Array.isArray(r.properties)){const e={};for(const t of r.properties){if(!t||"KeyValueProperty"!==t.type)continue;const r=t.key,s="Identifier"===r?.type||"StringLiteral"===r?.type?r.value:void 0;if(!s)continue;const i=t.value,o=this.resolvePossibleStringValuesFromExpression(i);1===o.length&&(e[s]=o[0])}if(Object.keys(e).length>0)return void this.symbolTable.set(t,e)}const s=this.resolvePossibleStringValuesFromExpression(r);s.length>0&&this.symbolTable.set(t,s)}catch{}}captureEnumDeclaration(e){try{if(!e||!e.id||!Array.isArray(e.members))return;const t="Identifier"===e.id.type?e.id.value:void 0;if(!t)return;const r={};for(const t of e.members){if(!t||!t.id)continue;const e=t.id,s="Identifier"===e.type||"StringLiteral"===e.type?e.value:void 0;if(!s)continue;const i=t.init??t.initializer;i&&"StringLiteral"===i.type&&(r[s]=i.value)}Object.keys(r).length>0&&this.symbolTable.set(t,r)}catch{}}resolvePossibleContextStringValues(e){return[...this.hooks.resolvePossibleContextStringValues?.(e)??[],...this.resolvePossibleStringValuesFromExpression(e)]}resolvePossibleKeyStringValues(e){return[...this.hooks.resolvePossibleKeyStringValues?.(e)??[],...this.resolvePossibleStringValuesFromExpression(e)]}resolvePossibleStringValuesFromExpression(e,t=!1){if("StringLiteral"===e.type)return e.value||t?[e.value]:[];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValuesFromExpression(e.consequent,t),...this.resolvePossibleStringValuesFromExpression(e.alternate,t)]}if("Identifier"===e.type&&"undefined"===e.value)return[];if("TemplateLiteral"===e.type)return this.resolvePossibleStringValuesFromTemplateString(e);if("MemberExpression"===e.type)try{const t=e.object,r=e.property;if("Identifier"===t.type){const e=this.symbolTable.get(t.value);if(e&&"string"!=typeof e&&!Array.isArray(e)){let t;if("Identifier"===r.type?t=r.value:"Computed"===r.type&&"StringLiteral"===r.expression?.type&&(t=r.expression.value),t&&void 0!==e[t])return[e[t]]}}}catch{}if(e.left&&e.right)try{const r=this.resolvePossibleStringValuesFromExpression(e.left,t),s=this.resolvePossibleStringValuesFromExpression(e.right,t);if(r.length>0&&s.length>0){const e=[];for(const t of r)for(const r of s)e.push(`${t}${r}`);return e}}catch{}if("NumericLiteral"===e.type||"BooleanLiteral"===e.type)return[`${e.value}`];if("TsSatisfiesExpression"===e.type||"TsAsExpression"===e.type){const r=e.typeAnnotation;return this.resolvePossibleStringValuesFromType(r,t)}if("Identifier"===e.type){const t=this.symbolTable.get(e.value);return t&&Array.isArray(t)?t:[]}return[]}resolvePossibleStringValuesFromType(e,t=!1){if("TsUnionType"===e.type)return e.types.flatMap(e=>this.resolvePossibleStringValuesFromType(e,t));if("TsLiteralType"===e.type){if("StringLiteral"===e.literal.type)return e.literal.value||t?[e.literal.value]:[];if("TemplateLiteral"===e.literal.type)return this.resolvePossibleStringValuesFromTemplateLiteralType(e.literal);if("NumericLiteral"===e.literal.type||"BooleanLiteral"===e.literal.type)return[`${e.literal.value}`]}return[]}resolvePossibleStringValuesFromTemplateString(e){if(1===e.quasis.length&&0===e.expressions.length)return[e.quasis[0].cooked||""];const[t,...r]=e.quasis;return e.expressions.reduce((e,t,s)=>e.flatMap(e=>{const i=r[s]?.cooked??"";return this.resolvePossibleStringValuesFromExpression(t,!0).map(t=>`${e}${t}${i}`)}),[t.cooked??""])}resolvePossibleStringValuesFromTemplateLiteralType(e){if(1===e.quasis.length&&0===e.types.length)return[e.quasis[0].cooked||""];const[t,...r]=e.quasis;return e.types.reduce((e,t,s)=>e.flatMap(e=>{const i=r[s]?.cooked??"";return this.resolvePossibleStringValuesFromType(t,!0).map(t=>`${e}${t}${i}`)}),[t.cooked??""])}}export{e as ExpressionResolver};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.19.2",
3
+ "version": "1.20.0",
4
4
  "description": "A unified, high-performance i18next CLI.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.ts CHANGED
@@ -22,7 +22,7 @@ const program = new Command()
22
22
  program
23
23
  .name('i18next-cli')
24
24
  .description('A unified, high-performance i18next CLI.')
25
- .version('1.19.2')
25
+ .version('1.20.0')
26
26
 
27
27
  // new: global config override option
28
28
  program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)')
@@ -53,7 +53,8 @@ export class ASTVisitors {
53
53
  config: Omit<I18nextToolkitConfig, 'plugins'>,
54
54
  pluginContext: PluginContext,
55
55
  logger: Logger,
56
- hooks?: ASTVisitorHooks
56
+ hooks?: ASTVisitorHooks,
57
+ expressionResolver?: ExpressionResolver
57
58
  ) {
58
59
  this.pluginContext = pluginContext
59
60
  this.config = config
@@ -66,7 +67,8 @@ export class ASTVisitors {
66
67
  }
67
68
 
68
69
  this.scopeManager = new ScopeManager(config)
69
- this.expressionResolver = new ExpressionResolver(this.hooks)
70
+ // use shared resolver when provided so captured enums/objects are visible across files
71
+ this.expressionResolver = expressionResolver ?? new ExpressionResolver(this.hooks)
70
72
  this.callExpressionHandler = new CallExpressionHandler(config, pluginContext, logger, this.expressionResolver)
71
73
  this.jsxHandler = new JSXHandler(config, pluginContext, this.expressionResolver)
72
74
  }
@@ -119,6 +121,12 @@ export class ASTVisitors {
119
121
  // resolve identifiers / member expressions that reference them.
120
122
  this.expressionResolver.captureVariableDeclarator(node)
121
123
  break
124
+ case 'TSEnumDeclaration':
125
+ case 'TsEnumDeclaration':
126
+ case 'TsEnumDecl':
127
+ // capture enums into resolver symbol table
128
+ this.expressionResolver.captureEnumDeclaration(node)
129
+ break
122
130
  case 'CallExpression':
123
131
  this.callExpressionHandler.handleCallExpression(node, this.scopeManager.getVarFromScope.bind(this.scopeManager))
124
132
  break
@@ -152,7 +160,11 @@ export class ASTVisitors {
152
160
  this.expressionResolver.captureVariableDeclarator(item)
153
161
  continue
154
162
  }
155
-
163
+ // enum declarations can appear as ExportDeclaration.declaration earlier; be permissive
164
+ if (item && item.id && Array.isArray(item.members)) {
165
+ this.expressionResolver.captureEnumDeclaration(item)
166
+ // continue to allow further traversal
167
+ }
156
168
  // Common case: VariableDeclaration which contains .declarations (VariableDeclarator[])
157
169
  if (item.type === 'VariableDeclaration' && Array.isArray(item.declarations)) {
158
170
  for (const decl of item.declarations) {
@@ -5,6 +5,7 @@ import { processFile } from './extractor'
5
5
  import { ConsoleLogger } from '../../utils/logger'
6
6
  import { initializePlugins, createPluginContext } from '../plugin-manager'
7
7
  import { ASTVisitors } from './ast-visitors'
8
+ import { ExpressionResolver } from '../parsers/expression-resolver'
8
9
 
9
10
  /**
10
11
  * Main function for finding translation keys across all source files in a project.
@@ -81,7 +82,9 @@ export async function findKeys (
81
82
  } satisfies ASTVisitorHooks
82
83
 
83
84
  // 3. Create the visitor instance, passing it the context.
84
- const astVisitors = new ASTVisitors(otherConfig, pluginContext, logger, hooks)
85
+ // Use a shared ExpressionResolver so captured enums/objects in one file are available when resolving MemberExpressions
86
+ const sharedExpressionResolver = new ExpressionResolver(hooks)
87
+ const astVisitors = new ASTVisitors(otherConfig, pluginContext, logger, hooks, sharedExpressionResolver)
85
88
 
86
89
  // 4. "Wire up" the visitor's scope method to the context.
87
90
  // This avoids a circular dependency while giving plugins access to the scope.
@@ -120,19 +120,6 @@ function buildNewTranslationsForNs (
120
120
  pluralSeparator = '_',
121
121
  contextSeparator = '_',
122
122
  } = config.extract
123
-
124
- // Debugging hook: enable detailed logs by setting environment variable
125
- // I18NEXT_DEBUG=1 when running tests (or local runs).
126
- const DEBUG = true
127
- const debugLog = (...args: any[]) => { if (DEBUG) console.log('[i18next-debug]', ...args) }
128
-
129
- if (DEBUG) {
130
- debugLog('buildNewTranslationsForNs start', { locale, namespace, keySeparator, pluralSeparator, primaryLanguage })
131
- debugLog('nsKeys (count):', nsKeys.length)
132
- // shallow snapshot of existingTranslations (avoid huge dumps)
133
- try { debugLog('existingTranslations keys:', getNestedKeys(existingTranslations, keySeparator ?? '.').slice(0, 50)) } catch (e) { debugLog('could not list existing keys', e) }
134
- }
135
-
136
123
  // Get the plural categories for the target language
137
124
  const targetLanguagePluralCategories = new Set<string>()
138
125
  // Track cardinal plural categories separately so we can special-case single-"other" languages
@@ -310,11 +297,8 @@ function buildNewTranslationsForNs (
310
297
  // Use resolveDefaultValue to compute a sensible default, providing namespace and locale context.
311
298
  resolvedValue = resolveDefaultValue(emptyDefaultValue, String(base), namespace || config?.extract?.defaultNS || 'translation', locale, defaultValue)
312
299
  }
313
- debugLog('expanding plural variant', { finalKey, existingVariantValue, resolvedValue })
314
-
315
300
  setNestedValue(newTranslations, finalKey, resolvedValue, keySeparator ?? '.')
316
301
  } else {
317
- debugLog('keeping existing plural variant', { finalKey, existingVariantValue })
318
302
  // Keep existing translation
319
303
  setNestedValue(newTranslations, finalKey, existingVariantValue, keySeparator ?? '.')
320
304
  }
@@ -341,10 +325,6 @@ function buildNewTranslationsForNs (
341
325
 
342
326
  const isStaleObject = typeof existingValue === 'object' && existingValue !== null && isLeafInNewKeys && !objectKeys.has(key) && !shouldPreserveObject
343
327
 
344
- if (DEBUG) {
345
- debugLog('processing key', { key, existingValueType: typeof existingValue, isLeafInNewKeys, shouldPreserveObject, isStaleObject, defaultValue })
346
- }
347
-
348
328
  // Special handling for existing objects that should be preserved
349
329
  if (shouldPreserveObject) {
350
330
  setNestedValue(newTranslations, key, existingValue, keySeparator ?? '.')
@@ -407,10 +387,6 @@ function buildNewTranslationsForNs (
407
387
  }
408
388
  }
409
389
 
410
- if (DEBUG) {
411
- debugLog('final decision for key', { key, existingValue, valueToSet, typeofExisting: typeof existingValue, typeofValueToSet: typeof valueToSet })
412
- }
413
-
414
390
  setNestedValue(newTranslations, key, valueToSet, keySeparator ?? '.')
415
391
  }
416
392
 
@@ -541,7 +517,12 @@ export async function getTranslations (
541
517
  // or is a flat mapping of translation keys -> values.
542
518
  // If it's flat (values are primitives), we must NOT treat each translation key as a namespace.
543
519
  const existingKeys = Object.keys(existingMergedFile)
544
- const existingIsNamespaced = existingKeys.some(k => {
520
+ // Treat the file as namespaced only when the user is using namespaces.
521
+ // If defaultNS === false the project stores translations at the top-level
522
+ // (possibly as nested objects when keySeparator is '.'), which should NOT
523
+ // be interpreted as "namespaced files". This avoids splitting a single
524
+ // merged translations file into artificial namespace buckets on re-extract.
525
+ const existingIsNamespaced = (config.extract.defaultNS !== false) && existingKeys.some(k => {
545
526
  const v = (existingMergedFile as any)[k]
546
527
  return typeof v === 'object' && v !== null && !Array.isArray(v)
547
528
  })
@@ -63,6 +63,34 @@ export class ExpressionResolver {
63
63
  }
64
64
  }
65
65
 
66
+ /**
67
+ * Capture a TypeScript enum declaration so members can be resolved later.
68
+ * Accepts SWC node shapes like `TsEnumDeclaration` / `TSEnumDeclaration`.
69
+ */
70
+ captureEnumDeclaration (node: any): void {
71
+ try {
72
+ if (!node || !node.id || !Array.isArray(node.members)) return
73
+ const name = node.id.type === 'Identifier' ? node.id.value : undefined
74
+ if (!name) return
75
+ const map: Record<string, string> = {}
76
+ for (const m of node.members) {
77
+ if (!m || !m.id) continue
78
+ const keyNode = m.id
79
+ const memberName = keyNode.type === 'Identifier' ? keyNode.value : keyNode.type === 'StringLiteral' ? keyNode.value : undefined
80
+ if (!memberName) continue
81
+ const init = (m as any).init ?? (m as any).initializer
82
+ if (init && init.type === 'StringLiteral') {
83
+ map[memberName] = init.value
84
+ }
85
+ }
86
+ if (Object.keys(map).length > 0) {
87
+ this.symbolTable.set(name, map)
88
+ }
89
+ } catch {
90
+ // noop
91
+ }
92
+ }
93
+
66
94
  /**
67
95
  * Resolves an expression to one or more possible context string values that can be
68
96
  * determined statically from the AST. This is a wrapper around the plugin hook
@@ -140,7 +168,9 @@ export class ExpressionResolver {
140
168
  let propName: string | undefined
141
169
  if (prop.type === 'Identifier') propName = prop.value
142
170
  else if (prop.type === 'Computed' && prop.expression?.type === 'StringLiteral') propName = prop.expression.value
143
- if (propName && base[propName] !== undefined) return [base[propName]]
171
+ if (propName && base[propName] !== undefined) {
172
+ return [base[propName]]
173
+ }
144
174
  }
145
175
  }
146
176
  } catch {}
@@ -1,5 +1,6 @@
1
1
  import type { Module } from '@swc/core';
2
2
  import type { PluginContext, I18nextToolkitConfig, Logger, ASTVisitorHooks, ScopeInfo } from '../../types';
3
+ import { ExpressionResolver } from '../parsers/expression-resolver';
3
4
  /**
4
5
  * AST visitor class that traverses JavaScript/TypeScript syntax trees to extract translation keys.
5
6
  *
@@ -39,7 +40,7 @@ export declare class ASTVisitors {
39
40
  * @param pluginContext - Context for adding discovered translation keys
40
41
  * @param logger - Logger for warnings and debug information
41
42
  */
42
- constructor(config: Omit<I18nextToolkitConfig, 'plugins'>, pluginContext: PluginContext, logger: Logger, hooks?: ASTVisitorHooks);
43
+ constructor(config: Omit<I18nextToolkitConfig, 'plugins'>, pluginContext: PluginContext, logger: Logger, hooks?: ASTVisitorHooks, expressionResolver?: ExpressionResolver);
43
44
  /**
44
45
  * Main entry point for AST traversal.
45
46
  * Creates a root scope and begins the recursive walk through the syntax tree.
@@ -1 +1 @@
1
- {"version":3,"file":"ast-visitors.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/ast-visitors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAQ,MAAM,WAAW,CAAA;AAC7C,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAM1G;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAe;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuC;IAC9D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,KAAK,CAAiB;IAE9B,IAAW,UAAU,gBAEpB;IAED,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAc;IAC3C,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAoB;IACvD,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAuB;IAC7D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAY;IAEvC;;;;;;OAMG;gBAED,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,SAAS,CAAC,EAC7C,aAAa,EAAE,aAAa,EAC5B,MAAM,EAAE,MAAM,EACd,KAAK,CAAC,EAAE,eAAe;IAkBzB;;;;;OAKG;IACI,KAAK,CAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAQjC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,IAAI;IAuFZ;;;;;;;;OAQG;IACI,eAAe,CAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS;CAG7D"}
1
+ {"version":3,"file":"ast-visitors.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/ast-visitors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAQ,MAAM,WAAW,CAAA;AAC7C,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,aAAa,CAAA;AAE1G,OAAO,EAAE,kBAAkB,EAAE,MAAM,gCAAgC,CAAA;AAInE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAe;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAuC;IAC9D,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,KAAK,CAAiB;IAE9B,IAAW,UAAU,gBAEpB;IAED,OAAO,CAAC,QAAQ,CAAC,YAAY,CAAc;IAC3C,OAAO,CAAC,QAAQ,CAAC,kBAAkB,CAAoB;IACvD,OAAO,CAAC,QAAQ,CAAC,qBAAqB,CAAuB;IAC7D,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAY;IAEvC;;;;;;OAMG;gBAED,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,SAAS,CAAC,EAC7C,aAAa,EAAE,aAAa,EAC5B,MAAM,EAAE,MAAM,EACd,KAAK,CAAC,EAAE,eAAe,EACvB,kBAAkB,CAAC,EAAE,kBAAkB;IAmBzC;;;;;OAKG;IACI,KAAK,CAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAQjC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,IAAI;IAiGZ;;;;;;;;OAQG;IACI,eAAe,CAAE,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,SAAS;CAG7D"}
@@ -1 +1 @@
1
- {"version":3,"file":"key-finder.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/key-finder.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,oBAAoB,EAAmB,MAAM,aAAa,CAAA;AAM9F;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAsB,QAAQ,CAC5B,MAAM,EAAE,oBAAoB,EAC5B,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC;IAAE,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAAC,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CAAE,CAAC,CA2E1E"}
1
+ {"version":3,"file":"key-finder.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/key-finder.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,EAAE,oBAAoB,EAAmB,MAAM,aAAa,CAAA;AAO9F;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAsB,QAAQ,CAC5B,MAAM,EAAE,oBAAoB,EAC5B,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC;IAAE,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,CAAC;IAAC,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,CAAA;CAAE,CAAC,CA6E1E"}
@@ -1 +1 @@
1
- {"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AA4cnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,EAC5B,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC9E,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA2G9B"}
1
+ {"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAobnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,EAC5B,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC9E,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAgH9B"}
@@ -15,6 +15,11 @@ export declare class ExpressionResolver {
15
15
  * @param node - VariableDeclarator-like node (has .id and .init)
16
16
  */
17
17
  captureVariableDeclarator(node: any): void;
18
+ /**
19
+ * Capture a TypeScript enum declaration so members can be resolved later.
20
+ * Accepts SWC node shapes like `TsEnumDeclaration` / `TSEnumDeclaration`.
21
+ */
22
+ captureEnumDeclaration(node: any): void;
18
23
  /**
19
24
  * Resolves an expression to one or more possible context string values that can be
20
25
  * determined statically from the AST. This is a wrapper around the plugin hook
@@ -1 +1 @@
1
- {"version":3,"file":"expression-resolver.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/expression-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAkD,MAAM,WAAW,CAAA;AAC3F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,KAAK,CAAiB;IAK9B,OAAO,CAAC,WAAW,CAA4D;gBAElE,KAAK,EAAE,eAAe;IAInC;;;;;;;;;OASG;IACH,yBAAyB,CAAE,IAAI,EAAE,GAAG,GAAG,IAAI;IAwC3C;;;;;;;OAOG;IACH,kCAAkC,CAAE,UAAU,EAAE,UAAU,GAAG,MAAM,EAAE;IAKrE;;;;;;;OAOG;IACH,8BAA8B,CAAE,UAAU,EAAE,UAAU,GAAG,MAAM,EAAE;IAKjE;;;;;;;;;;;;;;;;;;OAkBG;IACH,OAAO,CAAC,yCAAyC;IAgFjD,OAAO,CAAC,mCAAmC;IAwB3C;;;;;;OAMG;IACH,OAAO,CAAC,6CAA6C;IAyBrD;;;;;;OAMG;IACH,OAAO,CAAC,kDAAkD;CAwB3D"}
1
+ {"version":3,"file":"expression-resolver.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/expression-resolver.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAkD,MAAM,WAAW,CAAA;AAC3F,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,aAAa,CAAA;AAElD,qBAAa,kBAAkB;IAC7B,OAAO,CAAC,KAAK,CAAiB;IAK9B,OAAO,CAAC,WAAW,CAA4D;gBAElE,KAAK,EAAE,eAAe;IAInC;;;;;;;;;OASG;IACH,yBAAyB,CAAE,IAAI,EAAE,GAAG,GAAG,IAAI;IAwC3C;;;OAGG;IACH,sBAAsB,CAAE,IAAI,EAAE,GAAG,GAAG,IAAI;IAwBxC;;;;;;;OAOG;IACH,kCAAkC,CAAE,UAAU,EAAE,UAAU,GAAG,MAAM,EAAE;IAKrE;;;;;;;OAOG;IACH,8BAA8B,CAAE,UAAU,EAAE,UAAU,GAAG,MAAM,EAAE;IAKjE;;;;;;;;;;;;;;;;;;OAkBG;IACH,OAAO,CAAC,yCAAyC;IAkFjD,OAAO,CAAC,mCAAmC;IAwB3C;;;;;;OAMG;IACH,OAAO,CAAC,6CAA6C;IAyBrD;;;;;;OAMG;IACH,OAAO,CAAC,kDAAkD;CAwB3D"}