i18next-cli 1.3.0 → 1.5.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 CHANGED
@@ -5,6 +5,24 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.5.0](https://github.com/i18next/i18next-cli/compare/v1.4.0...v1.5.0) - 2025-10-02
9
+
10
+ ### Added
11
+ - **Extractor:** Added wildcard support to the `extract.functions` option. Patterns starting with `*.` (e.g., `'*.t'`) will now match any function call ending with that suffix, making configuration easier for projects with multiple translation function instances.
12
+
13
+ ### Fixed
14
+ - **Extractor:** Fixed a bug that caused incorrect key sorting when a mix of flat and nested keys were present (e.g., `person` and `person-foo`). Sorting is now correctly applied to the top-level keys of the final generated object. [#27](https://github.com/i18next/i18next-cli/issues/27)
15
+ - **Extractor:** Fixed a bug where refactoring a nested key into its parent (e.g., changing `t('person.name')` to `t('person')`) would not correctly remove the old nested object from the translation file. [#28](https://github.com/i18next/i18next-cli/issues/28)
16
+
17
+ ## [1.4.0](https://github.com/i18next/i18next-cli/compare/v1.3.0...v1.4.0) - 2025-10-02
18
+
19
+ ### Added
20
+ - **Plugin System:** Introduced a new `afterSync` plugin hook. This hook runs after the extractor has finished processing and writing files, providing plugins with the final results. This is ideal for post-processing tasks, such as generating a report of newly added keys.
21
+
22
+ ### Fixed
23
+ - **Extractor:** Fixed a bug where translation keys inside class methods were not being extracted, particularly when using member expressions based on `this` (e.g., `this._i18n.t('key')`). [#25](https://github.com/i18next/i18next-cli/issues/25)
24
+ - **Extractor:** Fixed a critical bug where `removeUnusedKeys` would fail to remove keys from a file if it was the last key remaining. The extractor now correctly processes and empties files and namespaces when all keys have been removed from the source code. [#26](https://github.com/i18next/i18next-cli/issues/26)
25
+
8
26
  ## [1.3.0](https://github.com/i18next/i18next-cli/compare/v1.2.1...v1.3.0) - 2025-10-02
9
27
 
10
28
  ### Added
package/README.md CHANGED
@@ -305,8 +305,8 @@ export default defineConfig({
305
305
  // Note: `output` path must not contain `{{namespace}}` when this is true.
306
306
  mergeNamespaces: false,
307
307
 
308
- // Translation functions to detect
309
- functions: ['t', 'i18n.t', 'i18next.t'],
308
+ // Translation functions to detect. Supports wildcards (e.g., '*.t').
309
+ functions: ['t', '*.t', 'i18next.t'],
310
310
 
311
311
  // React components to analyze
312
312
  transComponents: ['Trans', 'Translation'],
@@ -386,37 +386,30 @@ export default defineConfig({
386
386
 
387
387
  ### Plugin System
388
388
 
389
- Create custom plugins to extend extraction capabilities. The plugin system is powerful enough to support non-JavaScript files (e.g., HTML, Handlebars) by using the `onEnd` hook with custom parsers.
389
+ Create custom plugins to extend the capabilities of `i18next-cli`. The plugin system provides several hooks that allow you to tap into different stages of the extraction process.
390
+
391
+ **Available Hooks:**
392
+
393
+ - `setup`: Runs once when the CLI is initialized. Use it for any setup tasks.
394
+ - `onLoad`: Runs for each file *before* it is parsed. You can use this to transform code (e.g., transpile a custom language to JavaScript).
395
+ - `onVisitNode`: Runs for every node in the Abstract Syntax Tree (AST) of a parsed JavaScript/TypeScript file. This is useful for finding custom translation patterns in your code.
396
+ - `onEnd`: Runs after all JS/TS files have been parsed but *before* the final keys are compared with existing translation files. This is the ideal hook for parsing non-JavaScript files (like `.html`, `.vue`, or `.svelte`) and adding their keys to the collection.
397
+ - `afterSync`: Runs after the extractor has compared the found keys with your translation files and generated the final results. This is perfect for post-processing tasks, like generating a report of newly added keys.
398
+
399
+ **Example Plugin (`my-custom-plugin.mjs`):**
390
400
 
391
401
  ```typescript
392
- import { defineConfig, Plugin } from 'i18next-cli';
402
+ import { glob } from 'glob';
403
+ import { readFile, writeFile } from 'node:fs/promises';
393
404
 
394
- const myCustomPlugin = (): Plugin => ({
405
+ export const myCustomPlugin = () => ({
395
406
  name: 'my-custom-plugin',
396
407
 
397
- async setup() {
398
- // Initialize plugin
399
- },
400
-
401
- async onLoad(code: string, file: string) {
402
- // Transform code before parsing
403
- return code;
404
- },
405
-
406
- onVisitNode(node: any, context: PluginContext) {
407
- // Custom AST node processing
408
- if (node.type === 'CallExpression') {
409
- // Extract custom translation patterns
410
- context.addKey({
411
- key: 'custom.key',
412
- defaultValue: 'Custom Value',
413
- ns: 'custom'
414
- });
415
- }
416
- },
417
-
418
- async onEnd(allKeys: Map<string, ExtractedKey>) {
419
- // Process all extracted keys or add additional keys from non-JS files
408
+ /**
409
+ * Runs after the core extractor has finished but before comparison.
410
+ * Ideal for adding keys from non-JS/TS files.
411
+ */
412
+ async onEnd(allKeys) {
420
413
  // Example: Parse HTML files for data-i18n attributes
421
414
  const htmlFiles = await glob('src/**/*.html');
422
415
  for (const file of htmlFiles) {
@@ -424,16 +417,62 @@ const myCustomPlugin = (): Plugin => ({
424
417
  const matches = content.match(/data-i18n="([^"]+)"/g) || [];
425
418
  for (const match of matches) {
426
419
  const key = match.replace(/data-i18n="([^"]+)"/, '$1');
427
- allKeys.set(`translation:${key}`, { key, ns: 'translation' });
420
+ // Add the found key to the collection
421
+ allKeys.set(`translation:${key}`, { key, ns: 'translation', defaultValue: key });
422
+ }
423
+ }
424
+ },
425
+
426
+ /**
427
+ * Runs after the extractor has generated the final translation results.
428
+ * Ideal for reporting or post-processing.
429
+ */
430
+ async afterSync(results, config) {
431
+ const primaryLanguage = config.extract.primaryLanguage || config.locales[0];
432
+ const newKeys = [];
433
+
434
+ for (const result of results) {
435
+ // Find the result for the primary language
436
+ if (!result.path.includes(`/${primaryLanguage}/`)) continue;
437
+
438
+ const newKeysFlat = Object.keys(result.newTranslations);
439
+ const existingKeysFlat = Object.keys(result.existingTranslations);
440
+
441
+ // Find keys that are in the new file but not the old one
442
+ for (const key of newKeysFlat) {
443
+ if (!existingKeysFlat.includes(key)) {
444
+ newKeys.push({
445
+ key: key,
446
+ defaultValue: result.newTranslations[key],
447
+ });
448
+ }
428
449
  }
429
450
  }
451
+
452
+ if (newKeys.length > 0) {
453
+ console.log(`[My Plugin] Found ${newKeys.length} new keys!`);
454
+ // Example: Write a report for your copywriter
455
+ await writeFile('new-keys-report.json', JSON.stringify(newKeys, null, 2));
456
+ }
430
457
  }
431
458
  });
459
+ ```
460
+
461
+ **Configuration (`i18next.config.ts`):**
462
+
463
+ ```typescript
464
+ import { defineConfig } from 'i18next-cli';
465
+ import { myCustomPlugin } from './my-custom-plugin.mjs';
432
466
 
433
467
  export default defineConfig({
434
468
  locales: ['en', 'de'],
435
- plugins: [myCustomPlugin()],
436
- // ... other config
469
+ extract: {
470
+ input: ['src/**/*.{ts,tsx}'],
471
+ output: 'locales/{{language}}/{{namespace}}.json',
472
+ },
473
+ plugins: [
474
+ myCustomPlugin(),
475
+ ],
437
476
  });
438
477
  ```
439
478
 
package/dist/cjs/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e=require("commander"),t=require("chokidar"),n=require("glob"),o=require("chalk"),i=require("./config.js"),a=require("./heuristic-config.js"),r=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var c=require("./types-generator.js"),s=require("./syncer.js"),l=require("./migrator.js"),u=require("./init.js"),d=require("./linter.js"),g=require("./status.js"),p=require("./locize.js");const f=new e.Command;f.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.3.0"),f.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").action(async e=>{const a=await i.ensureConfig(),c=async()=>{const t=await r.runExtractor(a,{isWatchMode:e.watch,isDryRun:e.dryRun});e.ci&&t&&(console.error(o.red.bold("\n[CI Mode] Error: Translation files were updated. Please commit the changes.")),console.log(o.yellow("💡 Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started")),console.log(` Learn more: ${o.cyan("npx i18next-cli locize-sync")}`),process.exit(1))};if(await c(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(a.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}),f.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,t)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const o=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async()=>{await l.runMigrator()}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
2
+ "use strict";var e=require("commander"),t=require("chokidar"),n=require("glob"),o=require("chalk"),i=require("./config.js"),a=require("./heuristic-config.js"),r=require("./extractor/core/extractor.js");require("node:path"),require("node:fs/promises"),require("jiti");var c=require("./types-generator.js"),s=require("./syncer.js"),l=require("./migrator.js"),u=require("./init.js"),d=require("./linter.js"),g=require("./status.js"),p=require("./locize.js");const f=new e.Command;f.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.5.0"),f.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").action(async e=>{const a=await i.ensureConfig(),c=async()=>{const t=await r.runExtractor(a,{isWatchMode:e.watch,isDryRun:e.dryRun});e.ci&&t&&(console.error(o.red.bold("\n[CI Mode] Error: Translation files were updated. Please commit the changes.")),console.log(o.yellow("💡 Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started")),console.log(` Learn more: ${o.cyan("npx i18next-cli locize-sync")}`),process.exit(1))};if(await c(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(a.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),c()})}}),f.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,t)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const o=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async()=>{await l.runMigrator()}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
@@ -1 +1 @@
1
- "use strict";var e=require("ora"),t=require("chalk"),r=require("@swc/core"),a=require("node:fs/promises"),o=require("node:path"),n=require("./key-finder.js"),s=require("./translation-manager.js"),i=require("../../utils/validation.js"),c=require("../plugin-manager.js"),l=require("../parsers/comment-parser.js"),u=require("../../utils/logger.js"),g=require("../../utils/file-utils.js");let f=!1;function y(e,t,r,a=new u.ConsoleLogger){if(e&&"object"==typeof e){for(const o of t)try{o.onVisitNode?.(e,r)}catch(e){a.warn(`Plugin ${o.name} onVisitNode failed:`,e)}for(const o of Object.keys(e)){const n=e[o];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&y(e,t,r,a);else n&&"object"==typeof n&&y(n,t,r,a)}}}exports.extract=async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage),e.extract.functions||=["t"],e.extract.transComponents||=["Trans"];const{allKeys:t,objectKeys:r}=await n.findKeys(e);return s.getTranslations(t,r,e)},exports.processFile=async function(e,t,o,n,s=new u.ConsoleLogger){try{let i=await a.readFile(e,"utf-8");for(const r of t.plugins||[])i=await(r.onLoad?.(i,e))??i;const u=await r.parse(i,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0}),g=c.createPluginContext(o);l.extractKeysFromComments(i,g,t),n.visit(u),(t.plugins||[]).length>0&&y(u,t.plugins||[],g,s)}catch(t){throw new i.ExtractorError("Failed to process file",e,t)}},exports.runExtractor=async function(r,{isWatchMode:c=!1,isDryRun:l=!1}={},y=new u.ConsoleLogger){r.extract.primaryLanguage||=r.locales[0]||"en",r.extract.secondaryLanguages||=r.locales.filter(e=>e!==r?.extract?.primaryLanguage),i.validateExtractorConfig(r);const d=e("Running i18next key extractor...\n").start();try{const{allKeys:e,objectKeys:i}=await n.findKeys(r,y);d.text=`Found ${e.size} unique keys. Updating translation files...`;const u=await s.getTranslations(e,i,r);let p=!1;for(const e of u)if(e.updated&&(p=!0,!l)){const n=g.serializeTranslationFile(e.newTranslations,r.extract.outputFormat,r.extract.indentation);await a.mkdir(o.dirname(e.path),{recursive:!0}),await a.writeFile(e.path,n),y.info(t.green(`Updated: ${e.path}`))}return d.succeed(t.bold("Extraction complete!")),p&&function(e=!1){if(e&&f)return;console.log(t.yellow.bold("\n💡 Tip: Tired of running the extractor manually?")),console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,'),console.log(" where keys are created and translated automatically as you code."),console.log(` Learn more: ${t.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${t.cyan("https://youtu.be/joPsZghT3wM")}`),e&&(f=!0)}(c),p}catch(e){throw d.fail(t.red("Extraction failed.")),e}};
1
+ "use strict";var e=require("ora"),t=require("chalk"),a=require("@swc/core"),r=require("node:fs/promises"),o=require("node:path"),n=require("./key-finder.js"),s=require("./translation-manager.js"),i=require("../../utils/validation.js"),c=require("../plugin-manager.js"),l=require("../parsers/comment-parser.js"),u=require("../../utils/logger.js"),g=require("../../utils/file-utils.js");let f=!1;function p(e,t,a,r=new u.ConsoleLogger){if(e&&"object"==typeof e){for(const o of t)try{o.onVisitNode?.(e,a)}catch(e){r.warn(`Plugin ${o.name} onVisitNode failed:`,e)}for(const o of Object.keys(e)){const n=e[o];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&p(e,t,a,r);else n&&"object"==typeof n&&p(n,t,a,r)}}}exports.extract=async function(e){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage),e.extract.functions||=["t"],e.extract.transComponents||=["Trans"];const{allKeys:t,objectKeys:a}=await n.findKeys(e);return s.getTranslations(t,a,e)},exports.processFile=async function(e,t,o,n,s=new u.ConsoleLogger){try{let i=await r.readFile(e,"utf-8");for(const a of t.plugins||[])i=await(a.onLoad?.(i,e))??i;const u=await a.parse(i,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0}),g=c.createPluginContext(o);l.extractKeysFromComments(i,g,t),n.visit(u),(t.plugins||[]).length>0&&p(u,t.plugins||[],g,s)}catch(t){throw new i.ExtractorError("Failed to process file",e,t)}},exports.runExtractor=async function(a,{isWatchMode:c=!1,isDryRun:l=!1}={},p=new u.ConsoleLogger){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(e=>e!==a?.extract?.primaryLanguage),a.extract.functions||=["t"],a.extract.transComponents||=["Trans"],i.validateExtractorConfig(a);const y=e("Running i18next key extractor...\n").start();try{const{allKeys:e,objectKeys:i}=await n.findKeys(a,p);y.text=`Found ${e.size} unique keys. Updating translation files...`;const u=await s.getTranslations(e,i,a);let d=!1;for(const e of u)if(e.updated&&(d=!0,!l)){const n=g.serializeTranslationFile(e.newTranslations,a.extract.outputFormat,a.extract.indentation);await r.mkdir(o.dirname(e.path),{recursive:!0}),await r.writeFile(e.path,n),p.info(t.green(`Updated: ${e.path}`))}if((a.plugins||[]).length>0){y.text="Running post-extraction plugins...";for(const e of a.plugins||[])await(e.afterSync?.(u,a))}return y.succeed(t.bold("Extraction complete!")),d&&function(e=!1){if(e&&f)return;console.log(t.yellow.bold("\n💡 Tip: Tired of running the extractor manually?")),console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,'),console.log(" where keys are created and translated automatically as you code."),console.log(` Learn more: ${t.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${t.cyan("https://youtu.be/joPsZghT3wM")}`),e&&(f=!0)}(c),d}catch(e){throw y.fail(t.red("Extraction failed.")),e}};
@@ -1 +1 @@
1
- "use strict";var t=require("node:path"),e=require("../../utils/nested-object.js"),s=require("../../utils/file-utils.js");function a(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}exports.getTranslations=async function(r,n,o){o.extract.primaryLanguage||=o.locales[0]||"en",o.extract.secondaryLanguages||=o.locales.filter(t=>t!==o?.extract?.primaryLanguage);const c=o.extract.primaryLanguage,l=o.extract.defaultNS??"translation",u=o.extract.keySeparator??".",i=[...o.extract.preservePatterns||[]],p=o.extract.mergeNamespaces??!1,f=o.extract.indentation??2,g=o.extract.removeUnusedKeys??!0;for(const t of n)i.push(`${t}.*`);const d=i.map(a),x=new Map;for(const t of r.values()){const e=t.ns||l;x.has(e)||x.set(e,[]),x.get(e).push(t)}const y=[];for(const a of o.locales){const r=p?await s.loadTranslationFile(t.resolve(process.cwd(),s.getOutputPath(o.extract.output,a)))||{}:null,n={};for(const[l,i]of x.entries()){const x=s.getOutputPath(o.extract.output,a,p?void 0:l),N=t.resolve(process.cwd(),x),h=p?r?.[l]||{}:await s.loadTranslationFile(N)||{},m=g?{}:JSON.parse(JSON.stringify(h)),w=e.getNestedKeys(h,u);for(const t of w)if(d.some(e=>e.test(t))){const s=e.getNestedValue(h,t,u);e.setNestedValue(m,t,s,u)}const O=!1===o.extract.sort?i:[...i].sort("function"==typeof o.extract.sort?o.extract.sort:(t,e)=>t.key.localeCompare(e.key));for(const{key:t,defaultValue:s}of O){const r=e.getNestedValue(h,t,u)??(a===c?s:o.extract.defaultValue??"");e.setNestedValue(m,t,r,u)}if(p)n[l]=m;else{const t=JSON.stringify(h,null,f),e=JSON.stringify(m,null,f);y.push({path:N,updated:e!==t,newTranslations:m,existingTranslations:h})}}if(p){const e=s.getOutputPath(o.extract.output,a),c=t.resolve(process.cwd(),e),l=JSON.stringify(r,null,f),u=JSON.stringify(n,null,f);y.push({path:c,updated:u!==l,newTranslations:n,existingTranslations:r||{}})}}return y};
1
+ "use strict";var t=require("node:path"),e=require("glob"),s=require("../../utils/nested-object.js"),a=require("../../utils/file-utils.js");function n(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}function o(t,e,a,n,o,r){const{keySeparator:c=".",sort:i=!0,removeUnusedKeys:u=!0,primaryLanguage:l,defaultValue:f=""}=a.extract;let g=u?{}:JSON.parse(JSON.stringify(e));const p=s.getNestedKeys(e,c??".");for(const t of p)if(o.some(e=>e.test(t))){const a=s.getNestedValue(e,t,c??".");s.setNestedValue(g,t,a,c??".")}for(const{key:a,defaultValue:o}of t){const i=s.getNestedValue(e,a,c??"."),u=!t.some(t=>t.key.startsWith(`${a}${c}`)&&t.key!==a),p="object"==typeof i&&null!==i&&u&&!r.has(a),y=void 0===i||p?n===l?o:f:i;s.setNestedValue(g,a,y,c??".")}if(!1!==i){const e={},s=Object.keys(g),a=new Map;for(const e of t){const t=!1===c?e.key:e.key.split(c)[0];a.has(t)||a.set(t,e)}s.sort((t,e)=>{if("function"==typeof i){const s=a.get(t),n=a.get(e);if(s&&n)return i(s,n)}return t.localeCompare(e)});for(const t of s)e[t]=g[t];g=e}return g}exports.getTranslations=async function(s,r,c){c.extract.primaryLanguage||=c.locales[0]||"en",c.extract.secondaryLanguages||=c.locales.filter(t=>t!==c?.extract?.primaryLanguage);const i=c.extract.defaultNS??"translation",u=[...c.extract.preservePatterns||[]],l=c.extract.indentation??2;for(const t of r)u.push(`${t}.*`);const f=u.map(n),g=new Map;for(const t of s.values()){const e=t.ns||i;g.has(e)||g.set(e,[]),g.get(e).push(t)}const p=[],y=Array.isArray(c.extract.ignore)?c.extract.ignore:c.extract.ignore?[c.extract.ignore]:[];for(const s of c.locales){if(c.extract.mergeNamespaces||!c.extract.output.includes("{{namespace}}")){const e={},n=a.getOutputPath(c.extract.output,s),i=t.resolve(process.cwd(),n),u=await a.loadTranslationFile(i)||{},y=new Set([...g.keys(),...Object.keys(u)]);for(const t of y){const a=g.get(t)||[],n=u[t]||{};e[t]=o(a,n,c,s,f,r)}const d=JSON.stringify(u,null,l),x=JSON.stringify(e,null,l);p.push({path:i,updated:x!==d,newTranslations:e,existingTranslations:u})}else{const n=new Set(g.keys()),i=a.getOutputPath(c.extract.output,s,"*"),u=await e.glob(i,{ignore:y});for(const e of u)n.add(t.basename(e,t.extname(e)));for(const e of n){const n=g.get(e)||[],i=a.getOutputPath(c.extract.output,s,e),u=t.resolve(process.cwd(),i),y=await a.loadTranslationFile(u)||{},d=o(n,y,c,s,f,r),x=JSON.stringify(y,null,l),h=JSON.stringify(d,null,l);p.push({path:u,updated:h!==x,newTranslations:d,existingTranslations:y})}}}return p};
@@ -1 +1 @@
1
- "use strict";var e=require("./jsx-parser.js"),t=require("./ast-utils.js");exports.ASTVisitors=class{pluginContext;config;logger;scopeStack=[];objectKeys=new Set;constructor(e,t,n){this.pluginContext=t,this.config=e,this.logger=n}visit(e){this.enterScope(),this.walk(e),this.exitScope()}walk(e){if(!e)return;let t=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.enterScope(),t=!0),e.type){case"VariableDeclarator":this.handleVariableDeclarator(e);break;case"CallExpression":this.handleCallExpression(e);break;case"JSXElement":this.handleJSXElement(e)}for(const t in e){if("span"===t)continue;const n=e[t];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&this.walk(e);else n&&"object"==typeof n&&this.walk(n)}t&&this.exitScope()}enterScope(){this.scopeStack.push(new Map)}exitScope(){this.scopeStack.pop()}setVarInScope(e,t){this.scopeStack.length>0&&this.scopeStack[this.scopeStack.length-1].set(e,t)}getVarFromScope(e){for(let t=this.scopeStack.length-1;t>=0;t--)if(this.scopeStack[t].has(e))return this.scopeStack[t].get(e)}handleVariableDeclarator(e){const t=e.init;if(!t)return;const n="AwaitExpression"===t.type&&"CallExpression"===t.argument.type?t.argument:"CallExpression"===t.type?t:null;if(!n)return;const r=n.callee;if("Identifier"===r.type){const t=this.getUseTranslationConfig(r.value);if(t)return void this.handleUseTranslationDeclarator(e,n,t)}"MemberExpression"===r.type&&"Identifier"===r.property.type&&"getFixedT"===r.property.value&&this.handleGetFixedTDeclarator(e,n)}handleUseTranslationDeclarator(e,n,r){let i;if("Identifier"===e.id.type&&(i=e.id.value),"ArrayPattern"===e.id.type){const t=e.id.elements[0];"Identifier"===t?.type&&(i=t.value)}if("ObjectPattern"===e.id.type)for(const t of e.id.properties){if("AssignmentPatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value){i="t";break}if("KeyValuePatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value&&"Identifier"===t.value.type){i=t.value.value;break}}if(!i)return;const s=n.arguments?.[r.nsArg]?.expression;let a;"StringLiteral"===s?.type?a=s.value:"ArrayExpression"===s?.type&&"StringLiteral"===s.elements[0]?.expression.type&&(a=s.elements[0].expression.value);const o=n.arguments?.[r.keyPrefixArg]?.expression;let l;if("ObjectExpression"===o?.type){const e=t.getObjectPropValue(o,"keyPrefix");l="string"==typeof e?e:void 0}this.setVarInScope(i,{defaultNs:a,keyPrefix:l})}handleGetFixedTDeclarator(e,t){if("Identifier"!==e.id.type||!e.init||"CallExpression"!==e.init.type)return;const n=e.id.value,r=t.arguments,i=r[1]?.expression,s=r[2]?.expression,a="StringLiteral"===i?.type?i.value:void 0,o="StringLiteral"===s?.type?s.value:void 0;(a||o)&&this.setVarInScope(n,{defaultNs:a,keyPrefix:o})}handleCallExpression(e){const n=this.getFunctionName(e.callee);if(!n)return;const r=this.getVarFromScope(n);if(!((this.config.extract.functions||["t"]).includes(n)||void 0!==r)||0===e.arguments.length)return;const i=e.arguments[0].expression;let s=[];if("StringLiteral"===i.type)s.push(i.value);else if("ArrowFunctionExpression"===i.type){const e=this.extractKeyFromSelector(i);e&&s.push(e)}else if("ArrayExpression"===i.type)for(const e of i.elements)"StringLiteral"===e?.expression.type&&s.push(e.expression.value);if(s=s.filter(e=>!!e),0===s.length)return;let a=!1;const o=this.config.extract.pluralSeparator??"_";for(let e=0;e<s.length;e++)s[e].endsWith(`${o}ordinal`)&&(a=!0,s[e]=s[e].slice(0,-8));let l,p;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?p=t:"StringLiteral"===t.type&&(l=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(p=t)}const u=p?t.getObjectPropValue(p,"defaultValue"):void 0,c="string"==typeof u?u:l;for(let e=0;e<s.length;e++){let n,i=s[e];if(p){const e=t.getObjectPropValue(p,"ns");"string"==typeof e&&(n=e)}!n&&r?.defaultNs&&(n=r.defaultNs);const o=this.config.extract.nsSeparator??":";if(!n&&o&&i.includes(o)){const e=i.split(o);n=e.shift(),i=e.join(o)}n||(n=this.config.extract.defaultNS);let l=i;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";l=`${r.keyPrefix}${e}${i}`}const u=e===s.length-1&&c||i;if(p){const e=t.getObjectProperty(p,"context");if("ConditionalExpression"===e?.value?.type){const t=this.resolvePossibleStringValues(e.value),r=this.config.extract.contextSeparator??"_";if(t.length>0){t.forEach(e=>{this.pluginContext.addKey({key:`${l}${r}${e}`,ns:n,defaultValue:u})}),this.pluginContext.addKey({key:l,ns:n,defaultValue:u});continue}}const r=t.getObjectPropValue(p,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${l}${e}${r}`,ns:n,defaultValue:u});continue}const i=void 0!==t.getObjectPropValue(p,"count"),s=!0===t.getObjectPropValue(p,"ordinal");if(i||a){this.handlePluralKeys(l,n,p,s||a);continue}!0===t.getObjectPropValue(p,"returnObjects")&&this.objectKeys.add(l)}this.pluginContext.addKey({key:l,ns:n,defaultValue:u})}}handlePluralKeys(e,n,r,i){try{const s=i?"ordinal":"cardinal",a=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:s}).resolvedOptions().pluralCategories,o=this.config.extract.pluralSeparator??"_",l=t.getObjectPropValue(r,"defaultValue"),p=t.getObjectPropValue(r,`defaultValue${o}other`),u=t.getObjectPropValue(r,`defaultValue${o}ordinal${o}other`);for(const s of a){const a=i?`defaultValue${o}ordinal${o}${s}`:`defaultValue${o}${s}`,c=t.getObjectPropValue(r,a);let f;f="string"==typeof c?c:"one"===s&&"string"==typeof l?l:i&&"string"==typeof u?u:i||"string"!=typeof p?"string"==typeof l?l:e:p;const y=i?`${e}${o}ordinal${o}${s}`:`${e}${o}${s}`;this.pluginContext.addKey({key:y,ns:n,defaultValue:f,hasCount:!0,isOrdinal:i})}}catch(i){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const s=t.getObjectPropValue(r,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof s?s:e})}}handleSimplePluralKeys(e,t,n){try{const r=new Intl.PluralRules(this.config.extract?.primaryLanguage).resolvedOptions().pluralCategories,i=this.config.extract.pluralSeparator??"_";for(const s of r)this.pluginContext.addKey({key:`${e}${i}${s}`,ns:n,defaultValue:t,hasCount:!0})}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}".`),this.pluginContext.addKey({key:e,ns:n,defaultValue:t})}}handleJSXElement(t){const n=this.getElementName(t);if(n&&(this.config.extract.transComponents||["Trans"]).includes(n)){const n=e.extractFromTransComponent(t,this.config);if(n){if(!n.ns){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===e?.type&&"JSXExpressionContainer"===e.value?.type&&"Identifier"===e.value.expression.type){const t=e.value.expression.value,r=this.getVarFromScope(t);r?.defaultNs&&(n.ns=r.defaultNs)}}if(n.ns||(n.ns=this.config.extract.defaultNS),n.contextExpression){const e=this.resolvePossibleStringValues(n.contextExpression),t=this.config.extract.contextSeparator??"_";if(e.length>0){for(const r of e)this.pluginContext.addKey({key:`${n.key}${t}${r}`,ns:n.ns,defaultValue:n.defaultValue});"StringLiteral"!==n.contextExpression.type&&this.pluginContext.addKey(n)}}else if(n.hasCount){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),r=!!e,i=n.optionsNode??{type:"ObjectExpression",properties:[],span:{start:0,end:0,ctxt:0}};i.properties.push({type:"KeyValueProperty",key:{type:"Identifier",value:"defaultValue",optional:!1,span:{start:0,end:0,ctxt:0}},value:{type:"StringLiteral",value:n.defaultValue,span:{start:0,end:0,ctxt:0}}}),this.handlePluralKeys(n.key,n.ns,i,r)}else this.pluginContext.addKey(n)}}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let n=t;const r=[];for(;"MemberExpression"===n.type;){const e=n.property;if("Identifier"===e.type)r.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;r.unshift(e.expression.value)}n=n.object}if(r.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return r.join(t)}return null}resolvePossibleStringValues(e){if("StringLiteral"===e.type)return[e.value];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValues(e.consequent),...this.resolvePossibleStringValues(e.alternate)]}return"Identifier"===e.type&&e.value,[]}getUseTranslationConfig(e){const t=this.config.extract.useTranslationNames||["useTranslation"];for(const n of t){if("string"==typeof n&&n===e)return{name:e,nsArg:0,keyPrefixArg:1};if("object"==typeof n&&n.name===e)return{name:n.name,nsArg:n.nsArg??0,keyPrefixArg:n.keyPrefixArg??1}}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let n=e;for(;"MemberExpression"===n.type;){if("Identifier"!==n.property.type)return null;t.unshift(n.property.value),n=n.object}return"Identifier"!==n.type?null:(t.unshift(n.value),t.join("."))}return null}};
1
+ "use strict";var e=require("./jsx-parser.js"),t=require("./ast-utils.js");exports.ASTVisitors=class{pluginContext;config;logger;scopeStack=[];objectKeys=new Set;constructor(e,t,n){this.pluginContext=t,this.config=e,this.logger=n}visit(e){this.enterScope(),this.walk(e),this.exitScope()}walk(e){if(!e)return;let t=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.enterScope(),t=!0),e.type){case"VariableDeclarator":this.handleVariableDeclarator(e);break;case"CallExpression":this.handleCallExpression(e);break;case"JSXElement":this.handleJSXElement(e)}for(const t in e){if("span"===t)continue;const n=e[t];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&this.walk(e);else n&&"object"==typeof n&&this.walk(n)}t&&this.exitScope()}enterScope(){this.scopeStack.push(new Map)}exitScope(){this.scopeStack.pop()}setVarInScope(e,t){this.scopeStack.length>0&&this.scopeStack[this.scopeStack.length-1].set(e,t)}getVarFromScope(e){for(let t=this.scopeStack.length-1;t>=0;t--)if(this.scopeStack[t].has(e))return this.scopeStack[t].get(e)}handleVariableDeclarator(e){const t=e.init;if(!t)return;const n="AwaitExpression"===t.type&&"CallExpression"===t.argument.type?t.argument:"CallExpression"===t.type?t:null;if(!n)return;const r=n.callee;if("Identifier"===r.type){const t=this.getUseTranslationConfig(r.value);if(t)return void this.handleUseTranslationDeclarator(e,n,t)}"MemberExpression"===r.type&&"Identifier"===r.property.type&&"getFixedT"===r.property.value&&this.handleGetFixedTDeclarator(e,n)}handleUseTranslationDeclarator(e,n,r){let i;if("Identifier"===e.id.type&&(i=e.id.value),"ArrayPattern"===e.id.type){const t=e.id.elements[0];"Identifier"===t?.type&&(i=t.value)}if("ObjectPattern"===e.id.type)for(const t of e.id.properties){if("AssignmentPatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value){i="t";break}if("KeyValuePatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value&&"Identifier"===t.value.type){i=t.value.value;break}}if(!i)return;const s=n.arguments?.[r.nsArg]?.expression;let a;"StringLiteral"===s?.type?a=s.value:"ArrayExpression"===s?.type&&"StringLiteral"===s.elements[0]?.expression.type&&(a=s.elements[0].expression.value);const o=n.arguments?.[r.keyPrefixArg]?.expression;let l;if("ObjectExpression"===o?.type){const e=t.getObjectPropValue(o,"keyPrefix");l="string"==typeof e?e:void 0}this.setVarInScope(i,{defaultNs:a,keyPrefix:l})}handleGetFixedTDeclarator(e,t){if("Identifier"!==e.id.type||!e.init||"CallExpression"!==e.init.type)return;const n=e.id.value,r=t.arguments,i=r[1]?.expression,s=r[2]?.expression,a="StringLiteral"===i?.type?i.value:void 0,o="StringLiteral"===s?.type?s.value:void 0;(a||o)&&this.setVarInScope(n,{defaultNs:a,keyPrefix:o})}handleCallExpression(e){const n=this.getFunctionName(e.callee);if(!n)return;const r=this.getVarFromScope(n),i=this.config.extract.functions||["t"];let s=void 0!==r;if(!s)for(const e of i)if(e.startsWith("*.")){if(n.endsWith(e.substring(1))){s=!0;break}}else if(e===n){s=!0;break}if(!s||0===e.arguments.length)return;const a=e.arguments[0].expression;let o=[];if("StringLiteral"===a.type)o.push(a.value);else if("ArrowFunctionExpression"===a.type){const e=this.extractKeyFromSelector(a);e&&o.push(e)}else if("ArrayExpression"===a.type)for(const e of a.elements)"StringLiteral"===e?.expression.type&&o.push(e.expression.value);if(o=o.filter(e=>!!e),0===o.length)return;let l=!1;const p=this.config.extract.pluralSeparator??"_";for(let e=0;e<o.length;e++)o[e].endsWith(`${p}ordinal`)&&(l=!0,o[e]=o[e].slice(0,-8));let u,c;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?c=t:"StringLiteral"===t.type&&(u=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(c=t)}const f=c?t.getObjectPropValue(c,"defaultValue"):void 0,y="string"==typeof f?f:u;for(let e=0;e<o.length;e++){let n,i=o[e];if(c){const e=t.getObjectPropValue(c,"ns");"string"==typeof e&&(n=e)}!n&&r?.defaultNs&&(n=r.defaultNs);const s=this.config.extract.nsSeparator??":";if(!n&&s&&i.includes(s)){const e=i.split(s);n=e.shift(),i=e.join(s)}n||(n=this.config.extract.defaultNS);let a=i;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";a=`${r.keyPrefix}${e}${i}`}const p=e===o.length-1&&y||i;if(c){const e=t.getObjectProperty(c,"context");if("ConditionalExpression"===e?.value?.type){const t=this.resolvePossibleStringValues(e.value),r=this.config.extract.contextSeparator??"_";if(t.length>0){t.forEach(e=>{this.pluginContext.addKey({key:`${a}${r}${e}`,ns:n,defaultValue:p})}),this.pluginContext.addKey({key:a,ns:n,defaultValue:p});continue}}const r=t.getObjectPropValue(c,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${a}${e}${r}`,ns:n,defaultValue:p});continue}const i=void 0!==t.getObjectPropValue(c,"count"),s=!0===t.getObjectPropValue(c,"ordinal");if(i||l){this.handlePluralKeys(a,n,c,s||l);continue}!0===t.getObjectPropValue(c,"returnObjects")&&this.objectKeys.add(a)}this.pluginContext.addKey({key:a,ns:n,defaultValue:p})}}handlePluralKeys(e,n,r,i){try{const s=i?"ordinal":"cardinal",a=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:s}).resolvedOptions().pluralCategories,o=this.config.extract.pluralSeparator??"_",l=t.getObjectPropValue(r,"defaultValue"),p=t.getObjectPropValue(r,`defaultValue${o}other`),u=t.getObjectPropValue(r,`defaultValue${o}ordinal${o}other`);for(const s of a){const a=i?`defaultValue${o}ordinal${o}${s}`:`defaultValue${o}${s}`,c=t.getObjectPropValue(r,a);let f;f="string"==typeof c?c:"one"===s&&"string"==typeof l?l:i&&"string"==typeof u?u:i||"string"!=typeof p?"string"==typeof l?l:e:p;const y=i?`${e}${o}ordinal${o}${s}`:`${e}${o}${s}`;this.pluginContext.addKey({key:y,ns:n,defaultValue:f,hasCount:!0,isOrdinal:i})}}catch(i){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const s=t.getObjectPropValue(r,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof s?s:e})}}handleSimplePluralKeys(e,t,n){try{const r=new Intl.PluralRules(this.config.extract?.primaryLanguage).resolvedOptions().pluralCategories,i=this.config.extract.pluralSeparator??"_";for(const s of r)this.pluginContext.addKey({key:`${e}${i}${s}`,ns:n,defaultValue:t,hasCount:!0})}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}".`),this.pluginContext.addKey({key:e,ns:n,defaultValue:t})}}handleJSXElement(t){const n=this.getElementName(t);if(n&&(this.config.extract.transComponents||["Trans"]).includes(n)){const n=e.extractFromTransComponent(t,this.config);if(n){if(!n.ns){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===e?.type&&"JSXExpressionContainer"===e.value?.type&&"Identifier"===e.value.expression.type){const t=e.value.expression.value,r=this.getVarFromScope(t);r?.defaultNs&&(n.ns=r.defaultNs)}}if(n.ns||(n.ns=this.config.extract.defaultNS),n.contextExpression){const e=this.resolvePossibleStringValues(n.contextExpression),t=this.config.extract.contextSeparator??"_";if(e.length>0){for(const r of e)this.pluginContext.addKey({key:`${n.key}${t}${r}`,ns:n.ns,defaultValue:n.defaultValue});"StringLiteral"!==n.contextExpression.type&&this.pluginContext.addKey(n)}}else if(n.hasCount){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),r=!!e,i=n.optionsNode??{type:"ObjectExpression",properties:[],span:{start:0,end:0,ctxt:0}};i.properties.push({type:"KeyValueProperty",key:{type:"Identifier",value:"defaultValue",optional:!1,span:{start:0,end:0,ctxt:0}},value:{type:"StringLiteral",value:n.defaultValue,span:{start:0,end:0,ctxt:0}}}),this.handlePluralKeys(n.key,n.ns,i,r)}else this.pluginContext.addKey(n)}}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let n=t;const r=[];for(;"MemberExpression"===n.type;){const e=n.property;if("Identifier"===e.type)r.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;r.unshift(e.expression.value)}n=n.object}if(r.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return r.join(t)}return null}resolvePossibleStringValues(e){if("StringLiteral"===e.type)return[e.value];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValues(e.consequent),...this.resolvePossibleStringValues(e.alternate)]}return"Identifier"===e.type&&e.value,[]}getUseTranslationConfig(e){const t=this.config.extract.useTranslationNames||["useTranslation"];for(const n of t){if("string"==typeof n&&n===e)return{name:e,nsArg:0,keyPrefixArg:1};if("object"==typeof n&&n.name===e)return{name:n.name,nsArg:n.nsArg??0,keyPrefixArg:n.keyPrefixArg??1}}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let n=e;for(;"MemberExpression"===n.type;){if("Identifier"!==n.property.type)return null;t.unshift(n.property.value),n=n.object}if("ThisExpression"===n.type)t.unshift("this");else{if("Identifier"!==n.type)return null;t.unshift(n.value)}return t.join(".")}return null}};
package/dist/esm/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import n from"chalk";import{ensureConfig as i,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as r}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as s}from"./types-generator.js";import{runSyncer as l}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as p}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as f,runLocizeDownload as u,runLocizeMigrate as h}from"./locize.js";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.3.0"),w.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").action(async t=>{const a=await i(),c=async()=>{const o=await r(a,{isWatchMode:t.watch,isDryRun:t.dryRun});t.ci&&o&&(console.error(n.red.bold("\n[CI Mode] Error: Translation files were updated. Please commit the changes.")),console.log(n.yellow("💡 Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started")),console.log(` Learn more: ${n.cyan("npx i18next-cli locize-sync")}`),process.exit(1))};if(await c(),t.watch){console.log("\nWatching for changes...");o.watch(await e(a.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),c()})}}),w.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(t,o)=>{let e=await a();if(!e){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),e=t}await g(e,{detail:t,namespace:o.namespace})}),w.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async t=>{const n=await i(),a=()=>s(n);if(await a(),t.watch){console.log("\nWatching for changes...");o.watch(await e(n.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await i();await l(t)}),w.command("migrate-config").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async()=>{await m()}),w.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(p),w.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async t=>{const i=async()=>{let t=await a();if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=o}await d(t)};if(await i(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){o.watch(await e(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),i()})}}}),w.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async t=>{const o=await i();await f(o,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=await i();await u(o,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=await i();await h(o,t)}),w.parse(process.argv);
2
+ import{Command as t}from"commander";import o from"chokidar";import{glob as e}from"glob";import n from"chalk";import{ensureConfig as i,loadConfig as a}from"./config.js";import{detectConfig as c}from"./heuristic-config.js";import{runExtractor as r}from"./extractor/core/extractor.js";import"node:path";import"node:fs/promises";import"jiti";import{runTypesGenerator as s}from"./types-generator.js";import{runSyncer as l}from"./syncer.js";import{runMigrator as m}from"./migrator.js";import{runInit as p}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as g}from"./status.js";import{runLocizeSync as f,runLocizeDownload as u,runLocizeMigrate as h}from"./locize.js";const w=new t;w.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.5.0"),w.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").action(async t=>{const a=await i(),c=async()=>{const o=await r(a,{isWatchMode:t.watch,isDryRun:t.dryRun});t.ci&&o&&(console.error(n.red.bold("\n[CI Mode] Error: Translation files were updated. Please commit the changes.")),console.log(n.yellow("💡 Tip: Tired of committing JSON files? locize syncs your team automatically => https://www.locize.com/docs/getting-started")),console.log(` Learn more: ${n.cyan("npx i18next-cli locize-sync")}`),process.exit(1))};if(await c(),t.watch){console.log("\nWatching for changes...");o.watch(await e(a.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),c()})}}),w.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(t,o)=>{let e=await a();if(!e){console.log(n.blue("No config file found. Attempting to detect project structure..."));const t=await c();t||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),e=t}await g(e,{detail:t,namespace:o.namespace})}),w.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async t=>{const n=await i(),a=()=>s(n);if(await a(),t.watch){console.log("\nWatching for changes...");o.watch(await e(n.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),w.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await i();await l(t)}),w.command("migrate-config").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async()=>{await m()}),w.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(p),w.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async t=>{const i=async()=>{let t=await a();if(!t){console.log(n.blue("No config file found. Attempting to detect project structure..."));const o=await c();o||(console.error(n.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${n.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(n.green("Project structure detected successfully!")),t=o}await d(t)};if(await i(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){o.watch(await e(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),i()})}}}),w.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async t=>{const o=await i();await f(o,t)}),w.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const o=await i();await u(o,t)}),w.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const o=await i();await h(o,t)}),w.parse(process.argv);
@@ -1 +1 @@
1
- import t from"ora";import o from"chalk";import{parse as e}from"@swc/core";import{mkdir as a,writeFile as r,readFile as n}from"node:fs/promises";import{dirname as i}from"node:path";import{findKeys as s}from"./key-finder.js";import{getTranslations as c}from"./translation-manager.js";import{validateExtractorConfig as l,ExtractorError as f}from"../../utils/validation.js";import{createPluginContext as m}from"../plugin-manager.js";import{extractKeysFromComments as p}from"../parsers/comment-parser.js";import{ConsoleLogger as u}from"../../utils/logger.js";import{serializeTranslationFile as y}from"../../utils/file-utils.js";let g=!1;async function d(e,{isWatchMode:n=!1,isDryRun:f=!1}={},m=new u){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage),l(e);const p=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:l}=await s(e,m);p.text=`Found ${t.size} unique keys. Updating translation files...`;const u=await c(t,l,e);let d=!1;for(const t of u)if(t.updated&&(d=!0,!f)){const n=y(t.newTranslations,e.extract.outputFormat,e.extract.indentation);await a(i(t.path),{recursive:!0}),await r(t.path,n),m.info(o.green(`Updated: ${t.path}`))}return p.succeed(o.bold("Extraction complete!")),d&&function(t=!1){if(t&&g)return;console.log(o.yellow.bold("\n💡 Tip: Tired of running the extractor manually?")),console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,'),console.log(" where keys are created and translated automatically as you code."),console.log(` Learn more: ${o.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${o.cyan("https://youtu.be/joPsZghT3wM")}`),t&&(g=!0)}(n),d}catch(t){throw p.fail(o.red("Extraction failed.")),t}}async function w(t,o,a,r,i=new u){try{let s=await n(t,"utf-8");for(const e of o.plugins||[])s=await(e.onLoad?.(s,t))??s;const c=await e(s,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0}),l=m(a);p(s,l,o),r.visit(c),(o.plugins||[]).length>0&&h(c,o.plugins||[],l,i)}catch(o){throw new f("Failed to process file",t,o)}}function h(t,o,e,a=new u){if(t&&"object"==typeof t){for(const r of o)try{r.onVisitNode?.(t,e)}catch(t){a.warn(`Plugin ${r.name} onVisitNode failed:`,t)}for(const r of Object.keys(t)){const n=t[r];if(Array.isArray(n))for(const t of n)t&&"object"==typeof t&&h(t,o,e,a);else n&&"object"==typeof n&&h(n,o,e,a)}}}async function x(t){t.extract.primaryLanguage||=t.locales[0]||"en",t.extract.secondaryLanguages||=t.locales.filter(o=>o!==t?.extract?.primaryLanguage),t.extract.functions||=["t"],t.extract.transComponents||=["Trans"];const{allKeys:o,objectKeys:e}=await s(t);return c(o,e,t)}export{x as extract,w as processFile,d as runExtractor};
1
+ import t from"ora";import o from"chalk";import{parse as e}from"@swc/core";import{mkdir as a,writeFile as n,readFile as r}from"node:fs/promises";import{dirname as i}from"node:path";import{findKeys as s}from"./key-finder.js";import{getTranslations as c}from"./translation-manager.js";import{validateExtractorConfig as l,ExtractorError as f}from"../../utils/validation.js";import{createPluginContext as p}from"../plugin-manager.js";import{extractKeysFromComments as u}from"../parsers/comment-parser.js";import{ConsoleLogger as m}from"../../utils/logger.js";import{serializeTranslationFile as g}from"../../utils/file-utils.js";let y=!1;async function d(e,{isWatchMode:r=!1,isDryRun:f=!1}={},p=new m){e.extract.primaryLanguage||=e.locales[0]||"en",e.extract.secondaryLanguages||=e.locales.filter(t=>t!==e?.extract?.primaryLanguage),e.extract.functions||=["t"],e.extract.transComponents||=["Trans"],l(e);const u=t("Running i18next key extractor...\n").start();try{const{allKeys:t,objectKeys:l}=await s(e,p);u.text=`Found ${t.size} unique keys. Updating translation files...`;const m=await c(t,l,e);let d=!1;for(const t of m)if(t.updated&&(d=!0,!f)){const r=g(t.newTranslations,e.extract.outputFormat,e.extract.indentation);await a(i(t.path),{recursive:!0}),await n(t.path,r),p.info(o.green(`Updated: ${t.path}`))}if((e.plugins||[]).length>0){u.text="Running post-extraction plugins...";for(const t of e.plugins||[])await(t.afterSync?.(m,e))}return u.succeed(o.bold("Extraction complete!")),d&&function(t=!1){if(t&&y)return;console.log(o.yellow.bold("\n💡 Tip: Tired of running the extractor manually?")),console.log(' Discover a real-time "push" workflow with `saveMissing` and Locize AI,'),console.log(" where keys are created and translated automatically as you code."),console.log(` Learn more: ${o.cyan("https://www.locize.com/blog/i18next-savemissing-ai-automation")}`),console.log(` Watch the video: ${o.cyan("https://youtu.be/joPsZghT3wM")}`),t&&(y=!0)}(r),d}catch(t){throw u.fail(o.red("Extraction failed.")),t}}async function w(t,o,a,n,i=new m){try{let s=await r(t,"utf-8");for(const e of o.plugins||[])s=await(e.onLoad?.(s,t))??s;const c=await e(s,{syntax:"typescript",tsx:!0,decorators:!0,comments:!0}),l=p(a);u(s,l,o),n.visit(c),(o.plugins||[]).length>0&&x(c,o.plugins||[],l,i)}catch(o){throw new f("Failed to process file",t,o)}}function x(t,o,e,a=new m){if(t&&"object"==typeof t){for(const n of o)try{n.onVisitNode?.(t,e)}catch(t){a.warn(`Plugin ${n.name} onVisitNode failed:`,t)}for(const n of Object.keys(t)){const r=t[n];if(Array.isArray(r))for(const t of r)t&&"object"==typeof t&&x(t,o,e,a);else r&&"object"==typeof r&&x(r,o,e,a)}}}async function h(t){t.extract.primaryLanguage||=t.locales[0]||"en",t.extract.secondaryLanguages||=t.locales.filter(o=>o!==t?.extract?.primaryLanguage),t.extract.functions||=["t"],t.extract.transComponents||=["Trans"];const{allKeys:o,objectKeys:e}=await s(t);return c(o,e,t)}export{h as extract,w as processFile,d as runExtractor};
@@ -1 +1 @@
1
- import{resolve as t}from"node:path";import{getNestedKeys as e,getNestedValue as s,setNestedValue as a}from"../../utils/nested-object.js";import{loadTranslationFile as r,getOutputPath as o}from"../../utils/file-utils.js";function n(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}async function c(c,i,l){l.extract.primaryLanguage||=l.locales[0]||"en",l.extract.secondaryLanguages||=l.locales.filter(t=>t!==l?.extract?.primaryLanguage);const u=l.extract.primaryLanguage,p=l.extract.defaultNS??"translation",f=l.extract.keySeparator??".",x=[...l.extract.preservePatterns||[]],g=l.extract.mergeNamespaces??!1,d=l.extract.indentation??2,y=l.extract.removeUnusedKeys??!0;for(const t of i)x.push(`${t}.*`);const m=x.map(n),w=new Map;for(const t of c.values()){const e=t.ns||p;w.has(e)||w.set(e,[]),w.get(e).push(t)}const h=[];for(const n of l.locales){const c=g?await r(t(process.cwd(),o(l.extract.output,n)))||{}:null,i={};for(const[p,x]of w.entries()){const w=o(l.extract.output,n,g?void 0:p),N=t(process.cwd(),w),S=g?c?.[p]||{}:await r(N)||{},J=y?{}:JSON.parse(JSON.stringify(S)),O=e(S,f);for(const t of O)if(m.some(e=>e.test(t))){const e=s(S,t,f);a(J,t,e,f)}const $=!1===l.extract.sort?x:[...x].sort("function"==typeof l.extract.sort?l.extract.sort:(t,e)=>t.key.localeCompare(e.key));for(const{key:t,defaultValue:e}of $){const r=s(S,t,f)??(n===u?e:l.extract.defaultValue??"");a(J,t,r,f)}if(g)i[p]=J;else{const t=JSON.stringify(S,null,d),e=JSON.stringify(J,null,d);h.push({path:N,updated:e!==t,newTranslations:J,existingTranslations:S})}}if(g){const e=o(l.extract.output,n),s=t(process.cwd(),e),a=JSON.stringify(c,null,d),r=JSON.stringify(i,null,d);h.push({path:s,updated:r!==a,newTranslations:i,existingTranslations:c||{}})}}return h}export{c as getTranslations};
1
+ import{resolve as t,basename as e,extname as o}from"node:path";import{glob as s}from"glob";import{getNestedKeys as n,getNestedValue as r,setNestedValue as a}from"../../utils/nested-object.js";import{getOutputPath as c,loadTranslationFile as i}from"../../utils/file-utils.js";function f(t){const e=`^${t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*")}$`;return new RegExp(e)}function u(t,e,o,s,c,i){const{keySeparator:f=".",sort:u=!0,removeUnusedKeys:l=!0,primaryLanguage:p,defaultValue:g=""}=o.extract;let y=l?{}:JSON.parse(JSON.stringify(e));const x=n(e,f??".");for(const t of x)if(c.some(e=>e.test(t))){const o=r(e,t,f??".");a(y,t,o,f??".")}for(const{key:o,defaultValue:n}of t){const c=r(e,o,f??"."),u=!t.some(t=>t.key.startsWith(`${o}${f}`)&&t.key!==o),l="object"==typeof c&&null!==c&&u&&!i.has(o);a(y,o,void 0===c||l?s===p?n:g:c,f??".")}if(!1!==u){const e={},o=Object.keys(y),s=new Map;for(const e of t){const t=!1===f?e.key:e.key.split(f)[0];s.has(t)||s.set(t,e)}o.sort((t,e)=>{if("function"==typeof u){const o=s.get(t),n=s.get(e);if(o&&n)return u(o,n)}return t.localeCompare(e)});for(const t of o)e[t]=y[t];y=e}return y}async function l(n,r,a){a.extract.primaryLanguage||=a.locales[0]||"en",a.extract.secondaryLanguages||=a.locales.filter(t=>t!==a?.extract?.primaryLanguage);const l=a.extract.defaultNS??"translation",p=[...a.extract.preservePatterns||[]],g=a.extract.indentation??2;for(const t of r)p.push(`${t}.*`);const y=p.map(f),x=new Map;for(const t of n.values()){const e=t.ns||l;x.has(e)||x.set(e,[]),x.get(e).push(t)}const m=[],d=Array.isArray(a.extract.ignore)?a.extract.ignore:a.extract.ignore?[a.extract.ignore]:[];for(const n of a.locales){if(a.extract.mergeNamespaces||!a.extract.output.includes("{{namespace}}")){const e={},o=c(a.extract.output,n),s=t(process.cwd(),o),f=await i(s)||{},l=new Set([...x.keys(),...Object.keys(f)]);for(const t of l){const o=x.get(t)||[],s=f[t]||{};e[t]=u(o,s,a,n,y,r)}const p=JSON.stringify(f,null,g),d=JSON.stringify(e,null,g);m.push({path:s,updated:d!==p,newTranslations:e,existingTranslations:f})}else{const f=new Set(x.keys()),l=c(a.extract.output,n,"*"),p=await s(l,{ignore:d});for(const t of p)f.add(e(t,o(t)));for(const e of f){const o=x.get(e)||[],s=c(a.extract.output,n,e),f=t(process.cwd(),s),l=await i(f)||{},p=u(o,l,a,n,y,r),d=JSON.stringify(l,null,g),w=JSON.stringify(p,null,g);m.push({path:f,updated:w!==d,newTranslations:p,existingTranslations:l})}}}return m}export{l as getTranslations};
@@ -1 +1 @@
1
- import{extractFromTransComponent as e}from"./jsx-parser.js";import{getObjectPropValue as t,getObjectProperty as n}from"./ast-utils.js";class i{pluginContext;config;logger;scopeStack=[];objectKeys=new Set;constructor(e,t,n){this.pluginContext=t,this.config=e,this.logger=n}visit(e){this.enterScope(),this.walk(e),this.exitScope()}walk(e){if(!e)return;let t=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.enterScope(),t=!0),e.type){case"VariableDeclarator":this.handleVariableDeclarator(e);break;case"CallExpression":this.handleCallExpression(e);break;case"JSXElement":this.handleJSXElement(e)}for(const t in e){if("span"===t)continue;const n=e[t];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&this.walk(e);else n&&"object"==typeof n&&this.walk(n)}t&&this.exitScope()}enterScope(){this.scopeStack.push(new Map)}exitScope(){this.scopeStack.pop()}setVarInScope(e,t){this.scopeStack.length>0&&this.scopeStack[this.scopeStack.length-1].set(e,t)}getVarFromScope(e){for(let t=this.scopeStack.length-1;t>=0;t--)if(this.scopeStack[t].has(e))return this.scopeStack[t].get(e)}handleVariableDeclarator(e){const t=e.init;if(!t)return;const n="AwaitExpression"===t.type&&"CallExpression"===t.argument.type?t.argument:"CallExpression"===t.type?t:null;if(!n)return;const i=n.callee;if("Identifier"===i.type){const t=this.getUseTranslationConfig(i.value);if(t)return void this.handleUseTranslationDeclarator(e,n,t)}"MemberExpression"===i.type&&"Identifier"===i.property.type&&"getFixedT"===i.property.value&&this.handleGetFixedTDeclarator(e,n)}handleUseTranslationDeclarator(e,n,i){let r;if("Identifier"===e.id.type&&(r=e.id.value),"ArrayPattern"===e.id.type){const t=e.id.elements[0];"Identifier"===t?.type&&(r=t.value)}if("ObjectPattern"===e.id.type)for(const t of e.id.properties){if("AssignmentPatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value){r="t";break}if("KeyValuePatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value&&"Identifier"===t.value.type){r=t.value.value;break}}if(!r)return;const s=n.arguments?.[i.nsArg]?.expression;let a;"StringLiteral"===s?.type?a=s.value:"ArrayExpression"===s?.type&&"StringLiteral"===s.elements[0]?.expression.type&&(a=s.elements[0].expression.value);const o=n.arguments?.[i.keyPrefixArg]?.expression;let l;if("ObjectExpression"===o?.type){const e=t(o,"keyPrefix");l="string"==typeof e?e:void 0}this.setVarInScope(r,{defaultNs:a,keyPrefix:l})}handleGetFixedTDeclarator(e,t){if("Identifier"!==e.id.type||!e.init||"CallExpression"!==e.init.type)return;const n=e.id.value,i=t.arguments,r=i[1]?.expression,s=i[2]?.expression,a="StringLiteral"===r?.type?r.value:void 0,o="StringLiteral"===s?.type?s.value:void 0;(a||o)&&this.setVarInScope(n,{defaultNs:a,keyPrefix:o})}handleCallExpression(e){const i=this.getFunctionName(e.callee);if(!i)return;const r=this.getVarFromScope(i);if(!((this.config.extract.functions||["t"]).includes(i)||void 0!==r)||0===e.arguments.length)return;const s=e.arguments[0].expression;let a=[];if("StringLiteral"===s.type)a.push(s.value);else if("ArrowFunctionExpression"===s.type){const e=this.extractKeyFromSelector(s);e&&a.push(e)}else if("ArrayExpression"===s.type)for(const e of s.elements)"StringLiteral"===e?.expression.type&&a.push(e.expression.value);if(a=a.filter(e=>!!e),0===a.length)return;let o=!1;const l=this.config.extract.pluralSeparator??"_";for(let e=0;e<a.length;e++)a[e].endsWith(`${l}ordinal`)&&(o=!0,a[e]=a[e].slice(0,-8));let p,u;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?u=t:"StringLiteral"===t.type&&(p=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(u=t)}const c=u?t(u,"defaultValue"):void 0,f="string"==typeof c?c:p;for(let e=0;e<a.length;e++){let i,s=a[e];if(u){const e=t(u,"ns");"string"==typeof e&&(i=e)}!i&&r?.defaultNs&&(i=r.defaultNs);const l=this.config.extract.nsSeparator??":";if(!i&&l&&s.includes(l)){const e=s.split(l);i=e.shift(),s=e.join(l)}i||(i=this.config.extract.defaultNS);let p=s;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";p=`${r.keyPrefix}${e}${s}`}const c=e===a.length-1&&f||s;if(u){const e=n(u,"context");if("ConditionalExpression"===e?.value?.type){const t=this.resolvePossibleStringValues(e.value),n=this.config.extract.contextSeparator??"_";if(t.length>0){t.forEach(e=>{this.pluginContext.addKey({key:`${p}${n}${e}`,ns:i,defaultValue:c})}),this.pluginContext.addKey({key:p,ns:i,defaultValue:c});continue}}const r=t(u,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${p}${e}${r}`,ns:i,defaultValue:c});continue}const s=void 0!==t(u,"count"),a=!0===t(u,"ordinal");if(s||o){this.handlePluralKeys(p,i,u,a||o);continue}!0===t(u,"returnObjects")&&this.objectKeys.add(p)}this.pluginContext.addKey({key:p,ns:i,defaultValue:c})}}handlePluralKeys(e,n,i,r){try{const s=r?"ordinal":"cardinal",a=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:s}).resolvedOptions().pluralCategories,o=this.config.extract.pluralSeparator??"_",l=t(i,"defaultValue"),p=t(i,`defaultValue${o}other`),u=t(i,`defaultValue${o}ordinal${o}other`);for(const s of a){const a=t(i,r?`defaultValue${o}ordinal${o}${s}`:`defaultValue${o}${s}`);let c;c="string"==typeof a?a:"one"===s&&"string"==typeof l?l:r&&"string"==typeof u?u:r||"string"!=typeof p?"string"==typeof l?l:e:p;const f=r?`${e}${o}ordinal${o}${s}`:`${e}${o}${s}`;this.pluginContext.addKey({key:f,ns:n,defaultValue:c,hasCount:!0,isOrdinal:r})}}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const s=t(i,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof s?s:e})}}handleSimplePluralKeys(e,t,n){try{const i=new Intl.PluralRules(this.config.extract?.primaryLanguage).resolvedOptions().pluralCategories,r=this.config.extract.pluralSeparator??"_";for(const s of i)this.pluginContext.addKey({key:`${e}${r}${s}`,ns:n,defaultValue:t,hasCount:!0})}catch(i){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}".`),this.pluginContext.addKey({key:e,ns:n,defaultValue:t})}}handleJSXElement(t){const n=this.getElementName(t);if(n&&(this.config.extract.transComponents||["Trans"]).includes(n)){const n=e(t,this.config);if(n){if(!n.ns){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===e?.type&&"JSXExpressionContainer"===e.value?.type&&"Identifier"===e.value.expression.type){const t=e.value.expression.value,i=this.getVarFromScope(t);i?.defaultNs&&(n.ns=i.defaultNs)}}if(n.ns||(n.ns=this.config.extract.defaultNS),n.contextExpression){const e=this.resolvePossibleStringValues(n.contextExpression),t=this.config.extract.contextSeparator??"_";if(e.length>0){for(const i of e)this.pluginContext.addKey({key:`${n.key}${t}${i}`,ns:n.ns,defaultValue:n.defaultValue});"StringLiteral"!==n.contextExpression.type&&this.pluginContext.addKey(n)}}else if(n.hasCount){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),i=!!e,r=n.optionsNode??{type:"ObjectExpression",properties:[],span:{start:0,end:0,ctxt:0}};r.properties.push({type:"KeyValueProperty",key:{type:"Identifier",value:"defaultValue",optional:!1,span:{start:0,end:0,ctxt:0}},value:{type:"StringLiteral",value:n.defaultValue,span:{start:0,end:0,ctxt:0}}}),this.handlePluralKeys(n.key,n.ns,r,i)}else this.pluginContext.addKey(n)}}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let n=t;const i=[];for(;"MemberExpression"===n.type;){const e=n.property;if("Identifier"===e.type)i.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;i.unshift(e.expression.value)}n=n.object}if(i.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return i.join(t)}return null}resolvePossibleStringValues(e){if("StringLiteral"===e.type)return[e.value];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValues(e.consequent),...this.resolvePossibleStringValues(e.alternate)]}return"Identifier"===e.type&&e.value,[]}getUseTranslationConfig(e){const t=this.config.extract.useTranslationNames||["useTranslation"];for(const n of t){if("string"==typeof n&&n===e)return{name:e,nsArg:0,keyPrefixArg:1};if("object"==typeof n&&n.name===e)return{name:n.name,nsArg:n.nsArg??0,keyPrefixArg:n.keyPrefixArg??1}}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let n=e;for(;"MemberExpression"===n.type;){if("Identifier"!==n.property.type)return null;t.unshift(n.property.value),n=n.object}return"Identifier"!==n.type?null:(t.unshift(n.value),t.join("."))}return null}}export{i as ASTVisitors};
1
+ import{extractFromTransComponent as e}from"./jsx-parser.js";import{getObjectPropValue as t,getObjectProperty as n}from"./ast-utils.js";class i{pluginContext;config;logger;scopeStack=[];objectKeys=new Set;constructor(e,t,n){this.pluginContext=t,this.config=e,this.logger=n}visit(e){this.enterScope(),this.walk(e),this.exitScope()}walk(e){if(!e)return;let t=!1;switch("Function"!==e.type&&"ArrowFunctionExpression"!==e.type&&"FunctionExpression"!==e.type||(this.enterScope(),t=!0),e.type){case"VariableDeclarator":this.handleVariableDeclarator(e);break;case"CallExpression":this.handleCallExpression(e);break;case"JSXElement":this.handleJSXElement(e)}for(const t in e){if("span"===t)continue;const n=e[t];if(Array.isArray(n))for(const e of n)e&&"object"==typeof e&&this.walk(e);else n&&"object"==typeof n&&this.walk(n)}t&&this.exitScope()}enterScope(){this.scopeStack.push(new Map)}exitScope(){this.scopeStack.pop()}setVarInScope(e,t){this.scopeStack.length>0&&this.scopeStack[this.scopeStack.length-1].set(e,t)}getVarFromScope(e){for(let t=this.scopeStack.length-1;t>=0;t--)if(this.scopeStack[t].has(e))return this.scopeStack[t].get(e)}handleVariableDeclarator(e){const t=e.init;if(!t)return;const n="AwaitExpression"===t.type&&"CallExpression"===t.argument.type?t.argument:"CallExpression"===t.type?t:null;if(!n)return;const i=n.callee;if("Identifier"===i.type){const t=this.getUseTranslationConfig(i.value);if(t)return void this.handleUseTranslationDeclarator(e,n,t)}"MemberExpression"===i.type&&"Identifier"===i.property.type&&"getFixedT"===i.property.value&&this.handleGetFixedTDeclarator(e,n)}handleUseTranslationDeclarator(e,n,i){let r;if("Identifier"===e.id.type&&(r=e.id.value),"ArrayPattern"===e.id.type){const t=e.id.elements[0];"Identifier"===t?.type&&(r=t.value)}if("ObjectPattern"===e.id.type)for(const t of e.id.properties){if("AssignmentPatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value){r="t";break}if("KeyValuePatternProperty"===t.type&&"Identifier"===t.key.type&&"t"===t.key.value&&"Identifier"===t.value.type){r=t.value.value;break}}if(!r)return;const s=n.arguments?.[i.nsArg]?.expression;let a;"StringLiteral"===s?.type?a=s.value:"ArrayExpression"===s?.type&&"StringLiteral"===s.elements[0]?.expression.type&&(a=s.elements[0].expression.value);const o=n.arguments?.[i.keyPrefixArg]?.expression;let l;if("ObjectExpression"===o?.type){const e=t(o,"keyPrefix");l="string"==typeof e?e:void 0}this.setVarInScope(r,{defaultNs:a,keyPrefix:l})}handleGetFixedTDeclarator(e,t){if("Identifier"!==e.id.type||!e.init||"CallExpression"!==e.init.type)return;const n=e.id.value,i=t.arguments,r=i[1]?.expression,s=i[2]?.expression,a="StringLiteral"===r?.type?r.value:void 0,o="StringLiteral"===s?.type?s.value:void 0;(a||o)&&this.setVarInScope(n,{defaultNs:a,keyPrefix:o})}handleCallExpression(e){const i=this.getFunctionName(e.callee);if(!i)return;const r=this.getVarFromScope(i),s=this.config.extract.functions||["t"];let a=void 0!==r;if(!a)for(const e of s)if(e.startsWith("*.")){if(i.endsWith(e.substring(1))){a=!0;break}}else if(e===i){a=!0;break}if(!a||0===e.arguments.length)return;const o=e.arguments[0].expression;let l=[];if("StringLiteral"===o.type)l.push(o.value);else if("ArrowFunctionExpression"===o.type){const e=this.extractKeyFromSelector(o);e&&l.push(e)}else if("ArrayExpression"===o.type)for(const e of o.elements)"StringLiteral"===e?.expression.type&&l.push(e.expression.value);if(l=l.filter(e=>!!e),0===l.length)return;let p=!1;const u=this.config.extract.pluralSeparator??"_";for(let e=0;e<l.length;e++)l[e].endsWith(`${u}ordinal`)&&(p=!0,l[e]=l[e].slice(0,-8));let c,f;if(e.arguments.length>1){const t=e.arguments[1].expression;"ObjectExpression"===t.type?f=t:"StringLiteral"===t.type&&(c=t.value)}if(e.arguments.length>2){const t=e.arguments[2].expression;"ObjectExpression"===t.type&&(f=t)}const y=f?t(f,"defaultValue"):void 0,g="string"==typeof y?y:c;for(let e=0;e<l.length;e++){let i,s=l[e];if(f){const e=t(f,"ns");"string"==typeof e&&(i=e)}!i&&r?.defaultNs&&(i=r.defaultNs);const a=this.config.extract.nsSeparator??":";if(!i&&a&&s.includes(a)){const e=s.split(a);i=e.shift(),s=e.join(a)}i||(i=this.config.extract.defaultNS);let o=s;if(r?.keyPrefix){const e=this.config.extract.keySeparator??".";o=`${r.keyPrefix}${e}${s}`}const u=e===l.length-1&&g||s;if(f){const e=n(f,"context");if("ConditionalExpression"===e?.value?.type){const t=this.resolvePossibleStringValues(e.value),n=this.config.extract.contextSeparator??"_";if(t.length>0){t.forEach(e=>{this.pluginContext.addKey({key:`${o}${n}${e}`,ns:i,defaultValue:u})}),this.pluginContext.addKey({key:o,ns:i,defaultValue:u});continue}}const r=t(f,"context");if("string"==typeof r&&r){const e=this.config.extract.contextSeparator??"_";this.pluginContext.addKey({key:`${o}${e}${r}`,ns:i,defaultValue:u});continue}const s=void 0!==t(f,"count"),a=!0===t(f,"ordinal");if(s||p){this.handlePluralKeys(o,i,f,a||p);continue}!0===t(f,"returnObjects")&&this.objectKeys.add(o)}this.pluginContext.addKey({key:o,ns:i,defaultValue:u})}}handlePluralKeys(e,n,i,r){try{const s=r?"ordinal":"cardinal",a=new Intl.PluralRules(this.config.extract?.primaryLanguage,{type:s}).resolvedOptions().pluralCategories,o=this.config.extract.pluralSeparator??"_",l=t(i,"defaultValue"),p=t(i,`defaultValue${o}other`),u=t(i,`defaultValue${o}ordinal${o}other`);for(const s of a){const a=t(i,r?`defaultValue${o}ordinal${o}${s}`:`defaultValue${o}${s}`);let c;c="string"==typeof a?a:"one"===s&&"string"==typeof l?l:r&&"string"==typeof u?u:r||"string"!=typeof p?"string"==typeof l?l:e:p;const f=r?`${e}${o}ordinal${o}${s}`:`${e}${o}${s}`;this.pluginContext.addKey({key:f,ns:n,defaultValue:c,hasCount:!0,isOrdinal:r})}}catch(r){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}". Falling back to simple key extraction.`);const s=t(i,"defaultValue");this.pluginContext.addKey({key:e,ns:n,defaultValue:"string"==typeof s?s:e})}}handleSimplePluralKeys(e,t,n){try{const i=new Intl.PluralRules(this.config.extract?.primaryLanguage).resolvedOptions().pluralCategories,r=this.config.extract.pluralSeparator??"_";for(const s of i)this.pluginContext.addKey({key:`${e}${r}${s}`,ns:n,defaultValue:t,hasCount:!0})}catch(i){this.logger.warn(`Could not determine plural rules for language "${this.config.extract?.primaryLanguage}".`),this.pluginContext.addKey({key:e,ns:n,defaultValue:t})}}handleJSXElement(t){const n=this.getElementName(t);if(n&&(this.config.extract.transComponents||["Trans"]).includes(n)){const n=e(t,this.config);if(n){if(!n.ns){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"t"===e.name.value);if("JSXAttribute"===e?.type&&"JSXExpressionContainer"===e.value?.type&&"Identifier"===e.value.expression.type){const t=e.value.expression.value,i=this.getVarFromScope(t);i?.defaultNs&&(n.ns=i.defaultNs)}}if(n.ns||(n.ns=this.config.extract.defaultNS),n.contextExpression){const e=this.resolvePossibleStringValues(n.contextExpression),t=this.config.extract.contextSeparator??"_";if(e.length>0){for(const i of e)this.pluginContext.addKey({key:`${n.key}${t}${i}`,ns:n.ns,defaultValue:n.defaultValue});"StringLiteral"!==n.contextExpression.type&&this.pluginContext.addKey(n)}}else if(n.hasCount){const e=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),i=!!e,r=n.optionsNode??{type:"ObjectExpression",properties:[],span:{start:0,end:0,ctxt:0}};r.properties.push({type:"KeyValueProperty",key:{type:"Identifier",value:"defaultValue",optional:!1,span:{start:0,end:0,ctxt:0}},value:{type:"StringLiteral",value:n.defaultValue,span:{start:0,end:0,ctxt:0}}}),this.handlePluralKeys(n.key,n.ns,r,i)}else this.pluginContext.addKey(n)}}}getElementName(e){if("Identifier"===e.opening.name.type)return e.opening.name.value;if("JSXMemberExpression"===e.opening.name.type){let t=e.opening.name;const n=[];for(;"JSXMemberExpression"===t.type;)"Identifier"===t.property.type&&n.unshift(t.property.value),t=t.object;return"Identifier"===t.type&&n.unshift(t.value),n.join(".")}}extractKeyFromSelector(e){let t=e.body;if("BlockStatement"===t.type){const e=t.stmts.find(e=>"ReturnStatement"===e.type);if("ReturnStatement"!==e?.type||!e.argument)return null;t=e.argument}let n=t;const i=[];for(;"MemberExpression"===n.type;){const e=n.property;if("Identifier"===e.type)i.unshift(e.value);else{if("Computed"!==e.type||"StringLiteral"!==e.expression.type)return null;i.unshift(e.expression.value)}n=n.object}if(i.length>0){const e=this.config.extract.keySeparator,t="string"==typeof e?e:".";return i.join(t)}return null}resolvePossibleStringValues(e){if("StringLiteral"===e.type)return[e.value];if("ConditionalExpression"===e.type){return[...this.resolvePossibleStringValues(e.consequent),...this.resolvePossibleStringValues(e.alternate)]}return"Identifier"===e.type&&e.value,[]}getUseTranslationConfig(e){const t=this.config.extract.useTranslationNames||["useTranslation"];for(const n of t){if("string"==typeof n&&n===e)return{name:e,nsArg:0,keyPrefixArg:1};if("object"==typeof n&&n.name===e)return{name:n.name,nsArg:n.nsArg??0,keyPrefixArg:n.keyPrefixArg??1}}}getFunctionName(e){if("Identifier"===e.type)return e.value;if("MemberExpression"===e.type){const t=[];let n=e;for(;"MemberExpression"===n.type;){if("Identifier"!==n.property.type)return null;t.unshift(n.property.value),n=n.object}if("ThisExpression"===n.type)t.unshift("this");else{if("Identifier"!==n.type)return null;t.unshift(n.value)}return t.join(".")}return null}}export{i as ASTVisitors};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.3.0",
3
+ "version": "1.5.0",
4
4
  "description": "A unified, high-performance i18next CLI.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.ts CHANGED
