i18next-cli 1.22.0 → 1.22.2
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 +8 -0
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/status.js +1 -1
- package/dist/cjs/types-generator.js +1 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/status.js +1 -1
- package/dist/esm/types-generator.js +1 -1
- package/package.json +1 -1
- package/src/cli.ts +1 -1
- package/src/status.ts +38 -10
- package/src/types-generator.ts +3 -1
- package/types/types-generator.d.ts.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,14 @@ All notable changes to this project will be documented in this file.
|
|
|
5
5
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
|
|
6
6
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
7
7
|
|
|
8
|
+
## [1.22.2](https://github.com/i18next/i18next-cli/compare/v1.22.1...v1.22.2) - 2025-11-08
|
|
9
|
+
|
|
10
|
+
- **Status Command:** Fixed incorrect plural key requirements for languages with different pluralization rules. The status report now correctly evaluates each language based on its own plural categories instead of incorrectly using the primary language's rules. For example, Swedish (which only requires `_one` and `_other` forms) will now show 100% completion when both forms are present, even when other languages in the project like French require additional forms (`_many`). This ensures accurate translation progress reporting across multilingual projects with varying plural rules. [#98](https://github.com/i18next/i18next-cli/issues/98)
|
|
11
|
+
|
|
12
|
+
## [1.22.1](https://github.com/i18next/i18next-cli/compare/v1.22.0...v1.22.1) - 2025-11-06
|
|
13
|
+
|
|
14
|
+
- **Types-Generator:** Add a comment to the start of the types file to note it is auto-generated [#97](https://github.com/i18next/i18next-cli/pull/97)
|
|
15
|
+
|
|
8
16
|
## [1.22.0](https://github.com/i18next/i18next-cli/compare/v1.21.1...v1.22.0) - 2025-11-06
|
|
9
17
|
|
|
10
18
|
- **Plugin System:** Enhanced `ExtractedKey` type and plugin hooks to support location metadata tracking. Plugins can now access file paths, etc. for each extracted translation key via the `locations` array property. [#95](https://github.com/i18next/i18next-cli/issues/95)
|
package/dist/cjs/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var e=require("commander"),t=require("chokidar"),o=require("glob"),n=require("minimatch"),i=require("chalk"),a=require("./config.js"),r=require("./heuristic-config.js"),c=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var s=require("./types-generator.js"),l=require("./syncer.js"),u=require("./migrator.js"),g=require("./init.js"),d=require("./linter.js"),p=require("./status.js"),f=require("./locize.js");const m=new e.Command;m.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.22.
|
|
2
|
+
"use strict";var e=require("commander"),t=require("chokidar"),o=require("glob"),n=require("minimatch"),i=require("chalk"),a=require("./config.js"),r=require("./heuristic-config.js"),c=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var s=require("./types-generator.js"),l=require("./syncer.js"),u=require("./migrator.js"),g=require("./init.js"),d=require("./linter.js"),p=require("./status.js"),f=require("./locize.js");const m=new e.Command;m.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.22.2"),m.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),m.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").action(async e=>{try{const o=m.opts().config,i=await a.ensureConfig(o),r=async()=>{const t=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.extract.input),o=y(i.extract.ignore),a=h(i.extract.output),c=[...o,...a].filter(Boolean),s=e.filter(e=>!c.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}catch(e){console.error("Error running extractor:",e),process.exit(1)}}),m.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,t)=>{const o=m.opts().config;let n=await a.loadConfig(o);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await r.detectConfig();e||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),n=e}await p.runStatus(n,{detail:e,namespace:t.namespace})}),m.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const o=m.opts().config,i=await a.ensureConfig(o),r=()=>s.runTypesGenerator(i);if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.types?.input||[]),o=[...y(i.extract?.ignore)].filter(Boolean),a=e.filter(e=>!o.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}),m.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=m.opts().config,t=await a.ensureConfig(e);await l.runSyncer(t)}),m.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),m.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(g.runInit),m.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const o=m.opts().config,c=async()=>{let e=await a.loadConfig(o);if(!e){console.log(i.blue("No config file found. Attempting to detect project structure..."));const t=await r.detectConfig();t||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),e=t}await d.runLinterCli(e)};if(await c(),e.watch){console.log("\nWatching for changes...");const e=await a.loadConfig(o);if(e?.extract?.input){const o=await w(e.extract.input),i=[...y(e.extract.ignore),...h(e.extract.output)].filter(Boolean),a=o.filter(e=>!i.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}}),m.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeSync(o,e)}),m.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeDownload(o,e)}),m.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeMigrate(o,e)}),m.parse(process.argv);const y=e=>Array.isArray(e)?e:e?[e]:[],h=e=>e&&"string"==typeof e?[e.replace(/\{\{[^}]+\}\}/g,"*")]:[],w=async(e=[])=>{const t=y(e),n=await Promise.all(t.map(e=>o.glob(e||"",{nodir:!0})));return Array.from(new Set(n.flat()))};
|
package/dist/cjs/status.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("chalk"),
|
|
1
|
+
"use strict";var e=require("chalk"),t=require("ora"),a=require("node:path"),o=require("./extractor/core/key-finder.js"),s=require("./utils/nested-object.js"),n=require("./utils/file-utils.js"),l=require("./utils/funnel-msg-tracker.js");function r(t,a,o){const s=o>0?Math.round(a/o*100):100,n=c(s);console.log(`${e.bold(t)}: ${n} ${s}% (${a}/${o})`)}function c(t){const a=Math.floor(t/100*20),o=20-a;return`[${e.green("".padStart(a,"■"))}${"".padStart(o,"□")}]`}async function i(){if(await l.shouldShowFunnel("status"))return console.log(e.yellow.bold("\n✨ Take your localization to the next level!")),console.log("Manage translations with your team in the cloud with locize => https://www.locize.com/docs/getting-started"),console.log(`Run ${e.cyan("npx i18next-cli locize-migrate")} to get started.`),l.recordFunnelShown("status")}exports.runStatus=async function(l,u={}){l.extract.primaryLanguage||=l.locales[0]||"en",l.extract.secondaryLanguages||=l.locales.filter(e=>e!==l?.extract?.primaryLanguage);const d=t("Analyzing project localization status...\n").start();try{const t=await async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage);const{allKeys:t}=await o.findKeys(e),{secondaryLanguages:l,keySeparator:r=".",defaultNS:c="translation",mergeNamespaces:i=!1,pluralSeparator:u="_"}=e.extract,d=new Map;for(const e of t.values()){const t=e.ns||c||"translation";d.has(t)||d.set(t,[]),d.get(t).push(e)}const y={totalBaseKeys:t.size,keysByNs:d,locales:new Map};for(const t of l){let o=0,l=0;const c=new Map,g=i?await n.loadTranslationFile(a.resolve(process.cwd(),n.getOutputPath(e.extract.output,t)))||{}:null;for(const[y,f]of d.entries()){const d=i?g?.[y]||{}:await n.loadTranslationFile(a.resolve(process.cwd(),n.getOutputPath(e.extract.output,t,y)))||{};let p=0,$=0;const m=[],h=(e,t)=>{try{const a=t?"ordinal":"cardinal";return new Intl.PluralRules(e,{type:a}).resolvedOptions().pluralCategories}catch(e){return new Intl.PluralRules("en",{type:t?"ordinal":"cardinal"}).resolvedOptions().pluralCategories}};for(const{key:e,hasCount:a,isOrdinal:o,isExpandedPlural:n}of f)if(a)if(n){const a=e.split(u),o=a[a.length-1],n=a.length>=2&&"ordinal"===a[a.length-2],l=n?a[a.length-1]:o;if(h(t,n).includes(l)){$++;const t=!!s.getNestedValue(d,e,r??".");t&&p++,m.push({key:e,isTranslated:t})}}else{const a=h(t,o||!1);for(const t of a){$++;const a=o?`${e}${u}ordinal${u}${t}`:`${e}${u}${t}`,n=!!s.getNestedValue(d,a,r??".");n&&p++,m.push({key:a,isTranslated:n})}}else{$++;const t=!!s.getNestedValue(d,e,r??".");t&&p++,m.push({key:e,isTranslated:t})}c.set(y,{totalKeys:$,translatedKeys:p,keyDetails:m}),o+=p,l+=$}y.locales.set(t,{totalKeys:l,totalTranslated:o,namespaces:c})}return y}(l);d.succeed("Analysis complete."),await async function(t,a,o){o.detail?await async function(t,a,o,s){if(o===a.extract.primaryLanguage)return void console.log(e.yellow(`Locale "${o}" is the primary language. All keys are considered present.`));if(!a.locales.includes(o))return void console.error(e.red(`Error: Locale "${o}" is not defined in your configuration.`));const n=t.locales.get(o);if(!n)return void console.error(e.red(`Error: Locale "${o}" is not a valid secondary language.`));console.log(e.bold(`\nKey Status for "${e.cyan(o)}":`));const l=Array.from(t.keysByNs.values()).flat().length;r("Overall",n.totalTranslated,n.totalKeys);const c=s?[s]:Array.from(n.namespaces.keys()).sort();for(const t of c){const a=n.namespaces.get(t);a&&(console.log(e.cyan.bold(`\nNamespace: ${t}`)),r("Namespace Progress",a.translatedKeys,a.totalKeys),a.keyDetails.forEach(({key:t,isTranslated:a})=>{const o=a?e.green("✓"):e.red("✗");console.log(` ${o} ${t}`)}))}const u=l-n.totalTranslated;u>0?console.log(e.yellow.bold(`\nSummary: Found ${u} missing translations for "${o}".`)):console.log(e.green.bold(`\nSummary: 🎉 All keys are translated for "${o}".`));await i()}(t,a,o.detail,o.namespace):o.namespace?await async function(t,a,o){const s=t.keysByNs.get(o);if(!s)return void console.error(e.red(`Error: Namespace "${o}" was not found in your source code.`));console.log(e.cyan.bold(`\nStatus for Namespace: "${o}"`)),console.log("------------------------");for(const[e,a]of t.locales.entries()){const t=a.namespaces.get(o);if(t){const a=t.totalKeys>0?Math.round(t.translatedKeys/t.totalKeys*100):100,o=c(a);console.log(`- ${e}: ${o} ${a}% (${t.translatedKeys}/${t.totalKeys} keys)`)}}await i()}(t,0,o.namespace):await async function(t,a){const{primaryLanguage:o}=a.extract;console.log(e.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${e.bold(t.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${e.bold(t.keysByNs.size)}`),console.log(`🌍 Locales: ${e.bold(a.locales.join(", "))}`),console.log(`✅ Primary Language: ${e.bold(o)}`),console.log("\nTranslation Progress:");for(const[e,a]of t.locales.entries()){const t=a.totalKeys>0?Math.round(a.totalTranslated/a.totalKeys*100):100,o=c(t);console.log(`- ${e}: ${o} ${t}% (${a.totalTranslated}/${a.totalKeys} keys)`)}await i()}(t,a)}(t,l,u)}catch(e){d.fail("Failed to generate status report."),console.error(e)}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("i18next-resources-for-ts"),t=require("glob"),r=require("ora"),s=require("chalk"),i=require("node:fs/promises"),n=require("node:path"),
|
|
1
|
+
"use strict";var e=require("i18next-resources-for-ts"),t=require("glob"),r=require("ora"),s=require("chalk"),i=require("node:fs/promises"),n=require("node:path"),a=require("./utils/file-utils.js");exports.runTypesGenerator=async function(o){const c=r("Generating TypeScript types for translations...\n").start();try{o.extract.primaryLanguage||=o.locales[0]||"en";let r=o.extract.output||`locales/${o.extract.primaryLanguage}/*.json`;if(r=a.getOutputPath(r,o.extract.primaryLanguage||"en","*"),o.types||(o.types={input:r,output:"src/@types/i18next.d.ts"}),void 0===o.types.input&&(o.types.input=r),o.types.output||(o.types.output="src/@types/i18next.d.ts"),o.types.resourcesFile||(o.types.resourcesFile=n.join(n.dirname(o.types?.output),"resources.d.ts")),!o.types?.input||o.types?.input.length<0)return void console.log("No input defined!");const u=await t.glob(o.types?.input||[],{cwd:process.cwd()}),p=[];for(const e of u){const t=n.basename(e,n.extname(e)),r=await i.readFile(e,"utf-8"),s=JSON.parse(r);p.push({name:t,resources:s})}const l=[],y=o.types?.enableSelector||!1,d=` // This file is automatically generated by i18next-cli. Do not edit manually.\n${e.mergeResourcesAsInterface(p,{optimize:!!y})}`,f=n.resolve(process.cwd(),o.types?.output||""),m=n.resolve(process.cwd(),o.types.resourcesFile);let g;await i.mkdir(n.dirname(m),{recursive:!0}),await i.writeFile(m,d),l.push(` ${s.green("✓")} Resources interface written to ${o.types.resourcesFile}`);try{await i.access(f),g=!0}catch(e){g=!1}if(!g){const e=`// This file is automatically generated by i18next-cli. Do not edit manually.\nimport Resources from './${n.relative(n.dirname(f),m).replace(/\\/g,"/").replace(/\.d\.ts$/,"")}';\n\ndeclare module 'i18next' {\n interface CustomTypeOptions {\n enableSelector: ${"string"==typeof y?`"${y}"`:y};\n defaultNS: '${o.extract.defaultNS||"translation"}';\n resources: Resources;\n }\n}`;await i.mkdir(n.dirname(f),{recursive:!0}),await i.writeFile(f,e),l.push(` ${s.green("✓")} TypeScript definitions written to ${o.types.output||""}`)}c.succeed(s.bold("TypeScript definitions generated successfully.")),l.forEach(e=>console.log(e))}catch(e){c.fail(s.red("Failed to generate TypeScript definitions.")),console.error(e)}};
|
package/dist/esm/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import{minimatch as i}from"minimatch";import n from"chalk";import{ensureConfig as a,loadConfig as r}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as s}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as f}from"./init.js";import{runLinterCli as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as u,runLocizeDownload as y,runLocizeMigrate as h}from"./locize.js";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.22.
|
|
2
|
+
import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import{minimatch as i}from"minimatch";import n from"chalk";import{ensureConfig as a,loadConfig as r}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as s}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as f}from"./init.js";import{runLinterCli as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as u,runLocizeDownload as y,runLocizeMigrate as h}from"./locize.js";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.22.2"),w.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),w.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").action(async t=>{try{const e=w.opts().config,n=await a(e),r=async()=>{const o=await s(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!o?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&o&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),o};if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.extract.input),e=x(n.extract.ignore),a=j(n.extract.output),c=[...e,...a].filter(Boolean),s=t.filter(t=>!c.some(o=>i(t,o,{dot:!0})));o.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),w.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(t,o)=>{const e=w.opts().config;let i=await r(e);if(!i){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),i=t}await g(i,{detail:t,namespace:o.namespace})}),w.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async t=>{const e=w.opts().config,n=await a(e),r=()=>l(n);if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.types?.input||[]),e=[...x(n.extract?.ignore)].filter(Boolean),a=t.filter(t=>!e.some(o=>i(t,o,{dot:!0})));o.watch(a,{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=w.opts().config,o=await a(t);await p(o)}),w.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await m(t)}),w.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(f),w.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async t=>{const e=w.opts().config,a=async()=>{let t=await r(e);if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=o}await d(t)};if(await a(),t.watch){console.log("\nWatching for changes...");const t=await r(e);if(t?.extract?.input){const e=await z(t.extract.input),n=[...x(t.extract.ignore),...j(t.extract.output)].filter(Boolean),r=e.filter(t=>!n.some(o=>i(t,o,{dot:!0})));o.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}}),w.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async t=>{const o=w.opts().config,e=await a(o);await u(e,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await y(e,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await h(e,t)}),w.parse(process.argv);const x=t=>Array.isArray(t)?t:t?[t]:[],j=t=>t&&"string"==typeof t?[t.replace(/\{\{[^}]+\}\}/g,"*")]:[],z=async(t=[])=>{const o=x(t),i=await Promise.all(o.map(t=>e(t||"",{nodir:!0})));return Array.from(new Set(i.flat()))};
|
package/dist/esm/status.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import e from"chalk";import o from"ora";import{resolve as t}from"node:path";import{findKeys as a}from"./extractor/core/key-finder.js";import{getNestedValue as s}from"./utils/nested-object.js";import{loadTranslationFile as n,getOutputPath as l}from"./utils/file-utils.js";import{shouldShowFunnel as r,recordFunnelShown as c}from"./utils/funnel-msg-tracker.js";async function i(r,c={}){r.extract.primaryLanguage||=r.locales[0]||"en",r.extract.secondaryLanguages||=r.locales.filter(e=>e!==r?.extract?.primaryLanguage);const i=o("Analyzing project localization status...\n").start();try{const o=await async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(o=>o!==e?.extract?.primaryLanguage);const{allKeys:o}=await a(e),{secondaryLanguages:r,keySeparator:c=".",defaultNS:i="translation",mergeNamespaces:u=!1,pluralSeparator:y="_"}=e.extract,d=new Map;for(const e of o.values()){const o=e.ns||i||"translation";d.has(o)||d.set(o,[]),d.get(o).push(e)}const g={totalBaseKeys:o.size,keysByNs:d,locales:new Map};for(const o of r){let a=0,r=0;const i=new Map,f=u?await n(t(process.cwd(),l(e.extract.output,o)))||{}:null;for(const[g,p]of d.entries()){const d=u?f?.[g]||{}:await n(t(process.cwd(),l(e.extract.output,o,g)))||{};let m=0,$=0;const w=[],h=(e,o)=>{try{const t=o?"ordinal":"cardinal";return new Intl.PluralRules(e,{type:t}).resolvedOptions().pluralCategories}catch(e){return new Intl.PluralRules("en",{type:o?"ordinal":"cardinal"}).resolvedOptions().pluralCategories}};for(const{key:e,hasCount:t,isOrdinal:a,isExpandedPlural:n}of p)if(t)if(n){const t=e.split(y),a=t[t.length-1],n=t.length>=2&&"ordinal"===t[t.length-2],l=n?t[t.length-1]:a;if(h(o,n).includes(l)){$++;const o=!!s(d,e,c??".");o&&m++,w.push({key:e,isTranslated:o})}}else{const t=h(o,a||!1);for(const o of t){$++;const t=a?`${e}${y}ordinal${y}${o}`:`${e}${y}${o}`,n=!!s(d,t,c??".");n&&m++,w.push({key:t,isTranslated:n})}}else{$++;const o=!!s(d,e,c??".");o&&m++,w.push({key:e,isTranslated:o})}i.set(g,{totalKeys:$,translatedKeys:m,keyDetails:w}),a+=m,r+=$}g.locales.set(o,{totalKeys:r,totalTranslated:a,namespaces:i})}return g}(r);i.succeed("Analysis complete."),await async function(o,t,a){a.detail?await async function(o,t,a,s){if(a===t.extract.primaryLanguage)return void console.log(e.yellow(`Locale "${a}" is the primary language. All keys are considered present.`));if(!t.locales.includes(a))return void console.error(e.red(`Error: Locale "${a}" is not defined in your configuration.`));const n=o.locales.get(a);if(!n)return void console.error(e.red(`Error: Locale "${a}" is not a valid secondary language.`));console.log(e.bold(`\nKey Status for "${e.cyan(a)}":`));const l=Array.from(o.keysByNs.values()).flat().length;u("Overall",n.totalTranslated,n.totalKeys);const r=s?[s]:Array.from(n.namespaces.keys()).sort();for(const o of r){const t=n.namespaces.get(o);t&&(console.log(e.cyan.bold(`\nNamespace: ${o}`)),u("Namespace Progress",t.translatedKeys,t.totalKeys),t.keyDetails.forEach(({key:o,isTranslated:t})=>{const a=t?e.green("✓"):e.red("✗");console.log(` ${a} ${o}`)}))}const c=l-n.totalTranslated;c>0?console.log(e.yellow.bold(`\nSummary: Found ${c} missing translations for "${a}".`)):console.log(e.green.bold(`\nSummary: 🎉 All keys are translated for "${a}".`));await d()}(o,t,a.detail,a.namespace):a.namespace?await async function(o,t,a){const s=o.keysByNs.get(a);if(!s)return void console.error(e.red(`Error: Namespace "${a}" was not found in your source code.`));console.log(e.cyan.bold(`\nStatus for Namespace: "${a}"`)),console.log("------------------------");for(const[e,t]of o.locales.entries()){const o=t.namespaces.get(a);if(o){const t=o.totalKeys>0?Math.round(o.translatedKeys/o.totalKeys*100):100,a=y(t);console.log(`- ${e}: ${a} ${t}% (${o.translatedKeys}/${o.totalKeys} keys)`)}}await d()}(o,0,a.namespace):await async function(o,t){const{primaryLanguage:a}=t.extract;console.log(e.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${e.bold(o.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${e.bold(o.keysByNs.size)}`),console.log(`🌍 Locales: ${e.bold(t.locales.join(", "))}`),console.log(`✅ Primary Language: ${e.bold(a)}`),console.log("\nTranslation Progress:");for(const[e,t]of o.locales.entries()){const o=t.totalKeys>0?Math.round(t.totalTranslated/t.totalKeys*100):100,a=y(o);console.log(`- ${e}: ${a} ${o}% (${t.totalTranslated}/${t.totalKeys} keys)`)}await d()}(o,t)}(o,r,c)}catch(e){i.fail("Failed to generate status report."),console.error(e)}}function u(o,t,a){const s=a>0?Math.round(t/a*100):100,n=y(s);console.log(`${e.bold(o)}: ${n} ${s}% (${t}/${a})`)}function y(o){const t=Math.floor(o/100*20),a=20-t;return`[${e.green("".padStart(t,"■"))}${"".padStart(a,"□")}]`}async function d(){if(await r("status"))return console.log(e.yellow.bold("\n✨ Take your localization to the next level!")),console.log("Manage translations with your team in the cloud with locize => https://www.locize.com/docs/getting-started"),console.log(`Run ${e.cyan("npx i18next-cli locize-migrate")} to get started.`),c("status")}export{i as runStatus};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{mergeResourcesAsInterface as e}from"i18next-resources-for-ts";import{glob as t}from"glob";import s from"ora";import r from"chalk";import{readFile as o,mkdir as i,writeFile as n,access as
|
|
1
|
+
import{mergeResourcesAsInterface as e}from"i18next-resources-for-ts";import{glob as t}from"glob";import s from"ora";import r from"chalk";import{readFile as o,mkdir as i,writeFile as n,access as a}from"node:fs/promises";import{join as p,dirname as c,basename as u,extname as l,resolve as y,relative as f}from"node:path";import{getOutputPath as d}from"./utils/file-utils.js";async function m(m){const g=s("Generating TypeScript types for translations...\n").start();try{m.extract.primaryLanguage||=m.locales[0]||"en";let s=m.extract.output||`locales/${m.extract.primaryLanguage}/*.json`;if(s=d(s,m.extract.primaryLanguage||"en","*"),m.types||(m.types={input:s,output:"src/@types/i18next.d.ts"}),void 0===m.types.input&&(m.types.input=s),m.types.output||(m.types.output="src/@types/i18next.d.ts"),m.types.resourcesFile||(m.types.resourcesFile=p(c(m.types?.output),"resources.d.ts")),!m.types?.input||m.types?.input.length<0)return void console.log("No input defined!");const w=await t(m.types?.input||[],{cwd:process.cwd()}),x=[];for(const e of w){const t=u(e,l(e)),s=await o(e,"utf-8"),r=JSON.parse(s);x.push({name:t,resources:r})}const h=[],$=m.types?.enableSelector||!1,S=` // This file is automatically generated by i18next-cli. Do not edit manually.\n${e(x,{optimize:!!$})}`,T=y(process.cwd(),m.types?.output||""),b=y(process.cwd(),m.types.resourcesFile);let F;await i(c(b),{recursive:!0}),await n(b,S),h.push(` ${r.green("✓")} Resources interface written to ${m.types.resourcesFile}`);try{await a(T),F=!0}catch(e){F=!1}if(!F){const e=`// This file is automatically generated by i18next-cli. Do not edit manually.\nimport Resources from './${f(c(T),b).replace(/\\/g,"/").replace(/\.d\.ts$/,"")}';\n\ndeclare module 'i18next' {\n interface CustomTypeOptions {\n enableSelector: ${"string"==typeof $?`"${$}"`:$};\n defaultNS: '${m.extract.defaultNS||"translation"}';\n resources: Resources;\n }\n}`;await i(c(T),{recursive:!0}),await n(T,e),h.push(` ${r.green("✓")} TypeScript definitions written to ${m.types.output||""}`)}g.succeed(r.bold("TypeScript definitions generated successfully.")),h.forEach(e=>console.log(e))}catch(e){g.fail(r.red("Failed to generate TypeScript definitions.")),console.error(e)}}export{m as runTypesGenerator};
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -22,7 +22,7 @@ const program = new Command()
|
|
|
22
22
|
program
|
|
23
23
|
.name('i18next-cli')
|
|
24
24
|
.description('A unified, high-performance i18next CLI.')
|
|
25
|
-
.version('1.22.
|
|
25
|
+
.version('1.22.2')
|
|
26
26
|
|
|
27
27
|
// new: global config override option
|
|
28
28
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)')
|
package/src/status.ts
CHANGED
|
@@ -123,20 +123,48 @@ async function generateStatusReport (config: I18nextToolkitConfig): Promise<Stat
|
|
|
123
123
|
let totalInNs = 0
|
|
124
124
|
const keyDetails: Array<{ key: string; isTranslated: boolean }> = []
|
|
125
125
|
|
|
126
|
-
//
|
|
126
|
+
// Get the plural categories for THIS specific locale
|
|
127
|
+
const getLocalePluralCategories = (locale: string, isOrdinal: boolean): string[] => {
|
|
128
|
+
try {
|
|
129
|
+
const type = isOrdinal ? 'ordinal' : 'cardinal'
|
|
130
|
+
const pluralRules = new Intl.PluralRules(locale, { type })
|
|
131
|
+
return pluralRules.resolvedOptions().pluralCategories
|
|
132
|
+
} catch (e) {
|
|
133
|
+
// Fallback to English if locale is invalid
|
|
134
|
+
const fallbackRules = new Intl.PluralRules('en', { type: isOrdinal ? 'ordinal' : 'cardinal' })
|
|
135
|
+
return fallbackRules.resolvedOptions().pluralCategories
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
127
139
|
for (const { key: baseKey, hasCount, isOrdinal, isExpandedPlural } of keysInNs) {
|
|
128
140
|
if (hasCount) {
|
|
129
|
-
// Rely only on the extractor-provided flag; extractor must set isExpandedPlural
|
|
130
141
|
if (isExpandedPlural) {
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
|
|
135
|
-
|
|
142
|
+
// This is an already-expanded plural variant key (e.g., key_one, key_other)
|
|
143
|
+
// Check if this specific variant is needed for the target locale
|
|
144
|
+
const keyParts = baseKey.split(pluralSeparator)
|
|
145
|
+
const lastPart = keyParts[keyParts.length - 1]
|
|
146
|
+
|
|
147
|
+
// Determine if this is an ordinal or cardinal plural
|
|
148
|
+
const isOrdinalVariant = keyParts.length >= 2 && keyParts[keyParts.length - 2] === 'ordinal'
|
|
149
|
+
const category = isOrdinalVariant ? keyParts[keyParts.length - 1] : lastPart
|
|
150
|
+
|
|
151
|
+
// Get the plural categories for this locale
|
|
152
|
+
const localePluralCategories = getLocalePluralCategories(locale, isOrdinalVariant)
|
|
153
|
+
|
|
154
|
+
// Only count this key if it's a plural form used by this locale
|
|
155
|
+
if (localePluralCategories.includes(category)) {
|
|
156
|
+
totalInNs++
|
|
157
|
+
const value = getNestedValue(translationsForNs, baseKey, keySeparator ?? '.')
|
|
158
|
+
const isTranslated = !!value
|
|
159
|
+
if (isTranslated) translatedInNs++
|
|
160
|
+
keyDetails.push({ key: baseKey, isTranslated })
|
|
161
|
+
}
|
|
136
162
|
} else {
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
163
|
+
// This is a base plural key without expanded variants
|
|
164
|
+
// Expand it according to THIS locale's plural rules
|
|
165
|
+
const localePluralCategories = getLocalePluralCategories(locale, isOrdinal || false)
|
|
166
|
+
|
|
167
|
+
for (const category of localePluralCategories) {
|
|
140
168
|
totalInNs++
|
|
141
169
|
const pluralKey = isOrdinal
|
|
142
170
|
? `${baseKey}${pluralSeparator}ordinal${pluralSeparator}${category}`
|
package/src/types-generator.ts
CHANGED
|
@@ -77,7 +77,9 @@ export async function runTypesGenerator (config: I18nextToolkitConfig) {
|
|
|
77
77
|
const logMessages: string[] = []
|
|
78
78
|
|
|
79
79
|
const enableSelector = config.types?.enableSelector || false
|
|
80
|
-
const interfaceDefinition =
|
|
80
|
+
const interfaceDefinition = ` // This file is automatically generated by i18next-cli. Do not edit manually.
|
|
81
|
+
${mergeResourcesAsInterface(resources, { optimize: !!enableSelector })}`
|
|
82
|
+
|
|
81
83
|
const outputPath = resolve(process.cwd(), config.types?.output || '')
|
|
82
84
|
const resourcesOutputPath = resolve(process.cwd(), config.types.resourcesFile)
|
|
83
85
|
await mkdir(dirname(resourcesOutputPath), { recursive: true })
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-generator.d.ts","sourceRoot":"","sources":["../src/types-generator.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAanD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,iBAAiB,CAAE,MAAM,EAAE,oBAAoB,
|
|
1
|
+
{"version":3,"file":"types-generator.d.ts","sourceRoot":"","sources":["../src/types-generator.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAanD;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AACH,wBAAsB,iBAAiB,CAAE,MAAM,EAAE,oBAAoB,iBA4EpE"}
|