i18next-cli 1.19.0 → 1.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +4 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/extractor.js +1 -1
- package/dist/cjs/linter.js +1 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/extractor/core/extractor.js +1 -1
- package/dist/esm/linter.js +1 -1
- package/package.json +1 -1
- package/src/cli.ts +1 -1
- package/src/extractor/core/extractor.ts +10 -4
- package/src/linter.ts +9 -2
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/linter.d.ts.map +1 -1
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.19.1](https://github.com/i18next/i18next-cli/compare/v1.19.0...v1.19.1) - 2025-10-31
|
|
9
|
+
|
|
10
|
+
- fix: Prevent parser crashes on TypeScript files that use angle‑bracket type assertions (e.g. `const x = <SomeType>getValue()`). The extractor and linter now choose SWC's TSX parsing mode based on the file extension (`.tsx` => JSX enabled, `.ts`/`.mts`/`.cts` => JSX disabled), avoiding accidental JSX parsing of compile‑time casts. [#84](https://github.com/i18next/i18next-cli/issues/84)
|
|
11
|
+
|
|
8
12
|
## [1.19.0](https://github.com/i18next/i18next-cli/compare/v1.18.1...v1.19.0) - 2025-10-31
|
|
9
13
|
|
|
10
14
|
- feat(extractor): improve key extraction to detect translation keys stored in local variables, object properties and simple string expressions [#83](https://github.com/i18next/i18next-cli/issues/83)
|
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
|
+
"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.1"),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
|
|
1
|
+
"use strict";var t=require("ora"),e=require("chalk"),a=require("@swc/core"),r=require("node:fs/promises"),n=require("node:path"),o=require("./key-finder.js"),s=require("./translation-manager.js"),i=require("../../utils/validation.js"),c=require("../parsers/comment-parser.js"),l=require("../../utils/logger.js"),u=require("../../utils/file-utils.js"),g=require("../../utils/funnel-msg-tracker.js");exports.extract=async function(t,{syncPrimaryWithDefaults:e=!1}={}){t.extract.primaryLanguage||=t.locales[0]||"en",t.extract.secondaryLanguages||=t.locales.filter(e=>e!==t?.extract?.primaryLanguage),t.extract.functions||=["t","*.t"],t.extract.transComponents||=["Trans"];const{allKeys:a,objectKeys:r}=await o.findKeys(t);return s.getTranslations(a,r,t,{syncPrimaryWithDefaults:e})},exports.processFile=async function(t,e,o,s,u,g=new l.ConsoleLogger){try{let i=await r.readFile(t,"utf-8");for(const a of e)try{const e=await(a.onLoad?.(i,t));void 0!==e&&(i=e)}catch(t){g.warn(`Plugin ${a.name} onLoad failed:`,t)}const l=n.extname(t).toLowerCase(),y=".ts"===l||".tsx"===l||".mts"===l||".cts"===l,d=".tsx"===l,m=await a.parse(i,{syntax:y?"typescript":"ecmascript",tsx:d,decorators:!0,dynamicImport:!0,comments:!0});s.getVarFromScope=o.getVarFromScope.bind(o),o.visit(m),c.extractKeysFromComments(i,s,u,o.getVarFromScope.bind(o))}catch(e){throw new i.ExtractorError("Failed to process file",t,e)}},exports.runExtractor=async function(a,{isWatchMode:c=!1,isDryRun:y=!1,syncPrimaryWithDefaults:d=!1}={},m=new l.ConsoleLogger){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(t=>t!==a?.extract?.primaryLanguage),a.extract.functions||=["t","*.t"],a.extract.transComponents||=["Trans"],i.validateExtractorConfig(a);const f=a.plugins||[],p=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:i}=await o.findKeys(a,m);p.text=`Found ${t.size} unique keys. Updating translation files...`;const c=await s.getTranslations(t,i,a,{syncPrimaryWithDefaults:d});let l=!1;for(const t of c)if(t.updated&&(l=!0,!y)){const o=u.serializeTranslationFile(t.newTranslations,a.extract.outputFormat,a.extract.indentation);await r.mkdir(n.dirname(t.path),{recursive:!0}),await r.writeFile(t.path,o),m.info(e.green(`Updated: ${t.path}`))}if(f.length>0){p.text="Running post-extraction plugins...";for(const t of f)await(t.afterSync?.(c,a))}return p.succeed(e.bold("Extraction complete!")),l&&await async function(){if(!await g.shouldShowFunnel("extract"))return;return console.log(e.yellow.bold("\n💡 Tip: Tired of running the extractor manually?")),console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,'),console.log(" where keys are created and translated automatically as you code."),console.log(` Learn more: ${e.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${e.cyan("https://youtu.be/joPsZghT3wM")}`),g.recordFunnelShown("extract")}(),l}catch(t){throw p.fail(e.red("Extraction failed.")),t}};
|
package/dist/cjs/linter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("glob"),t=require("node:fs/promises"),r=require("@swc/core"),n=require("node:
|
|
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)}};
|
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
|
+
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.1"),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 t from"ora";import a from"chalk";import{parse as e}from"@swc/core";import{mkdir as o,writeFile as r,readFile as n}from"node:fs/promises";import{dirname as i}from"node:path";import{findKeys as
|
|
1
|
+
import t from"ora";import a from"chalk";import{parse as e}from"@swc/core";import{mkdir as o,writeFile as r,readFile as n}from"node:fs/promises";import{dirname as s,extname as i}from"node:path";import{findKeys as c}from"./key-finder.js";import{getTranslations as l}from"./translation-manager.js";import{validateExtractorConfig as m,ExtractorError as u}from"../../utils/validation.js";import{extractKeysFromComments as f}from"../parsers/comment-parser.js";import{ConsoleLogger as p}from"../../utils/logger.js";import{serializeTranslationFile as y}from"../../utils/file-utils.js";import{shouldShowFunnel as g,recordFunnelShown as d}from"../../utils/funnel-msg-tracker.js";async function w(e,{isWatchMode:n=!1,isDryRun:i=!1,syncPrimaryWithDefaults:u=!1}={},f=new p){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage),e.extract.functions||=["t","*.t"],e.extract.transComponents||=["Trans"],m(e);const w=e.plugins||[],x=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:n}=await c(e,f);x.text=`Found ${t.size} unique keys. Updating translation files...`;const m=await l(t,n,e,{syncPrimaryWithDefaults:u});let p=!1;for(const t of m)if(t.updated&&(p=!0,!i)){const n=y(t.newTranslations,e.extract.outputFormat,e.extract.indentation);await o(s(t.path),{recursive:!0}),await r(t.path,n),f.info(a.green(`Updated: ${t.path}`))}if(w.length>0){x.text="Running post-extraction plugins...";for(const t of w)await(t.afterSync?.(m,e))}return x.succeed(a.bold("Extraction complete!")),p&&await async function(){if(!await g("extract"))return;return console.log(a.yellow.bold("\n💡 Tip: Tired of running the extractor manually?")),console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,'),console.log(" where keys are created and translated automatically as you code."),console.log(` Learn more: ${a.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${a.cyan("https://youtu.be/joPsZghT3wM")}`),d("extract")}(),p}catch(t){throw x.fail(a.red("Extraction failed.")),t}}async function x(t,a,o,r,s,c=new p){try{let l=await n(t,"utf-8");for(const e of a)try{const a=await(e.onLoad?.(l,t));void 0!==a&&(l=a)}catch(t){c.warn(`Plugin ${e.name} onLoad failed:`,t)}const m=i(t).toLowerCase(),u=".ts"===m||".tsx"===m||".mts"===m||".cts"===m,p=".tsx"===m,y=await e(l,{syntax:u?"typescript":"ecmascript",tsx:p,decorators:!0,dynamicImport:!0,comments:!0});r.getVarFromScope=o.getVarFromScope.bind(o),o.visit(y),f(l,r,s,o.getVarFromScope.bind(o))}catch(a){throw new u("Failed to process file",t,a)}}async function h(t,{syncPrimaryWithDefaults:a=!1}={}){t.extract.primaryLanguage||=t.locales[0]||"en",t.extract.secondaryLanguages||=t.locales.filter(a=>a!==t?.extract?.primaryLanguage),t.extract.functions||=["t","*.t"],t.extract.transComponents||=["Trans"];const{allKeys:e,objectKeys:o}=await c(t);return l(e,o,t,{syncPrimaryWithDefaults:a})}export{h as extract,x as processFile,w as runExtractor};
|
package/dist/esm/linter.js
CHANGED
|
@@ -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{
|
|
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};
|
package/package.json
CHANGED
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.
|
|
25
|
+
.version('1.19.1')
|
|
26
26
|
|
|
27
27
|
// new: global config override option
|
|
28
28
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)')
|
|
@@ -2,7 +2,7 @@ import ora from 'ora'
|
|
|
2
2
|
import chalk from 'chalk'
|
|
3
3
|
import { parse } from '@swc/core'
|
|
4
4
|
import { mkdir, readFile, writeFile } from 'node:fs/promises'
|
|
5
|
-
import { dirname } from 'node:path'
|
|
5
|
+
import { dirname, extname } from 'node:path'
|
|
6
6
|
import type { Logger, I18nextToolkitConfig, Plugin, PluginContext } from '../../types'
|
|
7
7
|
import { findKeys } from './key-finder'
|
|
8
8
|
import { getTranslations } from './translation-manager'
|
|
@@ -154,11 +154,17 @@ export async function processFile (
|
|
|
154
154
|
}
|
|
155
155
|
}
|
|
156
156
|
|
|
157
|
+
// Determine parser options from file extension so .ts is not parsed as TSX
|
|
158
|
+
const fileExt = extname(file).toLowerCase()
|
|
159
|
+
const isTypeScriptFile = fileExt === '.ts' || fileExt === '.tsx' || fileExt === '.mts' || fileExt === '.cts'
|
|
160
|
+
const isTSX = fileExt === '.tsx'
|
|
161
|
+
|
|
157
162
|
const ast = await parse(code, {
|
|
158
|
-
syntax: 'typescript',
|
|
159
|
-
tsx:
|
|
163
|
+
syntax: isTypeScriptFile ? 'typescript' : 'ecmascript',
|
|
164
|
+
tsx: isTSX,
|
|
160
165
|
decorators: true,
|
|
161
|
-
|
|
166
|
+
dynamicImport: true,
|
|
167
|
+
comments: true,
|
|
162
168
|
})
|
|
163
169
|
|
|
164
170
|
// "Wire up" the visitor's scope method to the context.
|
package/src/linter.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { glob } from 'glob'
|
|
2
2
|
import { readFile } from 'node:fs/promises'
|
|
3
3
|
import { parse } from '@swc/core'
|
|
4
|
+
import { extname } from 'node:path'
|
|
4
5
|
import { EventEmitter } from 'node:events'
|
|
5
6
|
import chalk from 'chalk'
|
|
6
7
|
import ora from 'ora'
|
|
@@ -57,9 +58,15 @@ export class Linter extends EventEmitter<LinterEventMap> {
|
|
|
57
58
|
|
|
58
59
|
for (const file of sourceFiles) {
|
|
59
60
|
const code = await readFile(file, 'utf-8')
|
|
61
|
+
|
|
62
|
+
// Determine parser options from file extension so .ts is not parsed as TSX
|
|
63
|
+
const fileExt = extname(file).toLowerCase()
|
|
64
|
+
const isTypeScriptFile = fileExt === '.ts' || fileExt === '.tsx' || fileExt === '.mts' || fileExt === '.cts'
|
|
65
|
+
const isTSX = fileExt === '.tsx'
|
|
66
|
+
|
|
60
67
|
const ast = await parse(code, {
|
|
61
|
-
syntax: 'typescript',
|
|
62
|
-
tsx:
|
|
68
|
+
syntax: isTypeScriptFile ? 'typescript' : 'ecmascript',
|
|
69
|
+
tsx: isTSX,
|
|
63
70
|
decorators: true
|
|
64
71
|
})
|
|
65
72
|
const hardcodedStrings = findHardcodedStrings(ast, code, config)
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractor.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/extractor.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAKtF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAK5C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,oBAAoB,EAC5B,EACE,WAAmB,EACnB,QAAgB,EAChB,uBAA+B,EAChC,GAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,uBAAuB,CAAC,EAAE,OAAO,CAAC;CAC9B,EACN,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,OAAO,CAAC,CAyDlB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EAAE,EACjB,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,aAAa,EAC5B,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,SAAS,CAAC,EAC7C,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,IAAI,CAAC,
|
|
1
|
+
{"version":3,"file":"extractor.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/extractor.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,oBAAoB,EAAE,MAAM,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AAKtF,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAA;AAK5C;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,oBAAoB,EAC5B,EACE,WAAmB,EACnB,QAAgB,EAChB,uBAA+B,EAChC,GAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;IACnB,uBAAuB,CAAC,EAAE,OAAO,CAAC;CAC9B,EACN,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,OAAO,CAAC,CAyDlB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,OAAO,EAAE,MAAM,EAAE,EACjB,WAAW,EAAE,WAAW,EACxB,aAAa,EAAE,aAAa,EAC5B,MAAM,EAAE,IAAI,CAAC,oBAAoB,EAAE,SAAS,CAAC,EAC7C,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,IAAI,CAAC,CA0Cf;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAE,MAAM,EAAE,oBAAoB,EAAE,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,sDAO3I"}
|
package/types/linter.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linter.d.ts","sourceRoot":"","sources":["../src/linter.ts"],"names":[],"mappings":"
|
|
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"}
|