@@ -21,7 +21,7 @@ const program = new Command()
21
21
  program
22
22
  .name('i18next-cli')
23
23
  .description('A unified, high-performance i18next CLI.')
24
- .version('1.3.0')
24
+ .version('1.5.0')
25
25
 
26
26
  program
27
27
  .command('extract')
@@ -55,6 +55,10 @@ export async function runExtractor (
55
55
  config.extract.primaryLanguage ||= config.locales[0] || 'en'
56
56
  config.extract.secondaryLanguages ||= config.locales.filter((l: string) => l !== config?.extract?.primaryLanguage)
57
57
 
58
+ // Ensure default function and component names are set if not provided.
59
+ config.extract.functions ||= ['t']
60
+ config.extract.transComponents ||= ['Trans']
61
+
58
62
  validateExtractorConfig(config)
59
63
 
60
64
  const spinner = ora('Running i18next key extractor...\n').start()
@@ -83,6 +87,14 @@ export async function runExtractor (
83
87
  }
84
88
  }
85
89
 
90
+ // Run afterSync hooks from plugins
91
+ if ((config.plugins || []).length > 0) {
92
+ spinner.text = 'Running post-extraction plugins...'
93
+ for (const plugin of (config.plugins || [])) {
94
+ await plugin.afterSync?.(results, config)
95
+ }
96
+ }
97
+
86
98
  spinner.succeed(chalk.bold('Extraction complete!'))
