i18next-cli 1.11.5 → 1.11.6

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,10 @@ 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.11.6](https://github.com/i18next/i18next-cli/compare/v1.11.5...v1.11.6) - 2025-10-19
9
+
10
+ - Fix Trans child indexing to match react-i18next and handle layout-only whitespace correctly [#63](https://github.com/i18next/i18next-cli/issues/63)
11
+
8
12
  ## [1.11.5](https://github.com/i18next/i18next-cli/compare/v1.11.4...v1.11.5) - 2025-10-17
9
13
 
10
14
  - **Extractor:** ignore formatting-only JSXText nodes when serializing <Trans> children to avoid inflated component placeholder indexes and incorrect keys caused by indentation/newlines — fixes [#66](https://github.com/i18next/i18next-cli/issues/66)
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.11.5"),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.").option("--sync-primary","Sync primary language values with default values from code.").action(async e=>{try{const o=await i.ensureConfig(),a=async()=>{const t=await r.runExtractor(o,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}catch(e){console.error("Error running extractor:",e),process.exit(1)}}),f.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,t)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const o=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await l.runMigrator(e)}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
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.11.6"),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.").option("--sync-primary","Sync primary language values with default values from code.").action(async e=>{try{const o=await i.ensureConfig(),a=async()=>{const t=await r.runExtractor(o,{isWatchMode:!!e.watch,isDryRun:!!e.dryRun,syncPrimaryWithDefaults:!!e.syncPrimary});return e.ci&&!t?(console.log("✅ No files were updated."),process.exit(0)):e.ci&&t&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),t};if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}catch(e){console.error("Error running extractor:",e),process.exit(1)}}),f.command("status [locale]").description("Display translation status. Provide a locale for a detailed key-by-key view.").option("-n, --namespace <ns>","Filter the status report by a specific namespace").action(async(e,t)=>{let n=await i.loadConfig();if(!n){console.log(o.blue("No config file found. Attempting to detect project structure..."));const e=await a.detectConfig();e||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),n=e}await g.runStatus(n,{detail:e,namespace:t.namespace})}),f.command("types").description("Generate TypeScript definitions from translation resource files.").option("-w, --watch","Watch for file changes and re-run the type generator.").action(async e=>{const o=await i.ensureConfig(),a=()=>c.runTypesGenerator(o);if(await a(),e.watch){console.log("\nWatching for changes...");t.watch(await n.glob(o.types?.input||[]),{persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),a()})}}),f.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const e=await i.ensureConfig();await s.runSyncer(e)}),f.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async e=>{await l.runMigrator(e)}),f.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(u.runInit),f.command("lint").description("Find potential issues like hardcoded strings in your codebase.").option("-w, --watch","Watch for file changes and re-run the linter.").action(async e=>{const r=async()=>{let e=await i.loadConfig();if(!e){console.log(o.blue("No config file found. Attempting to detect project structure..."));const t=await a.detectConfig();t||(console.error(o.red("Could not automatically detect your project structure.")),console.log(`Please create a config file first by running: ${o.cyan("npx i18next-cli init")}`),process.exit(1)),console.log(o.green("Project structure detected successfully!")),e=t}await d.runLinter(e)};if(await r(),e.watch){console.log("\nWatching for changes...");const e=await i.loadConfig();if(e?.extract?.input){t.watch(await n.glob(e.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",e=>{console.log(`\nFile changed: ${e}`),r()})}}}),f.command("locize-sync").description("Synchronize local translations with your locize project.").option("--update-values","Update values of existing translations on locize.").option("--src-lng-only","Check for changes in source language only.").option("--compare-mtime","Compare modification times when syncing.").option("--dry-run","Run the command without making any changes.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeSync(t,e)}),f.command("locize-download").description("Download all translations from your locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeDownload(t,e)}),f.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async e=>{const t=await i.ensureConfig();await p.runLocizeMigrate(t,e)}),f.parse(process.argv);
@@ -1 +1 @@
1
- "use strict";var e=require("./ast-utils.js");exports.extractFromTransComponent=function(t,n){const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),r=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),a=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),p=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let s;a||"JSXAttribute"!==p?.type||"JSXExpressionContainer"!==p.value?.type||"ObjectExpression"!==p.value.expression.type||(s=e.getObjectProperty(p.value.expression,"count"));const o=!!a||!!s,l=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),u="JSXAttribute"===l?.type&&"JSXExpressionContainer"===l.value?.type&&"ObjectExpression"===l.value.expression.type?l.value.expression:void 0,y=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),f=!!y,v=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let c="JSXAttribute"===v?.type&&"JSXExpressionContainer"===v.value?.type?v.value.expression:"JSXAttribute"===v?.type&&"StringLiteral"===v.value?.type?v.value:void 0;const d=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let m;if(m="JSXAttribute"===d?.type&&"StringLiteral"===d.value?.type?d.value.value:void 0,u&&(void 0===m&&(m=e.getObjectPropValue(u,"ns")),void 0===c)){const t=e.getObjectProperty(u,"context");t?.value&&(c=t.value)}const S=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),i=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n"),r={n:0};function a(e){if(!e||!e.length)return"";let t="";for(const p of e)if(p)if("JSXText"!==p.type){if("JSXExpressionContainer"===p.type){const e=p.expression;if(!e)continue;if("StringLiteral"===e.type)t+=e.value;else if("Identifier"===e.type)t+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const n=e.properties[0];n&&"KeyValueProperty"===n.type&&n.key&&"Identifier"===n.key.type?t+=`{{${n.key.value}}}`:n&&"Identifier"===n.type&&(t+=`{{${n.value}}}`)}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?t+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type&&(t+=`{{${e.callee.value}}}`);r.n++;continue}if("JSXElement"===p.type){let e;if(p.opening&&p.opening.name&&"Identifier"===p.opening.name.type&&(e=p.opening.name.value),e&&n.has(e)){t+=`<${e}>${a(p.children||[])}</${e}>`}else{const e=r.n;r.n++;t+=`<${e}>${a(p.children||[])}</${e}>`}continue}"JSXFragment"!==p.type||(t+=a(p.children||[]))}else i(p)||(t+=p.value,r.n++);return t}const p=a(e);return String(p).replace(/\s+/g," ").trim()}(t.children,n);let g,b,x;if("JSXAttribute"===r?.type&&"StringLiteral"===r.value?.type)g=r.value.value;else{const e=n.extract.defaultValue;g="string"==typeof e?e:""}if("JSXAttribute"===i?.type){if("StringLiteral"===i.value?.type){if(b=i.value,x=b.value,!x||""===x.trim())return console.warn("Ignoring Trans component with empty i18nKey"),null;if(m&&"StringLiteral"===b.type){const e=n.extract.nsSeparator??":",t=b.value;if(e&&t.startsWith(`${m}${e}`)){if(x=t.slice(`${m}${e}`.length),!x||""===x.trim())return console.warn("Ignoring Trans component with i18nKey that becomes empty after namespace removal"),null;b={...b,value:x}}}}else"JSXExpressionContainer"===i.value?.type&&"JSXEmptyExpression"!==i.value.expression.type&&(b=i.value.expression);if(!b)return null}return r||!x||S.trim()?!r&&S.trim()&&(g=S):g=x,{keyExpression:b,serializedChildren:S,ns:m,defaultValue:g,hasCount:o,isOrdinal:f,contextExpression:c,optionsNode:u}};
1
+ "use strict";var e=require("./ast-utils.js");exports.extractFromTransComponent=function(t,n){const i=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),r=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),p=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),s=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let o;p||"JSXAttribute"!==s?.type||"JSXExpressionContainer"!==s.value?.type||"ObjectExpression"!==s.value.expression.type||(o=e.getObjectProperty(s.value.expression,"count"));const a=!!p||!!o,l=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),u="JSXAttribute"===l?.type&&"JSXExpressionContainer"===l.value?.type&&"ObjectExpression"===l.value.expression.type?l.value.expression:void 0,y=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),f=!!y,c=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let v="JSXAttribute"===c?.type&&"JSXExpressionContainer"===c.value?.type?c.value.expression:"JSXAttribute"===c?.type&&"StringLiteral"===c.value?.type?c.value:void 0;const S=t.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let x;if(x="JSXAttribute"===S?.type&&"StringLiteral"===S.value?.type?S.value.value:void 0,u&&(void 0===x&&(x=e.getObjectPropValue(u,"ns")),void 0===v)){const t=e.getObjectProperty(u,"context");t?.value&&(v=t.value)}const d=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),i=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n");function r(e,t,p=!1){if(!e||!e.length)return;let s=0,o=e.length-1;for(;s<=o&&i(e[s]);)s++;for(;o>=s&&i(e[o]);)o--;const a=s<=o?e.slice(s,o+1):[];for(let e=0;e<a.length;e++){const s=a[e];if(s)if("JSXText"!==s.type)if("JSXExpressionContainer"!==s.type){if("JSXElement"===s.type){const e=s.opening&&s.opening.name&&"Identifier"===s.opening.name.type?s.opening.name.value:void 0;e&&n.has(e)?r(s.children||[],t,!1):(t.push(s),r(s.children||[],t,!0));continue}"JSXFragment"!==s.type||r(s.children||[],t,p)}else{if(p&&s.expression&&"ObjectExpression"===s.expression.type){const e=s.expression.properties&&s.expression.properties[0];if(e&&"KeyValueProperty"===e.type)continue}if(s.expression&&"StringLiteral"===s.expression.type){const n=String(s.expression.value||""),r=/^\s*$/.test(n)&&!n.includes("\n"),p=a[e-1],o=a[e+1];if(r){const n=a[e+2];if(o&&"JSXText"===o.type&&i(o)&&n&&("JSXElement"===n.type||"JSXFragment"===n.type)){const t=a[e-1],n=a[e-2];if(!t||"JSXText"!==t.type||n&&"JSXExpressionContainer"===n.type)continue}if(p&&("JSXElement"===p.type||"JSXFragment"===p.type)&&o&&"JSXText"===o.type&&i(o))continue;const r=!o||"JSXText"===o.type&&!i(o);if(p&&"JSXText"===p.type&&r){const e=t[t.length-1];if(e&&"JSXText"===e.type){e.value=String(e.value)+s.expression.value;continue}}if(p&&("JSXElement"===p.type||"JSXFragment"===p.type)&&o&&"JSXText"===o.type&&i(o))continue}}t.push(s)}else{if(i(s)){const n=t[t.length-1],i=a[e-1];if(n){if(i&&"JSXExpressionContainer"===i.type)continue;if("JSXText"===n.type&&i&&"JSXText"===i.type){n.value=String(n.value)+s.value;continue}}}t.push(s)}}}const p=[];function s(e){if(!e||0===e.length)return"";let t="";for(const r of e)if(r)if("JSXText"!==r.type){if("JSXExpressionContainer"===r.type){const e=r.expression;if(!e)continue;if("StringLiteral"===e.type)t+=e.value;else if("Identifier"===e.type)t+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const n=e.properties[0];n&&"KeyValueProperty"===n.type&&n.key&&"Identifier"===n.key.type?t+=`{{${n.key.value}}}`:n&&"Identifier"===n.type?t+=`{{${n.value}}}`:t+="{{value}}"}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?t+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type?t+=`{{${e.callee.value}}}`:t+="{{value}}";continue}if("JSXElement"===r.type){let e;if(r.opening&&r.opening.name&&"Identifier"===r.opening.name.type&&(e=r.opening.name.value),e&&n.has(e)){t+=`<${e}>${s(r.children||[])}</${e}>`}else{const e=p.indexOf(r);t+=`<${e}>${s(r.children||[])}</${e}>`}continue}"JSXFragment"!==r.type||(t+=s(r.children||[]))}else i(r)||(t+=r.value);return t}r(e,p,!1);const o=s(e);return String(o).replace(/\s+/g," ").trim()}(t.children,n);let g,J,X;if("JSXAttribute"===r?.type&&"StringLiteral"===r.value?.type)g=r.value.value;else{const e=n.extract.defaultValue;g="string"==typeof e?e:""}if("JSXAttribute"===i?.type){if("StringLiteral"===i.value?.type){if(J=i.value,X=J.value,!X||""===X.trim())return null;if(x&&"StringLiteral"===J.type){const e=n.extract.nsSeparator??":",t=J.value;if(e&&t.startsWith(`${x}${e}`)){if(X=t.slice(`${x}${e}`.length),!X||""===X.trim())return null;J={...J,value:X}}}}else"JSXExpressionContainer"===i.value?.type&&"JSXEmptyExpression"!==i.value.expression.type&&(J=i.value.expression);if(!J)return null}return r||!X||d.trim()?!r&&d.trim()&&(g=d):g=X,{keyExpression:J,serializedChildren:d,ns:x,defaultValue:g,hasCount:a,isOrdinal:f,contextExpression:v,optionsNode:u}};
package/dist/esm/cli.js CHANGED
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- import{Command as t}from"commander";import e from"chokidar";import{glob as o}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 p}from"./migrator.js";import{runInit as m}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as u}from"./status.js";import{runLocizeSync as f,runLocizeDownload as g,runLocizeMigrate as h}from"./locize.js";const y=new t;y.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.11.5"),y.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").action(async t=>{try{const n=await i(),a=async()=>{const e=await r(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!e?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&e&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),e};if(await a(),t.watch){console.log("\nWatching for changes...");e.watch(await o(n.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),y.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,e)=>{let o=await a();if(!o){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!")),o=t}await u(o,{detail:t,namespace:e.namespace})}),y.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...");e.watch(await o(n.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),y.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await i();await l(t)}),y.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await p(t)}),y.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(m),y.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 e=await c();e||(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=e}await d(t)};if(await i(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){e.watch(await o(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),i()})}}}),y.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 e=await i();await f(e,t)}),y.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const e=await i();await g(e,t)}),y.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const e=await i();await h(e,t)}),y.parse(process.argv);
2
+ import{Command as t}from"commander";import e from"chokidar";import{glob as o}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 p}from"./migrator.js";import{runInit as m}from"./init.js";import{runLinter as d}from"./linter.js";import{runStatus as u}from"./status.js";import{runLocizeSync as f,runLocizeDownload as g,runLocizeMigrate as h}from"./locize.js";const y=new t;y.name("i18next-cli").description("A unified, high-performance i18next CLI.").version("1.11.6"),y.command("extract").description("Extract translation keys from source files and update resource files.").option("-w, --watch","Watch for file changes and re-run the extractor.").option("--ci","Exit with a non-zero status code if any files are updated.").option("--dry-run","Run the extractor without writing any files to disk.").option("--sync-primary","Sync primary language values with default values from code.").action(async t=>{try{const n=await i(),a=async()=>{const e=await r(n,{isWatchMode:!!t.watch,isDryRun:!!t.dryRun,syncPrimaryWithDefaults:!!t.syncPrimary});return t.ci&&!e?(console.log("✅ No files were updated."),process.exit(0)):t.ci&&e&&(console.error("❌ Some files were updated. This should not happen in CI mode."),process.exit(1)),e};if(await a(),t.watch){console.log("\nWatching for changes...");e.watch(await o(n.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}catch(t){console.error("Error running extractor:",t),process.exit(1)}}),y.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,e)=>{let o=await a();if(!o){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!")),o=t}await u(o,{detail:t,namespace:e.namespace})}),y.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...");e.watch(await o(n.types?.input||[]),{persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),a()})}}),y.command("sync").description("Synchronize secondary language files with the primary language file.").action(async()=>{const t=await i();await l(t)}),y.command("migrate-config [configPath]").description("Migrate a legacy i18next-parser.config.js to the new format.").action(async t=>{await p(t)}),y.command("init").description("Create a new i18next.config.ts/js file with an interactive setup wizard.").action(m),y.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 e=await c();e||(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=e}await d(t)};if(await i(),t.watch){console.log("\nWatching for changes...");const t=await a();if(t?.extract?.input){e.watch(await o(t.extract.input),{ignored:/node_modules/,persistent:!0}).on("change",t=>{console.log(`\nFile changed: ${t}`),i()})}}}),y.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 e=await i();await f(e,t)}),y.command("locize-download").description("Download all translations from your locize project.").action(async t=>{const e=await i();await g(e,t)}),y.command("locize-migrate").description("Migrate local translation files to a new locize project.").action(async t=>{const e=await i();await h(e,t)}),y.parse(process.argv);
@@ -1 +1 @@
1
- import{getObjectProperty as e,getObjectPropValue as t}from"./ast-utils.js";function n(n,i){const r=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),a=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),p=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),s=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let l;p||"JSXAttribute"!==s?.type||"JSXExpressionContainer"!==s.value?.type||"ObjectExpression"!==s.value.expression.type||(l=e(s.value.expression,"count"));const o=!!p||!!l,u=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),y="JSXAttribute"===u?.type&&"JSXExpressionContainer"===u.value?.type&&"ObjectExpression"===u.value.expression.type?u.value.expression:void 0,f=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),v=!!f,c=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let d="JSXAttribute"===c?.type&&"JSXExpressionContainer"===c.value?.type?c.value.expression:"JSXAttribute"===c?.type&&"StringLiteral"===c.value?.type?c.value:void 0;const m=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let S;if(S="JSXAttribute"===m?.type&&"StringLiteral"===m.value?.type?m.value.value:void 0,y&&(void 0===S&&(S=t(y,"ns")),void 0===d)){const t=e(y,"context");t?.value&&(d=t.value)}const g=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),i=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n"),r={n:0};function a(e){if(!e||!e.length)return"";let t="";for(const p of e)if(p)if("JSXText"!==p.type){if("JSXExpressionContainer"===p.type){const e=p.expression;if(!e)continue;if("StringLiteral"===e.type)t+=e.value;else if("Identifier"===e.type)t+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const n=e.properties[0];n&&"KeyValueProperty"===n.type&&n.key&&"Identifier"===n.key.type?t+=`{{${n.key.value}}}`:n&&"Identifier"===n.type&&(t+=`{{${n.value}}}`)}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?t+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type&&(t+=`{{${e.callee.value}}}`);r.n++;continue}if("JSXElement"===p.type){let e;if(p.opening&&p.opening.name&&"Identifier"===p.opening.name.type&&(e=p.opening.name.value),e&&n.has(e)){t+=`<${e}>${a(p.children||[])}</${e}>`}else{const e=r.n;r.n++;t+=`<${e}>${a(p.children||[])}</${e}>`}continue}"JSXFragment"!==p.type||(t+=a(p.children||[]))}else i(p)||(t+=p.value,r.n++);return t}const p=a(e);return String(p).replace(/\s+/g," ").trim()}(n.children,i);let x,b,J;if("JSXAttribute"===a?.type&&"StringLiteral"===a.value?.type)x=a.value.value;else{const e=i.extract.defaultValue;x="string"==typeof e?e:""}if("JSXAttribute"===r?.type){if("StringLiteral"===r.value?.type){if(b=r.value,J=b.value,!J||""===J.trim())return console.warn("Ignoring Trans component with empty i18nKey"),null;if(S&&"StringLiteral"===b.type){const e=i.extract.nsSeparator??":",t=b.value;if(e&&t.startsWith(`${S}${e}`)){if(J=t.slice(`${S}${e}`.length),!J||""===J.trim())return console.warn("Ignoring Trans component with i18nKey that becomes empty after namespace removal"),null;b={...b,value:J}}}}else"JSXExpressionContainer"===r.value?.type&&"JSXEmptyExpression"!==r.value.expression.type&&(b=r.value.expression);if(!b)return null}return a||!J||g.trim()?!a&&g.trim()&&(x=g):x=J,{keyExpression:b,serializedChildren:g,ns:S,defaultValue:x,hasCount:o,isOrdinal:v,contextExpression:d,optionsNode:y}}export{n as extractFromTransComponent};
1
+ import{getObjectProperty as e,getObjectPropValue as t}from"./ast-utils.js";function n(n,i){const r=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"i18nKey"===e.name.value),p=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"defaults"===e.name.value),s=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"count"===e.name.value),o=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"values"===e.name.value);let a;s||"JSXAttribute"!==o?.type||"JSXExpressionContainer"!==o.value?.type||"ObjectExpression"!==o.value.expression.type||(a=e(o.value.expression,"count"));const l=!!s||!!a,u=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"tOptions"===e.name.value),y="JSXAttribute"===u?.type&&"JSXExpressionContainer"===u.value?.type&&"ObjectExpression"===u.value.expression.type?u.value.expression:void 0,f=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ordinal"===e.name.value),c=!!f,v=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"context"===e.name.value);let S="JSXAttribute"===v?.type&&"JSXExpressionContainer"===v.value?.type?v.value.expression:"JSXAttribute"===v?.type&&"StringLiteral"===v.value?.type?v.value:void 0;const x=n.opening.attributes?.find(e=>"JSXAttribute"===e.type&&"Identifier"===e.name.type&&"ns"===e.name.value);let d;if(d="JSXAttribute"===x?.type&&"StringLiteral"===x.value?.type?x.value.value:void 0,y&&(void 0===d&&(d=t(y,"ns")),void 0===S)){const t=e(y,"context");t?.value&&(S=t.value)}const J=function(e,t){if(!e||0===e.length)return"";const n=new Set(t.extract.transKeepBasicHtmlNodesFor??["br","strong","i","p"]),i=e=>e&&"JSXText"===e.type&&/^\s*$/.test(e.value)&&e.value.includes("\n");function r(e,t,p=!1){if(!e||!e.length)return;let s=0,o=e.length-1;for(;s<=o&&i(e[s]);)s++;for(;o>=s&&i(e[o]);)o--;const a=s<=o?e.slice(s,o+1):[];for(let e=0;e<a.length;e++){const s=a[e];if(s)if("JSXText"!==s.type)if("JSXExpressionContainer"!==s.type){if("JSXElement"===s.type){const e=s.opening&&s.opening.name&&"Identifier"===s.opening.name.type?s.opening.name.value:void 0;e&&n.has(e)?r(s.children||[],t,!1):(t.push(s),r(s.children||[],t,!0));continue}"JSXFragment"!==s.type||r(s.children||[],t,p)}else{if(p&&s.expression&&"ObjectExpression"===s.expression.type){const e=s.expression.properties&&s.expression.properties[0];if(e&&"KeyValueProperty"===e.type)continue}if(s.expression&&"StringLiteral"===s.expression.type){const n=String(s.expression.value||""),r=/^\s*$/.test(n)&&!n.includes("\n"),p=a[e-1],o=a[e+1];if(r){const n=a[e+2];if(o&&"JSXText"===o.type&&i(o)&&n&&("JSXElement"===n.type||"JSXFragment"===n.type)){const t=a[e-1],n=a[e-2];if(!t||"JSXText"!==t.type||n&&"JSXExpressionContainer"===n.type)continue}if(p&&("JSXElement"===p.type||"JSXFragment"===p.type)&&o&&"JSXText"===o.type&&i(o))continue;const r=!o||"JSXText"===o.type&&!i(o);if(p&&"JSXText"===p.type&&r){const e=t[t.length-1];if(e&&"JSXText"===e.type){e.value=String(e.value)+s.expression.value;continue}}if(p&&("JSXElement"===p.type||"JSXFragment"===p.type)&&o&&"JSXText"===o.type&&i(o))continue}}t.push(s)}else{if(i(s)){const n=t[t.length-1],i=a[e-1];if(n){if(i&&"JSXExpressionContainer"===i.type)continue;if("JSXText"===n.type&&i&&"JSXText"===i.type){n.value=String(n.value)+s.value;continue}}}t.push(s)}}}const p=[];function s(e){if(!e||0===e.length)return"";let t="";for(const r of e)if(r)if("JSXText"!==r.type){if("JSXExpressionContainer"===r.type){const e=r.expression;if(!e)continue;if("StringLiteral"===e.type)t+=e.value;else if("Identifier"===e.type)t+=`{{${e.value}}}`;else if("ObjectExpression"===e.type){const n=e.properties[0];n&&"KeyValueProperty"===n.type&&n.key&&"Identifier"===n.key.type?t+=`{{${n.key.value}}}`:n&&"Identifier"===n.type?t+=`{{${n.value}}}`:t+="{{value}}"}else"MemberExpression"===e.type&&e.property&&"Identifier"===e.property.type?t+=`{{${e.property.value}}}`:"CallExpression"===e.type&&"Identifier"===e.callee?.type?t+=`{{${e.callee.value}}}`:t+="{{value}}";continue}if("JSXElement"===r.type){let e;if(r.opening&&r.opening.name&&"Identifier"===r.opening.name.type&&(e=r.opening.name.value),e&&n.has(e)){t+=`<${e}>${s(r.children||[])}</${e}>`}else{const e=p.indexOf(r);t+=`<${e}>${s(r.children||[])}</${e}>`}continue}"JSXFragment"!==r.type||(t+=s(r.children||[]))}else i(r)||(t+=r.value);return t}r(e,p,!1);const o=s(e);return String(o).replace(/\s+/g," ").trim()}(n.children,i);let X,g,m;if("JSXAttribute"===p?.type&&"StringLiteral"===p.value?.type)X=p.value.value;else{const e=i.extract.defaultValue;X="string"==typeof e?e:""}if("JSXAttribute"===r?.type){if("StringLiteral"===r.value?.type){if(g=r.value,m=g.value,!m||""===m.trim())return null;if(d&&"StringLiteral"===g.type){const e=i.extract.nsSeparator??":",t=g.value;if(e&&t.startsWith(`${d}${e}`)){if(m=t.slice(`${d}${e}`.length),!m||""===m.trim())return null;g={...g,value:m}}}}else"JSXExpressionContainer"===r.value?.type&&"JSXEmptyExpression"!==r.value.expression.type&&(g=r.value.expression);if(!g)return null}return p||!m||J.trim()?!p&&J.trim()&&(X=J):X=m,{keyExpression:g,serializedChildren:J,ns:d,defaultValue:X,hasCount:l,isOrdinal:c,contextExpression:S,optionsNode:y}}export{n as extractFromTransComponent};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "i18next-cli",
3
- "version": "1.11.5",
3
+ "version": "1.11.6",
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.11.5')
24
+ .version('1.11.6')
25
25
 
