i18next-cli 1.2.0 ā 1.3.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 +13 -0
- package/README.md +10 -2
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/extractor.js +1 -1
- package/dist/cjs/extractor/parsers/ast-visitors.js +1 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/extractor/core/extractor.js +1 -1
- package/dist/esm/extractor/parsers/ast-visitors.js +1 -1
- package/package.json +1 -1
- package/src/cli.ts +39 -14
- package/src/extractor/core/extractor.ts +30 -10
- package/src/extractor/parsers/ast-visitors.ts +3 -1
- package/types/extractor/core/extractor.d.ts +4 -1
- package/types/extractor/core/extractor.d.ts.map +1 -1
- package/types/extractor/parsers/ast-visitors.d.ts.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,19 @@ 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.3.0](https://github.com/i18next/i18next-cli/compare/v1.2.1...v1.3.0) - 2025-10-02
|
|
9
|
+
|
|
10
|
+
### Added
|
|
11
|
+
- **Linter:** Introduced a new `--watch` flag for the `lint` command, enabling it to run automatically on file changes for real-time feedback during development.
|
|
12
|
+
- **Extractor:** Introduced a new `--dry-run` flag for the `extract` command. When used, the extractor will report potential changes but will not write any files to disk, which is useful for validation in CI/CD pipelines. [#22](https://github.com/i18next/i18next-cli/issues/22)
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
- **Extractor:** Reduced console noise in `extract --watch` mode. The promotional tip is now only displayed once per watch session, instead of after every file change. [#20](https://github.com/i18next/i18next-cli/issues/20)
|
|
16
|
+
|
|
17
|
+
## [1.2.1](https://github.com/i18next/i18next-cli/compare/v1.2.0...v1.2.1) - 2025-10-02
|
|
18
|
+
|
|
19
|
+
- **Extractor:** Fixed a bug where translation keys inside class methods were not being extracted. This was caused by a fragile AST traversal logic that has now been made more robust. [19](https://github.com/i18next/i18next-cli/issues/19)
|
|
20
|
+
|
|
8
21
|
## [1.2.0](https://github.com/i18next/i18next-cli/compare/v1.1.0...v1.2.0) - 2025-10-02
|
|
9
22
|
|
|
10
23
|
### Added
|
package/README.md
CHANGED
|
@@ -111,6 +111,7 @@ npx i18next-cli extract [options]
|
|
|
111
111
|
**Options:**
|
|
112
112
|
- `--watch, -w`: Re-run automatically when files change
|
|
113
113
|
- `--ci`: Exit with non-zero status if any files are updated (for CI/CD)
|
|
114
|
+
- `--dry-run`: Does not change any files - useful in combination with `--ci` (for CI/CD)
|
|
114
115
|
|
|
115
116
|
**Examples:**
|
|
116
117
|
```bash
|
|
@@ -195,6 +196,13 @@ Analyzes your source code for internationalization issues like hardcoded strings
|
|
|
195
196
|
npx i18next-cli lint
|
|
196
197
|
```
|
|
197
198
|
|
|
199
|
+
## Watch Mode
|
|
200
|
+
|
|
201
|
+
Use watch mode to automatically lint on save:
|
|
202
|
+
|
|
203
|
+
```bash
|
|
204
|
+
npx i18next-cli lint --watch
|
|
205
|
+
|
|
198
206
|
### `migrate-config`
|
|
199
207
|
Automatically migrates a legacy `i18next-parser.config.js` file to the new `i18next.config.ts` format.
|
|
200
208
|
|
|
@@ -339,8 +347,8 @@ export default defineConfig({
|
|
|
339
347
|
],
|
|
340
348
|
|
|
341
349
|
// Output formatting
|
|
342
|
-
sort: true,
|
|
343
|
-
indentation: 2,
|
|
350
|
+
sort: true, // can be also a sort function => i.e. (a, b) => a.key > b.key ? -1 : a.key < b.key ? 1 : 0, // sort in reverse order
|
|
351
|
+
indentation: 2, // can be also a string
|
|
344
352
|
|
|
345
353
|
// Primary language settings
|
|
346
354
|
primaryLanguage: 'en', // Defaults to the first locale in the `locales` array
|
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"),
|
|
2
|
+
"use strict";var e=require("commander"),t=require("chokidar"),n=require("glob"),o=require("chalk"),i=require("./config.js"),a=require("./heuristic-config.js"),r=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var c=require("./types-generator.js"),s=require("./syncer.js"),l=require("./migrator.js"),u=require("./init.js"),d=require("./linter.js"),g=require("./status.js"),p=require("./locize.js");const f=new e.Command;f.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.3.0"),f.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.").action(async e=>{const a=await i.ensureConfig(),c=async()=>{const t=await r.runExtractor(a,{isWatchMode:e.watch,isDryRun:e.dryRun});e.ci&&t&&(console.error(o.red.bold("\n[CI Mode] Error: Translation files were updated. Please commit the changes.")),console.log(o.yellow("š” Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started")),console.log(` Learn more: ${o.cyan("npx i18next-cli locize-sync")}`),process.exit(1))};if(await c(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(a.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}),f.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)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.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=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async()=>{await l.runMigrator()}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.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 r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.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=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("ora"),t=require("chalk"),
|
|
1
|
+
"use strict";var e=require("ora"),t=require("chalk"),r=require("@swc/core"),a=require("node:fs/promises"),o=require("node:path"),n=require("./key-finder.js"),s=require("./translation-manager.js"),i=require("../../utils/validation.js"),c=require("../plugin-manager.js"),l=require("../parsers/comment-parser.js"),u=require("../../utils/logger.js"),g=require("../../utils/file-utils.js");let f=!1;function y(e,t,r,a=new u.ConsoleLogger){if(e&&"object"==typeof e){for(const o of t)try{o.onVisitNode?.(e,r)}catch(e){a.warn(`Plugin ${o.name} onVisitNode failed:`,e)}for(const o of Object.keys(e)){const n=e[o];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&y(e,t,r,a);else n&&"object"==typeof n&&y(n,t,r,a)}}}exports.extract=async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage),e.extract.functions||=["t"],e.extract.transComponents||=["Trans"];const{allKeys:t,objectKeys:r}=await n.findKeys(e);return s.getTranslations(t,r,e)},exports.processFile=async function(e,t,o,n,s=new u.ConsoleLogger){try{let i=await a.readFile(e,"utf-8");for(const r of t.plugins||[])i=await(r.onLoad?.(i,e))??i;const u=await r.parse(i,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0}),g=c.createPluginContext(o);l.extractKeysFromComments(i,g,t),n.visit(u),(t.plugins||[]).length>0&&y(u,t.plugins||[],g,s)}catch(t){throw new i.ExtractorError("Failed to process file",e,t)}},exports.runExtractor=async function(r,{isWatchMode:c=!1,isDryRun:l=!1}={},y=new u.ConsoleLogger){r.extract.primaryLanguage||=r.locales[0]||"en",r.extract.secondaryLanguages||=r.locales.filter(e=>e!==r?.extract?.primaryLanguage),i.validateExtractorConfig(r);const d=e("Running i18next key extractor...\n").start();try{const{allKeys:e,objectKeys:i}=await n.findKeys(r,y);d.text=`Found ${e.size} unique keys. Updating translation files...`;const u=await s.getTranslations(e,i,r);let p=!1;for(const e of u)if(e.updated&&(p=!0,!l)){const n=g.serializeTranslationFile(e.newTranslations,r.extract.outputFormat,r.extract.indentation);await a.mkdir(o.dirname(e.path),{recursive:!0}),await a.writeFile(e.path,n),y.info(t.green(`Updated: ${e.path}`))}return d.succeed(t.bold("Extraction complete!")),p&&function(e=!1){if(e&&f)return;console.log(t.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: ${t.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${t.cyan("https://youtu.be/joPsZghT3wM")}`),e&&(f=!0)}(c),p}catch(e){throw d.fail(t.red("Extraction failed.")),e}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./jsx-parser.js"),t=require("./ast-utils.js");exports.ASTVisitors=class{pluginContext;config;logger;scopeStack=[];objectKeys=new Set;constructor(e,t,n){this.pluginContext=t,this.config=e,this.logger=n}visit(e){this.enterScope(),this.walk(e),this.exitScope()}walk(e){if(!e)return;let t=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.enterScope(),t=!0),e.type){case"VariableDeclarator":this.handleVariableDeclarator(e);break;case"CallExpression":this.handleCallExpression(e);break;case"JSXElement":this.handleJSXElement(e)}for(const t in e){if("span"===t)continue;const n=e[t];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&this.walk(e);else n&&n
|
|
1
|
+
"use strict";var e=require("./jsx-parser.js"),t=require("./ast-utils.js");exports.ASTVisitors=class{pluginContext;config;logger;scopeStack=[];objectKeys=new Set;constructor(e,t,n){this.pluginContext=t,this.config=e,this.logger=n}visit(e){this.enterScope(),this.walk(e),this.exitScope()}walk(e){if(!e)return;let t=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.enterScope(),t=!0),e.type){case"VariableDeclarator":this.handleVariableDeclarator(e);break;case"CallExpression":this.handleCallExpression(e);break;case"JSXElement":this.handleJSXElement(e)}for(const t in e){if("span"===t)continue;const n=e[t];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&this.walk(e);else n&&"object"==typeof n&&this.walk(n)}t&&this.exitScope()}enterScope(){this.scopeStack.push(new Map)}exitScope(){this.scopeStack.pop()}setVarInScope(e,t){this.scopeStack.length>0&&this.scopeStack[this.scopeStack.length-1].set(e,t)}getVarFromScope(e){for(let t=this.scopeStack.length-1;t>=0;t--)if(this.scopeStack[t].has(e))return this.scopeStack[t].get(e)}handleVariableDeclarator(e){const t=e.init;if(!t)return;const n="AwaitExpression"===t.type&&"CallExpression"===t.argument.type?t.argument:"CallExpression"===t.type?t:null;if(!n)return;const r=n.callee;if("Identifier"===r.type){const t=this.getUseTranslationConfig(r.value);if(t)return void this.handleUseTranslationDeclarator(e,n,t)}"MemberExpression"===r.type&&"Identifier"===r.property.type&&"getFixedT"===r.property.value&&this.handleGetFixedTDeclarator(e,n)}handleUseTranslationDeclarator(e,n,r){let i;if("Identifier"===e.id.type&&(i=e.id.value),"ArrayPattern"===e.id.type){const t=e.id.elements[0];"Identifier"===t?.type&&(i=t.value)}if("ObjectPattern"===e.id.type)for(const t of e.id.properties){if("AssignmentPatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value){i="t";break}if("KeyValuePatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value&&"Identifier"===t.value.type){i=t.value.value;break}}if(!i)return;const s=n.arguments?.[r.nsArg]?.expression;let a;"StringLiteral"===s?.type?a=s.value:"ArrayExpression"===s?.type&&"StringLiteral"===s.elements[0]?.expression.type&&(a=s.elements[0].expression.value);const o=n.arguments?.[r.keyPrefixArg]?.expression;let l;if("ObjectExpression"===o?.type){const e=t.getObjectPropValue(o,"keyPrefix");l="string"==typeof e?e:void 0}this.setVarInScope(i,{defaultNs:a,keyPrefix:l})}handleGetFixedTDeclarator(e,t){if("Identifier"!==e.id.type||!e.init||"CallExpression"!==e.init.type)return;const n=e.id.value,r=t.arguments,i=r[1]?.expression,s=r[2]?.expression,a="StringLiteral"===i?.type?i.value:void 0,o="StringLiteral"===s?.type?s.value:void 0;(a||o)&&this.setVarInScope(n,{defaultNs:a,keyPrefix:o})}handleCallExpression(e){const n=this.getFunctionName(e.callee);if(!n)return;const r=this.getVarFromScope(n);if(!((this.config.extract.functions||["t"]).includes(n)||void 0!==r)||0===e.arguments.length)return;const i=e.arguments[0].expression;let s=[];if("StringLiteral"===i.type)s.push(i.value);else if("ArrowFunctionExpression"===i.type){const e=this.extractKeyFromSelector(i);e&&s.push(e)}else if("ArrayExpression"===i.type)for(const e of i.elements)"StringLiteral"===e?.expression.type&&s.push(e.expression.value);if(s=s.filter(e=>!!e),0===s.length)return;let a=!1;const o=this.config.extract.pluralSeparator??"_";for(let e=0;e<s.length;e++)s[e].endsWith(`${o}ordinal`)&&(a=!0,s[e]=s[e].slice(0,-8));let l,p;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?p=t:"StringLiteral"===t.type&&(l=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(p=t)}const u=p?t.getObjectPropValue(p,"defaultValue"):void 0,c="string"==typeof u?u:l;for(let e=0;e<s.length;e++){let n,i=s[e];if(p){const e=t.getObjectPropValue(p,"ns");"string"==typeof e&&(n=e)}!n&&r?.defaultNs&&(n=r.defaultNs);const o=this.config.extract.nsSeparator??":";if(!n&&o&&i.includes(o)){const e=i.split(o);n=e.shift(),i=e.join(o)}n||(n=this.config.extract.defaultNS);let l=i;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";l=`${r.keyPrefix}${e}${i}`}const u=e===s.length-1&&c||i;if(p){const e=t.getObjectProperty(p,"context");if("ConditionalExpression"===e?.value?.type){const t=this.resolvePossibleStringValues(e.value),r=this.config.extract.contextSeparator??"_";if(t.length>0){t.forEach(e=>{this.pluginContext.addKey({key:`${l}${r}${e}`,ns:n,defaultValue:u})}),this.pluginContext.addKey({key:l,ns:n,defaultValue:u});continue}}const r=t.getObjectPropValue(p,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${l}${e}${r}`,ns:n,defaultValue:u});continue}const i=void 0!==t.getObjectPropValue(p,"count"),s=!0===t.getObjectPropValue(p,"ordinal");if(i||a){this.handlePluralKeys(l,n,p,s||a);continue}!0===t.getObjectPropValue(p,"returnObjects")&&this.objectKeys.add(l)}this.pluginContext.addKey({key:l,ns:n,defaultValue:u})}}handlePluralKeys(e,n,r,i){try{const s=i?"ordinal":"cardinal",a=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:s}).resolvedOptions().pluralCategories,o=this.config.extract.pluralSeparator??"_",l=t.getObjectPropValue(r,"defaultValue"),p=t.getObjectPropValue(r,`defaultValue${o}other`),u=t.getObjectPropValue(r,`defaultValue${o}ordinal${o}other`);for(const s of a){const a=i?`defaultValue${o}ordinal${o}${s}`:`defaultValue${o}${s}`,c=t.getObjectPropValue(r,a);let f;f="string"==typeof c?c:"one"===s&&"string"==typeof l?l:i&&"string"==typeof u?u:i||"string"!=typeof p?"string"==typeof l?l:e:p;const y=i?`${e}${o}ordinal${o}${s}`:`${e}${o}${s}`;this.pluginContext.addKey({key:y,ns:n,defaultValue:f,hasCount:!0,isOrdinal:i})}}catch(i){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const s=t.getObjectPropValue(r,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof s?s:e})}}handleSimplePluralKeys(e,t,n){try{const r=new Intl.PluralRules(this.config.extract?.primaryLanguage).resolvedOptions().pluralCategories,i=this.config.extract.pluralSeparator??"_";for(const s of r)this.pluginContext.addKey({key:`${e}${i}${s}`,ns:n,defaultValue:t,hasCount:!0})}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}".`),this.pluginContext.addKey({key:e,ns:n,defaultValue:t})}}handleJSXElement(t){const n=this.getElementName(t);if(n&&(this.config.extract.transComponents||["Trans"]).includes(n)){const n=e.extractFromTransComponent(t,this.config);if(n){if(!n.ns){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===e?.type&&"JSXExpressionContainer"===e.value?.type&&"Identifier"===e.value.expression.type){const t=e.value.expression.value,r=this.getVarFromScope(t);r?.defaultNs&&(n.ns=r.defaultNs)}}if(n.ns||(n.ns=this.config.extract.defaultNS),n.contextExpression){const e=this.resolvePossibleStringValues(n.contextExpression),t=this.config.extract.contextSeparator??"_";if(e.length>0){for(const r of e)this.pluginContext.addKey({key:`${n.key}${t}${r}`,ns:n.ns,defaultValue:n.defaultValue});"StringLiteral"!==n.contextExpression.type&&this.pluginContext.addKey(n)}}else if(n.hasCount){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),r=!!e,i=n.optionsNode??{type:"ObjectExpression",properties:[],span:{start:0,end:0,ctxt:0}};i.properties.push({type:"KeyValueProperty",key:{type:"Identifier",value:"defaultValue",optional:!1,span:{start:0,end:0,ctxt:0}},value:{type:"StringLiteral",value:n.defaultValue,span:{start:0,end:0,ctxt:0}}}),this.handlePluralKeys(n.key,n.ns,i,r)}else this.pluginContext.addKey(n)}}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let n=t;const r=[];for(;"MemberExpression"===n.type;){const e=n.property;if("Identifier"===e.type)r.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;r.unshift(e.expression.value)}n=n.object}if(r.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return r.join(t)}return null}resolvePossibleStringValues(e){if("StringLiteral"===e.type)return[e.value];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValues(e.consequent),...this.resolvePossibleStringValues(e.alternate)]}return"Identifier"===e.type&&e.value,[]}getUseTranslationConfig(e){const t=this.config.extract.useTranslationNames||["useTranslation"];for(const n of t){if("string"==typeof n&&n===e)return{name:e,nsArg:0,keyPrefixArg:1};if("object"==typeof n&&n.name===e)return{name:n.name,nsArg:n.nsArg??0,keyPrefixArg:n.keyPrefixArg??1}}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let n=e;for(;"MemberExpression"===n.type;){if("Identifier"!==n.property.type)return null;t.unshift(n.property.value),n=n.object}return"Identifier"!==n.type?null:(t.unshift(n.value),t.join("."))}return null}};
|
package/dist/esm/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as
|
|
2
|
+
import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import n from"chalk";import{ensureConfig as i,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as r}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as s}from"./types-generator.js";import{runSyncer as l}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as p}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as f,runLocizeDownload as u,runLocizeMigrate as h}from"./locize.js";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.3.0"),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.").action(async t=>{const a=await i(),c=async()=>{const o=await r(a,{isWatchMode:t.watch,isDryRun:t.dryRun});t.ci&&o&&(console.error(n.red.bold("\n[CI Mode] Error: Translation files were updated. Please commit the changes.")),console.log(n.yellow("š” Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started")),console.log(` Learn more: ${n.cyan("npx i18next-cli locize-sync")}`),process.exit(1))};if(await c(),t.watch){console.log("\nWatching for changes...");o.watch(await e(a.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),c()})}}),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)=>{let e=await a();if(!e){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!")),e=t}await g(e,{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 n=await i(),a=()=>s(n);if(await a(),t.watch){console.log("\nWatching for changes...");o.watch(await e(n.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await i();await l(t)}),w.command("migrate-config").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async()=>{await m()}),w.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(p),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 i=async()=>{let t=await a();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 i(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){o.watch(await e(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),i()})}}}),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=await i();await f(o,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=await i();await u(o,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=await i();await h(o,t)}),w.parse(process.argv);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import t from"ora";import o from"chalk";import{parse as e}from"@swc/core";import{mkdir as a,writeFile as r,readFile as n}from"node:fs/promises";import{dirname as
|
|
1
|
+
import t from"ora";import o from"chalk";import{parse as e}from"@swc/core";import{mkdir as a,writeFile as r,readFile as n}from"node:fs/promises";import{dirname as i}from"node:path";import{findKeys as s}from"./key-finder.js";import{getTranslations as c}from"./translation-manager.js";import{validateExtractorConfig as l,ExtractorError as f}from"../../utils/validation.js";import{createPluginContext as m}from"../plugin-manager.js";import{extractKeysFromComments as p}from"../parsers/comment-parser.js";import{ConsoleLogger as u}from"../../utils/logger.js";import{serializeTranslationFile as y}from"../../utils/file-utils.js";let g=!1;async function d(e,{isWatchMode:n=!1,isDryRun:f=!1}={},m=new u){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage),l(e);const p=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:l}=await s(e,m);p.text=`Found ${t.size} unique keys. Updating translation files...`;const u=await c(t,l,e);let d=!1;for(const t of u)if(t.updated&&(d=!0,!f)){const n=y(t.newTranslations,e.extract.outputFormat,e.extract.indentation);await a(i(t.path),{recursive:!0}),await r(t.path,n),m.info(o.green(`Updated: ${t.path}`))}return p.succeed(o.bold("Extraction complete!")),d&&function(t=!1){if(t&&g)return;console.log(o.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: ${o.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${o.cyan("https://youtu.be/joPsZghT3wM")}`),t&&(g=!0)}(n),d}catch(t){throw p.fail(o.red("Extraction failed.")),t}}async function w(t,o,a,r,i=new u){try{let s=await n(t,"utf-8");for(const e of o.plugins||[])s=await(e.onLoad?.(s,t))??s;const c=await e(s,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0}),l=m(a);p(s,l,o),r.visit(c),(o.plugins||[]).length>0&&h(c,o.plugins||[],l,i)}catch(o){throw new f("Failed to process file",t,o)}}function h(t,o,e,a=new u){if(t&&"object"==typeof t){for(const r of o)try{r.onVisitNode?.(t,e)}catch(t){a.warn(`Plugin ${r.name} onVisitNode failed:`,t)}for(const r of Object.keys(t)){const n=t[r];if(Array.isArray(n))for(const t of n)t&&"object"==typeof t&&h(t,o,e,a);else n&&"object"==typeof n&&h(n,o,e,a)}}}async function x(t){t.extract.primaryLanguage||=t.locales[0]||"en",t.extract.secondaryLanguages||=t.locales.filter(o=>o!==t?.extract?.primaryLanguage),t.extract.functions||=["t"],t.extract.transComponents||=["Trans"];const{allKeys:o,objectKeys:e}=await s(t);return c(o,e,t)}export{x as extract,w as processFile,d as runExtractor};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractFromTransComponent as e}from"./jsx-parser.js";import{getObjectPropValue as t,getObjectProperty as n}from"./ast-utils.js";class i{pluginContext;config;logger;scopeStack=[];objectKeys=new Set;constructor(e,t,n){this.pluginContext=t,this.config=e,this.logger=n}visit(e){this.enterScope(),this.walk(e),this.exitScope()}walk(e){if(!e)return;let t=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.enterScope(),t=!0),e.type){case"VariableDeclarator":this.handleVariableDeclarator(e);break;case"CallExpression":this.handleCallExpression(e);break;case"JSXElement":this.handleJSXElement(e)}for(const t in e){if("span"===t)continue;const n=e[t];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&this.walk(e);else n&&n
|
|
1
|
+
import{extractFromTransComponent as e}from"./jsx-parser.js";import{getObjectPropValue as t,getObjectProperty as n}from"./ast-utils.js";class i{pluginContext;config;logger;scopeStack=[];objectKeys=new Set;constructor(e,t,n){this.pluginContext=t,this.config=e,this.logger=n}visit(e){this.enterScope(),this.walk(e),this.exitScope()}walk(e){if(!e)return;let t=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.enterScope(),t=!0),e.type){case"VariableDeclarator":this.handleVariableDeclarator(e);break;case"CallExpression":this.handleCallExpression(e);break;case"JSXElement":this.handleJSXElement(e)}for(const t in e){if("span"===t)continue;const n=e[t];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&this.walk(e);else n&&"object"==typeof n&&this.walk(n)}t&&this.exitScope()}enterScope(){this.scopeStack.push(new Map)}exitScope(){this.scopeStack.pop()}setVarInScope(e,t){this.scopeStack.length>0&&this.scopeStack[this.scopeStack.length-1].set(e,t)}getVarFromScope(e){for(let t=this.scopeStack.length-1;t>=0;t--)if(this.scopeStack[t].has(e))return this.scopeStack[t].get(e)}handleVariableDeclarator(e){const t=e.init;if(!t)return;const n="AwaitExpression"===t.type&&"CallExpression"===t.argument.type?t.argument:"CallExpression"===t.type?t:null;if(!n)return;const i=n.callee;if("Identifier"===i.type){const t=this.getUseTranslationConfig(i.value);if(t)return void this.handleUseTranslationDeclarator(e,n,t)}"MemberExpression"===i.type&&"Identifier"===i.property.type&&"getFixedT"===i.property.value&&this.handleGetFixedTDeclarator(e,n)}handleUseTranslationDeclarator(e,n,i){let r;if("Identifier"===e.id.type&&(r=e.id.value),"ArrayPattern"===e.id.type){const t=e.id.elements[0];"Identifier"===t?.type&&(r=t.value)}if("ObjectPattern"===e.id.type)for(const t of e.id.properties){if("AssignmentPatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value){r="t";break}if("KeyValuePatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value&&"Identifier"===t.value.type){r=t.value.value;break}}if(!r)return;const s=n.arguments?.[i.nsArg]?.expression;let a;"StringLiteral"===s?.type?a=s.value:"ArrayExpression"===s?.type&&"StringLiteral"===s.elements[0]?.expression.type&&(a=s.elements[0].expression.value);const o=n.arguments?.[i.keyPrefixArg]?.expression;let l;if("ObjectExpression"===o?.type){const e=t(o,"keyPrefix");l="string"==typeof e?e:void 0}this.setVarInScope(r,{defaultNs:a,keyPrefix:l})}handleGetFixedTDeclarator(e,t){if("Identifier"!==e.id.type||!e.init||"CallExpression"!==e.init.type)return;const n=e.id.value,i=t.arguments,r=i[1]?.expression,s=i[2]?.expression,a="StringLiteral"===r?.type?r.value:void 0,o="StringLiteral"===s?.type?s.value:void 0;(a||o)&&this.setVarInScope(n,{defaultNs:a,keyPrefix:o})}handleCallExpression(e){const i=this.getFunctionName(e.callee);if(!i)return;const r=this.getVarFromScope(i);if(!((this.config.extract.functions||["t"]).includes(i)||void 0!==r)||0===e.arguments.length)return;const s=e.arguments[0].expression;let a=[];if("StringLiteral"===s.type)a.push(s.value);else if("ArrowFunctionExpression"===s.type){const e=this.extractKeyFromSelector(s);e&&a.push(e)}else if("ArrayExpression"===s.type)for(const e of s.elements)"StringLiteral"===e?.expression.type&&a.push(e.expression.value);if(a=a.filter(e=>!!e),0===a.length)return;let o=!1;const l=this.config.extract.pluralSeparator??"_";for(let e=0;e<a.length;e++)a[e].endsWith(`${l}ordinal`)&&(o=!0,a[e]=a[e].slice(0,-8));let p,u;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?u=t:"StringLiteral"===t.type&&(p=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(u=t)}const c=u?t(u,"defaultValue"):void 0,f="string"==typeof c?c:p;for(let e=0;e<a.length;e++){let i,s=a[e];if(u){const e=t(u,"ns");"string"==typeof e&&(i=e)}!i&&r?.defaultNs&&(i=r.defaultNs);const l=this.config.extract.nsSeparator??":";if(!i&&l&&s.includes(l)){const e=s.split(l);i=e.shift(),s=e.join(l)}i||(i=this.config.extract.defaultNS);let p=s;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";p=`${r.keyPrefix}${e}${s}`}const c=e===a.length-1&&f||s;if(u){const e=n(u,"context");if("ConditionalExpression"===e?.value?.type){const t=this.resolvePossibleStringValues(e.value),n=this.config.extract.contextSeparator??"_";if(t.length>0){t.forEach(e=>{this.pluginContext.addKey({key:`${p}${n}${e}`,ns:i,defaultValue:c})}),this.pluginContext.addKey({key:p,ns:i,defaultValue:c});continue}}const r=t(u,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${p}${e}${r}`,ns:i,defaultValue:c});continue}const s=void 0!==t(u,"count"),a=!0===t(u,"ordinal");if(s||o){this.handlePluralKeys(p,i,u,a||o);continue}!0===t(u,"returnObjects")&&this.objectKeys.add(p)}this.pluginContext.addKey({key:p,ns:i,defaultValue:c})}}handlePluralKeys(e,n,i,r){try{const s=r?"ordinal":"cardinal",a=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:s}).resolvedOptions().pluralCategories,o=this.config.extract.pluralSeparator??"_",l=t(i,"defaultValue"),p=t(i,`defaultValue${o}other`),u=t(i,`defaultValue${o}ordinal${o}other`);for(const s of a){const a=t(i,r?`defaultValue${o}ordinal${o}${s}`:`defaultValue${o}${s}`);let c;c="string"==typeof a?a:"one"===s&&"string"==typeof l?l:r&&"string"==typeof u?u:r||"string"!=typeof p?"string"==typeof l?l:e:p;const f=r?`${e}${o}ordinal${o}${s}`:`${e}${o}${s}`;this.pluginContext.addKey({key:f,ns:n,defaultValue:c,hasCount:!0,isOrdinal:r})}}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const s=t(i,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof s?s:e})}}handleSimplePluralKeys(e,t,n){try{const i=new Intl.PluralRules(this.config.extract?.primaryLanguage).resolvedOptions().pluralCategories,r=this.config.extract.pluralSeparator??"_";for(const s of i)this.pluginContext.addKey({key:`${e}${r}${s}`,ns:n,defaultValue:t,hasCount:!0})}catch(i){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}".`),this.pluginContext.addKey({key:e,ns:n,defaultValue:t})}}handleJSXElement(t){const n=this.getElementName(t);if(n&&(this.config.extract.transComponents||["Trans"]).includes(n)){const n=e(t,this.config);if(n){if(!n.ns){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===e?.type&&"JSXExpressionContainer"===e.value?.type&&"Identifier"===e.value.expression.type){const t=e.value.expression.value,i=this.getVarFromScope(t);i?.defaultNs&&(n.ns=i.defaultNs)}}if(n.ns||(n.ns=this.config.extract.defaultNS),n.contextExpression){const e=this.resolvePossibleStringValues(n.contextExpression),t=this.config.extract.contextSeparator??"_";if(e.length>0){for(const i of e)this.pluginContext.addKey({key:`${n.key}${t}${i}`,ns:n.ns,defaultValue:n.defaultValue});"StringLiteral"!==n.contextExpression.type&&this.pluginContext.addKey(n)}}else if(n.hasCount){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),i=!!e,r=n.optionsNode??{type:"ObjectExpression",properties:[],span:{start:0,end:0,ctxt:0}};r.properties.push({type:"KeyValueProperty",key:{type:"Identifier",value:"defaultValue",optional:!1,span:{start:0,end:0,ctxt:0}},value:{type:"StringLiteral",value:n.defaultValue,span:{start:0,end:0,ctxt:0}}}),this.handlePluralKeys(n.key,n.ns,r,i)}else this.pluginContext.addKey(n)}}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let n=t;const i=[];for(;"MemberExpression"===n.type;){const e=n.property;if("Identifier"===e.type)i.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;i.unshift(e.expression.value)}n=n.object}if(i.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return i.join(t)}return null}resolvePossibleStringValues(e){if("StringLiteral"===e.type)return[e.value];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValues(e.consequent),...this.resolvePossibleStringValues(e.alternate)]}return"Identifier"===e.type&&e.value,[]}getUseTranslationConfig(e){const t=this.config.extract.useTranslationNames||["useTranslation"];for(const n of t){if("string"==typeof n&&n===e)return{name:e,nsArg:0,keyPrefixArg:1};if("object"==typeof n&&n.name===e)return{name:n.name,nsArg:n.nsArg??0,keyPrefixArg:n.keyPrefixArg??1}}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let n=e;for(;"MemberExpression"===n.type;){if("Identifier"!==n.property.type)return null;t.unshift(n.property.value),n=n.object}return"Identifier"!==n.type?null:(t.unshift(n.value),t.join("."))}return null}}export{i as ASTVisitors};
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -21,18 +21,19 @@ const program = new Command()
|
|
|
21
21
|
program
|
|
22
22
|
.name('i18next-cli')
|
|
23
23
|
.description('A unified, high-performance i18next CLI.')
|
|
24
|
-
.version('1.
|
|
24
|
+
.version('1.3.0')
|
|
25
25
|
|
|
26
26
|
program
|
|
27
27
|
.command('extract')
|
|
28
28
|
.description('Extract translation keys from source files and update resource files.')
|
|
29
29
|
.option('-w, --watch', 'Watch for file changes and re-run the extractor.')
|
|
30
30
|
.option('--ci', 'Exit with a non-zero status code if any files are updated.')
|
|
31
|
+
.option('--dry-run', 'Run the extractor without writing any files to disk.')
|
|
31
32
|
.action(async (options) => {
|
|
32
33
|
const config = await ensureConfig()
|
|
33
34
|
|
|
34
35
|
const run = async () => {
|
|
35
|
-
const filesWereUpdated = await runExtractor(config)
|
|
36
|
+
const filesWereUpdated = await runExtractor(config, { isWatchMode: options.watch, isDryRun: options.dryRun })
|
|
36
37
|
if (options.ci && filesWereUpdated) {
|
|
37
38
|
console.error(chalk.red.bold('\n[CI Mode] Error: Translation files were updated. Please commit the changes.'))
|
|
38
39
|
console.log(chalk.yellow('š” Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started'))
|
|
@@ -120,20 +121,44 @@ program
|
|
|
120
121
|
program
|
|
121
122
|
.command('lint')
|
|
122
123
|
.description('Find potential issues like hardcoded strings in your codebase.')
|
|
123
|
-
.
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
if (!
|
|
129
|
-
console.
|
|
130
|
-
|
|
131
|
-
|
|
124
|
+
.option('-w, --watch', 'Watch for file changes and re-run the linter.')
|
|
125
|
+
.action(async (options) => {
|
|
126
|
+
const loadAndRunLinter = async () => {
|
|
127
|
+
// The existing logic for loading the config or detecting it is now inside this function
|
|
128
|
+
let config = await loadConfig()
|
|
129
|
+
if (!config) {
|
|
130
|
+
console.log(chalk.blue('No config file found. Attempting to detect project structure...'))
|
|
131
|
+
const detected = await detectConfig()
|
|
132
|
+
if (!detected) {
|
|
133
|
+
console.error(chalk.red('Could not automatically detect your project structure.'))
|
|
134
|
+
console.log(`Please create a config file first by running: ${chalk.cyan('npx i18next-cli init')}`)
|
|
135
|
+
process.exit(1)
|
|
136
|
+
}
|
|
137
|
+
console.log(chalk.green('Project structure detected successfully!'))
|
|
138
|
+
config = detected as I18nextToolkitConfig
|
|
139
|
+
}
|
|
140
|
+
await runLinter(config)
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Run the linter once initially
|
|
144
|
+
await loadAndRunLinter()
|
|
145
|
+
|
|
146
|
+
// If in watch mode, set up the chokidar watcher
|
|
147
|
+
if (options.watch) {
|
|
148
|
+
console.log('\nWatching for changes...')
|
|
149
|
+
// Re-load the config to get the correct input paths for the watcher
|
|
150
|
+
const config = await loadConfig()
|
|
151
|
+
if (config?.extract?.input) {
|
|
152
|
+
const watcher = chokidar.watch(await glob(config.extract.input), {
|
|
153
|
+
ignored: /node_modules/,
|
|
154
|
+
persistent: true,
|
|
155
|
+
})
|
|
156
|
+
watcher.on('change', path => {
|
|
157
|
+
console.log(`\nFile changed: ${path}`)
|
|
158
|
+
loadAndRunLinter() // Re-run on change
|
|
159
|
+
})
|
|
132
160
|
}
|
|
133
|
-
console.log(chalk.green('Project structure detected successfully!'))
|
|
134
|
-
config = detected as I18nextToolkitConfig
|
|
135
161
|
}
|
|
136
|
-
await runLinter(config)
|
|
137
162
|
})
|
|
138
163
|
|
|
139
164
|
program
|
|
@@ -13,6 +13,8 @@ import { ASTVisitors } from '../parsers/ast-visitors'
|
|
|
13
13
|
import { ConsoleLogger } from '../../utils/logger'
|
|
14
14
|
import { serializeTranslationFile } from '../../utils/file-utils'
|
|
15
15
|
|
|
16
|
+
let hasLocizeFunnelBeenPrintedInWatchMode = false
|
|
17
|
+
|
|
16
18
|
/**
|
|
17
19
|
* Main extractor function that runs the complete key extraction and file generation process.
|
|
18
20
|
*
|
|
@@ -41,6 +43,13 @@ import { serializeTranslationFile } from '../../utils/file-utils'
|
|
|
41
43
|
*/
|
|
42
44
|
export async function runExtractor (
|
|
43
45
|
config: I18nextToolkitConfig,
|
|
46
|
+
{
|
|
47
|
+
isWatchMode = false,
|
|
48
|
+
isDryRun = false
|
|
49
|
+
}: {
|
|
50
|
+
isWatchMode?: boolean,
|
|
51
|
+
isDryRun?: boolean,
|
|
52
|
+
} = {},
|
|
44
53
|
logger: Logger = new ConsoleLogger()
|
|
45
54
|
): Promise<boolean> {
|
|
46
55
|
config.extract.primaryLanguage ||= config.locales[0] || 'en'
|
|
@@ -60,14 +69,17 @@ export async function runExtractor (
|
|
|
60
69
|
for (const result of results) {
|
|
61
70
|
if (result.updated) {
|
|
62
71
|
anyFileUpdated = true
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
72
|
+
// Only write files if it's not a dry run.
|
|
73
|
+
if (!isDryRun) {
|
|
74
|
+
const fileContent = serializeTranslationFile(
|
|
75
|
+
result.newTranslations,
|
|
76
|
+
config.extract.outputFormat,
|
|
77
|
+
config.extract.indentation
|
|
78
|
+
)
|
|
79
|
+
await mkdir(dirname(result.path), { recursive: true })
|
|
80
|
+
await writeFile(result.path, fileContent)
|
|
81
|
+
logger.info(chalk.green(`Updated: ${result.path}`))
|
|
82
|
+
}
|
|
71
83
|
}
|
|
72
84
|
}
|
|
73
85
|
|
|
@@ -75,7 +87,7 @@ export async function runExtractor (
|
|
|
75
87
|
|
|
76
88
|
// Show the funnel message only if files were actually changed.
|
|
77
89
|
if (anyFileUpdated) {
|
|
78
|
-
printLocizeFunnel()
|
|
90
|
+
printLocizeFunnel(isWatchMode)
|
|
79
91
|
}
|
|
80
92
|
|
|
81
93
|
return anyFileUpdated
|
|
@@ -205,10 +217,18 @@ export async function extract (config: I18nextToolkitConfig) {
|
|
|
205
217
|
* Prints a promotional message for the locize saveMissing workflow.
|
|
206
218
|
* This message is shown after a successful extraction that resulted in changes.
|
|
207
219
|
*/
|
|
208
|
-
function printLocizeFunnel () {
|
|
220
|
+
function printLocizeFunnel (isWatchMode: boolean = false) {
|
|
221
|
+
// Only print if not in watch mode, or if in watch mode and not yet printed.
|
|
222
|
+
if (isWatchMode && hasLocizeFunnelBeenPrintedInWatchMode) {
|
|
223
|
+
return
|
|
224
|
+
}
|
|
209
225
|
console.log(chalk.yellow.bold('\nš” Tip: Tired of running the extractor manually?'))
|
|
210
226
|
console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,')
|
|
211
227
|
console.log(' where keys are created and translated automatically as you code.')
|
|
212
228
|
console.log(` Learn more: ${chalk.cyan('https://www.locize.com/blog/i18next-savemissing-ai-automation')}`)
|
|
213
229
|
console.log(` Watch the video: ${chalk.cyan('https://youtu.be/joPsZghT3wM')}`)
|
|
230
|
+
|
|
231
|
+
if (isWatchMode) {
|
|
232
|
+
hasLocizeFunnelBeenPrintedInWatchMode = true // Mark as printed for watch mode
|
|
233
|
+
}
|
|
214
234
|
}
|
|
@@ -132,7 +132,9 @@ export class ASTVisitors {
|
|
|
132
132
|
this.walk(item)
|
|
133
133
|
}
|
|
134
134
|
}
|
|
135
|
-
} else if (child && child
|
|
135
|
+
} else if (child && typeof child === 'object') {
|
|
136
|
+
// The condition for single objects should be the same as for array items.
|
|
137
|
+
// Do not require `child.type`. This allows traversal into class method bodies.
|
|
136
138
|
this.walk(child)
|
|
137
139
|
}
|
|
138
140
|
}
|
|
@@ -26,7 +26,10 @@ import { ASTVisitors } from '../parsers/ast-visitors';
|
|
|
26
26
|
* }
|
|
27
27
|
* ```
|
|
28
28
|
*/
|
|
29
|
-
export declare function runExtractor(config: I18nextToolkitConfig,
|
|
29
|
+
export declare function runExtractor(config: I18nextToolkitConfig, { isWatchMode, isDryRun }?: {
|
|
30
|
+
isWatchMode?: boolean;
|
|
31
|
+
isDryRun?: boolean;
|
|
32
|
+
}, logger?: Logger): Promise<boolean>;
|
|
30
33
|
/**
|
|
31
34
|
* Processes an individual source file for translation key extraction.
|
|
32
35
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extractor.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/extractor.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAiB,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAM5F,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;
|
|
1
|
+
{"version":3,"file":"extractor.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/extractor.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAiB,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAM5F,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAMrD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,oBAAoB,EAC5B,EACE,WAAmB,EACnB,QAAgB,EACjB,GAAE;IACD,WAAW,CAAC,EAAE,OAAO,CAAC;IACtB,QAAQ,CAAC,EAAE,OAAO,CAAC;CACf,EACN,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,OAAO,CAAC,CA6ClB;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAsB,WAAW,CAC/B,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,oBAAoB,EAC5B,OAAO,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAClC,WAAW,EAAE,WAAW,EACxB,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,IAAI,CAAC,CA8Bf;AAmCD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAE,MAAM,EAAE,oBAAoB,sDAO1D"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ast-visitors.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/ast-visitors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAA+G,MAAM,WAAW,CAAA;AACpJ,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAqB9E;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAe;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,UAAU,CAAoC;IAE/C,UAAU,cAAoB;IAErC;;;;;;OAMG;gBAED,MAAM,EAAE,oBAAoB,EAC5B,aAAa,EAAE,aAAa,EAC5B,MAAM,EAAE,MAAM;IAOhB;;;;;OAKG;IACI,KAAK,CAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAMjC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,IAAI;
|
|
1
|
+
{"version":3,"file":"ast-visitors.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/ast-visitors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAA+G,MAAM,WAAW,CAAA;AACpJ,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAqB9E;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAe;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAsB;IAC7C,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAQ;IAC/B,OAAO,CAAC,UAAU,CAAoC;IAE/C,UAAU,cAAoB;IAErC;;;;;;OAMG;gBAED,MAAM,EAAE,oBAAoB,EAC5B,aAAa,EAAE,aAAa,EAC5B,MAAM,EAAE,MAAM;IAOhB;;;;;OAKG;IACI,KAAK,CAAE,IAAI,EAAE,MAAM,GAAG,IAAI;IAMjC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,IAAI;IAsDZ;;;;;OAKG;IACH,OAAO,CAAC,UAAU;IAIlB;;;;;OAKG;IACH,OAAO,CAAC,SAAS;IAIjB;;;;;;;;OAQG;IACH,OAAO,CAAC,aAAa;IAMrB;;;;;;;;OAQG;IACH,OAAO,CAAC,eAAe;IASvB;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,wBAAwB;IAmChC;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,8BAA8B;IAwDtC;;;;;;;;;;;;OAYG;IACH,OAAO,CAAC,yBAAyB;IAoBjC;;;;;;;;;;;;;;OAcG;IACH,OAAO,CAAC,oBAAoB;IAyI5B;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,gBAAgB;IA4DxB;;;;;;;;OAQG;IACH,OAAO,CAAC,sBAAsB;IAkB9B;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;IA2ExB;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,cAAc;IAgBtB;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,sBAAsB;IA2C9B;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,2BAA2B;IAmBnC;;;;;;OAMG;IACH,OAAO,CAAC,uBAAuB;IAoB/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,OAAO,CAAC,eAAe;CAwBxB"}
|