i18next-cli 1.17.2 → 1.18.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.md +34 -3
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/translation-manager.js +1 -1
- package/dist/cjs/linter.js +1 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/extractor/core/translation-manager.js +1 -1
- package/dist/esm/linter.js +1 -1
- package/package.json +1 -1
- package/src/cli.ts +3 -3
- package/src/extractor/core/translation-manager.ts +54 -1
- package/src/linter.ts +93 -34
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/linter.d.ts +46 -2
- package/types/linter.d.ts.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,15 @@ 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.18.1](https://github.com/i18next/i18next-cli/compare/v1.18.0...v1.18.1) - 2025-10-30
|
|
9
|
+
|
|
10
|
+
- improve regression introduced in v1.17.2 [#82](https://github.com/i18next/i18next-cli/issues/82)
|
|
11
|
+
|
|
12
|
+
## [1.18.0](https://github.com/i18next/i18next-cli/compare/v1.17.2...v1.18.0) - 2025-10-30
|
|
13
|
+
|
|
14
|
+
- fix regression introduced in v1.17.2 [#82](https://github.com/i18next/i18next-cli/issues/82)
|
|
15
|
+
- enhancement(linter): use emitter for runLinter API [#79](https://github.com/i18next/i18next-cli/pull/79)
|
|
16
|
+
|
|
8
17
|
## [1.17.2](https://github.com/i18next/i18next-cli/compare/v1.17.1...v1.17.2) - 2025-10-29
|
|
9
18
|
|
|
10
19
|
- fix(status, extractor): avoid double‑expanding plural keys which could make locales show 0% translated [#81](https://github.com/i18next/i18next-cli/issues/81)
|
package/README.md
CHANGED
|
@@ -799,8 +799,14 @@ console.log('Files updated:', wasUpdated);
|
|
|
799
799
|
// Check translation status programmatically
|
|
800
800
|
await runStatus(config);
|
|
801
801
|
|
|
802
|
-
// Run linting
|
|
803
|
-
await runLinter(config);
|
|
802
|
+
// Run linting and get results
|
|
803
|
+
const { success, message, files } = await runLinter(config);
|
|
804
|
+
if (!success) {
|
|
805
|
+
console.error(message);
|
|
806
|
+
for (const [filename, issues] of Object.entries(files)) {
|
|
807
|
+
console.error(`${issues.length} issues found in ${filename}.`);
|
|
808
|
+
}
|
|
809
|
+
}
|
|
804
810
|
|
|
805
811
|
// Sync translation files
|
|
806
812
|
await runSyncer(config);
|
|
@@ -846,11 +852,36 @@ class I18nextExtractionPlugin {
|
|
|
846
852
|
### Available Functions
|
|
847
853
|
|
|
848
854
|
- `runExtractor(config, options?)` - Complete extraction with file writing
|
|
849
|
-
- `runLinter(config)` - Run linting analysis
|
|
855
|
+
- `runLinter(config)` - Run linting analysis and return results
|
|
850
856
|
- `runSyncer(config)` - Sync translation files
|
|
851
857
|
- `runStatus(config, options?)` - Get translation status
|
|
852
858
|
- `runTypesGenerator(config)` - Generate types
|
|
853
859
|
|
|
860
|
+
### Advanced Usage
|
|
861
|
+
|
|
862
|
+
#### `Linter` - Class that lints your codebase and emits events along the way
|
|
863
|
+
|
|
864
|
+
**Example usage**
|
|
865
|
+
|
|
866
|
+
```typescript
|
|
867
|
+
import { Linter } from 'i18next-cli';
|
|
868
|
+
import type { I18nextToolkitConfig } from 'i18next-cli';
|
|
869
|
+
|
|
870
|
+
const config: I18nextToolkitConfig = {
|
|
871
|
+
locales: ['en', 'de'],
|
|
872
|
+
extract: {
|
|
873
|
+
input: ['src/**/*.{ts,tsx,js,jsx}'],
|
|
874
|
+
output: 'locales/{{language}}/{{namespace}}.json',
|
|
875
|
+
},
|
|
876
|
+
};
|
|
877
|
+
|
|
878
|
+
const linter = new Linter(config);
|
|
879
|
+
|
|
880
|
+
linter.addEventListener('progress', ({ message }) => console.log(message));
|
|
881
|
+
|
|
882
|
+
await linter.run();
|
|
883
|
+
```
|
|
884
|
+
|
|
854
885
|
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.
|
|
855
886
|
|
|
856
887
|
## Known plugins
|
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.
|
|
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.18.1"),m.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),m.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").action(async e=>{try{const o=m.opts().config,i=await a.ensureConfig(o),r=async()=>{const t=await c.runExtractor(i,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.extract.input),o=y(i.extract.ignore),a=h(i.extract.output),c=[...o,...a].filter(Boolean),s=e.filter(e=>!c.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}catch(e){console.error("Error running extractor:",e),process.exit(1)}}),m.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,t)=>{const o=m.opts().config;let n=await a.loadConfig(o);if(!n){console.log(i.blue("No config file found. Attempting to detect project structure..."));const e=await r.detectConfig();e||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),n=e}await p.runStatus(n,{detail:e,namespace:t.namespace})}),m.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const o=m.opts().config,i=await a.ensureConfig(o),r=()=>s.runTypesGenerator(i);if(await r(),e.watch){console.log("\nWatching for changes...");const e=await w(i.types?.input||[]),o=[...y(i.extract?.ignore)].filter(Boolean),a=e.filter(e=>!o.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}),m.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=m.opts().config,t=await a.ensureConfig(e);await l.runSyncer(t)}),m.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await u.runMigrator(e)}),m.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(g.runInit),m.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const o=m.opts().config,c=async()=>{let e=await a.loadConfig(o);if(!e){console.log(i.blue("No config file found. Attempting to detect project structure..."));const t=await r.detectConfig();t||(console.error(i.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${i.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(i.green("Project structure detected successfully!")),e=t}await d.runLinterCli(e)};if(await c(),e.watch){console.log("\nWatching for changes...");const e=await a.loadConfig(o);if(e?.extract?.input){const o=await w(e.extract.input),i=[...y(e.extract.ignore),...h(e.extract.output)].filter(Boolean),a=o.filter(e=>!i.some(t=>n.minimatch(e,t,{dot:!0})));t.watch(a,{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}}),m.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeSync(o,e)}),m.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeDownload(o,e)}),m.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=m.opts().config,o=await a.ensureConfig(t);await f.runLocizeMigrate(o,e)}),m.parse(process.argv);const y=e=>Array.isArray(e)?e:e?[e]:[],h=e=>e&&"string"==typeof e?[e.replace(/\{\{[^}]+\}\}/g,"*")]:[],w=async(e=[])=>{const t=y(e),n=await Promise.all(t.map(e=>o.glob(e||"",{nodir:!0})));return Array.from(new Set(n.flat()))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),n=require("../../utils/file-utils.js"),r=require("../../utils/default-value.js");function a(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function o(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const s={},n=t?.extract?.pluralSeparator??"_",r=["zero","one","two","few","many","other"],a=r.map(e=>`ordinal${n}${e}`),l=Object.keys(e).sort((e,t)=>{const s=e=>{for(const t of a)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of r)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},o=s(e),l=s(t);if(o.isPlural&&l.isPlural){const e=o.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(o.isOrdinal!==l.isOrdinal)return o.isOrdinal?1:-1;const t=o.isOrdinal?a:r,s=t.indexOf(o.form),n=t.indexOf(l.form);return-1!==s&&-1!==n?s-n:o.form.localeCompare(l.form)}const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t,void 0,{sensitivity:"case"}):i});for(const n of l)s[n]=o(e[n],t);return s}function l(e,t,n,a,l,i=[],c=new Set,u=!1){const{keySeparator:f=".",sort:d=!0,removeUnusedKeys:p=!0,primaryLanguage:g,defaultValue:y="",pluralSeparator:h="_",contextSeparator:x="_"}=n.extract,m=new Set;let O=[];try{const e=new Intl.PluralRules(a,{type:"cardinal"}),t=new Intl.PluralRules(a,{type:"ordinal"});O=e.resolvedOptions().pluralCategories,O.forEach(e=>m.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>m.add(`ordinal_${e}`))}catch(e){const t=g||"en",s=new Intl.PluralRules(t,{type:"cardinal"}),n=new Intl.PluralRules(t,{type:"ordinal"});O=s.resolvedOptions().pluralCategories,O.forEach(e=>m.add(e)),n.resolvedOptions().pluralCategories.forEach(e=>m.add(`ordinal_${e}`))}const
|
|
1
|
+
"use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),n=require("../../utils/file-utils.js"),r=require("../../utils/default-value.js");function a(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function o(e,t){if("object"!=typeof e||null===e||Array.isArray(e))return e;const s={},n=t?.extract?.pluralSeparator??"_",r=["zero","one","two","few","many","other"],a=r.map(e=>`ordinal${n}${e}`),l=Object.keys(e).sort((e,t)=>{const s=e=>{for(const t of a)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!0,isPlural:!0,fullKey:e}}for(const t of r)if(e.endsWith(`${n}${t}`)){return{base:e.slice(0,-(n.length+t.length)),form:t,isOrdinal:!1,isPlural:!0,fullKey:e}}return{base:e,form:"",isOrdinal:!1,isPlural:!1,fullKey:e}},o=s(e),l=s(t);if(o.isPlural&&l.isPlural){const e=o.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(o.isOrdinal!==l.isOrdinal)return o.isOrdinal?1:-1;const t=o.isOrdinal?a:r,s=t.indexOf(o.form),n=t.indexOf(l.form);return-1!==s&&-1!==n?s-n:o.form.localeCompare(l.form)}const i=e.localeCompare(t,void 0,{sensitivity:"base"});return 0===i?e.localeCompare(t,void 0,{sensitivity:"case"}):i});for(const n of l)s[n]=o(e[n],t);return s}function l(e,t,n,a,l,i=[],c=new Set,u=!1){const{keySeparator:f=".",sort:d=!0,removeUnusedKeys:p=!0,primaryLanguage:g,defaultValue:y="",pluralSeparator:h="_",contextSeparator:x="_"}=n.extract,m=new Set;let O=[],v=[];try{const e=new Intl.PluralRules(a,{type:"cardinal"}),t=new Intl.PluralRules(a,{type:"ordinal"});O=e.resolvedOptions().pluralCategories,v=t.resolvedOptions().pluralCategories,O.forEach(e=>m.add(e)),t.resolvedOptions().pluralCategories.forEach(e=>m.add(`ordinal_${e}`))}catch(e){const t=g||"en",s=new Intl.PluralRules(t,{type:"cardinal"}),n=new Intl.PluralRules(t,{type:"ordinal"});O=s.resolvedOptions().pluralCategories,v=n.resolvedOptions().pluralCategories,O.forEach(e=>m.add(e)),n.resolvedOptions().pluralCategories.forEach(e=>m.add(`ordinal_${e}`))}const S=e.filter(({key:e,hasCount:t,isOrdinal:s})=>{if(i.some(t=>t.test(e)))return!1;if(!t)return!0;const n=e.split(h);if(t&&1===n.length)return!0;if(1===O.length&&"other"===O[0]&&1===n.length)return!0;if(s&&n.includes("ordinal")){const e=n[n.length-1];return m.has(`ordinal_${e}`)}if(t){const e=n[n.length-1];return m.has(e)}return!0}),N=new Set;for(const e of S)if(e.isExpandedPlural){const t=String(e.key).split(h);t.length>=3&&"ordinal"===t[t.length-2]?N.add(t.slice(0,-2).join(h)):N.add(t.slice(0,-1).join(h))}let $=p?{}:JSON.parse(JSON.stringify(t));const w=s.getNestedKeys(t,f??".");for(const e of w)if(i.some(t=>t.test(e))){const n=s.getNestedValue(t,e,f??".");s.setNestedValue($,e,n,f??".")}if(p){const e=s.getNestedKeys(t,f??".");for(const n of e){const e=n.split(h);if("zero"===e[e.length-1]){const r=e.slice(0,-1).join(h);if(S.some(({key:e})=>e.split(h).slice(0,-1).join(h)===r)){const e=s.getNestedValue(t,n,f??".");s.setNestedValue($,n,e,f??".")}}}}for(const{key:e,defaultValue:o,explicitDefault:i,hasCount:d,isExpandedPlural:p,isOrdinal:m}of S){if(d&&!p){const t=String(e).split(h);let s=e;if(t.length>=3&&"ordinal"===t[t.length-2]?s=t.slice(0,-2).join(h):t.length>=2&&(s=t.slice(0,-1).join(h)),N.has(s))continue}if(d&&!p){if(1===String(e).split(h).length&&a!==g){const i=e;if(N.has(i));else{const e=m?v:O;for(const c of e){const e=m?`${i}${h}ordinal${h}${c}`:`${i}${h}${c}`,u=s.getNestedValue(t,e,f??".");if(void 0===u){let t;t="string"==typeof o?o:r.resolveDefaultValue(y,String(i),l||n?.extract?.defaultNS||"translation",a,o),s.setNestedValue($,e,t,f??".")}else s.setNestedValue($,e,u,f??".")}}continue}}const w=s.getNestedValue(t,e,f??"."),b=!S.some(t=>t.key.startsWith(`${e}${f}`)&&t.key!==e),j="object"==typeof w&&null!==w&&(c.has(e)||!o||o===e),P="object"==typeof w&&null!==w&&b&&!c.has(e)&&!j;if(j){s.setNestedValue($,e,w,f??".");continue}let V;if(void 0===w||P)if(a===g)if(u){const t=o&&(o===e||e!==o&&(e.startsWith(o+h)||e.startsWith(o+x)));V=o&&!t?o:r.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",a,o)}else V=o||e;else V=r.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",a,o);else if(a===g&&u){const t=o&&(o===e||e!==o&&(e.startsWith(o+h)||e.startsWith(o+x)));V=(e.includes(h)||e.includes(x))&&!i?w:o&&!t?o:w}else V=w;s.setNestedValue($,e,V,f??".")}if(!0===d)return o($,n);if("function"==typeof d){const e={},t=Object.keys($),s=new Map;for(const e of S){const t=!1===f?e.key:e.key.split(f)[0];s.has(t)||s.set(t,e)}t.sort((e,t)=>{if("function"==typeof d){const n=s.get(e),r=s.get(t);if(n&&r)return d(n,r)}return e.localeCompare(t,void 0,{sensitivity:"base"})});for(const s of t)e[s]=o($[s],n);$=e}return $}exports.getTranslations=async function(s,r,o,{syncPrimaryWithDefaults:i=!1}={}){o.extract.primaryLanguage||=o.locales[0]||"en",o.extract.secondaryLanguages||=o.locales.filter(e=>e!==o?.extract?.primaryLanguage);const c=[...o.extract.preservePatterns||[]],u=o.extract.indentation??2;for(const e of r)c.push(`${e}.*`);const f=c.map(a),d="__no_namespace__",p=new Map;for(const e of s.values()){const t=e.nsIsImplicit&&!1===o.extract.defaultNS?d:String(e.ns??o.extract.defaultNS??"translation");p.has(t)||p.set(t,[]),p.get(t).push(e)}const g=[],y=Array.isArray(o.extract.ignore)?o.extract.ignore:o.extract.ignore?[o.extract.ignore]:[];for(const s of o.locales){if(o.extract.mergeNamespaces||"string"==typeof o.extract.output&&!o.extract.output.includes("{{namespace}}")){const t={},a=n.getOutputPath(o.extract.output,s),c=e.resolve(process.cwd(),a),y=await n.loadTranslationFile(c)||{},h=new Set([...p.keys(),...Object.keys(y)]);for(const e of h){const n=p.get(e)||[];if(e===d){const e=l(n,y,o,s,void 0,f,r,i);Object.assign(t,e)}else{const a=y[e]||{};t[e]=l(n,a,o,s,e,f,r,i)}}const x=JSON.stringify(y,null,u),m=JSON.stringify(t,null,u);g.push({path:c,updated:m!==x,newTranslations:t,existingTranslations:y})}else{const a=new Set(p.keys()),c=n.getOutputPath(o.extract.output,s,"*").replace(/\\/g,"/"),d=await t.glob(c,{ignore:y});for(const t of d)a.add(e.basename(t,e.extname(t)));for(const t of a){const a=p.get(t)||[],c=n.getOutputPath(o.extract.output,s,t),d=e.resolve(process.cwd(),c),y=await n.loadTranslationFile(d)||{},h=l(a,y,o,s,t,f,r,i),x=JSON.stringify(y,null,u),m=JSON.stringify(h,null,u);g.push({path:d,updated:m!==x,newTranslations:h,existingTranslations:y})}}}return g};
|
package/dist/cjs/linter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("glob"),t=require("node:fs/promises"),
|
|
1
|
+
"use strict";var e=require("glob"),t=require("node:fs/promises"),r=require("@swc/core"),n=require("node:events"),s=require("chalk"),o=require("ora");class i extends n.EventEmitter{config;constructor(e){super({captureRejections:!0}),this.config=e}wrapError(e){const t="Linter failed to run: ";if(e instanceof Error){if(e.message.startsWith(t))return e;const r=new Error(`${t}${e.message}`);return r.stack=e.stack,r}return new Error(`${t}${String(e)}`)}async run(){const{config:n}=this;try{this.emit("progress",{message:"Finding source files to analyze..."});const s=["node_modules/**"],o=Array.isArray(n.extract.ignore)?n.extract.ignore:n.extract.ignore?[n.extract.ignore]:[],i=await e.glob(n.extract.input,{ignore:[...s,...o]});this.emit("progress",{message:`Analyzing ${i.length} source files...`});let a=0;const u=new Map;for(const e of i){const s=await t.readFile(e,"utf-8"),o=c(await r.parse(s,{syntax:"typescript",tsx:!0,decorators:!0}),s,n);o.length>0&&(a+=o.length,u.set(e,o))}const l={success:0===a,message:a>0?`Linter found ${a} potential issues.`:"No issues found.",files:Object.fromEntries(u.entries())};return this.emit("done",l),l}catch(e){const t=this.wrapError(e);throw this.emit("error",t),t}}}const a=e=>/^(https|http|\/\/|^\/)/.test(e);function c(e,t,r){const n=[],s=[],o=e=>t.substring(0,e).split("\n").length,i=r.extract.transComponents||["Trans"],c=r.extract.ignoredTags||[],u=new Set([...i,"script","style","code",...c]),l=r.extract.ignoredAttributes||[],f=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...l]),p=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?p({name:e.opening.name}):null;const r=e=>{if(!e)return null;if("JSXIdentifier"===e.type&&(e.name||e.value))return e.name??e.value;if("Identifier"===e.type&&(e.name||e.value))return e.name??e.value;if("JSXMemberExpression"===e.type){const t=r(e.object),n=r(e.property);return t&&n?`${t}.${n}`:n??t}return e.name??e.value??e.property?.name??e.property?.value??null};return r(t)},g=e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r&&"object"==typeof r&&("JSXElement"===r.type||"JSXOpeningElement"===r.type||"JSXSelfClosingElement"===r.type)){const e=p(r);if(e&&u.has(e))return!0}}return!1},m=(e,t)=>{if(!e||"object"!=typeof e)return;const r=[...t,e];if("JSXText"===e.type){if(!g(r)){const t=e.value.trim();t&&t.length>1&&"..."!==t&&!a(t)&&isNaN(Number(t))&&!t.startsWith("{{")&&s.push(e)}}if("StringLiteral"===e.type){const t=r[r.length-2],n=g(r);if("JSXAttribute"===t?.type&&!f.has(t.name.value)&&!n){const t=e.value.trim();t&&"..."!==t&&!a(t)&&isNaN(Number(t))&&s.push(e)}}for(const t of Object.keys(e)){if("span"===t)continue;const n=e[t];Array.isArray(n)?n.forEach(e=>m(e,r)):n&&"object"==typeof n&&m(n,r)}};m(e,[]);let y=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,y);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),y=s+r.length)}return n}exports.Linter=i,exports.runLinter=async function(e){return new i(e).run()},exports.runLinterCli=async function(e){const t=new i(e),r=o().start();t.on("progress",e=>{r.text=e.message});try{const{success:e,message:n,files:o}=await t.run();if(e)r.succeed(s.green.bold(n));else{r.fail(s.red.bold(n));for(const[e,t]of Object.entries(o))console.log(s.yellow(`\n${e}`)),t.forEach(({text:e,line:t})=>{console.log(` ${s.gray(`${t}:`)} ${s.red("Error:")} Found hardcoded string: "${e}"`)});process.exit(1)}}catch(e){const n=t.wrapError(e);r.fail(n.message),console.error(n),process.exit(1)}};
|
package/dist/esm/cli.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import{minimatch as i}from"minimatch";import n from"chalk";import{ensureConfig as a,loadConfig as r}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as s}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as l}from"./types-generator.js";import{runSyncer as p}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as f}from"./init.js";import{
|
|
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.18.1"),w.option("-c, --config <path>","Path to i18next-cli config file (overrides detection)"),w.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").action(async t=>{try{const e=w.opts().config,n=await a(e),r=async()=>{const o=await s(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!o?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&o&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),o};if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.extract.input),e=x(n.extract.ignore),a=j(n.extract.output),c=[...e,...a].filter(Boolean),s=t.filter(t=>!c.some(o=>i(t,o,{dot:!0})));o.watch(s,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),w.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(t,o)=>{const e=w.opts().config;let i=await r(e);if(!i){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),i=t}await g(i,{detail:t,namespace:o.namespace})}),w.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async t=>{const e=w.opts().config,n=await a(e),r=()=>l(n);if(await r(),t.watch){console.log("\nWatching for changes...");const t=await z(n.types?.input||[]),e=[...x(n.extract?.ignore)].filter(Boolean),a=t.filter(t=>!e.some(o=>i(t,o,{dot:!0})));o.watch(a,{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),r()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=w.opts().config,o=await a(t);await p(o)}),w.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await m(t)}),w.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(f),w.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async t=>{const e=w.opts().config,a=async()=>{let t=await r(e);if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=o}await d(t)};if(await a(),t.watch){console.log("\nWatching for changes...");const t=await r(e);if(t?.extract?.input){const e=await z(t.extract.input),n=[...x(t.extract.ignore),...j(t.extract.output)].filter(Boolean),r=e.filter(t=>!n.some(o=>i(t,o,{dot:!0})));o.watch(r,{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}}),w.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async t=>{const o=w.opts().config,e=await a(o);await u(e,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await y(e,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=w.opts().config,e=await a(o);await h(e,t)}),w.parse(process.argv);const x=t=>Array.isArray(t)?t:t?[t]:[],j=t=>t&&"string"==typeof t?[t.replace(/\{\{[^}]+\}\}/g,"*")]:[],z=async(t=[])=>{const o=x(t),i=await Promise.all(o.map(t=>e(t||"",{nodir:!0})));return Array.from(new Set(i.flat()))};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolve as t,basename as e,extname as n}from"node:path";import{glob as s}from"glob";import{getNestedKeys as r,getNestedValue as o,setNestedValue as
|
|
1
|
+
import{resolve as t,basename as e,extname as n}from"node:path";import{glob as s}from"glob";import{getNestedKeys as r,getNestedValue as o,setNestedValue as i}from"../../utils/nested-object.js";import{getOutputPath as a,loadTranslationFile as l}from"../../utils/file-utils.js";import{resolveDefaultValue as c}from"../../utils/default-value.js";function f(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}function u(t,e){if("object"!=typeof t||null===t||Array.isArray(t))return t;const n={},s=e?.extract?.pluralSeparator??"_",r=["zero","one","two","few","many","other"],o=r.map(t=>`ordinal${s}${t}`),i=Object.keys(t).sort((t,e)=>{const n=t=>{for(const e of o)if(t.endsWith(`${s}${e}`)){return{base:t.slice(0,-(s.length+e.length)),form:e,isOrdinal:!0,isPlural:!0,fullKey:t}}for(const e of r)if(t.endsWith(`${s}${e}`)){return{base:t.slice(0,-(s.length+e.length)),form:e,isOrdinal:!1,isPlural:!0,fullKey:t}}return{base:t,form:"",isOrdinal:!1,isPlural:!1,fullKey:t}},i=n(t),a=n(e);if(i.isPlural&&a.isPlural){const t=i.base.localeCompare(a.base,void 0,{sensitivity:"base"});if(0!==t)return t;if(i.isOrdinal!==a.isOrdinal)return i.isOrdinal?1:-1;const e=i.isOrdinal?o:r,n=e.indexOf(i.form),s=e.indexOf(a.form);return-1!==n&&-1!==s?n-s:i.form.localeCompare(a.form)}const l=t.localeCompare(e,void 0,{sensitivity:"base"});return 0===l?t.localeCompare(e,void 0,{sensitivity:"case"}):l});for(const s of i)n[s]=u(t[s],e);return n}function p(t,e,n,s,a,l=[],f=new Set,p=!1){const{keySeparator:d=".",sort:g=!0,removeUnusedKeys:y=!0,primaryLanguage:h,defaultValue:m="",pluralSeparator:x="_",contextSeparator:O="_"}=n.extract,S=new Set;let $=[],v=[];try{const t=new Intl.PluralRules(s,{type:"cardinal"}),e=new Intl.PluralRules(s,{type:"ordinal"});$=t.resolvedOptions().pluralCategories,v=e.resolvedOptions().pluralCategories,$.forEach(t=>S.add(t)),e.resolvedOptions().pluralCategories.forEach(t=>S.add(`ordinal_${t}`))}catch(t){const e=h||"en",n=new Intl.PluralRules(e,{type:"cardinal"}),s=new Intl.PluralRules(e,{type:"ordinal"});$=n.resolvedOptions().pluralCategories,v=s.resolvedOptions().pluralCategories,$.forEach(t=>S.add(t)),s.resolvedOptions().pluralCategories.forEach(t=>S.add(`ordinal_${t}`))}const w=t.filter(({key:t,hasCount:e,isOrdinal:n})=>{if(l.some(e=>e.test(t)))return!1;if(!e)return!0;const s=t.split(x);if(e&&1===s.length)return!0;if(1===$.length&&"other"===$[0]&&1===s.length)return!0;if(n&&s.includes("ordinal")){const t=s[s.length-1];return S.has(`ordinal_${t}`)}if(e){const t=s[s.length-1];return S.has(t)}return!0}),b=new Set;for(const t of w)if(t.isExpandedPlural){const e=String(t.key).split(x);e.length>=3&&"ordinal"===e[e.length-2]?b.add(e.slice(0,-2).join(x)):b.add(e.slice(0,-1).join(x))}let j=y?{}:JSON.parse(JSON.stringify(e));const k=r(e,d??".");for(const t of k)if(l.some(e=>e.test(t))){const n=o(e,t,d??".");i(j,t,n,d??".")}if(y){const t=r(e,d??".");for(const n of t){const t=n.split(x);if("zero"===t[t.length-1]){const s=t.slice(0,-1).join(x);if(w.some(({key:t})=>t.split(x).slice(0,-1).join(x)===s)){const t=o(e,n,d??".");i(j,n,t,d??".")}}}}for(const{key:t,defaultValue:r,explicitDefault:l,hasCount:u,isExpandedPlural:g,isOrdinal:y}of w){if(u&&!g){const e=String(t).split(x);let n=t;if(e.length>=3&&"ordinal"===e[e.length-2]?n=e.slice(0,-2).join(x):e.length>=2&&(n=e.slice(0,-1).join(x)),b.has(n))continue}if(u&&!g){if(1===String(t).split(x).length&&s!==h){const l=t;if(b.has(l));else{const t=y?v:$;for(const f of t){const t=y?`${l}${x}ordinal${x}${f}`:`${l}${x}${f}`,u=o(e,t,d??".");if(void 0===u){let e;e="string"==typeof r?r:c(m,String(l),a||n?.extract?.defaultNS||"translation",s,r),i(j,t,e,d??".")}else i(j,t,u,d??".")}}continue}}const S=o(e,t,d??"."),k=!w.some(e=>e.key.startsWith(`${t}${d}`)&&e.key!==t),C="object"==typeof S&&null!==S&&(f.has(t)||!r||r===t),P="object"==typeof S&&null!==S&&k&&!f.has(t)&&!C;if(C){i(j,t,S,d??".");continue}let N;if(void 0===S||P)if(s===h)if(p){const e=r&&(r===t||t!==r&&(t.startsWith(r+x)||t.startsWith(r+O)));N=r&&!e?r:c(m,t,a||n?.extract?.defaultNS||"translation",s,r)}else N=r||t;else N=c(m,t,a||n?.extract?.defaultNS||"translation",s,r);else if(s===h&&p){const e=r&&(r===t||t!==r&&(t.startsWith(r+x)||t.startsWith(r+O)));N=(t.includes(x)||t.includes(O))&&!l?S:r&&!e?r:S}else N=S;i(j,t,N,d??".")}if(!0===g)return u(j,n);if("function"==typeof g){const t={},e=Object.keys(j),s=new Map;for(const t of w){const e=!1===d?t.key:t.key.split(d)[0];s.has(e)||s.set(e,t)}e.sort((t,e)=>{if("function"==typeof g){const n=s.get(t),r=s.get(e);if(n&&r)return g(n,r)}return t.localeCompare(e,void 0,{sensitivity:"base"})});for(const s of e)t[s]=u(j[s],n);j=t}return j}async function d(r,o,i,{syncPrimaryWithDefaults:c=!1}={}){i.extract.primaryLanguage||=i.locales[0]||"en",i.extract.secondaryLanguages||=i.locales.filter(t=>t!==i?.extract?.primaryLanguage);const u=[...i.extract.preservePatterns||[]],d=i.extract.indentation??2;for(const t of o)u.push(`${t}.*`);const g=u.map(f),y="__no_namespace__",h=new Map;for(const t of r.values()){const e=t.nsIsImplicit&&!1===i.extract.defaultNS?y:String(t.ns??i.extract.defaultNS??"translation");h.has(e)||h.set(e,[]),h.get(e).push(t)}const m=[],x=Array.isArray(i.extract.ignore)?i.extract.ignore:i.extract.ignore?[i.extract.ignore]:[];for(const r of i.locales){if(i.extract.mergeNamespaces||"string"==typeof i.extract.output&&!i.extract.output.includes("{{namespace}}")){const e={},n=a(i.extract.output,r),s=t(process.cwd(),n),f=await l(s)||{},u=new Set([...h.keys(),...Object.keys(f)]);for(const t of u){const n=h.get(t)||[];if(t===y){const t=p(n,f,i,r,void 0,g,o,c);Object.assign(e,t)}else{const s=f[t]||{};e[t]=p(n,s,i,r,t,g,o,c)}}const x=JSON.stringify(f,null,d),O=JSON.stringify(e,null,d);m.push({path:s,updated:O!==x,newTranslations:e,existingTranslations:f})}else{const f=new Set(h.keys()),u=a(i.extract.output,r,"*").replace(/\\/g,"/"),y=await s(u,{ignore:x});for(const t of y)f.add(e(t,n(t)));for(const e of f){const n=h.get(e)||[],s=a(i.extract.output,r,e),f=t(process.cwd(),s),u=await l(f)||{},y=p(n,u,i,r,e,g,o,c),x=JSON.stringify(u,null,d),O=JSON.stringify(y,null,d);m.push({path:f,updated:O!==x,newTranslations:y,existingTranslations:u})}}}return m}export{d as getTranslations};
|
package/dist/esm/linter.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{glob as e}from"glob";import{readFile as t}from"node:fs/promises";import{parse as
|
|
1
|
+
import{glob as e}from"glob";import{readFile as t}from"node:fs/promises";import{parse as r}from"@swc/core";import{EventEmitter as n}from"node:events";import s from"chalk";import o from"ora";class i extends n{config;constructor(e){super({captureRejections:!0}),this.config=e}wrapError(e){const t="Linter failed to run: ";if(e instanceof Error){if(e.message.startsWith(t))return e;const r=new Error(`${t}${e.message}`);return r.stack=e.stack,r}return new Error(`${t}${String(e)}`)}async run(){const{config:n}=this;try{this.emit("progress",{message:"Finding source files to analyze..."});const s=["node_modules/**"],o=Array.isArray(n.extract.ignore)?n.extract.ignore:n.extract.ignore?[n.extract.ignore]:[],i=await e(n.extract.input,{ignore:[...s,...o]});this.emit("progress",{message:`Analyzing ${i.length} source files...`});let a=0;const c=new Map;for(const e of i){const s=await t(e,"utf-8"),o=u(await r(s,{syntax:"typescript",tsx:!0,decorators:!0}),s,n);o.length>0&&(a+=o.length,c.set(e,o))}const l={success:0===a,message:a>0?`Linter found ${a} potential issues.`:"No issues found.",files:Object.fromEntries(c.entries())};return this.emit("done",l),l}catch(e){const t=this.wrapError(e);throw this.emit("error",t),t}}}async function a(e){return new i(e).run()}async function c(e){const t=new i(e),r=o().start();t.on("progress",e=>{r.text=e.message});try{const{success:e,message:n,files:o}=await t.run();if(e)r.succeed(s.green.bold(n));else{r.fail(s.red.bold(n));for(const[e,t]of Object.entries(o))console.log(s.yellow(`\n${e}`)),t.forEach(({text:e,line:t})=>{console.log(` ${s.gray(`${t}:`)} ${s.red("Error:")} Found hardcoded string: "${e}"`)});process.exit(1)}}catch(e){const n=t.wrapError(e);r.fail(n.message),console.error(n),process.exit(1)}}const l=e=>/^(https|http|\/\/|^\/)/.test(e);function u(e,t,r){const n=[],s=[],o=e=>t.substring(0,e).split("\n").length,i=r.extract.transComponents||["Trans"],a=r.extract.ignoredTags||[],c=new Set([...i,"script","style","code",...a]),u=r.extract.ignoredAttributes||[],f=new Set(["className","key","id","style","href","i18nKey","defaults","type","target",...u]),p=e=>{if(!e)return null;const t=e.name??e.opening?.name??e.opening?.name;if(!t)return e.opening?.name?p({name:e.opening.name}):null;const r=e=>{if(!e)return null;if("JSXIdentifier"===e.type&&(e.name||e.value))return e.name??e.value;if("Identifier"===e.type&&(e.name||e.value))return e.name??e.value;if("JSXMemberExpression"===e.type){const t=r(e.object),n=r(e.property);return t&&n?`${t}.${n}`:n??t}return e.name??e.value??e.property?.name??e.property?.value??null};return r(t)},m=e=>{for(let t=e.length-1;t>=0;t--){const r=e[t];if(r&&"object"==typeof r&&("JSXElement"===r.type||"JSXOpeningElement"===r.type||"JSXSelfClosingElement"===r.type)){const e=p(r);if(e&&c.has(e))return!0}}return!1},g=(e,t)=>{if(!e||"object"!=typeof e)return;const r=[...t,e];if("JSXText"===e.type){if(!m(r)){const t=e.value.trim();t&&t.length>1&&"..."!==t&&!l(t)&&isNaN(Number(t))&&!t.startsWith("{{")&&s.push(e)}}if("StringLiteral"===e.type){const t=r[r.length-2],n=m(r);if("JSXAttribute"===t?.type&&!f.has(t.name.value)&&!n){const t=e.value.trim();t&&"..."!==t&&!l(t)&&isNaN(Number(t))&&s.push(e)}}for(const t of Object.keys(e)){if("span"===t)continue;const n=e[t];Array.isArray(n)?n.forEach(e=>g(e,r)):n&&"object"==typeof n&&g(n,r)}};g(e,[]);let y=0;for(const e of s){const r=e.raw??e.value,s=t.indexOf(r,y);s>-1&&(n.push({text:e.value.trim(),line:o(s)}),y=s+r.length)}return n}export{i as Linter,a as runLinter,c as runLinterCli};
|
package/package.json
CHANGED
package/src/cli.ts
CHANGED
|
@@ -12,7 +12,7 @@ import { runTypesGenerator } from './types-generator'
|
|
|
12
12
|
import { runSyncer } from './syncer'
|
|
13
13
|
import { runMigrator } from './migrator'
|
|
14
14
|
import { runInit } from './init'
|
|
15
|
-
import {
|
|
15
|
+
import { runLinterCli } from './linter'
|
|
16
16
|
import { runStatus } from './status'
|
|
17
17
|
import { runLocizeSync, runLocizeDownload, runLocizeMigrate } from './locize'
|
|
18
18
|
import type { I18nextToolkitConfig } from './types'
|
|
@@ -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.
|
|
25
|
+
.version('1.18.1')
|
|
26
26
|
|
|
27
27
|
// new: global config override option
|
|
28
28
|
program.option('-c, --config <path>', 'Path to i18next-cli config file (overrides detection)')
|
|
@@ -174,7 +174,7 @@ program
|
|
|
174
174
|
console.log(chalk.green('Project structure detected successfully!'))
|
|
175
175
|
config = detected as I18nextToolkitConfig
|
|
176
176
|
}
|
|
177
|
-
await
|
|
177
|
+
await runLinterCli(config)
|
|
178
178
|
}
|
|
179
179
|
|
|
180
180
|
// Run the linter once initially
|
|
@@ -125,11 +125,13 @@ function buildNewTranslationsForNs (
|
|
|
125
125
|
const targetLanguagePluralCategories = new Set<string>()
|
|
126
126
|
// Track cardinal plural categories separately so we can special-case single-"other" languages
|
|
127
127
|
let cardinalCategories: string[] = []
|
|
128
|
+
let ordinalCategories: string[] = []
|
|
128
129
|
try {
|
|
129
130
|
const cardinalRules = new Intl.PluralRules(locale, { type: 'cardinal' })
|
|
130
131
|
const ordinalRules = new Intl.PluralRules(locale, { type: 'ordinal' })
|
|
131
132
|
|
|
132
133
|
cardinalCategories = cardinalRules.resolvedOptions().pluralCategories
|
|
134
|
+
ordinalCategories = ordinalRules.resolvedOptions().pluralCategories
|
|
133
135
|
cardinalCategories.forEach(cat => targetLanguagePluralCategories.add(cat))
|
|
134
136
|
ordinalRules.resolvedOptions().pluralCategories.forEach(cat => targetLanguagePluralCategories.add(`ordinal_${cat}`))
|
|
135
137
|
} catch (e) {
|
|
@@ -139,6 +141,7 @@ function buildNewTranslationsForNs (
|
|
|
139
141
|
const ordinalRules = new Intl.PluralRules(fallbackLang, { type: 'ordinal' })
|
|
140
142
|
|
|
141
143
|
cardinalCategories = cardinalRules.resolvedOptions().pluralCategories
|
|
144
|
+
ordinalCategories = ordinalRules.resolvedOptions().pluralCategories
|
|
142
145
|
cardinalCategories.forEach(cat => targetLanguagePluralCategories.add(cat))
|
|
143
146
|
ordinalRules.resolvedOptions().pluralCategories.forEach(cat => targetLanguagePluralCategories.add(`ordinal_${cat}`))
|
|
144
147
|
}
|
|
@@ -158,6 +161,12 @@ function buildNewTranslationsForNs (
|
|
|
158
161
|
// For plural keys, check if this specific plural form is needed for the target language
|
|
159
162
|
const keyParts = key.split(pluralSeparator)
|
|
160
163
|
|
|
164
|
+
// If this is a base plural key (no plural suffix), keep it so that the
|
|
165
|
+
// builder can expand it to the target locale's plural forms.
|
|
166
|
+
if (hasCount && keyParts.length === 1) {
|
|
167
|
+
return true
|
|
168
|
+
}
|
|
169
|
+
|
|
161
170
|
// Special-case single-cardinal-"other" languages (ja/zh/ko etc.):
|
|
162
171
|
// when the target language's cardinal categories are exactly ['other'],
|
|
163
172
|
// the extractor may have emitted the base key (no "_other" suffix).
|
|
@@ -241,7 +250,7 @@ function buildNewTranslationsForNs (
|
|
|
241
250
|
}
|
|
242
251
|
|
|
243
252
|
// 1. Build the object first, without any sorting.
|
|
244
|
-
for (const { key, defaultValue, explicitDefault, hasCount, isExpandedPlural } of filteredKeys) {
|
|
253
|
+
for (const { key, defaultValue, explicitDefault, hasCount, isExpandedPlural, isOrdinal } of filteredKeys) {
|
|
245
254
|
// If this is a base plural key (hasCount true but not an already-expanded variant)
|
|
246
255
|
// and we detected explicit expanded variants for this base, skip expanding the base.
|
|
247
256
|
if (hasCount && !isExpandedPlural) {
|
|
@@ -258,6 +267,50 @@ function buildNewTranslationsForNs (
|
|
|
258
267
|
}
|
|
259
268
|
}
|
|
260
269
|
|
|
270
|
+
// If this is a base plural key (no explicit suffix) and the locale is NOT the primary,
|
|
271
|
+
// expand it into locale-specific plural variants (e.g. key_one, key_other).
|
|
272
|
+
// Use the extracted defaultValue (fallback to base) for variant values.
|
|
273
|
+
if (hasCount && !isExpandedPlural) {
|
|
274
|
+
const parts = String(key).split(pluralSeparator)
|
|
275
|
+
const isBaseKey = parts.length === 1
|
|
276
|
+
if (isBaseKey && locale !== primaryLanguage) {
|
|
277
|
+
// If explicit expanded variants exist, do not expand the base.
|
|
278
|
+
const base = key
|
|
279
|
+
if (expandedBases.has(base)) {
|
|
280
|
+
// Skip expansion when explicit variants were provided
|
|
281
|
+
} else {
|
|
282
|
+
// choose categories based on ordinal flag
|
|
283
|
+
const categories = isOrdinal ? ordinalCategories : cardinalCategories
|
|
284
|
+
for (const category of categories) {
|
|
285
|
+
const finalKey = isOrdinal
|
|
286
|
+
? `${base}${pluralSeparator}ordinal${pluralSeparator}${category}`
|
|
287
|
+
: `${base}${pluralSeparator}${category}`
|
|
288
|
+
|
|
289
|
+
// Preserve existing translation if present; otherwise set a sensible default
|
|
290
|
+
const existingVariantValue = getNestedValue(existingTranslations, finalKey, keySeparator ?? '.')
|
|
291
|
+
if (existingVariantValue === undefined) {
|
|
292
|
+
// Prefer explicit defaultValue extracted for this key; fall back to configured defaultValue
|
|
293
|
+
// (resolved via resolveDefaultValue which handles functions or strings and accepts the full parameter set).
|
|
294
|
+
let resolvedValue: string
|
|
295
|
+
if (typeof defaultValue === 'string') {
|
|
296
|
+
resolvedValue = defaultValue
|
|
297
|
+
} else {
|
|
298
|
+
// Use resolveDefaultValue to compute a sensible default, providing namespace and locale context.
|
|
299
|
+
resolvedValue = resolveDefaultValue(emptyDefaultValue, String(base), namespace || config?.extract?.defaultNS || 'translation', locale, defaultValue)
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
setNestedValue(newTranslations, finalKey, resolvedValue, keySeparator ?? '.')
|
|
303
|
+
} else {
|
|
304
|
+
// Keep existing translation
|
|
305
|
+
setNestedValue(newTranslations, finalKey, existingVariantValue, keySeparator ?? '.')
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
// We've expanded variants for this base key; skip the normal single-key handling.
|
|
310
|
+
continue
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
261
314
|
const existingValue = getNestedValue(existingTranslations, key, keySeparator ?? '.')
|
|
262
315
|
const isLeafInNewKeys = !filteredKeys.some(otherKey => otherKey.key.startsWith(`${key}${keySeparator}`) && otherKey.key !== key)
|
|
263
316
|
|
package/src/linter.ts
CHANGED
|
@@ -1,10 +1,87 @@
|
|
|
1
1
|
import { glob } from 'glob'
|
|
2
2
|
import { readFile } from 'node:fs/promises'
|
|
3
3
|
import { parse } from '@swc/core'
|
|
4
|
+
import { EventEmitter } from 'node:events'
|
|
4
5
|
import chalk from 'chalk'
|
|
5
6
|
import ora from 'ora'
|
|
6
7
|
import type { I18nextToolkitConfig } from './types'
|
|
7
8
|
|
|
9
|
+
type LinterEventMap = {
|
|
10
|
+
progress: [{
|
|
11
|
+
message: string;
|
|
12
|
+
}];
|
|
13
|
+
done: [{
|
|
14
|
+
success: boolean;
|
|
15
|
+
message: string;
|
|
16
|
+
files: Record<string, HardcodedString[]>;
|
|
17
|
+
}];
|
|
18
|
+
error: [error: Error];
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export class Linter extends EventEmitter<LinterEventMap> {
|
|
22
|
+
private config: I18nextToolkitConfig
|
|
23
|
+
|
|
24
|
+
constructor (config: I18nextToolkitConfig) {
|
|
25
|
+
super({ captureRejections: true })
|
|
26
|
+
this.config = config
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
wrapError (error: unknown) {
|
|
30
|
+
const prefix = 'Linter failed to run: '
|
|
31
|
+
if (error instanceof Error) {
|
|
32
|
+
if (error.message.startsWith(prefix)) {
|
|
33
|
+
return error
|
|
34
|
+
}
|
|
35
|
+
const wrappedError = new Error(`${prefix}${error.message}`)
|
|
36
|
+
wrappedError.stack = error.stack
|
|
37
|
+
return wrappedError
|
|
38
|
+
}
|
|
39
|
+
return new Error(`${prefix}${String(error)}`)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async run () {
|
|
43
|
+
const { config } = this
|
|
44
|
+
try {
|
|
45
|
+
this.emit('progress', { message: 'Finding source files to analyze...' })
|
|
46
|
+
const defaultIgnore = ['node_modules/**']
|
|
47
|
+
const userIgnore = Array.isArray(config.extract.ignore)
|
|
48
|
+
? config.extract.ignore
|
|
49
|
+
: config.extract.ignore ? [config.extract.ignore] : []
|
|
50
|
+
|
|
51
|
+
const sourceFiles = await glob(config.extract.input, {
|
|
52
|
+
ignore: [...defaultIgnore, ...userIgnore]
|
|
53
|
+
})
|
|
54
|
+
this.emit('progress', { message: `Analyzing ${sourceFiles.length} source files...` })
|
|
55
|
+
let totalIssues = 0
|
|
56
|
+
const issuesByFile = new Map<string, HardcodedString[]>()
|
|
57
|
+
|
|
58
|
+
for (const file of sourceFiles) {
|
|
59
|
+
const code = await readFile(file, 'utf-8')
|
|
60
|
+
const ast = await parse(code, {
|
|
61
|
+
syntax: 'typescript',
|
|
62
|
+
tsx: true,
|
|
63
|
+
decorators: true
|
|
64
|
+
})
|
|
65
|
+
const hardcodedStrings = findHardcodedStrings(ast, code, config)
|
|
66
|
+
|
|
67
|
+
if (hardcodedStrings.length > 0) {
|
|
68
|
+
totalIssues += hardcodedStrings.length
|
|
69
|
+
issuesByFile.set(file, hardcodedStrings)
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const files = Object.fromEntries(issuesByFile.entries())
|
|
74
|
+
const data = { success: totalIssues === 0, message: totalIssues > 0 ? `Linter found ${totalIssues} potential issues.` : 'No issues found.', files }
|
|
75
|
+
this.emit('done', data)
|
|
76
|
+
return data
|
|
77
|
+
} catch (error) {
|
|
78
|
+
const wrappedError = this.wrapError(error)
|
|
79
|
+
this.emit('error', wrappedError)
|
|
80
|
+
throw wrappedError
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
8
85
|
/**
|
|
9
86
|
* Runs the i18next linter to detect hardcoded strings and other potential issues.
|
|
10
87
|
*
|
|
@@ -32,44 +109,25 @@ import type { I18nextToolkitConfig } from './types'
|
|
|
32
109
|
*
|
|
33
110
|
* await runLinter(config)
|
|
34
111
|
* // Outputs issues found or success message
|
|
35
|
-
* // Exits with code 1 if issues found, 0 if clean
|
|
36
112
|
* ```
|
|
37
113
|
*/
|
|
38
114
|
export async function runLinter (config: I18nextToolkitConfig) {
|
|
39
|
-
|
|
115
|
+
return new Linter(config).run()
|
|
116
|
+
}
|
|
40
117
|
|
|
118
|
+
export async function runLinterCli (config: I18nextToolkitConfig) {
|
|
119
|
+
const linter = new Linter(config)
|
|
120
|
+
const spinner = ora().start()
|
|
121
|
+
linter.on('progress', (event) => {
|
|
122
|
+
spinner.text = event.message
|
|
123
|
+
})
|
|
41
124
|
try {
|
|
42
|
-
const
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
: config.extract.ignore ? [config.extract.ignore] : []
|
|
46
|
-
|
|
47
|
-
const sourceFiles = await glob(config.extract.input, {
|
|
48
|
-
ignore: [...defaultIgnore, ...userIgnore]
|
|
49
|
-
})
|
|
50
|
-
let totalIssues = 0
|
|
51
|
-
const issuesByFile = new Map<string, HardcodedString[]>()
|
|
52
|
-
|
|
53
|
-
for (const file of sourceFiles) {
|
|
54
|
-
const code = await readFile(file, 'utf-8')
|
|
55
|
-
const ast = await parse(code, {
|
|
56
|
-
syntax: 'typescript',
|
|
57
|
-
tsx: true,
|
|
58
|
-
decorators: true
|
|
59
|
-
})
|
|
60
|
-
const hardcodedStrings = findHardcodedStrings(ast, code, config)
|
|
61
|
-
|
|
62
|
-
if (hardcodedStrings.length > 0) {
|
|
63
|
-
totalIssues += hardcodedStrings.length
|
|
64
|
-
issuesByFile.set(file, hardcodedStrings)
|
|
65
|
-
}
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
if (totalIssues > 0) {
|
|
69
|
-
spinner.fail(chalk.red.bold(`Linter found ${totalIssues} potential issues.`))
|
|
125
|
+
const { success, message, files } = await linter.run()
|
|
126
|
+
if (!success) {
|
|
127
|
+
spinner.fail(chalk.red.bold(message))
|
|
70
128
|
|
|
71
129
|
// Print detailed report after spinner fails
|
|
72
|
-
for (const [file, issues] of
|
|
130
|
+
for (const [file, issues] of Object.entries(files)) {
|
|
73
131
|
console.log(chalk.yellow(`\n${file}`))
|
|
74
132
|
issues.forEach(({ text, line }) => {
|
|
75
133
|
console.log(` ${chalk.gray(`${line}:`)} ${chalk.red('Error:')} Found hardcoded string: "${text}"`)
|
|
@@ -77,11 +135,12 @@ export async function runLinter (config: I18nextToolkitConfig) {
|
|
|
77
135
|
}
|
|
78
136
|
process.exit(1)
|
|
79
137
|
} else {
|
|
80
|
-
spinner.succeed(chalk.green.bold(
|
|
138
|
+
spinner.succeed(chalk.green.bold(message))
|
|
81
139
|
}
|
|
82
140
|
} catch (error) {
|
|
83
|
-
|
|
84
|
-
|
|
141
|
+
const wrappedError = linter.wrapError(error)
|
|
142
|
+
spinner.fail(wrappedError.message)
|
|
143
|
+
console.error(wrappedError)
|
|
85
144
|
process.exit(1)
|
|
86
145
|
}
|
|
87
146
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;
|
|
1
|
+
{"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAibnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,EAC5B,EAAE,uBAA+B,EAAE,GAAE;IAAE,uBAAuB,CAAC,EAAE,OAAO,CAAA;CAAO,GAC9E,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA6F9B"}
|
package/types/linter.d.ts
CHANGED
|
@@ -1,4 +1,32 @@
|
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
1
2
|
import type { I18nextToolkitConfig } from './types';
|
|
3
|
+
type LinterEventMap = {
|
|
4
|
+
progress: [
|
|
5
|
+
{
|
|
6
|
+
message: string;
|
|
7
|
+
}
|
|
8
|
+
];
|
|
9
|
+
done: [
|
|
10
|
+
{
|
|
11
|
+
success: boolean;
|
|
12
|
+
message: string;
|
|
13
|
+
files: Record<string, HardcodedString[]>;
|
|
14
|
+
}
|
|
15
|
+
];
|
|
16
|
+
error: [error: Error];
|
|
17
|
+
};
|
|
18
|
+
export declare class Linter extends EventEmitter<LinterEventMap> {
|
|
19
|
+
private config;
|
|
20
|
+
constructor(config: I18nextToolkitConfig);
|
|
21
|
+
wrapError(error: unknown): Error;
|
|
22
|
+
run(): Promise<{
|
|
23
|
+
success: boolean;
|
|
24
|
+
message: string;
|
|
25
|
+
files: {
|
|
26
|
+
[k: string]: HardcodedString[];
|
|
27
|
+
};
|
|
28
|
+
}>;
|
|
29
|
+
}
|
|
2
30
|
/**
|
|
3
31
|
* Runs the i18next linter to detect hardcoded strings and other potential issues.
|
|
4
32
|
*
|
|
@@ -26,8 +54,24 @@ import type { I18nextToolkitConfig } from './types';
|
|
|
26
54
|
*
|
|
27
55
|
* await runLinter(config)
|
|
28
56
|
* // Outputs issues found or success message
|
|
29
|
-
* // Exits with code 1 if issues found, 0 if clean
|
|
30
57
|
* ```
|
|
31
58
|
*/
|
|
32
|
-
export declare function runLinter(config: I18nextToolkitConfig): Promise<
|
|
59
|
+
export declare function runLinter(config: I18nextToolkitConfig): Promise<{
|
|
60
|
+
success: boolean;
|
|
61
|
+
message: string;
|
|
62
|
+
files: {
|
|
63
|
+
[k: string]: HardcodedString[];
|
|
64
|
+
};
|
|
65
|
+
}>;
|
|
66
|
+
export declare function runLinterCli(config: I18nextToolkitConfig): Promise<void>;
|
|
67
|
+
/**
|
|
68
|
+
* Represents a found hardcoded string with its location information.
|
|
69
|
+
*/
|
|
70
|
+
interface HardcodedString {
|
|
71
|
+
/** The hardcoded text content */
|
|
72
|
+
text: string;
|
|
73
|
+
/** Line number where the string was found */
|
|
74
|
+
line: number;
|
|
75
|
+
}
|
|
76
|
+
export {};
|
|
33
77
|
//# sourceMappingURL=linter.d.ts.map
|
package/types/linter.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"linter.d.ts","sourceRoot":"","sources":["../src/linter.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"linter.d.ts","sourceRoot":"","sources":["../src/linter.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAG1C,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,SAAS,CAAA;AAEnD,KAAK,cAAc,GAAG;IACpB,QAAQ,EAAE;QAAC;YACT,OAAO,EAAE,MAAM,CAAC;SACjB;KAAC,CAAC;IACH,IAAI,EAAE;QAAC;YACL,OAAO,EAAE,OAAO,CAAC;YACjB,OAAO,EAAE,MAAM,CAAC;YAChB,KAAK,EAAE,MAAM,CAAC,MAAM,EAAE,eAAe,EAAE,CAAC,CAAC;SAC1C;KAAC,CAAC;IACH,KAAK,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;CACvB,CAAA;AAED,qBAAa,MAAO,SAAQ,YAAY,CAAC,cAAc,CAAC;IACtD,OAAO,CAAC,MAAM,CAAsB;gBAEvB,MAAM,EAAE,oBAAoB;IAKzC,SAAS,CAAE,KAAK,EAAE,OAAO;IAanB,GAAG;;;;;;;CAyCV;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,SAAS,CAAE,MAAM,EAAE,oBAAoB;;;;;;GAE5D;AAED,wBAAsB,YAAY,CAAE,MAAM,EAAE,oBAAoB,iBA4B/D;AAED;;GAEG;AACH,UAAU,eAAe;IACvB,iCAAiC;IACjC,IAAI,EAAE,MAAM,CAAC;IACb,6CAA6C;IAC7C,IAAI,EAAE,MAAM,CAAC;CACd"}
|