i18next-cli 1.20.2 → 1.20.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -5,6 +5,10 @@ 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.3](https://github.com/i18next/i18next-cli/compare/v1.20.2...v1.20.3) - 2025-11-04
9
+
10
+ - improve(linter): tolerate JSX/TSX in `.ts` files by retrying parse with TSX enabled and emitting a per-file error (no global crash). [#75](https://github.com/i18next/i18next-cli/issues/75)
11
+
8
12
  ## [1.20.2](https://github.com/i18next/i18next-cli/compare/v1.20.1...v1.20.2) - 2025-11-03
9
13
 
10
14
  - fix(extractor): prevent per-file variable leakage so unrelated variables in other files are not resolved as translation keys [#88](https://github.com/i18next/i18next-cli/issues/88)
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.20.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.3"),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("glob"),t=require("node:fs/promises"),r=require("@swc/core"),n=require("node:path"),s=require("node:events"),o=require("chalk"),i=require("ora");class a extends s.EventEmitter{config;constructor(e){super({captureRejections:!0}),this.config=e}wrapError(e){const t="Linter failed to run: ";if(e instanceof Error){if(e.message.startsWith(t))return e;const r=new Error(`${t}${e.message}`);return r.stack=e.stack,r}return new Error(`${t}${String(e)}`)}async run(){const{config:s}=this;try{this.emit("progress",{message:"Finding source files to analyze..."});const o=["node_modules/**"],i=Array.isArray(s.extract.ignore)?s.extract.ignore:s.extract.ignore?[s.extract.ignore]:[],a=await e.glob(s.extract.input,{ignore:[...o,...i]});this.emit("progress",{message:`Analyzing ${a.length} source files...`});let c=0;const l=new Map;for(const e of a){const o=await t.readFile(e,"utf-8"),i=n.extname(e).toLowerCase(),a=".ts"===i||".tsx"===i||".mts"===i||".cts"===i,f=".tsx"===i,p=u(await r.parse(o,{syntax:a?"typescript":"ecmascript",tsx:f,decorators:!0}),o,s);p.length>0&&(c+=p.length,l.set(e,p))}const f={success:0===c,message:c>0?`Linter found ${c} potential issues.`:"No issues found.",files:Object.fromEntries(l.entries())};return this.emit("done",f),f}catch(e){const t=this.wrapError(e);throw this.emit("error",t),t}}}const c=e=>/^(https|http|\/\/|^\/)/.test(e);function u(e,t,r){const n=[],s=[],o=e=>t.substring(0,e).split("\n").length,i=r.extract.transComponents||["Trans"],a=r.extract.ignoredTags||[],u=new Set([...i,"script","style","code",...a]),l=r.extract.ignoredAttributes||[],f=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...l]),p=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?p({name:e.opening.name}):null;const r=e=>{if(!e)return null;if("JSXIdentifier"===e.type&&(e.name||e.value))return e.name??e.value;if("Identifier"===e.type&&(e.name||e.value))return e.name??e.value;if("JSXMemberExpression"===e.type){const t=r(e.object),n=r(e.property);return t&&n?`${t}.${n}`:n??t}return e.name??e.value??e.property?.name??e.property?.value??null};return r(t)},g=e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r&&"object"==typeof r&&("JSXElement"===r.type||"JSXOpeningElement"===r.type||"JSXSelfClosingElement"===r.type)){const e=p(r);if(e&&u.has(e))return!0}}return!1},m=(e,t)=>{if(!e||"object"!=typeof e)return;const r=[...t,e];if("JSXText"===e.type){if(!g(r)){const t=e.value.trim();t&&t.length>1&&"..."!==t&&!c(t)&&isNaN(Number(t))&&!t.startsWith("{{")&&s.push(e)}}if("StringLiteral"===e.type){const t=r[r.length-2],n=g(r);if("JSXAttribute"===t?.type&&!f.has(t.name.value)&&!n){const t=e.value.trim();t&&"..."!==t&&!c(t)&&isNaN(Number(t))&&s.push(e)}}for(const t of Object.keys(e)){if("span"===t)continue;const n=e[t];Array.isArray(n)?n.forEach(e=>m(e,r)):n&&"object"==typeof n&&m(n,r)}};m(e,[]);let y=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,y);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),y=s+r.length)}return n}exports.Linter=a,exports.runLinter=async function(e){return new a(e).run()},exports.runLinterCli=async function(e){const t=new a(e),r=i().start();t.on("progress",e=>{r.text=e.message});try{const{success:e,message:n,files:s}=await t.run();if(e)r.succeed(o.green.bold(n));else{r.fail(o.red.bold(n));for(const[e,t]of Object.entries(s))console.log(o.yellow(`\n${e}`)),t.forEach(({text:e,line:t})=>{console.log(` ${o.gray(`${t}:`)} ${o.red("Error:")} Found hardcoded string: "${e}"`)});process.exit(1)}}catch(e){const n=t.wrapError(e);r.fail(n.message),console.error(n),process.exit(1)}};
1
+ "use strict";var e=require("glob"),t=require("node:fs/promises"),r=require("@swc/core"),n=require("node:path"),s=require("node:events"),o=require("chalk"),i=require("ora");class a extends s.EventEmitter{config;constructor(e){super({captureRejections:!0}),this.config=e}wrapError(e){const t="Linter failed to run: ";if(e instanceof Error){if(e.message.startsWith(t))return e;const r=new Error(`${t}${e.message}`);return r.stack=e.stack,r}return new Error(`${t}${String(e)}`)}async run(){const{config:s}=this;try{this.emit("progress",{message:"Finding source files to analyze..."});const o=["node_modules/**"],i=Array.isArray(s.extract.ignore)?s.extract.ignore:s.extract.ignore?[s.extract.ignore]:[],a=await e.glob(s.extract.input,{ignore:[...o,...i]});this.emit("progress",{message:`Analyzing ${a.length} source files...`});let c=0;const l=new Map;for(const e of a){const o=await t.readFile(e,"utf-8"),i=n.extname(e).toLowerCase(),a=".ts"===i||".tsx"===i||".mts"===i||".cts"===i,p=".tsx"===i;let f;try{f=await r.parse(o,{syntax:a?"typescript":"ecmascript",tsx:p,decorators:!0})}catch(t){if(".ts"!==i||p){const e=this.wrapError(t);this.emit("error",e);continue}try{f=await r.parse(o,{syntax:"typescript",tsx:!0,decorators:!0}),this.emit("progress",{message:`Parsed ${e} using TSX fallback`})}catch(e){const t=this.wrapError(e);this.emit("error",t);continue}}const g=u(f,o,s);g.length>0&&(c+=g.length,l.set(e,g))}const p={success:0===c,message:c>0?`Linter found ${c} potential issues.`:"No issues found.",files:Object.fromEntries(l.entries())};return this.emit("done",p),p}catch(e){const t=this.wrapError(e);throw this.emit("error",t),t}}}const c=e=>/^(https|http|\/\/|^\/)/.test(e);function u(e,t,r){const n=[],s=[],o=e=>t.substring(0,e).split("\n").length,i=r.extract.transComponents||["Trans"],a=r.extract.ignoredTags||[],u=new Set([...i,"script","style","code",...a]),l=r.extract.ignoredAttributes||[],p=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...l]),f=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?f({name:e.opening.name}):null;const r=e=>{if(!e)return null;if("JSXIdentifier"===e.type&&(e.name||e.value))return e.name??e.value;if("Identifier"===e.type&&(e.name||e.value))return e.name??e.value;if("JSXMemberExpression"===e.type){const t=r(e.object),n=r(e.property);return t&&n?`${t}.${n}`:n??t}return e.name??e.value??e.property?.name??e.property?.value??null};return r(t)},g=e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r&&"object"==typeof r&&("JSXElement"===r.type||"JSXOpeningElement"===r.type||"JSXSelfClosingElement"===r.type)){const e=f(r);if(e&&u.has(e))return!0}}return!1},m=(e,t)=>{if(!e||"object"!=typeof e)return;const r=[...t,e];if("JSXText"===e.type){if(!g(r)){const t=e.value.trim();t&&t.length>1&&"..."!==t&&!c(t)&&isNaN(Number(t))&&!t.startsWith("{{")&&s.push(e)}}if("StringLiteral"===e.type){const t=r[r.length-2],n=g(r);if("JSXAttribute"===t?.type&&!p.has(t.name.value)&&!n){const t=e.value.trim();t&&"..."!==t&&!c(t)&&isNaN(Number(t))&&s.push(e)}}for(const t of Object.keys(e)){if("span"===t)continue;const n=e[t];Array.isArray(n)?n.forEach(e=>m(e,r)):n&&"object"==typeof n&&m(n,r)}};m(e,[]);let h=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,h);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),h=s+r.length)}return n}exports.Linter=a,exports.runLinter=async function(e){return new a(e).run()},exports.runLinterCli=async function(e){const t=new a(e),r=i().start();t.on("progress",e=>{r.text=e.message});try{const{success:e,message:n,files:s}=await t.run();if(e)r.succeed(o.green.bold(n));else{r.fail(o.red.bold(n));for(const[e,t]of Object.entries(s))console.log(o.yellow(`\n${e}`)),t.forEach(({text:e,line:t})=>{console.log(` ${o.gray(`${t}:`)} ${o.red("Error:")} Found hardcoded string: "${e}"`)});process.exit(1)}}catch(e){const n=t.wrapError(e);r.fail(n.message),console.error(n),process.exit(1)}};
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.20.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.3"),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{glob as e}from"glob";import{readFile as t}from"node:fs/promises";import{parse as r}from"@swc/core";import{extname as n}from"node:path";import{EventEmitter as s}from"node:events";import o from"chalk";import i from"ora";class a extends s{config;constructor(e){super({captureRejections:!0}),this.config=e}wrapError(e){const t="Linter failed to run: ";if(e instanceof Error){if(e.message.startsWith(t))return e;const r=new Error(`${t}${e.message}`);return r.stack=e.stack,r}return new Error(`${t}${String(e)}`)}async run(){const{config:s}=this;try{this.emit("progress",{message:"Finding source files to analyze..."});const o=["node_modules/**"],i=Array.isArray(s.extract.ignore)?s.extract.ignore:s.extract.ignore?[s.extract.ignore]:[],a=await e(s.extract.input,{ignore:[...o,...i]});this.emit("progress",{message:`Analyzing ${a.length} source files...`});let c=0;const l=new Map;for(const e of a){const o=await t(e,"utf-8"),i=n(e).toLowerCase(),a=".ts"===i||".tsx"===i||".mts"===i||".cts"===i,u=".tsx"===i,p=f(await r(o,{syntax:a?"typescript":"ecmascript",tsx:u,decorators:!0}),o,s);p.length>0&&(c+=p.length,l.set(e,p))}const u={success:0===c,message:c>0?`Linter found ${c} potential issues.`:"No issues found.",files:Object.fromEntries(l.entries())};return this.emit("done",u),u}catch(e){const t=this.wrapError(e);throw this.emit("error",t),t}}}async function c(e){return new a(e).run()}async function l(e){const t=new a(e),r=i().start();t.on("progress",e=>{r.text=e.message});try{const{success:e,message:n,files:s}=await t.run();if(e)r.succeed(o.green.bold(n));else{r.fail(o.red.bold(n));for(const[e,t]of Object.entries(s))console.log(o.yellow(`\n${e}`)),t.forEach(({text:e,line:t})=>{console.log(` ${o.gray(`${t}:`)} ${o.red("Error:")} Found hardcoded string: "${e}"`)});process.exit(1)}}catch(e){const n=t.wrapError(e);r.fail(n.message),console.error(n),process.exit(1)}}const u=e=>/^(https|http|\/\/|^\/)/.test(e);function f(e,t,r){const n=[],s=[],o=e=>t.substring(0,e).split("\n").length,i=r.extract.transComponents||["Trans"],a=r.extract.ignoredTags||[],c=new Set([...i,"script","style","code",...a]),l=r.extract.ignoredAttributes||[],f=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...l]),p=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?p({name:e.opening.name}):null;const r=e=>{if(!e)return null;if("JSXIdentifier"===e.type&&(e.name||e.value))return e.name??e.value;if("Identifier"===e.type&&(e.name||e.value))return e.name??e.value;if("JSXMemberExpression"===e.type){const t=r(e.object),n=r(e.property);return t&&n?`${t}.${n}`:n??t}return e.name??e.value??e.property?.name??e.property?.value??null};return r(t)},m=e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r&&"object"==typeof r&&("JSXElement"===r.type||"JSXOpeningElement"===r.type||"JSXSelfClosingElement"===r.type)){const e=p(r);if(e&&c.has(e))return!0}}return!1},g=(e,t)=>{if(!e||"object"!=typeof e)return;const r=[...t,e];if("JSXText"===e.type){if(!m(r)){const t=e.value.trim();t&&t.length>1&&"..."!==t&&!u(t)&&isNaN(Number(t))&&!t.startsWith("{{")&&s.push(e)}}if("StringLiteral"===e.type){const t=r[r.length-2],n=m(r);if("JSXAttribute"===t?.type&&!f.has(t.name.value)&&!n){const t=e.value.trim();t&&"..."!==t&&!u(t)&&isNaN(Number(t))&&s.push(e)}}for(const t of Object.keys(e)){if("span"===t)continue;const n=e[t];Array.isArray(n)?n.forEach(e=>g(e,r)):n&&"object"==typeof n&&g(n,r)}};g(e,[]);let y=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,y);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),y=s+r.length)}return n}export{a as Linter,c as runLinter,l as runLinterCli};
1
+ import{glob as e}from"glob";import{readFile as t}from"node:fs/promises";import{parse as r}from"@swc/core";import{extname as n}from"node:path";import{EventEmitter as s}from"node:events";import o from"chalk";import i from"ora";class a extends s{config;constructor(e){super({captureRejections:!0}),this.config=e}wrapError(e){const t="Linter failed to run: ";if(e instanceof Error){if(e.message.startsWith(t))return e;const r=new Error(`${t}${e.message}`);return r.stack=e.stack,r}return new Error(`${t}${String(e)}`)}async run(){const{config:s}=this;try{this.emit("progress",{message:"Finding source files to analyze..."});const o=["node_modules/**"],i=Array.isArray(s.extract.ignore)?s.extract.ignore:s.extract.ignore?[s.extract.ignore]:[],a=await e(s.extract.input,{ignore:[...o,...i]});this.emit("progress",{message:`Analyzing ${a.length} source files...`});let c=0;const l=new Map;for(const e of a){const o=await t(e,"utf-8"),i=n(e).toLowerCase(),a=".ts"===i||".tsx"===i||".mts"===i||".cts"===i,u=".tsx"===i;let p;try{p=await r(o,{syntax:a?"typescript":"ecmascript",tsx:u,decorators:!0})}catch(t){if(".ts"!==i||u){const e=this.wrapError(t);this.emit("error",e);continue}try{p=await r(o,{syntax:"typescript",tsx:!0,decorators:!0}),this.emit("progress",{message:`Parsed ${e} using TSX fallback`})}catch(e){const t=this.wrapError(e);this.emit("error",t);continue}}const m=f(p,o,s);m.length>0&&(c+=m.length,l.set(e,m))}const u={success:0===c,message:c>0?`Linter found ${c} potential issues.`:"No issues found.",files:Object.fromEntries(l.entries())};return this.emit("done",u),u}catch(e){const t=this.wrapError(e);throw this.emit("error",t),t}}}async function c(e){return new a(e).run()}async function l(e){const t=new a(e),r=i().start();t.on("progress",e=>{r.text=e.message});try{const{success:e,message:n,files:s}=await t.run();if(e)r.succeed(o.green.bold(n));else{r.fail(o.red.bold(n));for(const[e,t]of Object.entries(s))console.log(o.yellow(`\n${e}`)),t.forEach(({text:e,line:t})=>{console.log(` ${o.gray(`${t}:`)} ${o.red("Error:")} Found hardcoded string: "${e}"`)});process.exit(1)}}catch(e){const n=t.wrapError(e);r.fail(n.message),console.error(n),process.exit(1)}}const u=e=>/^(https|http|\/\/|^\/)/.test(e);function f(e,t,r){const n=[],s=[],o=e=>t.substring(0,e).split("\n").length,i=r.extract.transComponents||["Trans"],a=r.extract.ignoredTags||[],c=new Set([...i,"script","style","code",...a]),l=r.extract.ignoredAttributes||[],f=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...l]),p=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?p({name:e.opening.name}):null;const r=e=>{if(!e)return null;if("JSXIdentifier"===e.type&&(e.name||e.value))return e.name??e.value;if("Identifier"===e.type&&(e.name||e.value))return e.name??e.value;if("JSXMemberExpression"===e.type){const t=r(e.object),n=r(e.property);return t&&n?`${t}.${n}`:n??t}return e.name??e.value??e.property?.name??e.property?.value??null};return r(t)},m=e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r&&"object"==typeof r&&("JSXElement"===r.type||"JSXOpeningElement"===r.type||"JSXSelfClosingElement"===r.type)){const e=p(r);if(e&&c.has(e))return!0}}return!1},g=(e,t)=>{if(!e||"object"!=typeof e)return;const r=[...t,e];if("JSXText"===e.type){if(!m(r)){const t=e.value.trim();t&&t.length>1&&"..."!==t&&!u(t)&&isNaN(Number(t))&&!t.startsWith("{{")&&s.push(e)}}if("StringLiteral"===e.type){const t=r[r.length-2],n=m(r);if("JSXAttribute"===t?.type&&!f.has(t.name.value)&&!n){const t=e.value.trim();t&&"..."!==t&&!u(t)&&isNaN(Number(t))&&s.push(e)}}for(const t of Object.keys(e)){if("span"===t)continue;const n=e[t];Array.isArray(n)?n.forEach(e=>g(e,r)):n&&"object"==typeof n&&g(n,r)}};g(e,[]);let h=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,h);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),h=s+r.length)}return n}export{a as Linter,c as runLinter,l as runLinterCli};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.20.2",
3
+ "version": "1.20.3",
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.20.2')
25
+ .version('1.20.3')
26
26
 
27
27
  // new: global config override option
28
28
  program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)')
package/src/linter.ts CHANGED
@@ -64,11 +64,37 @@ export class Linter extends EventEmitter<LinterEventMap> {
64
64
  const isTypeScriptFile = fileExt === '.ts' || fileExt === '.tsx' || fileExt === '.mts' || fileExt === '.cts'
65
65
  const isTSX = fileExt === '.tsx'
66
66
 
67
- const ast = await parse(code, {
68
- syntax: isTypeScriptFile ? 'typescript' : 'ecmascript',
69
- tsx: isTSX,
70
- decorators: true
71
- })
67
+ let ast: any
68
+ try {
69
+ ast = await parse(code, {
70
+ syntax: isTypeScriptFile ? 'typescript' : 'ecmascript',
71
+ tsx: isTSX,
72
+ decorators: true
73
+ })
74
+ } catch (err) {
75
+ // Some projects use JSX/TSX in .ts files. Try one fallback parse with tsx:true
76
+ // if the original file was a .ts (not .tsx). If that still fails, emit error and continue.
77
+ if (fileExt === '.ts' && !isTSX) {
78
+ try {
79
+ ast = await parse(code, {
80
+ syntax: 'typescript',
81
+ tsx: true,
82
+ decorators: true
83
+ })
84
+ // optional: emit a progress message so consumers know a fallback happened
85
+ this.emit('progress', { message: `Parsed ${file} using TSX fallback` })
86
+ } catch (err2) {
87
+ const wrapped = this.wrapError(err2)
88
+ this.emit('error', wrapped)
89
+ continue
90
+ }
91
+ } else {
92
+ const wrapped = this.wrapError(err)
93
+ this.emit('error', wrapped)
94
+ continue
95
+ }
96
+ }
97
+
72
98
  const hardcodedStrings = findHardcodedStrings(ast, code, config)
73
99
 
74
100
  if (hardcodedStrings.length > 0) {
@@ -1 +1 @@
1
- {"version":3,"file":"linter.d.ts","sourceRoot":"","sources":["../src/linter.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAG1C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEnD,KAAK,cAAc,GAAG;IACpB,QAAQ,EAAE;QAAC;YACT,OAAO,EAAE,MAAM,CAAC;SACjB;KAAC,CAAC;IACH,IAAI,EAAE;QAAC;YACL,OAAO,EAAE,OAAO,CAAC;YACjB,OAAO,EAAE,MAAM,CAAC;YAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,EAAE,CAAC,CAAC;SAC1C;KAAC,CAAC;IACH,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;CACvB,CAAA;AAED,qBAAa,MAAO,SAAQ,YAAY,CAAC,cAAc,CAAC;IACtD,OAAO,CAAC,MAAM,CAAsB;gBAEvB,MAAM,EAAE,oBAAoB;IAKzC,SAAS,CAAE,KAAK,EAAE,OAAO;IAanB,GAAG;;;;;;;CA+CV;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,SAAS,CAAE,MAAM,EAAE,oBAAoB;;;;;;GAE5D;AAED,wBAAsB,YAAY,CAAE,MAAM,EAAE,oBAAoB,iBA4B/D;AAED;;GAEG;AACH,UAAU,eAAe;IACvB,iCAAiC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;CACd"}
1
+ {"version":3,"file":"linter.d.ts","sourceRoot":"","sources":["../src/linter.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAG1C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEnD,KAAK,cAAc,GAAG;IACpB,QAAQ,EAAE;QAAC;YACT,OAAO,EAAE,MAAM,CAAC;SACjB;KAAC,CAAC;IACH,IAAI,EAAE;QAAC;YACL,OAAO,EAAE,OAAO,CAAC;YACjB,OAAO,EAAE,MAAM,CAAC;YAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,EAAE,CAAC,CAAC;SAC1C;KAAC,CAAC;IACH,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;CACvB,CAAA;AAED,qBAAa,MAAO,SAAQ,YAAY,CAAC,cAAc,CAAC;IACtD,OAAO,CAAC,MAAM,CAAsB;gBAEvB,MAAM,EAAE,oBAAoB;IAKzC,SAAS,CAAE,KAAK,EAAE,OAAO;IAanB,GAAG;;;;;;;CAyEV;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,SAAS,CAAE,MAAM,EAAE,oBAAoB;;;;;;GAE5D;AAED,wBAAsB,YAAY,CAAE,MAAM,EAAE,oBAAoB,iBA4B/D;AAED;;GAEG;AACH,UAAU,eAAe;IACvB,iCAAiC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;CACd"}