i18next-cli 1.17.1 → 1.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +11 -1
- package/README.md +34 -3
- package/dist/cjs/cli.js +1 -1
- package/dist/cjs/extractor/core/key-finder.js +1 -1
- package/dist/cjs/extractor/core/translation-manager.js +1 -1
- package/dist/cjs/extractor/parsers/call-expression-handler.js +1 -1
- package/dist/cjs/extractor/parsers/comment-parser.js +1 -1
- package/dist/cjs/extractor/parsers/jsx-handler.js +1 -1
- package/dist/cjs/linter.js +1 -1
- package/dist/cjs/status.js +1 -1
- package/dist/esm/cli.js +1 -1
- package/dist/esm/extractor/core/key-finder.js +1 -1
- package/dist/esm/extractor/core/translation-manager.js +1 -1
- package/dist/esm/extractor/parsers/call-expression-handler.js +1 -1
- package/dist/esm/extractor/parsers/comment-parser.js +1 -1
- package/dist/esm/extractor/parsers/jsx-handler.js +1 -1
- package/dist/esm/linter.js +1 -1
- package/dist/esm/status.js +1 -1
- package/package.json +1 -1
- package/src/cli.ts +3 -3
- package/src/extractor/core/key-finder.ts +11 -0
- package/src/extractor/core/translation-manager.ts +94 -7
- package/src/extractor/parsers/call-expression-handler.ts +110 -0
- package/src/extractor/parsers/comment-parser.ts +12 -0
- package/src/extractor/parsers/jsx-handler.ts +18 -0
- package/src/linter.ts +93 -34
- package/src/status.ts +18 -10
- package/src/types.ts +3 -0
- package/types/extractor/core/key-finder.d.ts.map +1 -1
- package/types/extractor/core/translation-manager.d.ts.map +1 -1
- package/types/extractor/parsers/call-expression-handler.d.ts.map +1 -1
- package/types/extractor/parsers/jsx-handler.d.ts.map +1 -1
- package/types/linter.d.ts +46 -2
- package/types/linter.d.ts.map +1 -1
- package/types/types.d.ts +2 -0
- package/types/types.d.ts.map +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -5,7 +5,17 @@ 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.
|
|
8
|
+
## [1.18.0](https://github.com/i18next/i18next-cli/compare/v1.17.2...v1.18.0) - 2025-10-30
|
|
9
|
+
|
|
10
|
+
- fix regression introduced in v1.17.2 [#82](https://github.com/i18next/i18next-cli/issues/82)
|
|
11
|
+
- enhancement(linter): use emitter for runLinter API [#79](https://github.com/i18next/i18next-cli/pull/79)
|
|
12
|
+
|
|
13
|
+
## [1.17.2](https://github.com/i18next/i18next-cli/compare/v1.17.1...v1.17.2) - 2025-10-29
|
|
14
|
+
|
|
15
|
+
- fix(status, extractor): avoid double‑expanding plural keys which could make locales show 0% translated [#81](https://github.com/i18next/i18next-cli/issues/81)
|
|
16
|
+
- fix(extractor): emit base key for single‑category plural languages (ja, zh, ko) [#82](https://github.com/i18next/i18next-cli/issues/82)
|
|
17
|
+
|
|
18
|
+
## [1.17.1](https://github.com/i18next/i18next-cli/compare/v1.17.0...v1.17.1) - 2025-10-29
|
|
9
19
|
|
|
10
20
|
- fix: regression for windows introduced in v1.17.0
|
|
11
21
|
|
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.0"),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("glob"),r=require("./extractor.js"),t=require("../../utils/logger.js"),
|
|
1
|
+
"use strict";var e=require("glob"),r=require("./extractor.js"),t=require("../../utils/logger.js"),n=require("../plugin-manager.js"),o=require("./ast-visitors.js");exports.findKeys=async function(i,s=new t.ConsoleLogger){const{plugins:a,...c}=i,l=a||[],u=await async function(r){const t=["node_modules/**"],n=Array.isArray(r.extract.ignore)?r.extract.ignore:r.extract.ignore?[r.extract.ignore]:[];return await e.glob(r.extract.input,{ignore:[...t,...n],cwd:process.cwd()})}(i),g=new Map,x=n.createPluginContext(g,l,c,s),p={onBeforeVisitNode:e=>{for(const r of l)try{r.onVisitNode?.(e,x)}catch(e){s.warn(`Plugin ${r.name} onVisitNode failed:`,e)}},resolvePossibleKeyStringValues:e=>l.flatMap(r=>{try{return r.extractKeysFromExpression?.(e,i,s)??[]}catch(e){return s.warn(`Plugin ${r.name} extractKeysFromExpression failed:`,e),[]}}),resolvePossibleContextStringValues:e=>l.flatMap(r=>{try{return r.extractContextFromExpression?.(e,i,s)??[]}catch(e){return s.warn(`Plugin ${r.name} extractContextFromExpression failed:`,e),[]}})},d=new o.ASTVisitors(c,x,s,p);x.getVarFromScope=d.getVarFromScope.bind(d),await n.initializePlugins(l);for(const e of u)await r.processFile(e,l,d,x,c,s);for(const e of l)await(e.onEnd?.(g));const f=c.extract?.pluralSeparator??"_",y=["zero","one","two","few","many","other"];for(const e of g.values()){const r=String(e.key).split(f),t=r[r.length-1],n=r.length>=3&&"ordinal"===r[r.length-2];(y.includes(t)||n&&y.includes(t))&&(e.isExpandedPlural=!0)}return{allKeys:g,objectKeys:d.objectKeys}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("node:path"),t=require("glob"),s=require("../../utils/nested-object.js"),
|
|
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 o(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}function a(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"],o=r.map(e=>`ordinal${n}${e}`),l=Object.keys(e).sort((e,t)=>{const s=e=>{for(const t of o)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}},a=s(e),l=s(t);if(a.isPlural&&l.isPlural){const e=a.base.localeCompare(l.base,void 0,{sensitivity:"base"});if(0!==e)return e;if(a.isOrdinal!==l.isOrdinal)return a.isOrdinal?1:-1;const t=a.isOrdinal?o:r,s=t.indexOf(a.form),n=t.indexOf(l.form);return-1!==s&&-1!==n?s-n:a.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]=a(e[n],t);return s}function l(e,t,n,o,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(o,{type:"cardinal"}),t=new Intl.PluralRules(o,{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}),$=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]?$.add(t.slice(0,-2).join(h)):$.add(t.slice(0,-1).join(h))}let w=p?{}:JSON.parse(JSON.stringify(t));const N=s.getNestedKeys(t,f??".");for(const e of N)if(i.some(t=>t.test(e))){const n=s.getNestedValue(t,e,f??".");s.setNestedValue(w,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(w,n,e,f??".")}}}}for(const{key:e,defaultValue:a,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)),$.has(s))continue}if(d&&!p){if(1===String(e).split(h).length&&o!==g){const t=e;if($.has(t));else{const e=m?v:O;for(const n of e){const e=m?`${t}${h}ordinal${h}${n}`:`${t}${h}${n}`,r="string"==typeof a&&void 0!==a?a:t;s.setNestedValue(w,e,r,f??".")}}continue}}const N=s.getNestedValue(t,e,f??"."),b=!S.some(t=>t.key.startsWith(`${e}${f}`)&&t.key!==e),j="object"==typeof N&&null!==N&&(c.has(e)||!a||a===e),P="object"==typeof N&&null!==N&&b&&!c.has(e)&&!j;if(j){s.setNestedValue(w,e,N,f??".");continue}let k;if(void 0===N||P)if(o===g)if(u){const t=a&&(a===e||e!==a&&(e.startsWith(a+h)||e.startsWith(a+x)));k=a&&!t?a:r.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",o,a)}else k=a||e;else k=r.resolveDefaultValue(y,e,l||n?.extract?.defaultNS||"translation",o,a);else if(o===g&&u){const t=a&&(a===e||e!==a&&(e.startsWith(a+h)||e.startsWith(a+x)));k=(e.includes(h)||e.includes(x))&&!i?N:a&&!t?a:N}else k=N;s.setNestedValue(w,e,k,f??".")}if(!0===d)return a(w,n);if("function"==typeof d){const e={},t=Object.keys(w),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]=a(w[s],n);w=e}return w}exports.getTranslations=async function(s,r,a,{syncPrimaryWithDefaults:i=!1}={}){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(e=>e!==a?.extract?.primaryLanguage);const c=[...a.extract.preservePatterns||[]],u=a.extract.indentation??2;for(const e of r)c.push(`${e}.*`);const f=c.map(o),d="__no_namespace__",p=new Map;for(const e of s.values()){const t=e.nsIsImplicit&&!1===a.extract.defaultNS?d:String(e.ns??a.extract.defaultNS??"translation");p.has(t)||p.set(t,[]),p.get(t).push(e)}const g=[],y=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const s of a.locales){if(a.extract.mergeNamespaces||"string"==typeof a.extract.output&&!a.extract.output.includes("{{namespace}}")){const t={},o=n.getOutputPath(a.extract.output,s),c=e.resolve(process.cwd(),o),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,a,s,void 0,f,r,i);Object.assign(t,e)}else{const o=y[e]||{};t[e]=l(n,o,a,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 o=new Set(p.keys()),c=n.getOutputPath(a.extract.output,s,"*").replace(/\\/g,"/"),d=await t.glob(c,{ignore:y});for(const t of d)o.add(e.basename(t,e.extname(t)));for(const t of o){const o=p.get(t)||[],c=n.getOutputPath(a.extract.output,s,t),d=e.resolve(process.cwd(),c),y=await n.loadTranslationFile(d)||{},h=l(o,y,a,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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./ast-utils.js");exports.CallExpressionHandler=class{pluginContext;config;logger;expressionResolver;objectKeys=new Set;constructor(e,t,r,n){this.config=e,this.pluginContext=t,this.logger=r,this.expressionResolver=n}handleCallExpression(t,r){const n=this.getFunctionName(t.callee);if(!n)return;const
|
|
1
|
+
"use strict";var e=require("./ast-utils.js");exports.CallExpressionHandler=class{pluginContext;config;logger;expressionResolver;objectKeys=new Set;constructor(e,t,r,n){this.config=e,this.pluginContext=t,this.logger=r,this.expressionResolver=n}handleCallExpression(t,r){const n=this.getFunctionName(t.callee);if(!n)return;const s=r(n),o=this.config.extract.functions||["t","*.t"];let i=void 0!==s;if(!i)for(const e of o)if(e.startsWith("*.")){if(n.endsWith(e.substring(1))){i=!0;break}}else if(e===n){i=!0;break}if(!i||0===t.arguments.length)return;const{keysToProcess:l,isSelectorAPI:a}=this.handleCallExpressionArgument(t,0);if(0===l.length)return;let u=!1;const p=this.config.extract.pluralSeparator??"_";for(let e=0;e<l.length;e++)l[e].endsWith(`${p}ordinal`)&&(u=!0,l[e]=l[e].slice(0,-8));let f,c;if(t.arguments.length>1){const r=t.arguments[1].expression;"ObjectExpression"===r.type?c=r:"StringLiteral"===r.type?f=r.value:"TemplateLiteral"===r.type&&e.isSimpleTemplateLiteral(r)&&(f=r.quasis[0].cooked)}if(t.arguments.length>2){const e=t.arguments[2].expression;"ObjectExpression"===e.type&&(c=e)}const y=c?e.getObjectPropValue(c,"defaultValue"):void 0,g="string"==typeof y?y:f,h=e=>{if(!e||!Array.isArray(e.properties))return!1;for(const t of e.properties)if(t&&"KeyValueProperty"===t.type&&t.key){const e="Identifier"===t.key.type&&t.key.value||"StringLiteral"===t.key.type&&t.key.value;if("string"==typeof e&&e.startsWith("defaultValue"))return!0}return!1},d="string"==typeof g||h(c),x=h(c),k=Boolean(x||"string"==typeof g&&!("string"==typeof(v=g)&&/{{\s*count\s*}}/.test(v)));var v;for(let t=0;t<l.length;t++){let r,n=l[t];if(c){const t=e.getObjectPropValue(c,"ns");"string"==typeof t&&(r=t)}const o=this.config.extract.nsSeparator??":";if(!r&&o&&n.includes(o)){const e=n.split(o);if(r=e.shift(),n=e.join(o),!n||""===n.trim()){this.logger.warn(`Skipping key that became empty after namespace removal: '${r}${o}'`);continue}}!r&&s?.defaultNs&&(r=s.defaultNs),r||(r=this.config.extract.defaultNS);let i=n;if(s?.keyPrefix){const e=this.config.extract.keySeparator??".";if(i=!1!==e?s.keyPrefix.endsWith(e)?`${s.keyPrefix}${n}`:`${s.keyPrefix}${e}${n}`:`${s.keyPrefix}${n}`,!1!==e){if(i.split(e).some(e=>""===e.trim())){this.logger.warn(`Skipping key with empty segments: '${i}' (keyPrefix: '${s.keyPrefix}', key: '${n}')`);continue}}}const p=t===l.length-1&&g||n;if(c){const t=e.getObjectProperty(c,"context"),n=[];if("StringLiteral"===t?.value?.type||"NumericLiteral"===t?.value.type||"BooleanLiteral"===t?.value.type){const e=`${t.value.value}`,s=this.config.extract.contextSeparator??"_";""!==e&&n.push({key:`${i}${s}${e}`,ns:r,defaultValue:p,explicitDefault:d})}else if(t?.value){const e=this.expressionResolver.resolvePossibleContextStringValues(t.value),s=this.config.extract.contextSeparator??"_";e.length>0&&(e.forEach(e=>{n.push({key:`${i}${s}${e}`,ns:r,defaultValue:p,explicitDefault:d})}),n.push({key:i,ns:r,defaultValue:p,explicitDefault:d}))}const s=e=>{if(e){if("KeyValueProperty"===e.type&&e.key){if("Identifier"===e.key.type)return e.key.value;if("StringLiteral"===e.key.type)return e.key.value}return"KeyValueProperty"===e.type&&e.value&&"Identifier"===e.value.type?e.key&&"Identifier"===e.key.type?e.key.value:void 0:"ShorthandProperty"!==e.type&&"Identifier"!==e.type||!e.value?e.key&&"string"==typeof e.key?e.key:void 0:e.value}},o=(()=>{if(!c||!Array.isArray(c.properties))return!1;for(const e of c.properties){if("count"===s(e))return!0}return!1})(),l=(()=>{if(!c||!Array.isArray(c.properties))return!1;for(const e of c.properties){if("ordinal"===s(e))return!("KeyValueProperty"!==e.type||!e.value||"BooleanLiteral"!==e.value.type)&&Boolean(e.value.value)}return!1})();if(o||u){try{const e=u?"ordinal":"cardinal",t=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let s=!1;try{const r=new Intl.PluralRules(t,{type:e}).resolvedOptions().pluralCategories;1===r.length&&"other"===r[0]&&(s=!0)}catch{}if(!s){const t=new Set;for(const r of this.config.locales)try{new Intl.PluralRules(r,{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}catch{new Intl.PluralRules("en",{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}const r=Array.from(t).sort();1===r.length&&"other"===r[0]&&(s=!0)}if(s){if(n.length>0)for(const e of n)this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,hasCount:!0,isOrdinal:u});else this.pluginContext.addKey({key:i,ns:r,defaultValue:p,hasCount:!0,isOrdinal:u});continue}}catch(e){}this.config.extract.disablePlurals?n.length>0?n.forEach(this.pluginContext.addKey):this.pluginContext.addKey({key:i,ns:r,defaultValue:p,explicitDefault:d}):this.handlePluralKeys(i,r,c,l||u,g,k);continue}if(n.length>0){n.forEach(this.pluginContext.addKey);continue}!0===e.getObjectPropValue(c,"returnObjects")&&this.objectKeys.add(i)}a&&this.objectKeys.add(i),this.pluginContext.addKey({key:i,ns:r,defaultValue:p,explicitDefault:d})}}handleCallExpressionArgument(e,t){const r=e.arguments[t].expression,n=[];let s=!1;if("ArrowFunctionExpression"===r.type){const e=this.extractKeyFromSelector(r);e&&(n.push(e),s=!0)}else if("ArrayExpression"===r.type)for(const e of r.elements)e?.expression&&n.push(...this.expressionResolver.resolvePossibleKeyStringValues(e.expression));else n.push(...this.expressionResolver.resolvePossibleKeyStringValues(r));return{keysToProcess:n.filter(e=>!!e),isSelectorAPI:s}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let r=t;const n=[];for(;"MemberExpression"===r.type;){const e=r.property;if("Identifier"===e.type)n.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;n.unshift(e.expression.value)}r=r.object}if(n.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return n.join(t)}return null}handlePluralKeys(t,r,n,s,o,i){try{const l=s?"ordinal":"cardinal",a=new Set;for(const e of this.config.locales)try{const t=new Intl.PluralRules(e,{type:l});t.resolvedOptions().pluralCategories.forEach(e=>a.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:l});t.resolvedOptions().pluralCategories.forEach(e=>a.add(e))}const u=Array.from(a).sort(),p=this.config.extract.pluralSeparator??"_",f=e.getObjectPropValue(n,"defaultValue"),c=e.getObjectPropValue(n,`defaultValue${p}other`),y=e.getObjectPropValue(n,`defaultValue${p}ordinal${p}other`),g=e.getObjectProperty(n,"context"),h=[];if(g?.value){const e=this.expressionResolver.resolvePossibleContextStringValues(g.value);if(e.length>0)if("StringLiteral"===g.value.type)for(const r of e)r.length>0&&h.push({key:t,context:r});else{for(const r of e)r.length>0&&h.push({key:t,context:r});!1!==this.config.extract?.generateBasePluralForms&&h.push({key:t})}else h.push({key:t})}else h.push({key:t});const d=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let x=!1;try{const e=new Intl.PluralRules(d,{type:l}).resolvedOptions().pluralCategories;1===e.length&&"other"===e[0]&&(x=!0)}catch{x=!1}if(x||1===u.length&&"other"===u[0]){for(const{key:t,context:l}of h){const a=e.getObjectPropValue(n,`defaultValue${p}other`);let u;u="string"==typeof a?a:"string"==typeof f?f:"string"==typeof o?o:l?`${t}_${l}`:t;const c=this.config.extract.contextSeparator??"_",y=l?`${t}${c}${l}`:t;this.pluginContext.addKey({key:y,ns:r,defaultValue:u,hasCount:!0,isOrdinal:s,explicitDefault:Boolean(i||"string"==typeof a)})}return}for(const{key:t,context:l}of h)for(const a of u){const u=s?`defaultValue${p}ordinal${p}${a}`:`defaultValue${p}${a}`,g=e.getObjectPropValue(n,u);let h,d;if(h="string"==typeof g?g:"one"===a&&"string"==typeof f?f:"one"===a&&"string"==typeof o?o:s&&"string"==typeof y?y:s||"string"!=typeof c?"string"==typeof f?f:"string"==typeof o?o:t:c,l){const e=this.config.extract.contextSeparator??"_";d=s?`${t}${e}${l}${p}ordinal${p}${a}`:`${t}${e}${l}${p}${a}`}else d=s?`${t}${p}ordinal${p}${a}`:`${t}${p}${a}`;this.pluginContext.addKey({key:d,ns:r,defaultValue:h,hasCount:!0,isOrdinal:s,explicitDefault:Boolean(i||"string"==typeof g||"string"==typeof c)})}}catch(s){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const i=o||e.getObjectPropValue(n,"defaultValue");this.pluginContext.addKey({key:t,ns:r,defaultValue:"string"==typeof i?i:t})}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let r=e;for(;"MemberExpression"===r.type;){if("Identifier"!==r.property.type)return null;t.unshift(r.property.value),r=r.object}if("ThisExpression"===r.type)t.unshift("this");else{if("Identifier"!==r.type)return null;t.unshift(r.value)}return t.join(".")}return null}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";function e(e,t,n,s,a,r=!1){try{const o=r?"ordinal":"cardinal",l=new Set;for(const e of a.locales)try{const t=new Intl.PluralRules(e,{type:o});t.resolvedOptions().pluralCategories.forEach(e=>l.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:o});t.resolvedOptions().pluralCategories.forEach(e=>l.add(e))}const c=Array.from(l).sort(),u=a.extract.pluralSeparator??"_";for(const a of c){const o=r?`${e}${u}ordinal${u}${a}`:`${e}${u}${a}`;s.addKey({key:o,ns:n,defaultValue:t,hasCount:!0,isOrdinal:r})}}catch(a){s.addKey({key:e,ns:n,defaultValue:t})}}function t(e,t,n,s,a,r,o=!1){try{const l=o?"ordinal":"cardinal",c=new Set;for(const e of r.locales)try{const t=new Intl.PluralRules(e,{type:l});t.resolvedOptions().pluralCategories.forEach(e=>c.add(e))}catch(e){const t=new Intl.PluralRules(r.extract.primaryLanguage||"en",{type:l});t.resolvedOptions().pluralCategories.forEach(e=>c.add(e))}const u=Array.from(c).sort(),i=r.extract.pluralSeparator??"_";for(const r of u){const l=o?`${e}_${s}${i}ordinal${i}${r}`:`${e}_${s}${i}${r}`;a.addKey({key:l,ns:n,defaultValue:t,hasCount:!0,isOrdinal:o})}}catch(r){a.addKey({key:`${e}_${s}`,ns:n,defaultValue:t})}}function n(e){const t=/^\s*,\s*(['"])(.*?)\1/.exec(e);if(t)return t[2];const n=/^\s*,\s*\{[^}]*defaultValue\s*:\s*(['"])(.*?)\1/.exec(e);return n?n[2]:void 0}function s(e){const t=/^\s*,\s*\{[^}]*ns\s*:\s*(['"])(.*?)\1/.exec(e);if(t)return t[2]}function a(e){const t=/^\s*,\s*\{[^}]*context\s*:\s*(['"])(.*?)\1/.exec(e);if(t)return t[2]}function r(e){const t=/^\s*,\s*\{[^}]*count\s*:\s*(\d+)/.exec(e);if(t)return parseInt(t[1],10)}function o(e){const t=/^\s*,\s*\{[^}]*ordinal\s*:\s*(true|false)/.exec(e);if(t)return"true"===t[1]}function l(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}exports.extractKeysFromComments=function(c,u,i,d){const f=new RegExp("\\bt\\s*\\(\\s*(['\"])([^'\"]+)\\1","g"),
|
|
1
|
+
"use strict";function e(e,t,n,s,a,r=!1){try{const o=r?"ordinal":"cardinal",l=new Set;for(const e of a.locales)try{const t=new Intl.PluralRules(e,{type:o});t.resolvedOptions().pluralCategories.forEach(e=>l.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:o});t.resolvedOptions().pluralCategories.forEach(e=>l.add(e))}const c=Array.from(l).sort(),u=a.extract.pluralSeparator??"_";if(1===c.length&&"other"===c[0])return void s.addKey({key:e,ns:n,defaultValue:t,hasCount:!0});for(const a of c){const o=r?`${e}${u}ordinal${u}${a}`:`${e}${u}${a}`;s.addKey({key:o,ns:n,defaultValue:t,hasCount:!0,isOrdinal:r})}}catch(a){s.addKey({key:e,ns:n,defaultValue:t})}}function t(e,t,n,s,a,r,o=!1){try{const l=o?"ordinal":"cardinal",c=new Set;for(const e of r.locales)try{const t=new Intl.PluralRules(e,{type:l});t.resolvedOptions().pluralCategories.forEach(e=>c.add(e))}catch(e){const t=new Intl.PluralRules(r.extract.primaryLanguage||"en",{type:l});t.resolvedOptions().pluralCategories.forEach(e=>c.add(e))}const u=Array.from(c).sort(),i=r.extract.pluralSeparator??"_";for(const r of u){const l=o?`${e}_${s}${i}ordinal${i}${r}`:`${e}_${s}${i}${r}`;a.addKey({key:l,ns:n,defaultValue:t,hasCount:!0,isOrdinal:o})}}catch(r){a.addKey({key:`${e}_${s}`,ns:n,defaultValue:t})}}function n(e){const t=/^\s*,\s*(['"])(.*?)\1/.exec(e);if(t)return t[2];const n=/^\s*,\s*\{[^}]*defaultValue\s*:\s*(['"])(.*?)\1/.exec(e);return n?n[2]:void 0}function s(e){const t=/^\s*,\s*\{[^}]*ns\s*:\s*(['"])(.*?)\1/.exec(e);if(t)return t[2]}function a(e){const t=/^\s*,\s*\{[^}]*context\s*:\s*(['"])(.*?)\1/.exec(e);if(t)return t[2]}function r(e){const t=/^\s*,\s*\{[^}]*count\s*:\s*(\d+)/.exec(e);if(t)return parseInt(t[1],10)}function o(e){const t=/^\s*,\s*\{[^}]*ordinal\s*:\s*(true|false)/.exec(e);if(t)return"true"===t[1]}function l(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}exports.extractKeysFromComments=function(c,u,i,d){const f=new RegExp("\\bt\\s*\\(\\s*(['\"])([^'\"]+)\\1","g"),y=(i.extract.preservePatterns||[]).map(l),p=function(e){const t=[],n=new Set,s=/\/\/(.*)|\/\*([\s\S]*?)\*\//g;let a;for(;null!==(a=s.exec(e));){const e=(a[1]??a[2]).trim();e&&!n.has(e)&&(n.add(e),t.push(e))}return t}(c);for(const l of p){let c;for(;null!==(c=f.exec(l));){let f,p=c[2];if(!p||""===p.trim())continue;if(y.some(e=>e.test(p)))continue;const $=l.slice(c.index+c[0].length),x=n($),h=a($),g=r($),m=o($);let K=!1;const V=i.extract.pluralSeparator??"_";if(p.endsWith(`${V}ordinal`)){if(K=!0,p=p.slice(0,-(V.length+7)),!p||""===p.trim())continue;if(y.some(e=>e.test(p)))continue}const k=!0===m||K;f=s($);const w=i.extract.nsSeparator??":";if(!f&&w&&p.includes(w)){const e=p.split(w);if(f=e.shift(),p=e.join(w),!p||""===p.trim())continue;if(y.some(e=>e.test(p)))continue}if(!f&&d){const e=d("t");e?.defaultNs&&(f=e.defaultNs)}if(f||(f=i.extract.defaultNS),i.extract.disablePlurals)h?u.addKey({key:`${p}_${h}`,ns:f,defaultValue:x??p}):u.addKey({key:p,ns:f,defaultValue:x??p});else if(h&&g){t(p,x??p,f,h,u,i,k);!1!==i.extract?.generateBasePluralForms&&e(p,x??p,f,u,i,k)}else h?(u.addKey({key:p,ns:f,defaultValue:x??p}),u.addKey({key:`${p}_${h}`,ns:f,defaultValue:x??p})):g?e(p,x??p,f,u,i,k):u.addKey({key:p,ns:f,defaultValue:x??p})}}};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("./jsx-parser.js"),t=require("./ast-utils.js");exports.JSXHandler=class{config;pluginContext;expressionResolver;constructor(e,t,n){this.config=e,this.pluginContext=t,this.expressionResolver=n}handleJSXElement(t,n){const s=this.getElementName(t);if(s&&(this.config.extract.transComponents||["Trans"]).includes(s)){const s=e.extractFromTransComponent(t,this.config),a=[];if(s){if(s.keyExpression){const e=this.expressionResolver.resolvePossibleKeyStringValues(s.keyExpression);a.push(...e)}else a.push(s.serializedChildren);let e;const{contextExpression:
|
|
1
|
+
"use strict";var e=require("./jsx-parser.js"),t=require("./ast-utils.js");exports.JSXHandler=class{config;pluginContext;expressionResolver;constructor(e,t,n){this.config=e,this.pluginContext=t,this.expressionResolver=n}handleJSXElement(t,n){const s=this.getElementName(t);if(s&&(this.config.extract.transComponents||["Trans"]).includes(s)){const s=e.extractFromTransComponent(t,this.config),a=[];if(s){if(s.keyExpression){const e=this.expressionResolver.resolvePossibleKeyStringValues(s.keyExpression);a.push(...e)}else a.push(s.serializedChildren);let e;const{contextExpression:i,optionsNode:l,defaultValue:o,hasCount:r,isOrdinal:u,serializedChildren:f}=s;if(s.ns){const{ns:t}=s;e=a.map(e=>({key:e,ns:t,defaultValue:o||f,hasCount:r,isOrdinal:u}))}else{e=a.map(e=>{const t=this.config.extract.nsSeparator??":";let n;if(t&&e.includes(t)){let s;[n,...s]=e.split(t),e=s.join(t)}return{key:e,ns:n,defaultValue:o||f,hasCount:r,isOrdinal:u,explicitDefault:s.explicitDefault}});const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===i?.type&&"JSXExpressionContainer"===i.value?.type&&"Identifier"===i.value.expression.type){const t=n(i.value.expression.value);t?.defaultNs&&e.forEach(e=>{e.ns||(e.ns=t.defaultNs)})}}if(e.forEach(e=>{e.ns||(e.ns=this.config.extract.defaultNS)}),i&&r)if(this.config.extract.disablePlurals){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0)if("StringLiteral"===i.type)for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}else{e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n,a=this.expressionResolver.resolvePossibleContextStringValues(i),o=this.config.extract.contextSeparator??"_";if(a.length>0){e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l));for(const t of a)for(const n of e){const e=`${n.key}${o}${t}`;this.generatePluralKeysForTrans(e,n.defaultValue,n.ns,s,l,n.explicitDefault)}}else e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else if(i){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0){for(const s of t)for(const{key:t,ns:a,defaultValue:i}of e)this.pluginContext.addKey({key:`${t}${n}${s}`,ns:a,defaultValue:i});"StringLiteral"!==i.type&&e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else if(r)if(this.config.extract.disablePlurals)e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n;e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}}}generatePluralKeysForTrans(e,n,s,a,i,l){try{const o=a?"ordinal":"cardinal",r=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:o}).resolvedOptions().pluralCategories,u=this.config.extract.pluralSeparator??"_";let f,d;if(i&&(f=t.getObjectPropValue(i,`defaultValue${u}other`),d=t.getObjectPropValue(i,`defaultValue${u}ordinal${u}other`)),1===r.length&&"other"===r[0]){const o=i?t.getObjectPropValue(i,`defaultValue${u}other`):void 0,r="string"==typeof o?o:"string"==typeof n?n:e;return void this.pluginContext.addKey({key:e,ns:s,defaultValue:r,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof o||"string"==typeof f)})}for(const o of r){const r=a?`defaultValue${u}ordinal${u}${o}`:`defaultValue${u}${o}`,p=i?t.getObjectPropValue(i,r):void 0;let c;c="string"==typeof p?p:"one"===o&&"string"==typeof n?n:a&&"string"==typeof d?d:a||"string"!=typeof f?"string"==typeof n?n:e:f;const y=a?`${e}${u}ordinal${u}${o}`:`${e}${u}${o}`;this.pluginContext.addKey({key:y,ns:s,defaultValue:c,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof p||"string"==typeof f)})}}catch(t){this.pluginContext.addKey({key:e,ns:s,defaultValue:n})}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}};
|
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/cjs/status.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var e=require("chalk"),
|
|
1
|
+
"use strict";var e=require("chalk"),a=require("ora"),o=require("node:path"),t=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(a,o,t){const s=t>0?Math.round(o/t*100):100,n=c(s);console.log(`${e.bold(a)}: ${n} ${s}% (${o}/${t})`)}function c(a){const o=Math.floor(a/100*20),t=20-o;return`[${e.green("".padStart(o,"■"))}${"".padStart(t,"□")}]`}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=a("Analyzing project localization status...\n").start();try{const a=await async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(a=>a!==e?.extract?.primaryLanguage);const{allKeys:a}=await t.findKeys(e),{secondaryLanguages:l,keySeparator:r=".",defaultNS:c="translation",mergeNamespaces:i=!1,pluralSeparator:u="_"}=e.extract,d=new Map;for(const e of a.values()){const a=e.ns||c||"translation";d.has(a)||d.set(a,[]),d.get(a).push(e)}const y={totalBaseKeys:a.size,keysByNs:d,locales:new Map};for(const a of l){let t=0,l=0;const c=new Map,g=i?await n.loadTranslationFile(o.resolve(process.cwd(),n.getOutputPath(e.extract.output,a)))||{}:null;for(const[y,f]of d.entries()){const d=i?g?.[y]||{}:await n.loadTranslationFile(o.resolve(process.cwd(),n.getOutputPath(e.extract.output,a,y)))||{};let p=0,$=0;const m=[];for(const{key:e,hasCount:o,isOrdinal:t,isExpandedPlural:n}of f)if(o)if(n){$++;const a=!!s.getNestedValue(d,e,r??".");a&&p++,m.push({key:e,isTranslated:a})}else{const o=t?"ordinal":"cardinal",n=new Intl.PluralRules(a,{type:o}).resolvedOptions().pluralCategories;for(const a of n){$++;const o=t?`${e}${u}ordinal${u}${a}`:`${e}${u}${a}`,n=!!s.getNestedValue(d,o,r??".");n&&p++,m.push({key:o,isTranslated:n})}}else{$++;const a=!!s.getNestedValue(d,e,r??".");a&&p++,m.push({key:e,isTranslated:a})}c.set(y,{totalKeys:$,translatedKeys:p,keyDetails:m}),t+=p,l+=$}y.locales.set(a,{totalKeys:l,totalTranslated:t,namespaces:c})}return y}(l);d.succeed("Analysis complete."),await async function(a,o,t){t.detail?await async function(a,o,t,s){if(t===o.extract.primaryLanguage)return void console.log(e.yellow(`Locale "${t}" is the primary language. All keys are considered present.`));if(!o.locales.includes(t))return void console.error(e.red(`Error: Locale "${t}" is not defined in your configuration.`));const n=a.locales.get(t);if(!n)return void console.error(e.red(`Error: Locale "${t}" is not a valid secondary language.`));console.log(e.bold(`\nKey Status for "${e.cyan(t)}":`));const l=Array.from(a.keysByNs.values()).flat().length;r("Overall",n.totalTranslated,n.totalKeys);const c=s?[s]:Array.from(n.namespaces.keys()).sort();for(const a of c){const o=n.namespaces.get(a);o&&(console.log(e.cyan.bold(`\nNamespace: ${a}`)),r("Namespace Progress",o.translatedKeys,o.totalKeys),o.keyDetails.forEach(({key:a,isTranslated:o})=>{const t=o?e.green("✓"):e.red("✗");console.log(` ${t} ${a}`)}))}const u=l-n.totalTranslated;u>0?console.log(e.yellow.bold(`\nSummary: Found ${u} missing translations for "${t}".`)):console.log(e.green.bold(`\nSummary: 🎉 All keys are translated for "${t}".`));await i()}(a,o,t.detail,t.namespace):t.namespace?await async function(a,o,t){const s=a.keysByNs.get(t);if(!s)return void console.error(e.red(`Error: Namespace "${t}" was not found in your source code.`));console.log(e.cyan.bold(`\nStatus for Namespace: "${t}"`)),console.log("------------------------");for(const[e,o]of a.locales.entries()){const a=o.namespaces.get(t);if(a){const o=a.totalKeys>0?Math.round(a.translatedKeys/a.totalKeys*100):100,t=c(o);console.log(`- ${e}: ${t} ${o}% (${a.translatedKeys}/${a.totalKeys} keys)`)}}await i()}(a,0,t.namespace):await async function(a,o){const{primaryLanguage:t}=o.extract;console.log(e.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${e.bold(a.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${e.bold(a.keysByNs.size)}`),console.log(`🌍 Locales: ${e.bold(o.locales.join(", "))}`),console.log(`✅ Primary Language: ${e.bold(t)}`),console.log("\nTranslation Progress:");for(const[e,o]of a.locales.entries()){const a=o.totalKeys>0?Math.round(o.totalTranslated/o.totalKeys*100):100,t=c(a);console.log(`- ${e}: ${t} ${a}% (${o.totalTranslated}/${o.totalKeys} keys)`)}await i()}(a,o)}(a,l,u)}catch(e){d.fail("Failed to generate status report."),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{
|
|
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.0"),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{glob as
|
|
1
|
+
import{glob as t}from"glob";import{processFile as r}from"./extractor.js";import{ConsoleLogger as e}from"../../utils/logger.js";import{createPluginContext as o,initializePlugins as n}from"../plugin-manager.js";import{ASTVisitors as a}from"./ast-visitors.js";async function s(s,i=new e){const{plugins:c,...l}=s,p=c||[],u=await async function(r){const e=["node_modules/**"],o=Array.isArray(r.extract.ignore)?r.extract.ignore:r.extract.ignore?[r.extract.ignore]:[];return await t(r.extract.input,{ignore:[...e,...o],cwd:process.cwd()})}(s),f=new Map,g=o(f,p,l,i),m={onBeforeVisitNode:t=>{for(const r of p)try{r.onVisitNode?.(t,g)}catch(t){i.warn(`Plugin ${r.name} onVisitNode failed:`,t)}},resolvePossibleKeyStringValues:t=>p.flatMap(r=>{try{return r.extractKeysFromExpression?.(t,s,i)??[]}catch(t){return i.warn(`Plugin ${r.name} extractKeysFromExpression failed:`,t),[]}}),resolvePossibleContextStringValues:t=>p.flatMap(r=>{try{return r.extractContextFromExpression?.(t,s,i)??[]}catch(t){return i.warn(`Plugin ${r.name} extractContextFromExpression failed:`,t),[]}})},x=new a(l,g,i,m);g.getVarFromScope=x.getVarFromScope.bind(x),await n(p);for(const t of u)await r(t,p,x,g,l,i);for(const t of p)await(t.onEnd?.(f));const d=l.extract?.pluralSeparator??"_",w=["zero","one","two","few","many","other"];for(const t of f.values()){const r=String(t.key).split(d),e=r[r.length-1],o=r.length>=3&&"ordinal"===r[r.length-2];(w.includes(e)||o&&w.includes(e))&&(t.isExpandedPlural=!0)}return{allKeys:f,objectKeys:x.objectKeys}}export{s as findKeys};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{resolve as t,basename as e,extname 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 e=t;if(b.has(e));else{const t=y?v:$;for(const n of t){i(j,y?`${e}${x}ordinal${x}${n}`:`${e}${x}${n}`,"string"==typeof r&&void 0!==r?r:e,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};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{isSimpleTemplateLiteral as e,getObjectPropValue as t,getObjectProperty as r}from"./ast-utils.js";class n{pluginContext;config;logger;expressionResolver;objectKeys=new Set;constructor(e,t,r,n){this.config=e,this.pluginContext=t,this.logger=r,this.expressionResolver=n}handleCallExpression(n,
|
|
1
|
+
import{isSimpleTemplateLiteral as e,getObjectPropValue as t,getObjectProperty as r}from"./ast-utils.js";class n{pluginContext;config;logger;expressionResolver;objectKeys=new Set;constructor(e,t,r,n){this.config=e,this.pluginContext=t,this.logger=r,this.expressionResolver=n}handleCallExpression(n,s){const i=this.getFunctionName(n.callee);if(!i)return;const o=s(i),l=this.config.extract.functions||["t","*.t"];let a=void 0!==o;if(!a)for(const e of l)if(e.startsWith("*.")){if(i.endsWith(e.substring(1))){a=!0;break}}else if(e===i){a=!0;break}if(!a||0===n.arguments.length)return;const{keysToProcess:u,isSelectorAPI:f}=this.handleCallExpressionArgument(n,0);if(0===u.length)return;let p=!1;const c=this.config.extract.pluralSeparator??"_";for(let e=0;e<u.length;e++)u[e].endsWith(`${c}ordinal`)&&(p=!0,u[e]=u[e].slice(0,-8));let y,g;if(n.arguments.length>1){const t=n.arguments[1].expression;"ObjectExpression"===t.type?g=t:"StringLiteral"===t.type?y=t.value:"TemplateLiteral"===t.type&&e(t)&&(y=t.quasis[0].cooked)}if(n.arguments.length>2){const e=n.arguments[2].expression;"ObjectExpression"===e.type&&(g=e)}const h=g?t(g,"defaultValue"):void 0,d="string"==typeof h?h:y,x=e=>{if(!e||!Array.isArray(e.properties))return!1;for(const t of e.properties)if(t&&"KeyValueProperty"===t.type&&t.key){const e="Identifier"===t.key.type&&t.key.value||"StringLiteral"===t.key.type&&t.key.value;if("string"==typeof e&&e.startsWith("defaultValue"))return!0}return!1},k="string"==typeof d||x(g),v=x(g),$=Boolean(v||"string"==typeof d&&!("string"==typeof(m=d)&&/{{\s*count\s*}}/.test(m)));var m;for(let e=0;e<u.length;e++){let n,s=u[e];if(g){const e=t(g,"ns");"string"==typeof e&&(n=e)}const i=this.config.extract.nsSeparator??":";if(!n&&i&&s.includes(i)){const e=s.split(i);if(n=e.shift(),s=e.join(i),!s||""===s.trim()){this.logger.warn(`Skipping key that became empty after namespace removal: '${n}${i}'`);continue}}!n&&o?.defaultNs&&(n=o.defaultNs),n||(n=this.config.extract.defaultNS);let l=s;if(o?.keyPrefix){const e=this.config.extract.keySeparator??".";if(l=!1!==e?o.keyPrefix.endsWith(e)?`${o.keyPrefix}${s}`:`${o.keyPrefix}${e}${s}`:`${o.keyPrefix}${s}`,!1!==e){if(l.split(e).some(e=>""===e.trim())){this.logger.warn(`Skipping key with empty segments: '${l}' (keyPrefix: '${o.keyPrefix}', key: '${s}')`);continue}}}const a=e===u.length-1&&d||s;if(g){const e=r(g,"context"),s=[];if("StringLiteral"===e?.value?.type||"NumericLiteral"===e?.value.type||"BooleanLiteral"===e?.value.type){const t=`${e.value.value}`,r=this.config.extract.contextSeparator??"_";""!==t&&s.push({key:`${l}${r}${t}`,ns:n,defaultValue:a,explicitDefault:k})}else if(e?.value){const t=this.expressionResolver.resolvePossibleContextStringValues(e.value),r=this.config.extract.contextSeparator??"_";t.length>0&&(t.forEach(e=>{s.push({key:`${l}${r}${e}`,ns:n,defaultValue:a,explicitDefault:k})}),s.push({key:l,ns:n,defaultValue:a,explicitDefault:k}))}const i=e=>{if(e){if("KeyValueProperty"===e.type&&e.key){if("Identifier"===e.key.type)return e.key.value;if("StringLiteral"===e.key.type)return e.key.value}return"KeyValueProperty"===e.type&&e.value&&"Identifier"===e.value.type?e.key&&"Identifier"===e.key.type?e.key.value:void 0:"ShorthandProperty"!==e.type&&"Identifier"!==e.type||!e.value?e.key&&"string"==typeof e.key?e.key:void 0:e.value}},o=(()=>{if(!g||!Array.isArray(g.properties))return!1;for(const e of g.properties){if("count"===i(e))return!0}return!1})(),u=(()=>{if(!g||!Array.isArray(g.properties))return!1;for(const e of g.properties){if("ordinal"===i(e))return!("KeyValueProperty"!==e.type||!e.value||"BooleanLiteral"!==e.value.type)&&Boolean(e.value.value)}return!1})();if(o||p){try{const e=p?"ordinal":"cardinal",t=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let r=!1;try{const n=new Intl.PluralRules(t,{type:e}).resolvedOptions().pluralCategories;1===n.length&&"other"===n[0]&&(r=!0)}catch{}if(!r){const t=new Set;for(const r of this.config.locales)try{new Intl.PluralRules(r,{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}catch{new Intl.PluralRules("en",{type:e}).resolvedOptions().pluralCategories.forEach(e=>t.add(e))}const n=Array.from(t).sort();1===n.length&&"other"===n[0]&&(r=!0)}if(r){if(s.length>0)for(const e of s)this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue,hasCount:!0,isOrdinal:p});else this.pluginContext.addKey({key:l,ns:n,defaultValue:a,hasCount:!0,isOrdinal:p});continue}}catch(e){}this.config.extract.disablePlurals?s.length>0?s.forEach(this.pluginContext.addKey):this.pluginContext.addKey({key:l,ns:n,defaultValue:a,explicitDefault:k}):this.handlePluralKeys(l,n,g,u||p,d,$);continue}if(s.length>0){s.forEach(this.pluginContext.addKey);continue}!0===t(g,"returnObjects")&&this.objectKeys.add(l)}f&&this.objectKeys.add(l),this.pluginContext.addKey({key:l,ns:n,defaultValue:a,explicitDefault:k})}}handleCallExpressionArgument(e,t){const r=e.arguments[t].expression,n=[];let s=!1;if("ArrowFunctionExpression"===r.type){const e=this.extractKeyFromSelector(r);e&&(n.push(e),s=!0)}else if("ArrayExpression"===r.type)for(const e of r.elements)e?.expression&&n.push(...this.expressionResolver.resolvePossibleKeyStringValues(e.expression));else n.push(...this.expressionResolver.resolvePossibleKeyStringValues(r));return{keysToProcess:n.filter(e=>!!e),isSelectorAPI:s}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let r=t;const n=[];for(;"MemberExpression"===r.type;){const e=r.property;if("Identifier"===e.type)n.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;n.unshift(e.expression.value)}r=r.object}if(n.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return n.join(t)}return null}handlePluralKeys(e,n,s,i,o,l){try{const a=i?"ordinal":"cardinal",u=new Set;for(const e of this.config.locales)try{const t=new Intl.PluralRules(e,{type:a});t.resolvedOptions().pluralCategories.forEach(e=>u.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:a});t.resolvedOptions().pluralCategories.forEach(e=>u.add(e))}const f=Array.from(u).sort(),p=this.config.extract.pluralSeparator??"_",c=t(s,"defaultValue"),y=t(s,`defaultValue${p}other`),g=t(s,`defaultValue${p}ordinal${p}other`),h=r(s,"context"),d=[];if(h?.value){const t=this.expressionResolver.resolvePossibleContextStringValues(h.value);if(t.length>0)if("StringLiteral"===h.value.type)for(const r of t)r.length>0&&d.push({key:e,context:r});else{for(const r of t)r.length>0&&d.push({key:e,context:r});!1!==this.config.extract?.generateBasePluralForms&&d.push({key:e})}else d.push({key:e})}else d.push({key:e});const x=this.config.extract?.primaryLanguage||(Array.isArray(this.config.locales)?this.config.locales[0]:void 0)||"en";let k=!1;try{const e=new Intl.PluralRules(x,{type:a}).resolvedOptions().pluralCategories;1===e.length&&"other"===e[0]&&(k=!0)}catch{k=!1}if(k||1===f.length&&"other"===f[0]){for(const{key:e,context:r}of d){const a=t(s,`defaultValue${p}other`);let u;u="string"==typeof a?a:"string"==typeof c?c:"string"==typeof o?o:r?`${e}_${r}`:e;const f=this.config.extract.contextSeparator??"_",y=r?`${e}${f}${r}`:e;this.pluginContext.addKey({key:y,ns:n,defaultValue:u,hasCount:!0,isOrdinal:i,explicitDefault:Boolean(l||"string"==typeof a)})}return}for(const{key:e,context:r}of d)for(const a of f){const u=t(s,i?`defaultValue${p}ordinal${p}${a}`:`defaultValue${p}${a}`);let f,h;if(f="string"==typeof u?u:"one"===a&&"string"==typeof c?c:"one"===a&&"string"==typeof o?o:i&&"string"==typeof g?g:i||"string"!=typeof y?"string"==typeof c?c:"string"==typeof o?o:e:y,r){const t=this.config.extract.contextSeparator??"_";h=i?`${e}${t}${r}${p}ordinal${p}${a}`:`${e}${t}${r}${p}${a}`}else h=i?`${e}${p}ordinal${p}${a}`:`${e}${p}${a}`;this.pluginContext.addKey({key:h,ns:n,defaultValue:f,hasCount:!0,isOrdinal:i,explicitDefault:Boolean(l||"string"==typeof u||"string"==typeof y)})}}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const i=o||t(s,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof i?i:e})}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let r=e;for(;"MemberExpression"===r.type;){if("Identifier"!==r.property.type)return null;t.unshift(r.property.value),r=r.object}if("ThisExpression"===r.type)t.unshift("this");else{if("Identifier"!==r.type)return null;t.unshift(r.value)}return t.join(".")}return null}}export{n as CallExpressionHandler};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
function e(e,u,i,d){const f=new RegExp("\\bt\\s*\\(\\s*(['\"])([^'\"]+)\\1","g"),
|
|
1
|
+
function e(e,u,i,d){const f=new RegExp("\\bt\\s*\\(\\s*(['\"])([^'\"]+)\\1","g"),y=(i.extract.preservePatterns||[]).map(c),p=function(e){const t=[],n=new Set,s=/\/\/(.*)|\/\*([\s\S]*?)\*\//g;let a;for(;null!==(a=s.exec(e));){const e=(a[1]??a[2]).trim();e&&!n.has(e)&&(n.add(e),t.push(e))}return t}(e);for(const e of p){let c;for(;null!==(c=f.exec(e));){let f,p=c[2];if(!p||""===p.trim())continue;if(y.some(e=>e.test(p)))continue;const $=e.slice(c.index+c[0].length),x=s($),h=r($),g=o($),m=l($);let V=!1;const k=i.extract.pluralSeparator??"_";if(p.endsWith(`${k}ordinal`)){if(V=!0,p=p.slice(0,-(k.length+7)),!p||""===p.trim())continue;if(y.some(e=>e.test(p)))continue}const K=!0===m||V;f=a($);const w=i.extract.nsSeparator??":";if(!f&&w&&p.includes(w)){const e=p.split(w);if(f=e.shift(),p=e.join(w),!p||""===p.trim())continue;if(y.some(e=>e.test(p)))continue}if(!f&&d){const e=d("t");e?.defaultNs&&(f=e.defaultNs)}if(f||(f=i.extract.defaultNS),i.extract.disablePlurals)h?u.addKey({key:`${p}_${h}`,ns:f,defaultValue:x??p}):u.addKey({key:p,ns:f,defaultValue:x??p});else if(h&&g){n(p,x??p,f,h,u,i,K);!1!==i.extract?.generateBasePluralForms&&t(p,x??p,f,u,i,K)}else h?(u.addKey({key:p,ns:f,defaultValue:x??p}),u.addKey({key:`${p}_${h}`,ns:f,defaultValue:x??p})):g?t(p,x??p,f,u,i,K):u.addKey({key:p,ns:f,defaultValue:x??p})}}}function t(e,t,n,s,a,r=!1){try{const o=r?"ordinal":"cardinal",l=new Set;for(const e of a.locales)try{const t=new Intl.PluralRules(e,{type:o});t.resolvedOptions().pluralCategories.forEach(e=>l.add(e))}catch(e){const t=new Intl.PluralRules("en",{type:o});t.resolvedOptions().pluralCategories.forEach(e=>l.add(e))}const c=Array.from(l).sort(),u=a.extract.pluralSeparator??"_";if(1===c.length&&"other"===c[0])return void s.addKey({key:e,ns:n,defaultValue:t,hasCount:!0});for(const a of c){const o=r?`${e}${u}ordinal${u}${a}`:`${e}${u}${a}`;s.addKey({key:o,ns:n,defaultValue:t,hasCount:!0,isOrdinal:r})}}catch(a){s.addKey({key:e,ns:n,defaultValue:t})}}function n(e,t,n,s,a,r,o=!1){try{const l=o?"ordinal":"cardinal",c=new Set;for(const e of r.locales)try{const t=new Intl.PluralRules(e,{type:l});t.resolvedOptions().pluralCategories.forEach(e=>c.add(e))}catch(e){const t=new Intl.PluralRules(r.extract.primaryLanguage||"en",{type:l});t.resolvedOptions().pluralCategories.forEach(e=>c.add(e))}const u=Array.from(c).sort(),i=r.extract.pluralSeparator??"_";for(const r of u){const l=o?`${e}_${s}${i}ordinal${i}${r}`:`${e}_${s}${i}${r}`;a.addKey({key:l,ns:n,defaultValue:t,hasCount:!0,isOrdinal:o})}}catch(r){a.addKey({key:`${e}_${s}`,ns:n,defaultValue:t})}}function s(e){const t=/^\s*,\s*(['"])(.*?)\1/.exec(e);if(t)return t[2];const n=/^\s*,\s*\{[^}]*defaultValue\s*:\s*(['"])(.*?)\1/.exec(e);return n?n[2]:void 0}function a(e){const t=/^\s*,\s*\{[^}]*ns\s*:\s*(['"])(.*?)\1/.exec(e);if(t)return t[2]}function r(e){const t=/^\s*,\s*\{[^}]*context\s*:\s*(['"])(.*?)\1/.exec(e);if(t)return t[2]}function o(e){const t=/^\s*,\s*\{[^}]*count\s*:\s*(\d+)/.exec(e);if(t)return parseInt(t[1],10)}function l(e){const t=/^\s*,\s*\{[^}]*ordinal\s*:\s*(true|false)/.exec(e);if(t)return"true"===t[1]}function c(e){const t=`^${e.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(t)}export{e as extractKeysFromComments};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{extractFromTransComponent as e}from"./jsx-parser.js";import{getObjectPropValue as t}from"./ast-utils.js";class n{config;pluginContext;expressionResolver;constructor(e,t,n){this.config=e,this.pluginContext=t,this.expressionResolver=n}handleJSXElement(t,n){const s=this.getElementName(t);if(s&&(this.config.extract.transComponents||["Trans"]).includes(s)){const s=e(t,this.config),a=[];if(s){if(s.keyExpression){const e=this.expressionResolver.resolvePossibleKeyStringValues(s.keyExpression);a.push(...e)}else a.push(s.serializedChildren);let e;const{contextExpression:i,optionsNode:l,defaultValue:o,hasCount:r,isOrdinal:u,serializedChildren:f}=s;if(s.ns){const{ns:t}=s;e=a.map(e=>({key:e,ns:t,defaultValue:o||f,hasCount:r,isOrdinal:u}))}else{e=a.map(e=>{const t=this.config.extract.nsSeparator??":";let n;if(t&&e.includes(t)){let s;[n,...s]=e.split(t),e=s.join(t)}return{key:e,ns:n,defaultValue:o||f,hasCount:r,isOrdinal:u,explicitDefault:s.explicitDefault}});const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===i?.type&&"JSXExpressionContainer"===i.value?.type&&"Identifier"===i.value.expression.type){const t=n(i.value.expression.value);t?.defaultNs&&e.forEach(e=>{e.ns||(e.ns=t.defaultNs)})}}if(e.forEach(e=>{e.ns||(e.ns=this.config.extract.defaultNS)}),i&&r)if(this.config.extract.disablePlurals){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0)if("StringLiteral"===i.type)for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}else{e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n,a=this.expressionResolver.resolvePossibleContextStringValues(i),o=this.config.extract.contextSeparator??"_";if(a.length>0){e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l));for(const t of a)for(const n of e){const e=`${n.key}${o}${t}`;this.generatePluralKeysForTrans(e,n.defaultValue,n.ns,s,l,n.explicitDefault)}}else e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else if(i){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0){for(const s of t)for(const{key:t,ns:a,defaultValue:i}of e)this.pluginContext.addKey({key:`${t}${n}${s}`,ns:a,defaultValue:i});"StringLiteral"!==i.type&&e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else if(r)if(this.config.extract.disablePlurals)e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n;e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}}}generatePluralKeysForTrans(e,n,s,a,i,l){try{const o=a?"ordinal":"cardinal",r=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:o}).resolvedOptions().pluralCategories,u=this.config.extract.pluralSeparator??"_";let f,d;i&&(f=t(i,`defaultValue${u}other`),d=t(i,`defaultValue${u}ordinal${u}other`));for(const o of r){const r=i?t(i,a?`defaultValue${u}ordinal${u}${o}`:`defaultValue${u}${o}`):void 0;let p;p="string"==typeof r?r:"one"===o&&"string"==typeof n?n:a&&"string"==typeof d?d:a||"string"!=typeof f?"string"==typeof n?n:e:f;const c=a?`${e}${u}ordinal${u}${o}`:`${e}${u}${o}`;this.pluginContext.addKey({key:c,ns:s,defaultValue:p,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof r||"string"==typeof f)})}}catch(t){this.pluginContext.addKey({key:e,ns:s,defaultValue:n})}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}}export{n as JSXHandler};
|
|
1
|
+
import{extractFromTransComponent as e}from"./jsx-parser.js";import{getObjectPropValue as t}from"./ast-utils.js";class n{config;pluginContext;expressionResolver;constructor(e,t,n){this.config=e,this.pluginContext=t,this.expressionResolver=n}handleJSXElement(t,n){const s=this.getElementName(t);if(s&&(this.config.extract.transComponents||["Trans"]).includes(s)){const s=e(t,this.config),a=[];if(s){if(s.keyExpression){const e=this.expressionResolver.resolvePossibleKeyStringValues(s.keyExpression);a.push(...e)}else a.push(s.serializedChildren);let e;const{contextExpression:i,optionsNode:l,defaultValue:o,hasCount:r,isOrdinal:u,serializedChildren:f}=s;if(s.ns){const{ns:t}=s;e=a.map(e=>({key:e,ns:t,defaultValue:o||f,hasCount:r,isOrdinal:u}))}else{e=a.map(e=>{const t=this.config.extract.nsSeparator??":";let n;if(t&&e.includes(t)){let s;[n,...s]=e.split(t),e=s.join(t)}return{key:e,ns:n,defaultValue:o||f,hasCount:r,isOrdinal:u,explicitDefault:s.explicitDefault}});const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===i?.type&&"JSXExpressionContainer"===i.value?.type&&"Identifier"===i.value.expression.type){const t=n(i.value.expression.value);t?.defaultNs&&e.forEach(e=>{e.ns||(e.ns=t.defaultNs)})}}if(e.forEach(e=>{e.ns||(e.ns=this.config.extract.defaultNS)}),i&&r)if(this.config.extract.disablePlurals){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0)if("StringLiteral"===i.type)for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}else{e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});for(const s of t)for(const t of e){const e=`${t.key}${n}${s}`;this.pluginContext.addKey({key:e,ns:t.ns,defaultValue:t.defaultValue})}}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n,a=this.expressionResolver.resolvePossibleContextStringValues(i),o=this.config.extract.contextSeparator??"_";if(a.length>0){e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l));for(const t of a)for(const n of e){const e=`${n.key}${o}${t}`;this.generatePluralKeysForTrans(e,n.defaultValue,n.ns,s,l,n.explicitDefault)}}else e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else if(i){const t=this.expressionResolver.resolvePossibleContextStringValues(i),n=this.config.extract.contextSeparator??"_";if(t.length>0){for(const s of t)for(const{key:t,ns:a,defaultValue:i}of e)this.pluginContext.addKey({key:`${t}${n}${s}`,ns:a,defaultValue:i});"StringLiteral"!==i.type&&e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}else if(r)if(this.config.extract.disablePlurals)e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})});else{const n=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),s=!!n;e.forEach(e=>this.generatePluralKeysForTrans(e.key,e.defaultValue,e.ns,s,l,e.explicitDefault))}else e.forEach(e=>{this.pluginContext.addKey({key:e.key,ns:e.ns,defaultValue:e.defaultValue})})}}}generatePluralKeysForTrans(e,n,s,a,i,l){try{const o=a?"ordinal":"cardinal",r=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:o}).resolvedOptions().pluralCategories,u=this.config.extract.pluralSeparator??"_";let f,d;if(i&&(f=t(i,`defaultValue${u}other`),d=t(i,`defaultValue${u}ordinal${u}other`)),1===r.length&&"other"===r[0]){const o=i?t(i,`defaultValue${u}other`):void 0,r="string"==typeof o?o:"string"==typeof n?n:e;return void this.pluginContext.addKey({key:e,ns:s,defaultValue:r,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof o||"string"==typeof f)})}for(const o of r){const r=i?t(i,a?`defaultValue${u}ordinal${u}${o}`:`defaultValue${u}${o}`):void 0;let p;p="string"==typeof r?r:"one"===o&&"string"==typeof n?n:a&&"string"==typeof d?d:a||"string"!=typeof f?"string"==typeof n?n:e:f;const c=a?`${e}${u}ordinal${u}${o}`:`${e}${u}${o}`;this.pluginContext.addKey({key:c,ns:s,defaultValue:p,hasCount:!0,isOrdinal:a,explicitDefault:Boolean(l||"string"==typeof r||"string"==typeof f)})}}catch(t){this.pluginContext.addKey({key:e,ns:s,defaultValue:n})}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}}export{n as JSXHandler};
|
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/dist/esm/status.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import o from"chalk";import e from"ora";import{resolve as a}from"node:path";import{findKeys as t}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(o=>o!==r?.extract?.primaryLanguage);const i=e("Analyzing project localization status...\n").start();try{const e=await async function(o){o.extract.primaryLanguage||=o.locales[0]||"en",o.extract.secondaryLanguages||=o.locales.filter(e=>e!==o?.extract?.primaryLanguage);const{allKeys:e}=await t(o),{secondaryLanguages:r,keySeparator:c=".",defaultNS:i="translation",mergeNamespaces:y=!1,pluralSeparator:u="_"}=o.extract,d=new Map;for(const o of e.values()){const e=o.ns||i||"translation";d.has(e)||d.set(e,[]),d.get(e).push(o)}const g={totalBaseKeys:e.size,keysByNs:d,locales:new Map};for(const e of r){let t=0,r=0;const i=new Map,f=y?await n(a(process.cwd(),l(o.extract.output,e)))||{}:null;for(const[g,p]of d.entries()){const d=y?f?.[g]||{}:await n(a(process.cwd(),l(o.extract.output,e,g)))||{};let m=0,$=0;const w=[];for(const{key:o,hasCount:a,isOrdinal:t}of p)if(a){const a=t?"ordinal":"cardinal",n=new Intl.PluralRules(e,{type:a}).resolvedOptions().pluralCategories;for(const e of n){$++;const a=t?`${o}${u}ordinal${u}${e}`:`${o}${u}${e}`,n=!!s(d,a,c??".");n&&m++,w.push({key:a,isTranslated:n})}}else{$++;const e=!!s(d,o,c??".");e&&m++,w.push({key:o,isTranslated:e})}i.set(g,{totalKeys:$,translatedKeys:m,keyDetails:w}),t+=m,r+=$}g.locales.set(e,{totalKeys:r,totalTranslated:t,namespaces:i})}return g}(r);i.succeed("Analysis complete."),await async function(e,a,t){t.detail?await async function(e,a,t,s){if(t===a.extract.primaryLanguage)return void console.log(o.yellow(`Locale "${t}" is the primary language. All keys are considered present.`));if(!a.locales.includes(t))return void console.error(o.red(`Error: Locale "${t}" is not defined in your configuration.`));const n=e.locales.get(t);if(!n)return void console.error(o.red(`Error: Locale "${t}" is not a valid secondary language.`));console.log(o.bold(`\nKey Status for "${o.cyan(t)}":`));const l=Array.from(e.keysByNs.values()).flat().length;y("Overall",n.totalTranslated,n.totalKeys);const r=s?[s]:Array.from(n.namespaces.keys()).sort();for(const e of r){const a=n.namespaces.get(e);a&&(console.log(o.cyan.bold(`\nNamespace: ${e}`)),y("Namespace Progress",a.translatedKeys,a.totalKeys),a.keyDetails.forEach(({key:e,isTranslated:a})=>{const t=a?o.green("✓"):o.red("✗");console.log(` ${t} ${e}`)}))}const c=l-n.totalTranslated;c>0?console.log(o.yellow.bold(`\nSummary: Found ${c} missing translations for "${t}".`)):console.log(o.green.bold(`\nSummary: 🎉 All keys are translated for "${t}".`));await d()}(e,a,t.detail,t.namespace):t.namespace?await async function(e,a,t){const s=e.keysByNs.get(t);if(!s)return void console.error(o.red(`Error: Namespace "${t}" was not found in your source code.`));console.log(o.cyan.bold(`\nStatus for Namespace: "${t}"`)),console.log("------------------------");for(const[o,a]of e.locales.entries()){const e=a.namespaces.get(t);if(e){const a=e.totalKeys>0?Math.round(e.translatedKeys/e.totalKeys*100):100,t=u(a);console.log(`- ${o}: ${t} ${a}% (${e.translatedKeys}/${e.totalKeys} keys)`)}}await d()}(e,0,t.namespace):await async function(e,a){const{primaryLanguage:t}=a.extract;console.log(o.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${o.bold(e.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${o.bold(e.keysByNs.size)}`),console.log(`🌍 Locales: ${o.bold(a.locales.join(", "))}`),console.log(`✅ Primary Language: ${o.bold(t)}`),console.log("\nTranslation Progress:");for(const[o,a]of e.locales.entries()){const e=a.totalKeys>0?Math.round(a.totalTranslated/a.totalKeys*100):100,t=u(e);console.log(`- ${o}: ${t} ${e}% (${a.totalTranslated}/${a.totalKeys} keys)`)}await d()}(e,a)}(e,r,c)}catch(o){i.fail("Failed to generate status report."),console.error(o)}}function y(e,a,t){const s=t>0?Math.round(a/t*100):100,n=u(s);console.log(`${o.bold(e)}: ${n} ${s}% (${a}/${t})`)}function u(e){const a=Math.floor(e/100*20),t=20-a;return`[${o.green("".padStart(a,"■"))}${"".padStart(t,"□")}]`}async function d(){if(await r("status"))return console.log(o.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 ${o.cyan("npx i18next-cli locize-migrate")} to get started.`),c("status")}export{i as runStatus};
|
|
1
|
+
import o from"chalk";import e from"ora";import{resolve as a}from"node:path";import{findKeys as t}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(o=>o!==r?.extract?.primaryLanguage);const i=e("Analyzing project localization status...\n").start();try{const e=await async function(o){o.extract.primaryLanguage||=o.locales[0]||"en",o.extract.secondaryLanguages||=o.locales.filter(e=>e!==o?.extract?.primaryLanguage);const{allKeys:e}=await t(o),{secondaryLanguages:r,keySeparator:c=".",defaultNS:i="translation",mergeNamespaces:y=!1,pluralSeparator:u="_"}=o.extract,d=new Map;for(const o of e.values()){const e=o.ns||i||"translation";d.has(e)||d.set(e,[]),d.get(e).push(o)}const g={totalBaseKeys:e.size,keysByNs:d,locales:new Map};for(const e of r){let t=0,r=0;const i=new Map,f=y?await n(a(process.cwd(),l(o.extract.output,e)))||{}:null;for(const[g,p]of d.entries()){const d=y?f?.[g]||{}:await n(a(process.cwd(),l(o.extract.output,e,g)))||{};let m=0,$=0;const w=[];for(const{key:o,hasCount:a,isOrdinal:t,isExpandedPlural:n}of p)if(a)if(n){$++;const e=!!s(d,o,c??".");e&&m++,w.push({key:o,isTranslated:e})}else{const a=t?"ordinal":"cardinal",n=new Intl.PluralRules(e,{type:a}).resolvedOptions().pluralCategories;for(const e of n){$++;const a=t?`${o}${u}ordinal${u}${e}`:`${o}${u}${e}`,n=!!s(d,a,c??".");n&&m++,w.push({key:a,isTranslated:n})}}else{$++;const e=!!s(d,o,c??".");e&&m++,w.push({key:o,isTranslated:e})}i.set(g,{totalKeys:$,translatedKeys:m,keyDetails:w}),t+=m,r+=$}g.locales.set(e,{totalKeys:r,totalTranslated:t,namespaces:i})}return g}(r);i.succeed("Analysis complete."),await async function(e,a,t){t.detail?await async function(e,a,t,s){if(t===a.extract.primaryLanguage)return void console.log(o.yellow(`Locale "${t}" is the primary language. All keys are considered present.`));if(!a.locales.includes(t))return void console.error(o.red(`Error: Locale "${t}" is not defined in your configuration.`));const n=e.locales.get(t);if(!n)return void console.error(o.red(`Error: Locale "${t}" is not a valid secondary language.`));console.log(o.bold(`\nKey Status for "${o.cyan(t)}":`));const l=Array.from(e.keysByNs.values()).flat().length;y("Overall",n.totalTranslated,n.totalKeys);const r=s?[s]:Array.from(n.namespaces.keys()).sort();for(const e of r){const a=n.namespaces.get(e);a&&(console.log(o.cyan.bold(`\nNamespace: ${e}`)),y("Namespace Progress",a.translatedKeys,a.totalKeys),a.keyDetails.forEach(({key:e,isTranslated:a})=>{const t=a?o.green("✓"):o.red("✗");console.log(` ${t} ${e}`)}))}const c=l-n.totalTranslated;c>0?console.log(o.yellow.bold(`\nSummary: Found ${c} missing translations for "${t}".`)):console.log(o.green.bold(`\nSummary: 🎉 All keys are translated for "${t}".`));await d()}(e,a,t.detail,t.namespace):t.namespace?await async function(e,a,t){const s=e.keysByNs.get(t);if(!s)return void console.error(o.red(`Error: Namespace "${t}" was not found in your source code.`));console.log(o.cyan.bold(`\nStatus for Namespace: "${t}"`)),console.log("------------------------");for(const[o,a]of e.locales.entries()){const e=a.namespaces.get(t);if(e){const a=e.totalKeys>0?Math.round(e.translatedKeys/e.totalKeys*100):100,t=u(a);console.log(`- ${o}: ${t} ${a}% (${e.translatedKeys}/${e.totalKeys} keys)`)}}await d()}(e,0,t.namespace):await async function(e,a){const{primaryLanguage:t}=a.extract;console.log(o.cyan.bold("\ni18next Project Status")),console.log("------------------------"),console.log(`🔑 Keys Found: ${o.bold(e.totalBaseKeys)}`),console.log(`📚 Namespaces Found: ${o.bold(e.keysByNs.size)}`),console.log(`🌍 Locales: ${o.bold(a.locales.join(", "))}`),console.log(`✅ Primary Language: ${o.bold(t)}`),console.log("\nTranslation Progress:");for(const[o,a]of e.locales.entries()){const e=a.totalKeys>0?Math.round(a.totalTranslated/a.totalKeys*100):100,t=u(e);console.log(`- ${o}: ${t} ${e}% (${a.totalTranslated}/${a.totalKeys} keys)`)}await d()}(e,a)}(e,r,c)}catch(o){i.fail("Failed to generate status report."),console.error(o)}}function y(e,a,t){const s=t>0?Math.round(a/t*100):100,n=u(s);console.log(`${o.bold(e)}: ${n} ${s}% (${a}/${t})`)}function u(e){const a=Math.floor(e/100*20),t=20-a;return`[${o.green("".padStart(a,"■"))}${"".padStart(t,"□")}]`}async function d(){if(await r("status"))return console.log(o.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 ${o.cyan("npx i18next-cli locize-migrate")} to get started.`),c("status")}export{i as runStatus};
|