87
99
 
88
100
  // Show the funnel message only if files were actually changed.
@@ -1,5 +1,6 @@
1
1
  import { TranslationResult, ExtractedKey, I18nextToolkitConfig } from '../../types'
2
- import { resolve } from 'node:path'
2
+ import { resolve, basename, extname } from 'node:path'
3
+ import { glob } from 'glob'
3
4
  import { getNestedValue, setNestedValue, getNestedKeys } from '../../utils/nested-object'
4
5
  import { getOutputPath, loadTranslationFile } from '../../utils/file-utils'
5
6
 
@@ -14,32 +15,118 @@ function globToRegex (glob: string): RegExp {
14
15
  return new RegExp(regexString)
15
16
  }
16
17
 
18
+ /**
19
+ * A helper function to build a new translation object for a single namespace.
20
+ * This centralizes the core logic of merging keys.
21
+ */
22
+ function buildNewTranslationsForNs (
23
+ nsKeys: ExtractedKey[],
24
+ existingTranslations: Record<string, any>,
25
+ config: I18nextToolkitConfig,
26
+ locale: string,
27
+ preservePatterns: RegExp[],
28
+ objectKeys: Set<string>
29
+ ): Record<string, any> {
30
+ const {
31
+ keySeparator = '.',
32
+ sort = true,
33
+ removeUnusedKeys = true,
34
+ primaryLanguage,
35
+ defaultValue: emptyDefaultValue = '',
36
+ } = config.extract
37
+
38
+ // If `removeUnusedKeys` is true, start with an empty object. Otherwise, start with a clone of the existing translations.
39
+ let newTranslations: Record<string, any> = removeUnusedKeys
40
+ ? {}
41
+ : JSON.parse(JSON.stringify(existingTranslations))
42
+
43
+ // Preserve keys that match the configured patterns
44
+ const existingKeys = getNestedKeys(existingTranslations, keySeparator ?? '.')
45
+ for (const existingKey of existingKeys) {
46
+ if (preservePatterns.some(re => re.test(existingKey))) {
47
+ const value = getNestedValue(existingTranslations, existingKey, keySeparator ?? '.')
48
+ setNestedValue(newTranslations, existingKey, value, keySeparator ?? '.')
49
+ }
50
+ }
51
+
52
+ // 1. Build the object first, without any sorting.
53
+ for (const { key, defaultValue } of nsKeys) {
54
+ const existingValue = getNestedValue(existingTranslations, key, keySeparator ?? '.')
55
+ const isLeafInNewKeys = !nsKeys.some(otherKey => otherKey.key.startsWith(`${key}${keySeparator}`) && otherKey.key !== key)
56
+ const isStaleObject = typeof existingValue === 'object' && existingValue !== null && isLeafInNewKeys && !objectKeys.has(key)
57
+
58
+ const valueToSet = (existingValue === undefined || isStaleObject)
59
+ ? (locale === primaryLanguage ? defaultValue : emptyDefaultValue)
60
+ : existingValue
61
+
62
+ setNestedValue(newTranslations, key, valueToSet, keySeparator ?? '.')
63
+ }
64
+
65
+ // 2. If sorting is enabled, create a new sorted object from the one we just built.
66
+ if (sort !== false) {
67
+ const sortedObject: Record<string, any> = {}
68
+ const topLevelKeys = Object.keys(newTranslations)
69
+
70
+ // Create a map of top-level keys to a representative ExtractedKey object.
71
+ // This is needed for the custom sort function.
72
+ const keyMap = new Map<string, ExtractedKey>()
73
+ for (const ek of nsKeys) {
74
+ const topLevelKey = keySeparator === false ? ek.key : ek.key.split(keySeparator as string)[0]
75
+ if (!keyMap.has(topLevelKey)) {
76
+ keyMap.set(topLevelKey, ek)
77
+ }
78
+ }
79
+
80
+ topLevelKeys.sort((a, b) => {
81
+ if (typeof sort === 'function') {
82
+ const keyA = keyMap.get(a)
83
+ const keyB = keyMap.get(b)
84
+ // If we can find both original keys, use the custom comparator.
85
+ if (keyA && keyB) {
86
+ return sort(keyA, keyB)
87
+ }
88
+ }
89
+ // Fallback to default alphabetical sort for `sort: true` or if keys can't be mapped.
90
+ return a.localeCompare(b)
91
+ })
92
+
93
+ // 3. Rebuild the object in the final sorted order.
94
+ for (const key of topLevelKeys) {
95
+ sortedObject[key] = newTranslations[key]
96
+ }
97
+ newTranslations = sortedObject
98
+ }
99
+
100
+ return newTranslations
101
+ }
102
+
17
103
  /**
18
104
  * Processes extracted translation keys and generates translation files for all configured locales.
19
105
  *
20
106
  * This function:
21
107
  * 1. Groups keys by namespace
22
108
  * 2. For each locale and namespace combination:
23
- * - Reads existing translation files
24
- * - Preserves keys matching `preservePatterns`
25
- * - Merges in newly extracted keys
26
- * - Uses primary language defaults or empty strings for secondary languages
27
- * - Maintains key sorting based on configuration
109
+ * - Reads existing translation files
110
+ * - Preserves keys matching `preservePatterns` and those from `objectKeys`
111
+ * - Merges in newly extracted keys
112
+ * - Uses primary language defaults or empty strings for secondary languages
113
+ * - Maintains key sorting based on configuration
28
114
  * 3. Determines if files need updating by comparing content
29
115
  *
30
- * @param keys - Map of extracted translation keys with metadata
31
- * @param config - The i18next toolkit configuration object
32
- * @returns Promise resolving to array of translation results with update status
116
+ * @param keys - Map of extracted translation keys with metadata.
117
+ * @param objectKeys - A set of base keys that were called with the `returnObjects: true` option.
118
+ * @param config - The i18next toolkit configuration object.
119
+ * @returns Promise resolving to array of translation results with update status.
33
120
  *
34
121
  * @example
35
122
  * ```typescript
36
123
  * const keys = new Map([
37
- * ['translation:welcome', { key: 'welcome', defaultValue: 'Welcome!', ns: 'translation' }],
38
- * ['common:button.save', { key: 'button.save', defaultValue: 'Save', ns: 'common' }]
39
- * ])
124
+ * ['translation:welcome', { key: 'welcome', defaultValue: 'Welcome!', ns: 'translation' }],
125
+ * ]);
126
+ * const objectKeys = new Set(['countries']);
40
127
  *
41
- * const results = await getTranslations(keys, config)
42
- * // Results contain update status and new/existing translations for each locale
128
+ * const results = await getTranslations(keys, objectKeys, config);
129
+ * // Results contain update status and new/existing translations for each locale.
43
130
  * ```
44
131
  */
