i18next-cli 1.5.6 → 1.5.8
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 +15 -0
- package/README.md +11 -4
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/config.js +1 -1
- package/dist/cjs/extractor/parsers/ast-visitors.js +1 -1
- package/dist/cjs/index.js +1 -1
- package/dist/cjs/migrator.js +1 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/config.js +1 -1
- package/dist/esm/extractor/parsers/ast-visitors.js +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/migrator.js +1 -1
- package/package.json +1 -1
- package/src/cli.ts +4 -4
- package/src/config.ts +1 -1
- package/src/extractor/parsers/ast-visitors.ts +108 -15
- package/src/index.ts +1 -0
- package/src/migrator.ts +112 -48
- package/types/config.d.ts +5 -0
- package/types/config.d.ts.map +1 -1
- package/types/extractor/parsers/ast-visitors.d.ts +13 -1
- package/types/extractor/parsers/ast-visitors.d.ts.map +1 -1
- package/types/index.d.ts +1 -0
- package/types/index.d.ts.map +1 -1
- package/types/migrator.d.ts +14 -19
- package/types/migrator.d.ts.map +1 -1
- package/vitest.config.ts +0 -17
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,21 @@ 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.5.8](https://github.com/i18next/i18next-cli/compare/v1.5.7...v1.5.8) - 2025-10-05
|
|
9
|
+
|
|
10
|
+
- **Extractor:** Fixed namespace resolution/override order where explicitly passed `ns` options in `t()` calls were being incorrectly overridden by hook-level namespaces. The extractor now properly prioritizes explicit namespace options over inferred ones. [#32](https://github.com/i18next/i18next-cli/issues/32)
|
|
11
|
+
- **Extractor (`<Trans>`):** Fixed a bug where `context` and `count` props on Trans components were treated as mutually exclusive. The extractor now correctly generates all combinations of context and plural forms (e.g., `key_context_one`, `key_context_other`) to match i18next's behavior. [#33](https://github.com/i18next/i18next-cli/issues/33)
|
|
12
|
+
- **Extractor:** Fixed a bug where passing an empty string as a context value (e.g., `context: test ? 'male' : ''`) resulted in keys with trailing underscores. Empty strings are now treated as "no context" like i18next does, ensuring clean key generation. [#34](https://github.com/i18next/i18next-cli/issues/34)
|
|
13
|
+
|
|
14
|
+
## [1.5.7](https://github.com/i18next/i18next-cli/compare/v1.5.6...v1.5.7) - 2025-10-04
|
|
15
|
+
|
|
16
|
+
### Added
|
|
17
|
+
- **Migration:** Added support for custom config file paths in the `migrate-config` command. You can now use a positional argument to specify non-standard config file locations (e.g., `i18next-cli migrate-config my-config.mjs`). [#31](https://github.com/i18next/i18next-cli/issues/31)
|
|
18
|
+
- **Programmatic API:** Exported `runTypesGenerator` function for programmatic usage for build tool integration.
|
|
19
|
+
|
|
20
|
+
### Enhanced
|
|
21
|
+
- **Migration:** Added warning for deprecated `compatibilityJSON: 'v3'` option in legacy configs.
|
|
22
|
+
|
|
8
23
|
## [1.5.6](https://github.com/i18next/i18next-cli/compare/v1.5.5...v1.5.6) - 2025-10-03
|
|
9
24
|
|
|
10
25
|
- **Programmatic API:** Exported `runExtractor`, `runLinter`, `runSyncer`, and `runStatus` functions for programmatic usage. You can now use `i18next-cli` directly in your build scripts, Gulp tasks, or any Node.js application without running the CLI commands. [#30](https://github.com/i18next/i18next-cli/issues/30)
|
package/README.md
CHANGED
|
@@ -201,6 +201,9 @@ Automatically migrates a legacy `i18next-parser.config.js` file to the new `i18n
|
|
|
201
201
|
|
|
202
202
|
```bash
|
|
203
203
|
npx i18next-cli migrate-config
|
|
204
|
+
|
|
205
|
+
# Using custom path for old config
|
|
206
|
+
npx i18next-cli migrate-config i18next-parser.config.mjs
|
|
204
207
|
```
|
|
205
208
|
|
|
206
209
|
### Locize Integration
|
|
@@ -676,7 +679,7 @@ In addition to the CLI commands, `i18next-cli` can be used programmatically in y
|
|
|
676
679
|
### Basic Programmatic Usage
|
|
677
680
|
|
|
678
681
|
```typescript
|
|
679
|
-
import { runExtractor, runLinter, runSyncer, runStatus } from 'i18next-cli';
|
|
682
|
+
import { runExtractor, runLinter, runSyncer, runStatus, runTypesGenerator } from 'i18next-cli';
|
|
680
683
|
import type { I18nextToolkitConfig } from 'i18next-cli';
|
|
681
684
|
|
|
682
685
|
const config: I18nextToolkitConfig = {
|
|
@@ -692,13 +695,16 @@ const wasUpdated = await runExtractor(config);
|
|
|
692
695
|
console.log('Files updated:', wasUpdated);
|
|
693
696
|
|
|
694
697
|
// Check translation status programmatically
|
|
695
|
-
|
|
698
|
+
await runStatus(config);
|
|
696
699
|
|
|
697
700
|
// Run linting
|
|
698
|
-
|
|
701
|
+
await runLinter(config);
|
|
699
702
|
|
|
700
703
|
// Sync translation files
|
|
701
|
-
|
|
704
|
+
await runSyncer(config);
|
|
705
|
+
|
|
706
|
+
// types generattion
|
|
707
|
+
await runTypesGenerator(config);
|
|
702
708
|
```
|
|
703
709
|
|
|
704
710
|
### Build Tool Integration
|
|
@@ -741,6 +747,7 @@ class I18nextExtractionPlugin {
|
|
|
741
747
|
- `runLinter(config)` - Run linting analysis
|
|
742
748
|
- `runSyncer(config)` - Sync translation files
|
|
743
749
|
- `runStatus(config, options?)` - Get translation status
|
|
750
|
+
- `runTypesGenerator(config)` - Generate types
|
|
744
751
|
|
|
745
752
|
This programmatic API gives you the same power as the CLI but with full control over when and how it runs in your build process.
|
|
746
753
|
|
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"),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.5.
|
|
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.5.8"),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 [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await l.runMigrator(e)}),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);
|
package/dist/cjs/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("node:path"),r=require("node:url"),t=require("node:fs/promises"),n=require("jiti"),o=require("jsonc-parser"),i=require("inquirer"),a=require("chalk"),
|
|
1
|
+
"use strict";var e=require("node:path"),r=require("node:url"),t=require("node:fs/promises"),n=require("jiti"),o=require("jsonc-parser"),i=require("inquirer"),a=require("chalk"),s=require("./init.js"),c=require("./utils/logger.js");const u=["i18next.config.ts","i18next.config.js","i18next.config.mjs","i18next.config.cjs"];async function l(o=new c.ConsoleLogger){const i=await async function(){for(const r of u){const n=e.resolve(process.cwd(),r);try{return await t.access(n),n}catch{}}return null}();if(!i)return null;try{let e;if(i.endsWith(".ts")){const r=await f(),t=n.createJiti(process.cwd(),{alias:r,interopDefault:!1}),o=await t.import(i,{default:!0});e=o}else{const t=r.pathToFileURL(i).href,n=await import(`${t}?t=${Date.now()}`);e=n.default}return e?(e.extract||={},e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(r=>r!==e.extract.primaryLanguage),e):(o.error(`Error: No default export found in ${i}`),null)}catch(e){return o.error(`Error loading configuration from ${i}`),o.error(e),null}}async function f(){try{const r=await async function(){let r=process.cwd();for(;;){const n=e.join(r,"tsconfig.json");try{return await t.access(n),n}catch{const t=e.dirname(r);if(t===r)return null;r=t}}}();if(!r)return{};const n=await t.readFile(r,"utf-8"),i=o.parse(n),a=i.compilerOptions?.paths,s=i.compilerOptions?.baseUrl||".";if(!a)return{};const c={};for(const[r,t]of Object.entries(a))if(Array.isArray(t)&&t.length>0){const n=r.replace("/*",""),o=e.resolve(process.cwd(),s,t[0].replace("/*",""));c[n]=o}return c}catch(e){return{}}}exports.defineConfig=function(e){return e},exports.ensureConfig=async function(e=new c.ConsoleLogger){let r=await l();if(r)return r;const{shouldInit:t}=await i.prompt([{type:"confirm",name:"shouldInit",message:a.yellow("Configuration file not found. Would you like to create one now?"),default:!0}]);if(t){if(await s.runInit(),e.info(a.green("Configuration created. Resuming command...")),r=await l(),r)return r;e.error(a.red("Error: Failed to load configuration after creation. Please try running the command again.")),process.exit(1)}else e.info("Operation cancelled. Please create a configuration file to proceed."),process.exit(0)},exports.getTsConfigAliases=f,exports.loadConfig=l;
|
|
@@ -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&&"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),i=this.config.extract.functions||["t","*.t"];let s=void 0!==r;if(!s)for(const e of i)if(e.startsWith("*.")){if(n.endsWith(e.substring(1))){s=!0;break}}else if(e===n){s=!0;break}if(!s||0===e.arguments.length)return;const a=e.arguments[0].expression;let o=[],l=!1;if("StringLiteral"===a.type)o.push(a.value);else if("ArrowFunctionExpression"===a.type){const e=this.extractKeyFromSelector(a);e&&(o.push(e),l=!0)}else if("ArrayExpression"===a.type)for(const e of a.elements)"StringLiteral"===e?.expression.type&&o.push(e.expression.value);if(o=o.filter(e=>!!e),0===o.length)return;let p=!1;const u=this.config.extract.pluralSeparator??"_";for(let e=0;e<o.length;e++)o[e].endsWith(`${u}ordinal`)&&(p=!0,o[e]=o[e].slice(0,-8));let c,f;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?f=t:"StringLiteral"===t.type&&(c=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(f=t)}const y=f?t.getObjectPropValue(f,"defaultValue"):void 0,g="string"==typeof y?y:c;for(let e=0;e<o.length;e++){let n,i=o[e];if(f){const e=t.getObjectPropValue(f,"ns");"string"==typeof e&&(n=e)}!n&&r?.defaultNs&&(n=r.defaultNs);const s=this.config.extract.nsSeparator??":";if(!n&&s&&i.includes(s)){const e=i.split(s);n=e.shift(),i=e.join(s)}n||(n=this.config.extract.defaultNS);let a=i;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";a=`${r.keyPrefix}${e}${i}`}const u=e===o.length-1&&g||i;if(f){const e=t.getObjectProperty(f,"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:`${a}${r}${e}`,ns:n,defaultValue:u})}),this.pluginContext.addKey({key:a,ns:n,defaultValue:u});continue}}const r=t.getObjectPropValue(f,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${a}${e}${r}`,ns:n,defaultValue:u});continue}const i=void 0!==t.getObjectPropValue(f,"count"),s=!0===t.getObjectPropValue(f,"ordinal");if(i||p){this.handlePluralKeys(a,n,f,s||p);continue}!0===t.getObjectPropValue(f,"returnObjects")&&this.objectKeys.add(a)}l&&this.objectKeys.add(a),this.pluginContext.addKey({key:a,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}if("ThisExpression"===n.type)t.unshift("this");else{if("Identifier"!==n.type)return null;t.unshift(n.value)}return t.join(".")}return null}};
|
|
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),i=this.config.extract.functions||["t","*.t"];let s=void 0!==r;if(!s)for(const e of i)if(e.startsWith("*.")){if(n.endsWith(e.substring(1))){s=!0;break}}else if(e===n){s=!0;break}if(!s||0===e.arguments.length)return;const a=e.arguments[0].expression;let o=[],l=!1;if("StringLiteral"===a.type)o.push(a.value);else if("ArrowFunctionExpression"===a.type){const e=this.extractKeyFromSelector(a);e&&(o.push(e),l=!0)}else if("ArrayExpression"===a.type)for(const e of a.elements)"StringLiteral"===e?.expression.type&&o.push(e.expression.value);if(o=o.filter(e=>!!e),0===o.length)return;let u=!1;const p=this.config.extract.pluralSeparator??"_";for(let e=0;e<o.length;e++)o[e].endsWith(`${p}ordinal`)&&(u=!0,o[e]=o[e].slice(0,-8));let c,f;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?f=t:"StringLiteral"===t.type&&(c=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(f=t)}const g=f?t.getObjectPropValue(f,"defaultValue"):void 0,y="string"==typeof g?g:c;for(let e=0;e<o.length;e++){let n,i=o[e];if(f){const e=t.getObjectPropValue(f,"ns");"string"==typeof e&&(n=e)}const s=this.config.extract.nsSeparator??":";if(!n&&s&&i.includes(s)){const e=i.split(s);n=e.shift(),i=e.join(s)}!n&&r?.defaultNs&&(n=r.defaultNs),n||(n=this.config.extract.defaultNS);let a=i;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";a=`${r.keyPrefix}${e}${i}`}const p=e===o.length-1&&y||i;if(f){const e=t.getObjectProperty(f,"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:`${a}${r}${e}`,ns:n,defaultValue:p})}),this.pluginContext.addKey({key:a,ns:n,defaultValue:p});continue}}const r=t.getObjectPropValue(f,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${a}${e}${r}`,ns:n,defaultValue:p});continue}const i=void 0!==t.getObjectPropValue(f,"count"),s=!0===t.getObjectPropValue(f,"ordinal");if(i||u){this.handlePluralKeys(a,n,f,s||u);continue}!0===t.getObjectPropValue(f,"returnObjects")&&this.objectKeys.add(a)}l&&this.objectKeys.add(a),this.pluginContext.addKey({key:a,ns:n,defaultValue:p})}}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"),u=t.getObjectPropValue(r,`defaultValue${o}other`),p=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 p?p:i||"string"!=typeof u?"string"==typeof l?l:e:u;const g=i?`${e}${o}ordinal${o}${s}`:`${e}${o}${s}`;this.pluginContext.addKey({key:g,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&&n.hasCount){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),r=!!e,i=this.resolvePossibleStringValues(n.contextExpression),s=this.config.extract.contextSeparator??"_";if(i.length>0){this.generatePluralKeysForTrans(n.key,n.defaultValue,n.ns,r,n.optionsNode);for(const e of i){const t=`${n.key}${s}${e}`;this.generatePluralKeysForTrans(t,n.defaultValue,n.ns,r,n.optionsNode)}}else this.generatePluralKeysForTrans(n.key,n.defaultValue,n.ns,r,n.optionsNode)}else if(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;this.generatePluralKeysForTrans(n.key,n.defaultValue,n.ns,r,n.optionsNode)}else this.pluginContext.addKey(n)}}}generatePluralKeysForTrans(e,n,r,i,s){try{const a=i?"ordinal":"cardinal",o=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:a}).resolvedOptions().pluralCategories,l=this.config.extract.pluralSeparator??"_";let u,p;s&&(u=t.getObjectPropValue(s,`defaultValue${l}other`),p=t.getObjectPropValue(s,`defaultValue${l}ordinal${l}other`));for(const a of o){const o=i?`defaultValue${l}ordinal${l}${a}`:`defaultValue${l}${a}`,c=s?t.getObjectPropValue(s,o):void 0;let f;f="string"==typeof c?c:"one"===a&&"string"==typeof n?n:i&&"string"==typeof p?p:i||"string"!=typeof u?"string"==typeof n?n:e:u;const g=i?`${e}${l}ordinal${l}${a}`:`${e}${l}${a}`;this.pluginContext.addKey({key:g,ns:r,defaultValue:f,hasCount:!0,isOrdinal:i})}}catch(t){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`),this.pluginContext.addKey({key:e,ns:r,defaultValue: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?[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}if("ThisExpression"===n.type)t.unshift("this");else{if("Identifier"!==n.type)return null;t.unshift(n.value)}return t.join(".")}return null}};
|
package/dist/cjs/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var r=require("./config.js"),e=require("./extractor/core/extractor.js"),t=require("./extractor/core/key-finder.js"),n=require("./extractor/core/translation-manager.js"),s=require("./linter.js"),o=require("./syncer.js"),
|
|
1
|
+
"use strict";var r=require("./config.js"),e=require("./extractor/core/extractor.js"),t=require("./extractor/core/key-finder.js"),n=require("./extractor/core/translation-manager.js"),s=require("./linter.js"),o=require("./syncer.js"),a=require("./status.js"),i=require("./types-generator.js");exports.defineConfig=r.defineConfig,exports.extract=e.extract,exports.runExtractor=e.runExtractor,exports.findKeys=t.findKeys,exports.getTranslations=n.getTranslations,exports.runLinter=s.runLinter,exports.runSyncer=o.runSyncer,exports.runStatus=a.runStatus,exports.runTypesGenerator=i.runTypesGenerator;
|
package/dist/cjs/migrator.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("node:path"),t=require("node:fs/promises"),n=require("node:url")
|
|
1
|
+
"use strict";var e=require("node:path"),t=require("node:fs/promises"),n=require("node:url"),o=require("jiti"),s=require("./config.js");const r=e.resolve(process.cwd(),"i18next.config.ts"),i=["i18next.config.ts","i18next.config.js","i18next.config.mjs","i18next.config.cjs"],a=[".js",".mjs",".cjs",".ts"];async function c(e){if(a.some(t=>e.endsWith(t)))try{return await t.access(e),e}catch{return null}for(const n of a){const o=`${e}${n}`;try{return await t.access(o),o}catch{}}return null}exports.runMigrator=async function(a){let l;if(a){if(l=await c(e.resolve(process.cwd(),a)),!l)return console.log(`No legacy config file found at or near: ${a}`),void console.log("Tried extensions: .js, .mjs, .cjs, .ts")}else if(l=await c(e.resolve(process.cwd(),"i18next-parser.config")),!l)return console.log("No i18next-parser.config.* found. Nothing to migrate."),void console.log("Tried: i18next-parser.config.js, .mjs, .cjs, .ts");console.log(`Attempting to migrate legacy config from: ${l}...`);for(const n of i)try{const o=e.resolve(process.cwd(),n);return await t.access(o),void console.warn(`Warning: A new configuration file already exists at "${n}". Migration skipped to avoid overwriting.`)}catch(e){}const f=await async function(e){try{let t;if(e.endsWith(".ts")){const n=await s.getTsConfigAliases(),r=o.createJiti(process.cwd(),{alias:n,interopDefault:!1});t=await r.import(e,{default:!0})}else{const o=n.pathToFileURL(e).href;t=(await import(`${o}?t=${Date.now()}`)).default}return t}catch(t){return console.error(`Error loading legacy config from ${e}:`,t),null}}(l);if(!f)return void console.error("Could not read the legacy config file.");const u={locales:f.locales||["en"],extract:{input:f.input||"src/**/*.{js,jsx,ts,tsx}",output:(f.output||"locales/$LOCALE/$NAMESPACE.json").replace("$LOCALE","{{language}}").replace("$NAMESPACE","{{namespace}}"),defaultNS:f.defaultNamespace||"translation",keySeparator:f.keySeparator,nsSeparator:f.namespaceSeparator,contextSeparator:f.contextSeparator,functions:f.lexers?.js?.functions||["t","*.t"],transComponents:f.lexers?.js?.components||["Trans"]},types:{input:["locales/{{language}}/{{namespace}}.json"],output:"src/types/i18next.d.ts"}};u.extract.functions.includes("t")&&!u.extract.functions.includes("*.t")&&u.extract.functions.push("*.t");const p=`\nimport { defineConfig } from 'i18next-cli';\n\nexport default defineConfig(${JSON.stringify(u,null,2)});\n`;await t.writeFile(r,p.trim()),console.log("✅ Success! Migration complete."),console.log(`New configuration file created at: ${r}`),console.warn('\nPlease review the generated file and adjust paths for "types.input" if necessary.'),f.keepRemoved&&console.warn('Warning: The "keepRemoved" option is deprecated. Consider using the "preservePatterns" feature for dynamic keys.'),"v3"===f.i18nextOptions?.compatibilityJSON&&console.warn('Warning: compatibilityJSON "v3" is not supported in i18next-cli. Only i18next v4 format is supported.')};
|
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 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.5.
|
|
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.5.8"),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 [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(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);
|
package/dist/esm/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolve as r,join as t,dirname as o}from"node:path";import{pathToFileURL as n}from"node:url";import{access as e,readFile as i}from"node:fs/promises";import{createJiti as a}from"jiti";import{parse as c}from"jsonc-parser";import s from"inquirer";import f from"chalk";import{runInit as l}from"./init.js";import{ConsoleLogger as u}from"./utils/logger.js";const p=["i18next.config.ts","i18next.config.js","i18next.config.mjs","i18next.config.cjs"];function m(r){return r}async function d(
|
|
1
|
+
import{resolve as r,join as t,dirname as o}from"node:path";import{pathToFileURL as n}from"node:url";import{access as e,readFile as i}from"node:fs/promises";import{createJiti as a}from"jiti";import{parse as c}from"jsonc-parser";import s from"inquirer";import f from"chalk";import{runInit as l}from"./init.js";import{ConsoleLogger as u}from"./utils/logger.js";const p=["i18next.config.ts","i18next.config.js","i18next.config.mjs","i18next.config.cjs"];function m(r){return r}async function d(t=new u){const o=await async function(){for(const t of p){const o=r(process.cwd(),t);try{return await e(o),o}catch{}}return null}();if(!o)return null;try{let r;if(o.endsWith(".ts")){const t=await w(),n=a(process.cwd(),{alias:t,interopDefault:!1}),e=await n.import(o,{default:!0});r=e}else{const t=n(o).href,e=await import(`${t}?t=${Date.now()}`);r=e.default}return r?(r.extract||={},r.extract.primaryLanguage||=r.locales[0]||"en",r.extract.secondaryLanguages||=r.locales.filter(t=>t!==r.extract.primaryLanguage),r):(t.error(`Error: No default export found in ${o}`),null)}catch(r){return t.error(`Error loading configuration from ${o}`),t.error(r),null}}async function g(r=new u){let t=await d();if(t)return t;const{shouldInit:o}=await s.prompt([{type:"confirm",name:"shouldInit",message:f.yellow("Configuration file not found. Would you like to create one now?"),default:!0}]);if(o){if(await l(),r.info(f.green("Configuration created. Resuming command...")),t=await d(),t)return t;r.error(f.red("Error: Failed to load configuration after creation. Please try running the command again.")),process.exit(1)}else r.info("Operation cancelled. Please create a configuration file to proceed."),process.exit(0)}async function w(){try{const n=await async function(){let r=process.cwd();for(;;){const n=t(r,"tsconfig.json");try{return await e(n),n}catch{const t=o(r);if(t===r)return null;r=t}}}();if(!n)return{};const a=await i(n,"utf-8"),s=c(a),f=s.compilerOptions?.paths,l=s.compilerOptions?.baseUrl||".";if(!f)return{};const u={};for(const[t,o]of Object.entries(f))if(Array.isArray(o)&&o.length>0){const n=t.replace("/*",""),e=r(process.cwd(),l,o[0].replace("/*",""));u[n]=e}return u}catch(r){return{}}}export{m as defineConfig,g as ensureConfig,w as getTsConfigAliases,d as loadConfig};
|
|
@@ -1 +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&&"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),s=this.config.extract.functions||["t","*.t"];let a=void 0!==r;if(!a)for(const e of s)if(e.startsWith("*.")){if(i.endsWith(e.substring(1))){a=!0;break}}else if(e===i){a=!0;break}if(!a||0===e.arguments.length)return;const o=e.arguments[0].expression;let l=[],p=!1;if("StringLiteral"===o.type)l.push(o.value);else if("ArrowFunctionExpression"===o.type){const e=this.extractKeyFromSelector(o);e&&(l.push(e),p=!0)}else if("ArrayExpression"===o.type)for(const e of o.elements)"StringLiteral"===e?.expression.type&&l.push(e.expression.value);if(l=l.filter(e=>!!e),0===l.length)return;let u=!1;const c=this.config.extract.pluralSeparator??"_";for(let e=0;e<l.length;e++)l[e].endsWith(`${c}ordinal`)&&(u=!0,l[e]=l[e].slice(0,-8));let f,y;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?y=t:"StringLiteral"===t.type&&(f=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(y=t)}const g=y?t(y,"defaultValue"):void 0,d="string"==typeof g?g:f;for(let e=0;e<l.length;e++){let i,s=l[e];if(y){const e=t(y,"ns");"string"==typeof e&&(i=e)}!i&&r?.defaultNs&&(i=r.defaultNs);const a=this.config.extract.nsSeparator??":";if(!i&&a&&s.includes(a)){const e=s.split(a);i=e.shift(),s=e.join(a)}i||(i=this.config.extract.defaultNS);let o=s;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";o=`${r.keyPrefix}${e}${s}`}const c=e===l.length-1&&d||s;if(y){const e=n(y,"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:`${o}${n}${e}`,ns:i,defaultValue:c})}),this.pluginContext.addKey({key:o,ns:i,defaultValue:c});continue}}const r=t(y,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${o}${e}${r}`,ns:i,defaultValue:c});continue}const s=void 0!==t(y,"count"),a=!0===t(y,"ordinal");if(s||u){this.handlePluralKeys(o,i,y,a||u);continue}!0===t(y,"returnObjects")&&this.objectKeys.add(o)}p&&this.objectKeys.add(o),this.pluginContext.addKey({key:o,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}if("ThisExpression"===n.type)t.unshift("this");else{if("Identifier"!==n.type)return null;t.unshift(n.value)}return t.join(".")}return null}}export{i as ASTVisitors};
|
|
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),s=this.config.extract.functions||["t","*.t"];let a=void 0!==r;if(!a)for(const e of s)if(e.startsWith("*.")){if(i.endsWith(e.substring(1))){a=!0;break}}else if(e===i){a=!0;break}if(!a||0===e.arguments.length)return;const o=e.arguments[0].expression;let l=[],u=!1;if("StringLiteral"===o.type)l.push(o.value);else if("ArrowFunctionExpression"===o.type){const e=this.extractKeyFromSelector(o);e&&(l.push(e),u=!0)}else if("ArrayExpression"===o.type)for(const e of o.elements)"StringLiteral"===e?.expression.type&&l.push(e.expression.value);if(l=l.filter(e=>!!e),0===l.length)return;let p=!1;const f=this.config.extract.pluralSeparator??"_";for(let e=0;e<l.length;e++)l[e].endsWith(`${f}ordinal`)&&(p=!0,l[e]=l[e].slice(0,-8));let c,y;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?y=t:"StringLiteral"===t.type&&(c=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(y=t)}const g=y?t(y,"defaultValue"):void 0,d="string"==typeof g?g:c;for(let e=0;e<l.length;e++){let i,s=l[e];if(y){const e=t(y,"ns");"string"==typeof e&&(i=e)}const a=this.config.extract.nsSeparator??":";if(!i&&a&&s.includes(a)){const e=s.split(a);i=e.shift(),s=e.join(a)}!i&&r?.defaultNs&&(i=r.defaultNs),i||(i=this.config.extract.defaultNS);let o=s;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";o=`${r.keyPrefix}${e}${s}`}const f=e===l.length-1&&d||s;if(y){const e=n(y,"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:`${o}${n}${e}`,ns:i,defaultValue:f})}),this.pluginContext.addKey({key:o,ns:i,defaultValue:f});continue}}const r=t(y,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${o}${e}${r}`,ns:i,defaultValue:f});continue}const s=void 0!==t(y,"count"),a=!0===t(y,"ordinal");if(s||p){this.handlePluralKeys(o,i,y,a||p);continue}!0===t(y,"returnObjects")&&this.objectKeys.add(o)}u&&this.objectKeys.add(o),this.pluginContext.addKey({key:o,ns:i,defaultValue:f})}}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"),u=t(i,`defaultValue${o}other`),p=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 f;f="string"==typeof a?a:"one"===s&&"string"==typeof l?l:r&&"string"==typeof p?p:r||"string"!=typeof u?"string"==typeof l?l:e:u;const c=r?`${e}${o}ordinal${o}${s}`:`${e}${o}${s}`;this.pluginContext.addKey({key:c,ns:n,defaultValue:f,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&&n.hasCount){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),i=!!e,r=this.resolvePossibleStringValues(n.contextExpression),s=this.config.extract.contextSeparator??"_";if(r.length>0){this.generatePluralKeysForTrans(n.key,n.defaultValue,n.ns,i,n.optionsNode);for(const e of r){const t=`${n.key}${s}${e}`;this.generatePluralKeysForTrans(t,n.defaultValue,n.ns,i,n.optionsNode)}}else this.generatePluralKeysForTrans(n.key,n.defaultValue,n.ns,i,n.optionsNode)}else if(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;this.generatePluralKeysForTrans(n.key,n.defaultValue,n.ns,i,n.optionsNode)}else this.pluginContext.addKey(n)}}}generatePluralKeysForTrans(e,n,i,r,s){try{const a=r?"ordinal":"cardinal",o=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:a}).resolvedOptions().pluralCategories,l=this.config.extract.pluralSeparator??"_";let u,p;s&&(u=t(s,`defaultValue${l}other`),p=t(s,`defaultValue${l}ordinal${l}other`));for(const a of o){const o=s?t(s,r?`defaultValue${l}ordinal${l}${a}`:`defaultValue${l}${a}`):void 0;let f;f="string"==typeof o?o:"one"===a&&"string"==typeof n?n:r&&"string"==typeof p?p:r||"string"!=typeof u?"string"==typeof n?n:e:u;const c=r?`${e}${l}ordinal${l}${a}`:`${e}${l}${a}`;this.pluginContext.addKey({key:c,ns:i,defaultValue:f,hasCount:!0,isOrdinal:r})}}catch(t){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`),this.pluginContext.addKey({key:e,ns:i,defaultValue: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?[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}if("ThisExpression"===n.type)t.unshift("this");else{if("Identifier"!==n.type)return null;t.unshift(n.value)}return t.join(".")}return null}}export{i as ASTVisitors};
|
package/dist/esm/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export{defineConfig}from"./config.js";export{extract,runExtractor}from"./extractor/core/extractor.js";export{findKeys}from"./extractor/core/key-finder.js";export{getTranslations}from"./extractor/core/translation-manager.js";export{runLinter}from"./linter.js";export{runSyncer}from"./syncer.js";export{runStatus}from"./status.js";
|
|
1
|
+
export{defineConfig}from"./config.js";export{extract,runExtractor}from"./extractor/core/extractor.js";export{findKeys}from"./extractor/core/key-finder.js";export{getTranslations}from"./extractor/core/translation-manager.js";export{runLinter}from"./linter.js";export{runSyncer}from"./syncer.js";export{runStatus}from"./status.js";export{runTypesGenerator}from"./types-generator.js";
|
package/dist/esm/migrator.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolve as e}from"node:path";import{access as t,writeFile as
|
|
1
|
+
import{resolve as e}from"node:path";import{access as t,writeFile as o}from"node:fs/promises";import{pathToFileURL as n}from"node:url";import{createJiti as i}from"jiti";import{getTsConfigAliases as r}from"./config.js";const s=e(process.cwd(),"i18next.config.ts"),a=["i18next.config.ts","i18next.config.js","i18next.config.mjs","i18next.config.cjs"],c=[".js",".mjs",".cjs",".ts"];async function l(e){if(c.some(t=>e.endsWith(t)))try{return await t(e),e}catch{return null}for(const o of c){const n=`${e}${o}`;try{return await t(n),n}catch{}}return null}async function f(c){let f;if(c){if(f=await l(e(process.cwd(),c)),!f)return console.log(`No legacy config file found at or near: ${c}`),void console.log("Tried extensions: .js, .mjs, .cjs, .ts")}else if(f=await l(e(process.cwd(),"i18next-parser.config")),!f)return console.log("No i18next-parser.config.* found. Nothing to migrate."),void console.log("Tried: i18next-parser.config.js, .mjs, .cjs, .ts");console.log(`Attempting to migrate legacy config from: ${f}...`);for(const o of a)try{const n=e(process.cwd(),o);return await t(n),void console.warn(`Warning: A new configuration file already exists at "${o}". Migration skipped to avoid overwriting.`)}catch(e){}const p=await async function(e){try{let t;if(e.endsWith(".ts")){const o=await r(),n=i(process.cwd(),{alias:o,interopDefault:!1});t=await n.import(e,{default:!0})}else{const o=n(e).href;t=(await import(`${o}?t=${Date.now()}`)).default}return t}catch(t){return console.error(`Error loading legacy config from ${e}:`,t),null}}(f);if(!p)return void console.error("Could not read the legacy config file.");const u={locales:p.locales||["en"],extract:{input:p.input||"src/**/*.{js,jsx,ts,tsx}",output:(p.output||"locales/$LOCALE/$NAMESPACE.json").replace("$LOCALE","{{language}}").replace("$NAMESPACE","{{namespace}}"),defaultNS:p.defaultNamespace||"translation",keySeparator:p.keySeparator,nsSeparator:p.namespaceSeparator,contextSeparator:p.contextSeparator,functions:p.lexers?.js?.functions||["t","*.t"],transComponents:p.lexers?.js?.components||["Trans"]},types:{input:["locales/{{language}}/{{namespace}}.json"],output:"src/types/i18next.d.ts"}};u.extract.functions.includes("t")&&!u.extract.functions.includes("*.t")&&u.extract.functions.push("*.t");const d=`\nimport { defineConfig } from 'i18next-cli';\n\nexport default defineConfig(${JSON.stringify(u,null,2)});\n`;await o(s,d.trim()),console.log("✅ Success! Migration complete."),console.log(`New configuration file created at: ${s}`),console.warn('\nPlease review the generated file and adjust paths for "types.input" if necessary.'),p.keepRemoved&&console.warn('Warning: The "keepRemoved" option is deprecated. Consider using the "preservePatterns" feature for dynamic keys.'),"v3"===p.i18nextOptions?.compatibilityJSON&&console.warn('Warning: compatibilityJSON "v3" is not supported in i18next-cli. Only i18next v4 format is supported.')}export{f as runMigrator};
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -21,7 +21,7 @@ const program = new Command()
|
|
|
21
21
|
program
|
|
22
22
|
.name('i18next-cli')
|
|
23
23
|
.description('A unified, high-performance i18next CLI.')
|
|
24
|
-
.version('1.5.
|
|
24
|
+
.version('1.5.8')
|
|
25
25
|
|
|
26
26
|
program
|
|
27
27
|
.command('extract')
|
|
@@ -107,10 +107,10 @@ program
|
|
|
107
107
|
})
|
|
108
108
|
|
|
109
109
|
program
|
|
110
|
-
.command('migrate-config')
|
|
110
|
+
.command('migrate-config [configPath]')
|
|
111
111
|
.description('Migrate a legacy i18next-parser.config.js to the new format.')
|
|
112
|
-
.action(async () => {
|
|
113
|
-
await runMigrator()
|
|
112
|
+
.action(async (configPath) => {
|
|
113
|
+
await runMigrator(configPath)
|
|
114
114
|
})
|
|
115
115
|
|
|
116
116
|
program
|
package/src/config.ts
CHANGED
|
@@ -191,7 +191,7 @@ async function findTsConfigFile (): Promise<string | null> {
|
|
|
191
191
|
* Parses the project's tsconfig.json to extract path aliases for jiti.
|
|
192
192
|
* @returns A record of aliases for jiti's configuration.
|
|
193
193
|
*/
|
|
194
|
-
async function getTsConfigAliases (): Promise<Record<string, string>> {
|
|
194
|
+
export async function getTsConfigAliases (): Promise<Record<string, string>> {
|
|
195
195
|
try {
|
|
196
196
|
const tsConfigPath = await findTsConfigFile()
|
|
197
197
|
if (!tsConfigPath) return {}
|
|
@@ -454,12 +454,12 @@ export class ASTVisitors {
|
|
|
454
454
|
let key = keysToProcess[i]
|
|
455
455
|
let ns: string | undefined
|
|
456
456
|
|
|
457
|
-
// Determine namespace (explicit ns >
|
|
457
|
+
// Determine namespace (explicit ns > ns:key > scope ns > default)
|
|
458
|
+
// See https://www.i18next.com/overview/api#getfixedt
|
|
458
459
|
if (options) {
|
|
459
460
|
const nsVal = getObjectPropValue(options, 'ns')
|
|
460
461
|
if (typeof nsVal === 'string') ns = nsVal
|
|
461
462
|
}
|
|
462
|
-
if (!ns && scopeInfo?.defaultNs) ns = scopeInfo.defaultNs
|
|
463
463
|
|
|
464
464
|
const nsSeparator = this.config.extract.nsSeparator ?? ':'
|
|
465
465
|
if (!ns && nsSeparator && key.includes(nsSeparator)) {
|
|
@@ -467,6 +467,8 @@ export class ASTVisitors {
|
|
|
467
467
|
ns = parts.shift()
|
|
468
468
|
key = parts.join(nsSeparator)
|
|
469
469
|
}
|
|
470
|
+
|
|
471
|
+
if (!ns && scopeInfo?.defaultNs) ns = scopeInfo.defaultNs
|
|
470
472
|
if (!ns) ns = this.config.extract.defaultNS
|
|
471
473
|
|
|
472
474
|
let finalKey = key
|
|
@@ -677,7 +679,35 @@ export class ASTVisitors {
|
|
|
677
679
|
extractedKey.ns = this.config.extract.defaultNS
|
|
678
680
|
}
|
|
679
681
|
|
|
680
|
-
|
|
682
|
+
// Handle the combination of context and count
|
|
683
|
+
if (extractedKey.contextExpression && extractedKey.hasCount) {
|
|
684
|
+
// Find isOrdinal prop on the <Trans> component
|
|
685
|
+
const ordinalAttr = node.opening.attributes?.find(
|
|
686
|
+
(attr) =>
|
|
687
|
+
attr.type === 'JSXAttribute' &&
|
|
688
|
+
attr.name.type === 'Identifier' &&
|
|
689
|
+
attr.name.value === 'ordinal'
|
|
690
|
+
)
|
|
691
|
+
const isOrdinal = !!ordinalAttr
|
|
692
|
+
|
|
693
|
+
const contextValues = this.resolvePossibleStringValues(extractedKey.contextExpression)
|
|
694
|
+
const contextSeparator = this.config.extract.contextSeparator ?? '_'
|
|
695
|
+
|
|
696
|
+
// Generate all combinations of context and plural forms
|
|
697
|
+
if (contextValues.length > 0) {
|
|
698
|
+
// Generate base plural forms (no context)
|
|
699
|
+
this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, extractedKey.optionsNode)
|
|
700
|
+
|
|
701
|
+
// Generate context + plural combinations
|
|
702
|
+
for (const context of contextValues) {
|
|
703
|
+
const contextKey = `${extractedKey.key}${contextSeparator}${context}`
|
|
704
|
+
this.generatePluralKeysForTrans(contextKey, extractedKey.defaultValue, extractedKey.ns, isOrdinal, extractedKey.optionsNode)
|
|
705
|
+
}
|
|
706
|
+
} else {
|
|
707
|
+
// Fallback to just plural forms if context resolution fails
|
|
708
|
+
this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, extractedKey.optionsNode)
|
|
709
|
+
}
|
|
710
|
+
} else if (extractedKey.contextExpression) {
|
|
681
711
|
const contextValues = this.resolvePossibleStringValues(extractedKey.contextExpression)
|
|
682
712
|
const contextSeparator = this.config.extract.contextSeparator ?? '_'
|
|
683
713
|
|
|
@@ -700,21 +730,83 @@ export class ASTVisitors {
|
|
|
700
730
|
)
|
|
701
731
|
const isOrdinal = !!ordinalAttr
|
|
702
732
|
|
|
703
|
-
|
|
704
|
-
|
|
733
|
+
this.generatePluralKeysForTrans(extractedKey.key, extractedKey.defaultValue, extractedKey.ns, isOrdinal, extractedKey.optionsNode)
|
|
734
|
+
} else {
|
|
735
|
+
this.pluginContext.addKey(extractedKey)
|
|
736
|
+
}
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
/**
|
|
742
|
+
* Generates plural keys for Trans components, with support for tOptions plural defaults.
|
|
743
|
+
*
|
|
744
|
+
* @param key - Base key name for pluralization
|
|
745
|
+
* @param defaultValue - Default value for the keys
|
|
746
|
+
* @param ns - Namespace for the keys
|
|
747
|
+
* @param isOrdinal - Whether to generate ordinal plural forms
|
|
748
|
+
* @param optionsNode - Optional tOptions object expression for plural-specific defaults
|
|
749
|
+
*
|
|
750
|
+
* @private
|
|
751
|
+
*/
|
|
752
|
+
private generatePluralKeysForTrans (key: string, defaultValue: string | undefined, ns: string | undefined, isOrdinal: boolean, optionsNode?: ObjectExpression): void {
|
|
753
|
+
try {
|
|
754
|
+
const type = isOrdinal ? 'ordinal' : 'cardinal'
|
|
755
|
+
const pluralCategories = new Intl.PluralRules(this.config.extract?.primaryLanguage, { type }).resolvedOptions().pluralCategories
|
|
756
|
+
const pluralSeparator = this.config.extract.pluralSeparator ?? '_'
|
|
757
|
+
|
|
758
|
+
// Get plural-specific default values from tOptions if available
|
|
759
|
+
let otherDefault: string | undefined
|
|
760
|
+
let ordinalOtherDefault: string | undefined
|
|
761
|
+
|
|
762
|
+
if (optionsNode) {
|
|
763
|
+
otherDefault = getObjectPropValue(optionsNode, `defaultValue${pluralSeparator}other`) as string | undefined
|
|
764
|
+
ordinalOtherDefault = getObjectPropValue(optionsNode, `defaultValue${pluralSeparator}ordinal${pluralSeparator}other`) as string | undefined
|
|
765
|
+
}
|
|
705
766
|
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
value: { type: 'StringLiteral', value: extractedKey.defaultValue!, span: { start: 0, end: 0, ctxt: 0 } }
|
|
711
|
-
})
|
|
767
|
+
for (const category of pluralCategories) {
|
|
768
|
+
// Look for the most specific default value (e.g., defaultValue_ordinal_one)
|
|
769
|
+
const specificDefaultKey = isOrdinal ? `defaultValue${pluralSeparator}ordinal${pluralSeparator}${category}` : `defaultValue${pluralSeparator}${category}`
|
|
770
|
+
const specificDefault = optionsNode ? getObjectPropValue(optionsNode, specificDefaultKey) as string | undefined : undefined
|
|
712
771
|
|
|
713
|
-
|
|
772
|
+
// Determine the final default value using a clear fallback chain
|
|
773
|
+
let finalDefaultValue: string | undefined
|
|
774
|
+
if (typeof specificDefault === 'string') {
|
|
775
|
+
// 1. Use the most specific default if it exists (e.g., defaultValue_one)
|
|
776
|
+
finalDefaultValue = specificDefault
|
|
777
|
+
} else if (category === 'one' && typeof defaultValue === 'string') {
|
|
778
|
+
// 2. SPECIAL CASE: The 'one' category falls back to the main default value (children content)
|
|
779
|
+
finalDefaultValue = defaultValue
|
|
780
|
+
} else if (isOrdinal && typeof ordinalOtherDefault === 'string') {
|
|
781
|
+
// 3a. Other ordinal categories fall back to 'defaultValue_ordinal_other'
|
|
782
|
+
finalDefaultValue = ordinalOtherDefault
|
|
783
|
+
} else if (!isOrdinal && typeof otherDefault === 'string') {
|
|
784
|
+
// 3b. Other cardinal categories fall back to 'defaultValue_other'
|
|
785
|
+
finalDefaultValue = otherDefault
|
|
786
|
+
} else if (typeof defaultValue === 'string') {
|
|
787
|
+
// 4. If no '_other' is found, all categories can fall back to the main default value
|
|
788
|
+
finalDefaultValue = defaultValue
|
|
714
789
|
} else {
|
|
715
|
-
|
|
790
|
+
// 5. Final fallback to the base key itself
|
|
791
|
+
finalDefaultValue = key
|
|
716
792
|
}
|
|
793
|
+
|
|
794
|
+
const finalKey = isOrdinal
|
|
795
|
+
? `${key}${pluralSeparator}ordinal${pluralSeparator}${category}`
|
|
796
|
+
: `${key}${pluralSeparator}${category}`
|
|
797
|
+
|
|
798
|
+
this.pluginContext.addKey({
|
|
799
|
+
key: finalKey,
|
|
800
|
+
ns,
|
|
801
|
+
defaultValue: finalDefaultValue,
|
|
802
|
+
hasCount: true,
|
|
803
|
+
isOrdinal
|
|
804
|
+
})
|
|
717
805
|
}
|
|
806
|
+
} catch (e) {
|
|
807
|
+
this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`)
|
|
808
|
+
// Fallback to a simple key if Intl API fails
|
|
809
|
+
this.pluginContext.addKey({ key, ns, defaultValue })
|
|
718
810
|
}
|
|
719
811
|
}
|
|
720
812
|
|
|
@@ -810,7 +902,7 @@ export class ASTVisitors {
|
|
|
810
902
|
* determined statically from the AST.
|
|
811
903
|
*
|
|
812
904
|
* Supports:
|
|
813
|
-
* - StringLiteral -> single value
|
|
905
|
+
* - StringLiteral -> single value (filtered to exclude empty strings for context)
|
|
814
906
|
* - ConditionalExpression (ternary) -> union of consequent and alternate resolved values
|
|
815
907
|
* - The identifier `undefined` -> empty array
|
|
816
908
|
*
|
|
@@ -823,7 +915,8 @@ export class ASTVisitors {
|
|
|
823
915
|
*/
|
|
824
916
|
private resolvePossibleStringValues (expression: Expression): string[] {
|
|
825
917
|
if (expression.type === 'StringLiteral') {
|
|
826
|
-
|
|
918
|
+
// Filter out empty strings as they should be treated as "no context" like i18next does
|
|
919
|
+
return expression.value ? [expression.value] : []
|
|
827
920
|
}
|
|
828
921
|
|
|
829
922
|
if (expression.type === 'ConditionalExpression') { // This is a ternary operator
|
package/src/index.ts
CHANGED
package/src/migrator.ts
CHANGED
|
@@ -1,11 +1,8 @@
|
|
|
1
1
|
import { resolve } from 'node:path'
|
|
2
2
|
import { writeFile, access } from 'node:fs/promises'
|
|
3
3
|
import { pathToFileURL } from 'node:url'
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
* Path to the legacy i18next-parser configuration file
|
|
7
|
-
*/
|
|
8
|
-
const oldConfigPath = resolve(process.cwd(), 'i18next-parser.config.js')
|
|
4
|
+
import { createJiti } from 'jiti'
|
|
5
|
+
import { getTsConfigAliases } from './config'
|
|
9
6
|
|
|
10
7
|
/**
|
|
11
8
|
* Path where the new configuration file will be created
|
|
@@ -23,13 +20,76 @@ const POSSIBLE_NEW_CONFIGS = [
|
|
|
23
20
|
]
|
|
24
21
|
|
|
25
22
|
/**
|
|
26
|
-
*
|
|
23
|
+
* List of supported legacy configuration file extensions
|
|
24
|
+
*/
|
|
25
|
+
const LEGACY_CONFIG_EXTENSIONS = ['.js', '.mjs', '.cjs', '.ts']
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Helper function to find a legacy config file with various extensions
|
|
29
|
+
*/
|
|
30
|
+
async function findLegacyConfigFile (basePath: string): Promise<string | null> {
|
|
31
|
+
// If the provided path already has an extension, use it directly
|
|
32
|
+
if (LEGACY_CONFIG_EXTENSIONS.some(ext => basePath.endsWith(ext))) {
|
|
33
|
+
try {
|
|
34
|
+
await access(basePath)
|
|
35
|
+
return basePath
|
|
36
|
+
} catch {
|
|
37
|
+
return null
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// Try different extensions
|
|
42
|
+
for (const ext of LEGACY_CONFIG_EXTENSIONS) {
|
|
43
|
+
const fullPath = `${basePath}${ext}`
|
|
44
|
+
try {
|
|
45
|
+
await access(fullPath)
|
|
46
|
+
return fullPath
|
|
47
|
+
} catch {
|
|
48
|
+
// Continue to next extension
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return null
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Loads a legacy config file using the appropriate loader (jiti for TS, dynamic import for JS/MJS/CJS)
|
|
57
|
+
*/
|
|
58
|
+
async function loadLegacyConfig (configPath: string): Promise<any> {
|
|
59
|
+
try {
|
|
60
|
+
let config: any
|
|
61
|
+
|
|
62
|
+
// Use jiti for TypeScript files, native import for JavaScript
|
|
63
|
+
if (configPath.endsWith('.ts')) {
|
|
64
|
+
const aliases = await getTsConfigAliases()
|
|
65
|
+
const jiti = createJiti(process.cwd(), {
|
|
66
|
+
alias: aliases,
|
|
67
|
+
interopDefault: false,
|
|
68
|
+
})
|
|
69
|
+
|
|
70
|
+
const configModule = await jiti.import(configPath, { default: true })
|
|
71
|
+
config = configModule
|
|
72
|
+
} else {
|
|
73
|
+
const configUrl = pathToFileURL(configPath).href
|
|
74
|
+
const configModule = await import(`${configUrl}?t=${Date.now()}`)
|
|
75
|
+
config = configModule.default
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return config
|
|
79
|
+
} catch (error) {
|
|
80
|
+
console.error(`Error loading legacy config from ${configPath}:`, error)
|
|
81
|
+
return null
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Migrates a legacy i18next-parser configuration file to the new
|
|
27
87
|
* i18next-cli configuration format.
|
|
28
88
|
*
|
|
29
89
|
* This function:
|
|
30
|
-
* 1. Checks if a legacy config file exists
|
|
90
|
+
* 1. Checks if a legacy config file exists (supports .js, .mjs, .cjs, .ts)
|
|
31
91
|
* 2. Prevents migration if any new config file already exists
|
|
32
|
-
* 3. Dynamically imports the old configuration
|
|
92
|
+
* 3. Dynamically imports the old configuration using appropriate loader
|
|
33
93
|
* 4. Maps old configuration properties to new format:
|
|
34
94
|
* - `$LOCALE` → `{{language}}`
|
|
35
95
|
* - `$NAMESPACE` → `{{namespace}}`
|
|
@@ -38,41 +98,41 @@ const POSSIBLE_NEW_CONFIGS = [
|
|
|
38
98
|
* 5. Generates a new TypeScript configuration file
|
|
39
99
|
* 6. Provides warnings for deprecated features
|
|
40
100
|
*
|
|
101
|
+
* @param customConfigPath - Optional custom path to the legacy config file
|
|
102
|
+
*
|
|
41
103
|
* @example
|
|
42
|
-
* ```
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
46
|
-
*
|
|
47
|
-
*
|
|
48
|
-
* }
|
|
104
|
+
* ```bash
|
|
105
|
+
* # Migrate default config
|
|
106
|
+
* npx i18next-cli migrate-config
|
|
107
|
+
*
|
|
108
|
+
* # Migrate custom config with extension
|
|
109
|
+
* npx i18next-cli migrate-config i18next-parser.config.mjs
|
|
49
110
|
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* locales: ['en', 'de'],
|
|
53
|
-
* extract: {
|
|
54
|
-
* input: ['src/**\/*.js'],
|
|
55
|
-
* output: 'locales/{{language}}/{{namespace}}.json'
|
|
56
|
-
* }
|
|
57
|
-
* })
|
|
111
|
+
* # Migrate custom config without extension (will try .js, .mjs, .cjs, .ts)
|
|
112
|
+
* npx i18next-cli migrate-config my-custom-config
|
|
58
113
|
* ```
|
|
59
114
|
*/
|
|
60
|
-
export async function runMigrator () {
|
|
61
|
-
|
|
115
|
+
export async function runMigrator (customConfigPath?: string) {
|
|
116
|
+
let oldConfigPath: string | null
|
|
62
117
|
|
|
63
|
-
|
|
64
|
-
await
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
118
|
+
if (customConfigPath) {
|
|
119
|
+
oldConfigPath = await findLegacyConfigFile(resolve(process.cwd(), customConfigPath))
|
|
120
|
+
if (!oldConfigPath) {
|
|
121
|
+
console.log(`No legacy config file found at or near: ${customConfigPath}`)
|
|
122
|
+
console.log('Tried extensions: .js, .mjs, .cjs, .ts')
|
|
123
|
+
return
|
|
124
|
+
}
|
|
125
|
+
} else {
|
|
126
|
+
// Default behavior: look for i18next-parser.config.* files
|
|
127
|
+
oldConfigPath = await findLegacyConfigFile(resolve(process.cwd(), 'i18next-parser.config'))
|
|
128
|
+
if (!oldConfigPath) {
|
|
129
|
+
console.log('No i18next-parser.config.* found. Nothing to migrate.')
|
|
130
|
+
console.log('Tried: i18next-parser.config.js, .mjs, .cjs, .ts')
|
|
131
|
+
return
|
|
132
|
+
}
|
|
68
133
|
}
|
|
69
134
|
|
|
70
|
-
|
|
71
|
-
await access(oldConfigPath)
|
|
72
|
-
} catch (e) {
|
|
73
|
-
console.log('No i18next-parser.config.js found. Nothing to migrate.')
|
|
74
|
-
return
|
|
75
|
-
}
|
|
135
|
+
console.log(`Attempting to migrate legacy config from: ${oldConfigPath}...`)
|
|
76
136
|
|
|
77
137
|
// Check if ANY new config file already exists
|
|
78
138
|
for (const configFile of POSSIBLE_NEW_CONFIGS) {
|
|
@@ -86,10 +146,8 @@ export async function runMigrator () {
|
|
|
86
146
|
}
|
|
87
147
|
}
|
|
88
148
|
|
|
89
|
-
//
|
|
90
|
-
const
|
|
91
|
-
const oldConfigModule = await import(oldConfigUrl)
|
|
92
|
-
const oldConfig = oldConfigModule.default
|
|
149
|
+
// Load the legacy config using the appropriate loader
|
|
150
|
+
const oldConfig = await loadLegacyConfig(oldConfigPath)
|
|
93
151
|
|
|
94
152
|
if (!oldConfig) {
|
|
95
153
|
console.error('Could not read the legacy config file.')
|
|
@@ -101,7 +159,9 @@ export async function runMigrator () {
|
|
|
101
159
|
locales: oldConfig.locales || ['en'],
|
|
102
160
|
extract: {
|
|
103
161
|
input: oldConfig.input || 'src/**/*.{js,jsx,ts,tsx}',
|
|
104
|
-
output: (oldConfig.output || 'locales/$LOCALE/$NAMESPACE.json')
|
|
162
|
+
output: (oldConfig.output || 'locales/$LOCALE/$NAMESPACE.json')
|
|
163
|
+
.replace('$LOCALE', '{{language}}')
|
|
164
|
+
.replace('$NAMESPACE', '{{namespace}}'),
|
|
105
165
|
defaultNS: oldConfig.defaultNamespace || 'translation',
|
|
106
166
|
keySeparator: oldConfig.keySeparator,
|
|
107
167
|
nsSeparator: oldConfig.namespaceSeparator,
|
|
@@ -110,15 +170,12 @@ export async function runMigrator () {
|
|
|
110
170
|
functions: oldConfig.lexers?.js?.functions || ['t', '*.t'],
|
|
111
171
|
transComponents: oldConfig.lexers?.js?.components || ['Trans'],
|
|
112
172
|
},
|
|
113
|
-
|
|
114
|
-
input: 'locales/{{language}}/{{namespace}}.json', // Sensible default
|
|
173
|
+
types: {
|
|
174
|
+
input: ['locales/{{language}}/{{namespace}}.json'], // Sensible default
|
|
115
175
|
output: 'src/types/i18next.d.ts', // Sensible default
|
|
116
176
|
},
|
|
117
|
-
sync: {
|
|
118
|
-
primaryLanguage: oldConfig.locales?.[0] || 'en',
|
|
119
|
-
secondaryLanguages: oldConfig.locales.filter((l: string) => l !== (oldConfig.locales?.[0] || 'en'))
|
|
120
|
-
},
|
|
121
177
|
}
|
|
178
|
+
|
|
122
179
|
// Make the migration smarter: if 't' is a function, also add the '*.t' wildcard
|
|
123
180
|
// to provide better out-of-the-box support for common patterns like `i18n.t`.
|
|
124
181
|
if (newConfig.extract.functions.includes('t') && !newConfig.extract.functions.includes('*.t')) {
|
|
@@ -137,8 +194,15 @@ export default defineConfig(${JSON.stringify(newConfig, null, 2)});
|
|
|
137
194
|
|
|
138
195
|
console.log('✅ Success! Migration complete.')
|
|
139
196
|
console.log(`New configuration file created at: ${newConfigPath}`)
|
|
140
|
-
console.warn('\nPlease review the generated file and adjust paths for "
|
|
197
|
+
console.warn('\nPlease review the generated file and adjust paths for "types.input" if necessary.')
|
|
198
|
+
|
|
199
|
+
// Warning for deprecated features
|
|
141
200
|
if (oldConfig.keepRemoved) {
|
|
142
201
|
console.warn('Warning: The "keepRemoved" option is deprecated. Consider using the "preservePatterns" feature for dynamic keys.')
|
|
143
202
|
}
|
|
203
|
+
|
|
204
|
+
// Warning for compatibilityJSON v3
|
|
205
|
+
if (oldConfig.i18nextOptions?.compatibilityJSON === 'v3') {
|
|
206
|
+
console.warn('Warning: compatibilityJSON "v3" is not supported in i18next-cli. Only i18next v4 format is supported.')
|
|
207
|
+
}
|
|
144
208
|
}
|
package/types/config.d.ts
CHANGED
|
@@ -47,4 +47,9 @@ export declare function loadConfig(logger?: Logger): Promise<I18nextToolkitConfi
|
|
|
47
47
|
* @throws Exits the process if the user declines to create a config or if loading fails after creation.
|
|
48
48
|
*/
|
|
49
49
|
export declare function ensureConfig(logger?: Logger): Promise<I18nextToolkitConfig>;
|
|
50
|
+
/**
|
|
51
|
+
* Parses the project's tsconfig.json to extract path aliases for jiti.
|
|
52
|
+
* @returns A record of aliases for jiti's configuration.
|
|
53
|
+
*/
|
|
54
|
+
export declare function getTsConfigAliases(): Promise<Record<string, string>>;
|
|
50
55
|
//# sourceMappingURL=config.d.ts.map
|
package/types/config.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAc3D;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,YAAY,CAAE,MAAM,EAAE,oBAAoB,GAAG,oBAAoB,CAEhF;AAqBD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,UAAU,CAAE,MAAM,GAAE,MAA4B,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CA2C5G;AAED;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAE,MAAM,GAAE,MAA4B,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA8BvG"}
|
|
1
|
+
{"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAOA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,SAAS,CAAA;AAc3D;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,YAAY,CAAE,MAAM,EAAE,oBAAoB,GAAG,oBAAoB,CAEhF;AAqBD;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,wBAAsB,UAAU,CAAE,MAAM,GAAE,MAA4B,GAAG,OAAO,CAAC,oBAAoB,GAAG,IAAI,CAAC,CA2C5G;AAED;;;;;;GAMG;AACH,wBAAsB,YAAY,CAAE,MAAM,GAAE,MAA4B,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA8BvG;AAyBD;;;GAGG;AACH,wBAAsB,kBAAkB,IAAK,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAyB3E"}
|
|
@@ -188,6 +188,18 @@ export declare class ASTVisitors {
|
|
|
188
188
|
* @private
|
|
189
189
|
*/
|
|
190
190
|
private handleJSXElement;
|
|
191
|
+
/**
|
|
192
|
+
* Generates plural keys for Trans components, with support for tOptions plural defaults.
|
|
193
|
+
*
|
|
194
|
+
* @param key - Base key name for pluralization
|
|
195
|
+
* @param defaultValue - Default value for the keys
|
|
196
|
+
* @param ns - Namespace for the keys
|
|
197
|
+
* @param isOrdinal - Whether to generate ordinal plural forms
|
|
198
|
+
* @param optionsNode - Optional tOptions object expression for plural-specific defaults
|
|
199
|
+
*
|
|
200
|
+
* @private
|
|
201
|
+
*/
|
|
202
|
+
private generatePluralKeysForTrans;
|
|
191
203
|
/**
|
|
192
204
|
* Extracts element name from JSX opening tag.
|
|
193
205
|
*
|
|
@@ -223,7 +235,7 @@ export declare class ASTVisitors {
|
|
|
223
235
|
* determined statically from the AST.
|
|
224
236
|
*
|
|
225
237
|
* Supports:
|
|
226
|
-
* - StringLiteral -> single value
|
|
238
|
+
* - StringLiteral -> single value (filtered to exclude empty strings for context)
|
|
227
239
|
* - ConditionalExpression (ternary) -> union of consequent and alternate resolved values
|
|
228
240
|
* - The identifier `undefined` -> empty array
|
|
229
241
|
*
|
|
@@ -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;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;
|
|
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;IAuK5B;;;;;;;;;;;;;OAaG;IACH,OAAO,CAAC,gBAAgB;IA4DxB;;;;;;;;OAQG;IACH,OAAO,CAAC,sBAAsB;IAkB9B;;;;;;;;;OASG;IACH,OAAO,CAAC,gBAAgB;IA6FxB;;;;;;;;;;OAUG;IACH,OAAO,CAAC,0BAA0B;IA6DlC;;;;;;;;;;;OAWG;IACH,OAAO,CAAC,cAAc;IAgBtB;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,sBAAsB;IA2C9B;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,2BAA2B;IAoBnC;;;;;;OAMG;IACH,OAAO,CAAC,uBAAuB;IAoB/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,OAAO,CAAC,eAAe;CA2BxB"}
|
package/types/index.d.ts
CHANGED
|
@@ -4,4 +4,5 @@ export { extract, findKeys, getTranslations, runExtractor } from './extractor';
|
|
|
4
4
|
export { runLinter } from './linter';
|
|
5
5
|
export { runSyncer } from './syncer';
|
|
6
6
|
export { runStatus } from './status';
|
|
7
|
+
export { runTypesGenerator } from './types-generator';
|
|
7
8
|
//# sourceMappingURL=index.d.ts.map
|
package/types/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,oBAAoB,EACpB,MAAM,EACN,aAAa,EACb,YAAY,EACb,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AACvC,OAAO,EACL,OAAO,EACP,QAAQ,EACR,eAAe,EACf,YAAY,EACb,MAAM,aAAa,CAAA;AAEpB,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACV,oBAAoB,EACpB,MAAM,EACN,aAAa,EACb,YAAY,EACb,MAAM,SAAS,CAAA;AAChB,OAAO,EAAE,YAAY,EAAE,MAAM,UAAU,CAAA;AACvC,OAAO,EACL,OAAO,EACP,QAAQ,EACR,eAAe,EACf,YAAY,EACb,MAAM,aAAa,CAAA;AAEpB,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,SAAS,EAAE,MAAM,UAAU,CAAA;AACpC,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA"}
|
package/types/migrator.d.ts
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Migrates a legacy i18next-parser
|
|
2
|
+
* Migrates a legacy i18next-parser configuration file to the new
|
|
3
3
|
* i18next-cli configuration format.
|
|
4
4
|
*
|
|
5
5
|
* This function:
|
|
6
|
-
* 1. Checks if a legacy config file exists
|
|
6
|
+
* 1. Checks if a legacy config file exists (supports .js, .mjs, .cjs, .ts)
|
|
7
7
|
* 2. Prevents migration if any new config file already exists
|
|
8
|
-
* 3. Dynamically imports the old configuration
|
|
8
|
+
* 3. Dynamically imports the old configuration using appropriate loader
|
|
9
9
|
* 4. Maps old configuration properties to new format:
|
|
10
10
|
* - `$LOCALE` → `{{language}}`
|
|
11
11
|
* - `$NAMESPACE` → `{{namespace}}`
|
|
@@ -14,24 +14,19 @@
|
|
|
14
14
|
* 5. Generates a new TypeScript configuration file
|
|
15
15
|
* 6. Provides warnings for deprecated features
|
|
16
16
|
*
|
|
17
|
+
* @param customConfigPath - Optional custom path to the legacy config file
|
|
18
|
+
*
|
|
17
19
|
* @example
|
|
18
|
-
* ```
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* }
|
|
20
|
+
* ```bash
|
|
21
|
+
* # Migrate default config
|
|
22
|
+
* npx i18next-cli migrate-config
|
|
23
|
+
*
|
|
24
|
+
* # Migrate custom config with extension
|
|
25
|
+
* npx i18next-cli migrate-config i18next-parser.config.mjs
|
|
25
26
|
*
|
|
26
|
-
*
|
|
27
|
-
*
|
|
28
|
-
* locales: ['en', 'de'],
|
|
29
|
-
* extract: {
|
|
30
|
-
* input: ['src/**\/*.js'],
|
|
31
|
-
* output: 'locales/{{language}}/{{namespace}}.json'
|
|
32
|
-
* }
|
|
33
|
-
* })
|
|
27
|
+
* # Migrate custom config without extension (will try .js, .mjs, .cjs, .ts)
|
|
28
|
+
* npx i18next-cli migrate-config my-custom-config
|
|
34
29
|
* ```
|
|
35
30
|
*/
|
|
36
|
-
export declare function runMigrator(): Promise<void>;
|
|
31
|
+
export declare function runMigrator(customConfigPath?: string): Promise<void>;
|
|
37
32
|
//# sourceMappingURL=migrator.d.ts.map
|
package/types/migrator.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrator.d.ts","sourceRoot":"","sources":["../src/migrator.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"migrator.d.ts","sourceRoot":"","sources":["../src/migrator.ts"],"names":[],"mappings":"AAoFA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAsB,WAAW,CAAE,gBAAgB,CAAC,EAAE,MAAM,iBA6F3D"}
|
package/vitest.config.ts
DELETED
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
// eslint-disable-next-line import/no-unresolved
|
|
2
|
-
import swc from 'unplugin-swc'
|
|
3
|
-
import { defineConfig } from 'vitest/config'
|
|
4
|
-
|
|
5
|
-
export default defineConfig({
|
|
6
|
-
test: {
|
|
7
|
-
// Make vitest globals like `describe` and `it` available without importing
|
|
8
|
-
globals: true,
|
|
9
|
-
// Look for test files in the entire project
|
|
10
|
-
root: './',
|
|
11
|
-
coverage: {
|
|
12
|
-
include: ['src/**/*'],
|
|
13
|
-
exclude: ['src/types.ts', 'src/index.ts', 'src/extractor/index.ts']
|
|
14
|
-
}
|
|
15
|
-
},
|
|
16
|
-
plugins: [swc.vite()]
|
|
17
|
-
})
|