26
26
  program
27
27
  .command('extract')
@@ -182,7 +182,6 @@ export function extractFromTransComponent (node: JSXElement, config: I18nextTool
182
182
 
183
183
  // Validate that the key is not empty
184
184
  if (!processedKeyValue || processedKeyValue.trim() === '') {
185
- console.warn('Ignoring Trans component with empty i18nKey')
186
185
  return null
187
186
  }
188
187
 
@@ -197,7 +196,6 @@ export function extractFromTransComponent (node: JSXElement, config: I18nextTool
197
196
 
198
197
  // Validate processed key is not empty
199
198
  if (!processedKeyValue || processedKeyValue.trim() === '') {
200
- console.warn('Ignoring Trans component with i18nKey that becomes empty after namespace removal')
201
199
  return null
202
200
  }
203
201
 
@@ -254,26 +252,203 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
254
252
  /^\s*$/.test(n.value) &&
255
253
  n.value.includes('\n')
256
254
 
257
- // counter of "indexable" slots (increments for meaningful text, expression containers and non-preserved elements)
258
- const counter = { n: 0 }
255
+ // Build deterministic global slot list (pre-order)
256
+ function collectSlots (nodes: any[], slots: any[], parentIsNonPreserved = false) {
257
+ if (!nodes || !nodes.length) return
259
258
 
260
- function serialize (nodes: any[]): string {
261
- if (!nodes || !nodes.length) return ''
262
- let out = ''
259
+ // First, identify boundary whitespace nodes (start and end of sibling list)
260
+ // We trim ONLY pure-whitespace JSXText nodes from the boundaries
261
+ let startIdx = 0
262
+ let endIdx = nodes.length - 1
263
263
 
264
- for (const child of nodes) {
265
- if (!child) continue
264
+ // Skip leading boundary whitespace (pure whitespace JSXText only)
265
+ while (startIdx <= endIdx && isFormattingWhitespace(nodes[startIdx])) {
266
+ startIdx++
267
+ }
266
268
 
267
- if (child.type === 'JSXText') {
268
- if (!isFormattingWhitespace(child)) {
269
- out += child.value
270
- counter.n++
269
+ // Skip trailing boundary whitespace (pure whitespace JSXText only)
270
+ while (endIdx >= startIdx && isFormattingWhitespace(nodes[endIdx])) {
271
+ endIdx--
272
+ }
273
+
274
+ // Now process all nodes in the range [startIdx, endIdx] - this includes interior whitespace
275
+ const meaningfulNodes = startIdx <= endIdx ? nodes.slice(startIdx, endIdx + 1) : []
276
+
277
+ for (let i = 0; i < meaningfulNodes.length; i++) {
278
+ const n = meaningfulNodes[i]
279
+ if (!n) continue
280
+
281
+ if (n.type === 'JSXText') {
282
+ // Skip/merge pure-whitespace JSXText according to context:
283
+ // - If it immediately follows an expression container (and that expression
284
+ // wasn't originally a JSXText sibling), skip it (it's formatting).
285
+ // - If it follows an original JSXText sibling, merge it into that text.
286
+ if (isFormattingWhitespace(n)) {
287
+ const prevSlot = slots[slots.length - 1]
288
+ const prevOriginal = meaningfulNodes[i - 1]
289
+
290
+ if (prevSlot) {
291
+ // If the previous original sibling is an expression container, treat
292
+ // this formatting whitespace as formatting after an expression and skip it.
293
+ if (prevOriginal && prevOriginal.type === 'JSXExpressionContainer') {
294
+ continue
295
+ }
296
+ // Only merge into previous text when the previous original sibling was also JSXText.
297
+ if (prevSlot.type === 'JSXText' && prevOriginal && prevOriginal.type === 'JSXText') {
298
+ prevSlot.value = String(prevSlot.value) + n.value
299
+ continue
300
+ }
301
+ }
271
302
  }
303
+ // Add all other JSXText nodes
304
+ slots.push(n)
272
305
  continue
273
306
  }
274
307
 
275
- if (child.type === 'JSXExpressionContainer') {
276
- const expr = child.expression
308
+ if (n.type === 'JSXExpressionContainer') {
309
+ // If this expression is an object-expression placeholder like
310
+ // {{ key: value }} and we're inside a non-preserved parent element,
311
+ // treat it as part of the parent (do NOT add as a sibling/global slot).
312
+ if (parentIsNonPreserved && n.expression && n.expression.type === 'ObjectExpression') {
313
+ const prop = n.expression.properties && n.expression.properties[0]
314
+ if (prop && prop.type === 'KeyValueProperty') {
315
+ continue
316
+ }
317
+ }
318
+
319
+ // Handle pure-string expression containers (e.g. {" "}):
320
+ // - If it's pure space (no newline) and it directly follows a non-text sibling
321
+ // (element/fragment), treat it as formatting and skip it.
322
+ // - Otherwise, count it as a slot (do NOT merge it into previous JSXText).
323
+ if (n.expression && n.expression.type === 'StringLiteral') {
324
+ const textVal = String(n.expression.value || '')
325
+ const isPureSpaceNoNewline = /^\s*$/.test(textVal) && !textVal.includes('\n')
326
+ const prevOriginal = meaningfulNodes[i - 1]
327
+ const nextOriginal = meaningfulNodes[i + 1]
328
+
329
+ if (isPureSpaceNoNewline) {
330
+ // If the explicit {" "} is followed by a newline-only JSXText which
331
+ // itself is followed by an element/fragment, treat the {" "}
332
+ // as layout-only and skip it. This covers cases where the space
333
+ // precedes a newline-only separator before an element (fixes index
334
+ // shifting in object-expression span tests).
335
+ const nextNextOriginal = meaningfulNodes[i + 2]
336
+ if (
337
+ nextOriginal &&
338
+ nextOriginal.type === 'JSXText' &&
339
+ isFormattingWhitespace(nextOriginal) &&
340
+ nextNextOriginal &&
341
+ (nextNextOriginal.type === 'JSXElement' || nextNextOriginal.type === 'JSXFragment')
342
+ ) {
343
+ // Only skip this pure-space when it appears in one of these cases:
344
+ // - there is no previous original sibling (leading)
345
+ // - the previous original sibling is not a JSXText (e.g. element/expr)
346
+ // - OR the previous original is JSXText but it itself follows an expression
347
+ // (pattern: <expr>, JSXText, {" "}, newline-only JSXText, <element>)
348
+ const prevOriginal = meaningfulNodes[i - 1]
349
+ const prevPrevOriginal = meaningfulNodes[i - 2]
350
+ const shouldSkip =
351
+ !prevOriginal ||
352
+ prevOriginal.type !== 'JSXText' ||
353
+ (prevPrevOriginal && prevPrevOriginal.type === 'JSXExpressionContainer')
354
+
355
+ if (shouldSkip) {
356
+ continue
357
+ }
358
+ }
359
+
360
+ // Only treat {" "} as pure formatting to skip when it sits between
361
+ // an element/fragment and a newline-only JSXText. In that specific
362
+ // boundary case the explicit space is merely layout and must be ignored.
363
+ if (
364
+ prevOriginal &&
365
+ (prevOriginal.type === 'JSXElement' || prevOriginal.type === 'JSXFragment') &&
366
+ nextOriginal &&
367
+ nextOriginal.type === 'JSXText' &&
368
+ isFormattingWhitespace(nextOriginal)
369
+ ) {
370
+ continue
371
+ }
372
+
373
+ // 1) Merge into previous text when the previous original sibling is JSXText
374
+ // and the next original sibling is either missing or a non-formatting JSXText.
375
+ // This preserves "foo{' '}bar" as a single text node but avoids merging
376
+ // when the {" "} is followed by newline-only formatting before an element.
377
+ const nextIsTextNonFormatting = !nextOriginal || (nextOriginal.type === 'JSXText' && !isFormattingWhitespace(nextOriginal))
378
+ if (prevOriginal && prevOriginal.type === 'JSXText' && nextIsTextNonFormatting) {
379
+ const prevSlot = slots[slots.length - 1]
380
+ if (prevSlot && prevSlot.type === 'JSXText') {
381
+ prevSlot.value = String(prevSlot.value) + n.expression.value
382
+ continue
383
+ }
384
+ }
385
+
386
+ // 2) Skip when this explicit space sits between an element/fragment
387
+ // and a newline-only formatting JSXText (boundary formatting).
388
+ if (
389
+ prevOriginal &&
390
+ (prevOriginal.type === 'JSXElement' || prevOriginal.type === 'JSXFragment') &&
391
+ nextOriginal &&
392
+ nextOriginal.type === 'JSXText' &&
393
+ isFormattingWhitespace(nextOriginal)
394
+ ) {
395
+ continue
396
+ }
397
+ // 3) Otherwise fallthrough and count this expression as a slot.
398
+ }
399
+ }
400
+
401
+ // All JSXExpressionContainers count as slots for indexing.
402
+ slots.push(n)
403
+ continue
404
+ }
405
+
406
+ if (n.type === 'JSXElement') {
407
+ const tagName = n.opening && n.opening.name && n.opening.name.type === 'Identifier'
408
+ ? n.opening.name.value
409
+ : undefined
410
+ if (tagName && allowedTags.has(tagName)) {
411
+ // preserved tag: descend into children (tag itself is not a slot)
412
+ collectSlots(n.children || [], slots, false)
413
+ } else {
414
+ // non-preserved element: the element itself is a single slot.
415
+ // Pre-order: allocate the parent's slot first, then descend into its
416
+ // children. While descending, mark parentIsNonPreserved so
417
+ // KeyValueProperty-style object-expression placeholders are not added
418
+ // as separate sibling slots.
419
+ slots.push(n)
420
+ collectSlots(n.children || [], slots, true)
421
+ }
422
+ continue
423
+ }
424
+
425
+ if (n.type === 'JSXFragment') {
426
+ collectSlots(n.children || [], slots, parentIsNonPreserved)
427
+ continue
428
+ }
429
+
430
+ // ignore unknown node types
431
+ }
432
+ }
433
+
434
+ // prepare the global slot list for the whole subtree
435
+ const globalSlots: any[] = []
436
+ collectSlots(children, globalSlots, false)
437
+
438
+ function visitNodes (nodes: any[]): string {
439
+ if (!nodes || nodes.length === 0) return ''
440
+ let out = ''
441
+
442
+ for (const node of nodes) {
443
+ if (!node) continue
444
+
445
+ if (node.type === 'JSXText') {
446
+ if (!isFormattingWhitespace(node)) out += node.value
447
+ continue
448
+ }
449
+
450
+ if (node.type === 'JSXExpressionContainer') {
451
+ const expr = node.expression
277
452
  if (!expr) continue
278
453
 
279
454
  if (expr.type === 'StringLiteral') {
@@ -286,39 +461,40 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
286
461
  out += `{{${prop.key.value}}}`
287
462
  } else if (prop && prop.type === 'Identifier') {
288
463
  out += `{{${prop.value}}}`
464
+ } else {
465
+ out += '{{value}}'
289
466
  }
290
467
  } else if (expr.type === 'MemberExpression' && expr.property && expr.property.type === 'Identifier') {
291
468
  out += `{{${expr.property.value}}}`
292
469
  } else if (expr.type === 'CallExpression' && expr.callee?.type === 'Identifier') {
293
470
  out += `{{${expr.callee.value}}}`
471
+ } else {
472
+ out += '{{value}}'
294
473
  }
295
- // expression containers (including explicit {' '}) consume a slot
296
- counter.n++
297
474
  continue
298
475
  }
299
476
 
300
- if (child.type === 'JSXElement') {
477
+ if (node.type === 'JSXElement') {
301
478
  let tag: string | undefined
302
- if (child.opening && child.opening.name && child.opening.name.type === 'Identifier') {
303
- tag = child.opening.name.value
479
+ if (node.opening && node.opening.name && node.opening.name.type === 'Identifier') {
480
+ tag = node.opening.name.value
304
481
  }
305
482
 
306
483
  if (tag && allowedTags.has(tag)) {
307
- // preserved HTML tag: do NOT consume a numeric slot for the tag itself
308
- const inner = serialize(child.children || [])
484
+ const inner = visitNodes(node.children || [])
309
485
  out += `<${tag}>${inner}</${tag}>`
310
486
  } else {
311
- // non-preserved element: use current counter value as numeric index, then consume the slot
312
- const myIndex = counter.n
313
- counter.n++
314
- const inner = serialize(child.children || [])
315
- out += `<${myIndex}>${inner}</${myIndex}>`
487
+ // Use the pre-order globalSlots index so placeholder numbers reflect
488
+ // the global ordering (including nested slots collected earlier).
489
+ const idx = globalSlots.indexOf(node)
490
+ const inner = visitNodes(node.children || [])
491
+ out += `<${idx}>${inner}</${idx}>`
316
492
  }
317
493
  continue
318
494
  }
319
495
 
320
- if (child.type === 'JSXFragment') {
321
- out += serialize(child.children || [])
496
+ if (node.type === 'JSXFragment') {
497
+ out += visitNodes(node.children || [])
322
498
  continue
323
499
  }
324
500
 
@@ -328,6 +504,6 @@ function serializeJSXChildren (children: any[], config: I18nextToolkitConfig): s
328
504
  return out
329
505
  }
330
506
 
331
- const result = serialize(children)
507
+ const result = visitNodes(children)
332
508
  return String(result).replace(/\s+/g, ' ').trim()
333
509
  }
@@ -1 +1 @@
1
- {"version":3,"file":"jsx-parser.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/jsx-parser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,gBAAgB,EAAY,MAAM,WAAW,CAAA;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAGvD,MAAM,WAAW,sBAAsB;IACrC,gDAAgD;IAChD,aAAa,CAAC,EAAE,UAAU,CAAC;IAE3B,qDAAqD;IACrD,kBAAkB,EAAE,MAAM,CAAC;IAE3B,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,8DAA8D;IAC9D,EAAE,CAAC,EAAE,MAAM,CAAC;IAEZ,oEAAoE;IACpE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB,0DAA0D;IAC1D,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,8EAA8E;IAC9E,WAAW,CAAC,EAAE,gBAAgB,CAAC;IAE/B,mDAAmD;IACnD,iBAAiB,CAAC,EAAE,UAAU,CAAC;CAChC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,yBAAyB,CAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,oBAAoB,GAAG,sBAAsB,GAAG,IAAI,CAgLxH"}
1
+ {"version":3,"file":"jsx-parser.d.ts","sourceRoot":"","sources":["../../../src/extractor/parsers/jsx-parser.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,gBAAgB,EAAY,MAAM,WAAW,CAAA;AACnF,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAA;AAGvD,MAAM,WAAW,sBAAsB;IACrC,gDAAgD;IAChD,aAAa,CAAC,EAAE,UAAU,CAAC;IAE3B,qDAAqD;IACrD,kBAAkB,EAAE,MAAM,CAAC;IAE3B,mDAAmD;IACnD,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,8DAA8D;IAC9D,EAAE,CAAC,EAAE,MAAM,CAAC;IAEZ,oEAAoE;IACpE,QAAQ,CAAC,EAAE,OAAO,CAAC;IAEnB,0DAA0D;IAC1D,SAAS,CAAC,EAAE,OAAO,CAAC;IAEpB,8EAA8E;IAC9E,WAAW,CAAC,EAAE,gBAAgB,CAAC;IAE/B,mDAAmD;IACnD,iBAAiB,CAAC,EAAE,UAAU,CAAC;CAChC;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AACH,wBAAgB,yBAAyB,CAAE,IAAI,EAAE,UAAU,EAAE,MAAM,EAAE,oBAAoB,GAAG,sBAAsB,GAAG,IAAI,CA8KxH"}