45
132
  export async function getTranslations (
@@ -49,13 +136,9 @@ export async function getTranslations (
49
136
  ): Promise<TranslationResult[]> {
50
137
  config.extract.primaryLanguage ||= config.locales[0] || 'en'
51
138
  config.extract.secondaryLanguages ||= config.locales.filter((l: string) => l !== config?.extract?.primaryLanguage)
52
- const primaryLanguage = config.extract.primaryLanguage
53
139
  const defaultNS = config.extract.defaultNS ?? 'translation'
54
- const keySeparator = config.extract.keySeparator ?? '.'
55
140
  const patternsToPreserve = [...(config.extract.preservePatterns || [])]
56
- const mergeNamespaces = config.extract.mergeNamespaces ?? false
57
141
  const indentation = config.extract.indentation ?? 2
58
- const removeUnusedKeys = config.extract.removeUnusedKeys ?? true
59
142
 
60
143
  for (const key of objectKeys) {
61
144
  // Convert the object key to a glob pattern to preserve all its children
@@ -72,61 +155,59 @@ export async function getTranslations (
72
155
  }
73
156
 
74
157
  const results: TranslationResult[] = []
158
+ const userIgnore = Array.isArray(config.extract.ignore)
159
+ ? config.extract.ignore
160
+ : config.extract.ignore ? [config.extract.ignore] : []
75
161
 
162
+ // Process each locale one by one
76
163
  for (const locale of config.locales) {
77
- const existingMergedFile = mergeNamespaces
78
- ? await loadTranslationFile(resolve(process.cwd(), getOutputPath(config.extract.output, locale))) || {}
79
- : null
80
-
81
- const newMergedTranslations: Record<string, any> = {}
164
+ const shouldMerge = config.extract.mergeNamespaces || !config.extract.output.includes('{{namespace}}')
82
165
 
83
- for (const [ns, nsKeys] of keysByNS.entries()) {
84
- const outputPath = getOutputPath(config.extract.output, locale, mergeNamespaces ? undefined : ns)
166
+ // LOGIC PATH 1: Merged Namespaces
167
+ if (shouldMerge) {
168
+ const newMergedTranslations: Record<string, any> = {}
169
+ const outputPath = getOutputPath(config.extract.output, locale)
85
170
  const fullPath = resolve(process.cwd(), outputPath)
171
+ const existingMergedFile = await loadTranslationFile(fullPath) || {}
86
172
 
87
- const existingTranslations = mergeNamespaces
88
- ? existingMergedFile?.[ns] || {}
89
- : await loadTranslationFile(fullPath) || {}
90
-
91
- const newTranslations: Record<string, any> = removeUnusedKeys
92
- ? {}
93
- : JSON.parse(JSON.stringify(existingTranslations))
173
+ // The namespaces to process are from new keys AND the keys of the existing merged file
174
+ const namespacesToProcess = new Set([...keysByNS.keys(), ...Object.keys(existingMergedFile)])
94
175
 
95
- const existingKeys = getNestedKeys(existingTranslations, keySeparator)
96
- for (const existingKey of existingKeys) {
97
- if (preservePatterns.some(re => re.test(existingKey))) {
98
- const value = getNestedValue(existingTranslations, existingKey, keySeparator)
99
- setNestedValue(newTranslations, existingKey, value, keySeparator)
100
- }
176
+ for (const ns of namespacesToProcess) {
177
+ const nsKeys = keysByNS.get(ns) || []
178
+ const existingTranslations = existingMergedFile[ns] || {}
179
+ newMergedTranslations[ns] = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, preservePatterns, objectKeys)
101
180
  }
102
181
 
103
- const sortedKeys = config.extract.sort === false
104
- ? nsKeys
105
- : [...nsKeys].sort(typeof config.extract.sort === 'function'
106
- ? config.extract.sort
107
- : (a, b) => a.key.localeCompare(b.key))
108
- for (const { key, defaultValue } of sortedKeys) {
109
- const existingValue = getNestedValue(existingTranslations, key, keySeparator)
110
- const valueToSet = existingValue ?? (locale === primaryLanguage ? defaultValue : (config.extract.defaultValue ?? ''))
111
- setNestedValue(newTranslations, key, valueToSet, keySeparator)
182
+ const oldContent = JSON.stringify(existingMergedFile, null, indentation)
183
+ const newContent = JSON.stringify(newMergedTranslations, null, indentation)
184
+ // Push a single result for the merged file
185
+ results.push({ path: fullPath, updated: newContent !== oldContent, newTranslations: newMergedTranslations, existingTranslations: existingMergedFile })
186
+
187
+ // LOGIC PATH 2: Separate Namespace Files
188
+ } else {
189
+ // Find all namespaces that exist on disk for this locale
190
+ const namespacesToProcess = new Set(keysByNS.keys())
191
+ const existingNsPattern = getOutputPath(config.extract.output, locale, '*')
192
+ const existingNsFiles = await glob(existingNsPattern, { ignore: userIgnore })
193
+ for (const file of existingNsFiles) {
194
+ namespacesToProcess.add(basename(file, extname(file)))
112
195
  }
113
196
 
114
- if (mergeNamespaces) {
115
- newMergedTranslations[ns] = newTranslations
116
- } else {
197
+ // Process each namespace individually and create a result for each one
198
+ for (const ns of namespacesToProcess) {
199
+ const nsKeys = keysByNS.get(ns) || []
200
+ const outputPath = getOutputPath(config.extract.output, locale, ns)
201
+ const fullPath = resolve(process.cwd(), outputPath)
202
+ const existingTranslations = await loadTranslationFile(fullPath) || {}
203
+ const newTranslations = buildNewTranslationsForNs(nsKeys, existingTranslations, config, locale, preservePatterns, objectKeys)
204
+
117
205
  const oldContent = JSON.stringify(existingTranslations, null, indentation)
118
206
  const newContent = JSON.stringify(newTranslations, null, indentation)
207
+ // Push one result per namespace file
119
208
  results.push({ path: fullPath, updated: newContent !== oldContent, newTranslations, existingTranslations })
120
209
  }
121
210
  }
122
-
123
- if (mergeNamespaces) {
124
- const outputPath = getOutputPath(config.extract.output, locale)
125
- const fullPath = resolve(process.cwd(), outputPath)
126
- const oldContent = JSON.stringify(existingMergedFile, null, indentation)
127
- const newContent = JSON.stringify(newMergedTranslations, null, indentation)
128
- results.push({ path: fullPath, updated: newContent !== oldContent, newTranslations: newMergedTranslations, existingTranslations: existingMergedFile || {} })
129
- }
130
211
  }
131
212
 
132
213
  return results
@@ -373,7 +373,25 @@ export class ASTVisitors {
373
373
 
374
374
  // The scope lookup will only work for simple identifiers, which is okay for this fix.
375
375
  const scopeInfo = this.getVarFromScope(functionName)
376
- const isFunctionToParse = (this.config.extract.functions || ['t']).includes(functionName) || scopeInfo !== undefined
376
+ const configuredFunctions = this.config.extract.functions || ['t']
377
+ let isFunctionToParse = scopeInfo !== undefined // A scoped variable (from useTranslation, etc.) is always parsed.
378
+ if (!isFunctionToParse) {
379
+ for (const pattern of configuredFunctions) {
380
+ if (pattern.startsWith('*.')) {
381
+ // Handle wildcard suffix (e.g., '*.t' matches 'i18n.t')
382
+ if (functionName.endsWith(pattern.substring(1))) {
383
+ isFunctionToParse = true
384
+ break
385
+ }
386
+ } else {
387
+ // Handle exact match
388
+ if (pattern === functionName) {
389
+ isFunctionToParse = true
390
+ break
391
+ }
392
+ }
393
+ }
394
+ }
377
395
  if (!isFunctionToParse || node.arguments.length === 0) return
378
396
 
379
397
  const firstArg = node.arguments[0].expression
@@ -883,7 +901,10 @@ export class ASTVisitors {
883
901
  }
884
902
  current = current.object
885
903
  }
886
- if (current.type === 'Identifier') {
904
+ // Handle `this` as the base of the expression (e.g., this._i18n.t)
905
+ if (current.type === 'ThisExpression') {
906
+ parts.unshift('this')
907
+ } else if (current.type === 'Identifier') {
887
908
  parts.unshift(current.value)
888
909
  } else {
889
910
  return null // Base of the expression is not a simple identifier
package/src/types.ts CHANGED
@@ -228,6 +228,15 @@ export interface Plugin {
228
228
  * @param keys - Final map of all extracted keys
229
229
  */
230
230
  onEnd?: (keys: Map<string, { key: string; defaultValue?: string }>) => void | Promise<void>;
231
+
232
+ /**
233
+ * Hook called after all files have been processed and translation files have been generated.
234
+ * Useful for post-processing, validation, or reporting based on the final results.
235
+ *
236
+ * @param results - Array of translation results with update status and content.
237
+ * @param config - The i18next toolkit configuration object.
238
+ */
239
+ afterSync?: (results: TranslationResult[], config: I18nextToolkitConfig) => void | Promise<void>;
231
240
  }
232
241
 
233
242
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"extractor.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/extractor.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,MAAM,EAAE,YAAY,EAAiB,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAM5F,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAMrD;;;;;;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,CAAC,EAClC,WAAW,EAAE,WAAW,EACxB,MAAM,GAAE,MAA4B,GACnC,OAAO,CAAC,IAAI,CAAC,CA8Bf;AAmCD;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,OAAO,CAAE,MAAM,EAAE,oBAAoB,sDAO1D"}
@@ -5,26 +5,27 @@ import { TranslationResult, ExtractedKey, I18nextToolkitConfig } from '../../typ
5
5
  * This function:
6
6
  * 1. Groups keys by namespace
7
7
  * 2. For each locale and namespace combination:
8
- * - Reads existing translation files
9
- * - Preserves keys matching `preservePatterns`
10
- * - Merges in newly extracted keys
11
- * - Uses primary language defaults or empty strings for secondary languages
12
- * - Maintains key sorting based on configuration
8
+ * - Reads existing translation files
9
+ * - Preserves keys matching `preservePatterns` and those from `objectKeys`
10
+ * - Merges in newly extracted keys
11
+ * - Uses primary language defaults or empty strings for secondary languages
12
+ * - Maintains key sorting based on configuration
13
13
  * 3. Determines if files need updating by comparing content
14
14
  *
15
- * @param keys - Map of extracted translation keys with metadata
16
- * @param config - The i18next toolkit configuration object
17
- * @returns Promise resolving to array of translation results with update status
15
+ * @param keys - Map of extracted translation keys with metadata.
16
+ * @param objectKeys - A set of base keys that were called with the `returnObjects: true` option.
17
+ * @param config - The i18next toolkit configuration object.
18
+ * @returns Promise resolving to array of translation results with update status.
18
19
  *
19
20
  * @example
20
21
  * ```typescript
21
22
  * const keys = new Map([
22
- * ['translation:welcome', { key: 'welcome', defaultValue: 'Welcome!', ns: 'translation' }],
23
- * ['common:button.save', { key: 'button.save', defaultValue: 'Save', ns: 'common' }]
24
- * ])
23
+ * ['translation:welcome', { key: 'welcome', defaultValue: 'Welcome!', ns: 'translation' }],
24
+ * ]);
25
+ * const objectKeys = new Set(['countries']);
25
26
  *
26
- * const results = await getTranslations(keys, config)
27
- * // Results contain update status and new/existing translations for each locale
27
+ * const results = await getTranslations(keys, objectKeys, config);
28
+ * // Results contain update status and new/existing translations for each locale.
28
29
  * ```
29
30
  */
30
31
  export declare function getTranslations(keys: Map<string, ExtractedKey>, objectKeys: Set<string>, config: I18nextToolkitConfig): Promise<TranslationResult[]>;
@@ -1 +1 @@
1
- {"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAgBnF;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,GAC3B,OAAO,CAAC,iBAAiB,EAAE,CAAC,CAoF9B"}
1
+ {"version":3,"file":"translation-manager.d.ts","sourceRoot":"","sources":["../../../src/extractor/core/translation-manager.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,YAAY,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAsGnF;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,wBAAsB,eAAe,CACnC,IAAI,EAAE,GAAG,CAAC,MAAM,EAAE,YAAY,CAAC,EAC/B,UAAU,EAAE,GAAG,CAAC,MAAM,CAAC,EACvB,MAAM,EAAE,oBAAoB,GAC3B,OAAO,CAAC,iBAAiB,EAAE,CAAC,CA8E9B"}
@@ -1 +1 @@
1
- {"version":3,"file":"ast-visitors.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/ast-visitors.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAA+G,MAAM,WAAW,CAAA;AACpJ,OAAO,KAAK,EAAE,aAAa,EAAE,oBAAoB,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAqB9E;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,QAAQ,CAAC,aAAa,CAAe;IAC7C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;;OAeG;IACH,OAAO,CAAC,sBAAsB;IA2C9B;;;;;;;;;;;;;;;OAeG;IACH,OAAO,CAAC,2BAA2B;IAmBnC;;;;;;OAMG;IACH,OAAO,CAAC,uBAAuB;IAoB/B;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4BG;IACH,OAAO,CAAC,eAAe;CA2BxB"}
package/types/types.d.ts CHANGED
@@ -190,6 +190,14 @@ export interface Plugin {
190
190
  key: string;
191
191
  defaultValue?: string;
192
192
  }>) => void | Promise<void>;
193
+ /**
194
+ * Hook called after all files have been processed and translation files have been generated.
195
+ * Useful for post-processing, validation, or reporting based on the final results.
196
+ *
197
+ * @param results - Array of translation results with update status and content.
198
+ * @param config - The i18next toolkit configuration object.
199
+ */
200
+ afterSync?: (results: TranslationResult[], config: I18nextToolkitConfig) => void | Promise<void>;
193
201
  }
194
202
  /**
195
203
  * Represents an extracted translation key with its metadata.
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,IAAI,EAAE,UAAU,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AAEnE;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,MAAM,WAAW,oBAAoB;IACnC,iEAAiE;IACjE,OAAO,EAAE,MAAM,EAAE,CAAC;IAElB,2DAA2D;IAC3D,OAAO,EAAE;QACP,oEAAoE;QACpE,KAAK,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;QAEzB,4DAA4D;QAC5D,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,EAAE,CAAC;QAE3B,mGAAmG;QACnG,MAAM,EAAE,MAAM,CAAC;QAEf,wEAAwE;QACxE,SAAS,CAAC,EAAE,MAAM,CAAC;QAEnB,uEAAuE;QACvE,YAAY,CAAC,EAAE,MAAM,GAAG,KAAK,GAAG,IAAI,CAAC;QAErC,8EAA8E;QAC9E,WAAW,CAAC,EAAE,MAAM,GAAG,KAAK,G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