vite-bundled-i18n 0.3.0 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -19,6 +19,8 @@ export interface CliConfig {
19
19
  extractionScope?: 'global' | 'scoped';
20
20
  /** Optional dictionary configurations for compiled mode. */
21
21
  dictionaries?: Record<string, DictionaryConfig>;
22
+ /** Additional module specifiers that export `useI18n`. */
23
+ hookSources?: string[];
22
24
  }
23
25
  /**
24
26
  * Run the walker and print a summary table to stdout.
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as generateReports, l as generateBundles, n as walkAll, r as flattenLocaleKeys, s as writeTypes, t as compileAll } from "../compiler-B8vL51ge.js";
2
+ import { a as generateReports, l as generateBundles, n as walkAll, r as flattenLocaleKeys, s as writeTypes, t as compileAll } from "../compiler-76bzcfdD.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  //#region src/cli/commands.ts
@@ -21,7 +21,8 @@ function runWalker(config) {
21
21
  rootDir,
22
22
  localesDir,
23
23
  defaultLocale: config.defaultLocale,
24
- extractionScope
24
+ extractionScope,
25
+ hookSources: config.hookSources
25
26
  });
26
27
  }
27
28
  function collectScopeNames(analysis) {
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/commands.ts","../../src/cli/index.ts"],"sourcesContent":["import path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { compileAll } from '../extractor/compiler';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { flattenLocaleKeys } from '../extractor/reports';\n\nexport interface CliConfig {\n /** Glob patterns for page entry points. */\n pages: string[];\n /** Locales directory (relative to rootDir). */\n localesDir: string;\n /** All supported locale codes. */\n locales: string[];\n /** Default locale. */\n defaultLocale: string;\n /** Root directory. Defaults to process.cwd(). */\n rootDir?: string;\n /** Output directory for generated bundles. Defaults to '.i18n'. */\n outDir?: string;\n /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */\n typesOutPath?: string;\n /** Extraction scope. Defaults to 'global'. */\n extractionScope?: 'global' | 'scoped';\n /** Optional dictionary configurations for compiled mode. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\nfunction resolveConfig(config: CliConfig) {\n const rootDir = config.rootDir ?? process.cwd();\n const outDir = config.outDir ?? path.join(rootDir, '.i18n');\n const typesOutPath =\n config.typesOutPath ?? path.join(outDir, 'i18n-generated.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n });\n}\n\nfunction collectScopeNames(analysis: ProjectAnalysis): string[] {\n return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n\n // Count generated modules: one per route per locale, plus dictionary modules\n const routeModules = analysis.routes.length * config.locales.length;\n const dictModules =\n config.dictionaries && Object.keys(config.dictionaries).length > 0\n ? config.locales.length\n : 0;\n const total = routeModules + dictModules + 1; // +1 for manifest\n\n console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);\n}\n\n/**\n * Run analyze + generate + compile + report all at once.\n */\nexport function build(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n // Analyze: print table\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n // Generate bundles + types\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n console.log(`Compiled modules written to ${compiledOutDir}`);\n\n // Reports\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}`);\n console.log(\n `\\nDone. ${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s).`,\n );\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { analyze, generate, compile, report, build } from './commands';\nimport type { CliConfig } from './commands';\n\nconst COMMANDS = ['analyze', 'generate', 'compile', 'report', 'build'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nfunction printUsage(): void {\n console.log('Usage: vite-bundled-i18n <command> [--config <path>]');\n console.log('');\n console.log('Commands:');\n console.log(' analyze — Walk imports and print a summary of key usage per route');\n console.log(' generate — Generate tree-shaken bundles and TypeScript types');\n console.log(' report — Generate diagnostic reports (manifest, missing, unused, stats)');\n console.log(' compile — Compile pre-resolved flat Map modules for production');\n console.log(' build — Run analyze + generate + compile + report in one step');\n console.log('');\n console.log('Options:');\n console.log(' --config <path> Path to config file (default: i18n.config.json)');\n}\n\nfunction loadConfig(configPath: string): CliConfig {\n const resolved = path.resolve(configPath);\n if (!fs.existsSync(resolved)) {\n console.error(`Config file not found: ${resolved}`);\n process.exit(1);\n }\n\n const raw = fs.readFileSync(resolved, 'utf-8');\n return JSON.parse(raw) as CliConfig;\n}\n\nfunction parseArgs(argv: string[]): { command: Command; configPath: string } {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' && i + 1 < args.length) {\n configPath = args[++i];\n } else if (arg === '--help' || arg === '-h') {\n printUsage();\n process.exit(0);\n } else if (!command && COMMANDS.includes(arg as Command)) {\n command = arg as Command;\n } else {\n console.error(`Unknown argument: ${arg}`);\n printUsage();\n process.exit(1);\n }\n }\n\n if (!command) {\n printUsage();\n process.exit(1);\n }\n\n return { command: command!, configPath };\n}\n\nconst { command, configPath } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\nconst commands: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AA+BA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;CAC/C,MAAM,SAAS,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;AAQ3D,QAAO;EAAE;EAAS;EAAQ,cANxB,OAAO,gBAAgB,KAAK,KAAK,QAAQ,oBAAoB;EAMvB,YALrB,KAAK,WAAW,OAAO,WAAW,GACjD,OAAO,aACP,KAAK,KAAK,SAAS,OAAO,WAAW;EAGW,iBAF5B,OAAO,mBAAmB;EAEmB;;AAGvE,SAAS,UAAU,QAAoC;CACrD,MAAM,EAAE,SAAS,YAAY,oBAAoB,cAAc,OAAO;AAEtE,QAAO,QAAQ;EACb,OAAO,OAAO;EACd;EACA;EACA,eAAe,OAAO;EACtB;EACD,CAAC;;AAGJ,SAAS,kBAAkB,UAAqC;AAC9D,QAAO,CAAC,GAAG,IAAI,IAAI,SAAS,OAAO,SAAS,UAAU,MAAM,OAAO,CAAC,CAAC,CAAC,MAAM;;;;;AAM9E,SAAS,IAAI,KAAa,OAAuB;AAC/C,QAAO,MAAM,IAAI,OAAO,KAAK,IAAI,GAAG,QAAQ,IAAI,OAAO,CAAC;;;;;AAM1D,SAAS,WACP,SACA,MACM;CACN,MAAM,YAAY,QAAQ,KAAK,GAAG,MAChC,KAAK,IAAI,EAAE,QAAQ,GAAG,KAAK,KAAK,OAAO,EAAE,MAAM,IAAI,OAAO,CAAC,CAC5D;CAED,MAAM,MACJ,MACA,UAAU,KAAK,MAAM,IAAS,OAAO,IAAI,EAAE,CAAC,CAAC,KAAK,IAAS,GAC3D;CACF,MAAM,MACJ,MACA,UAAU,KAAK,MAAM,IAAS,OAAO,IAAI,EAAE,CAAC,CAAC,KAA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AK,QAAQ,WAAW;AACzC,KAAI,CAAC,GAAG,WAAW,SAAS,EAAE;AAC5B,UAAQ,MAAM,0BAA0B,WAAW;AACnD,UAAQ,KAAK,EAAE;;CAGjB,MAAM,MAAM,GAAG,aAAa,UAAU,QAAQ;AAC9C,QAAO,KAAK,MAAM,IAAI;;AAGxB,SAAS,UAAU,MAA0D;CAC3E,MAAM,OAAO,KAAK,MAAM,EAAE;CAC1B,IAAI;CACJ,IAAI,aAAa;AAEjB,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;AACjB,MAAI,QAAQ,cAAc,IAAI,IAAI,KAAK,OACrC,cAAa,KAAK,EAAE;WACX,QAAQ,YAAY,QAAQ,MAAM;AAC3C,eAAY;AACZ,WAAQ,KAAK,EAAE;aACN,CAAC,WAAW,SAAS,SAAS,IAAe,CACtD,WAAU;OACL;AACL,WAAQ,MAAM,qBAAqB,MAAM;AACzC,eAAY;AACZ,WAAQ,KAAK,EAAE;;;AAInB,KAAI,CAAC,SAAS;AACZ,cAAY;AACZ,UAAQ,KAAK,EAAE;;AAGjB,QAAO;EAAW;EAAU;EAAY;;AAG1C,IAAM,EAAE,SAAS,eAAe,UAAU,QAAQ,KAAK;AACvD,IAAM,SAAS,WAAW,WAAW;CAEuB;CAC1D;CACA;CACA;CACA;CACA;CACD,EAEQ,SAAS,OAAO"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/cli/commands.ts","../../src/cli/index.ts"],"sourcesContent":["import path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { compileAll } from '../extractor/compiler';\nimport type { ProjectAnalysis } from '../extractor/walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { flattenLocaleKeys } from '../extractor/reports';\n\nexport interface CliConfig {\n /** Glob patterns for page entry points. */\n pages: string[];\n /** Locales directory (relative to rootDir). */\n localesDir: string;\n /** All supported locale codes. */\n locales: string[];\n /** Default locale. */\n defaultLocale: string;\n /** Root directory. Defaults to process.cwd(). */\n rootDir?: string;\n /** Output directory for generated bundles. Defaults to '.i18n'. */\n outDir?: string;\n /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */\n typesOutPath?: string;\n /** Extraction scope. Defaults to 'global'. */\n extractionScope?: 'global' | 'scoped';\n /** Optional dictionary configurations for compiled mode. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Additional module specifiers that export `useI18n`. */\n hookSources?: string[];\n}\n\nfunction resolveConfig(config: CliConfig) {\n const rootDir = config.rootDir ?? process.cwd();\n const outDir = config.outDir ?? path.join(rootDir, '.i18n');\n const typesOutPath =\n config.typesOutPath ?? path.join(outDir, 'i18n-generated.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n hookSources: config.hookSources,\n });\n}\n\nfunction collectScopeNames(analysis: ProjectAnalysis): string[] {\n return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n\n // Count generated modules: one per route per locale, plus dictionary modules\n const routeModules = analysis.routes.length * config.locales.length;\n const dictModules =\n config.dictionaries && Object.keys(config.dictionaries).length > 0\n ? config.locales.length\n : 0;\n const total = routeModules + dictModules + 1; // +1 for manifest\n\n console.log(`Compiled ${total} module(s) to ${compiledOutDir}`);\n}\n\n/**\n * Run analyze + generate + compile + report all at once.\n */\nexport function build(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n // Analyze: print table\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n // Generate bundles + types\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n });\n console.log(`Compiled modules written to ${compiledOutDir}`);\n\n // Reports\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}`);\n console.log(\n `\\nDone. ${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s).`,\n );\n}\n","#!/usr/bin/env node\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { analyze, generate, compile, report, build } from './commands';\nimport type { CliConfig } from './commands';\n\nconst COMMANDS = ['analyze', 'generate', 'compile', 'report', 'build'] as const;\ntype Command = (typeof COMMANDS)[number];\n\nfunction printUsage(): void {\n console.log('Usage: vite-bundled-i18n <command> [--config <path>]');\n console.log('');\n console.log('Commands:');\n console.log(' analyze — Walk imports and print a summary of key usage per route');\n console.log(' generate — Generate tree-shaken bundles and TypeScript types');\n console.log(' report — Generate diagnostic reports (manifest, missing, unused, stats)');\n console.log(' compile — Compile pre-resolved flat Map modules for production');\n console.log(' build — Run analyze + generate + compile + report in one step');\n console.log('');\n console.log('Options:');\n console.log(' --config <path> Path to config file (default: i18n.config.json)');\n}\n\nfunction loadConfig(configPath: string): CliConfig {\n const resolved = path.resolve(configPath);\n if (!fs.existsSync(resolved)) {\n console.error(`Config file not found: ${resolved}`);\n process.exit(1);\n }\n\n const raw = fs.readFileSync(resolved, 'utf-8');\n return JSON.parse(raw) as CliConfig;\n}\n\nfunction parseArgs(argv: string[]): { command: Command; configPath: string } {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n\n for (let i = 0; i < args.length; i++) {\n const arg = args[i];\n if (arg === '--config' && i + 1 < args.length) {\n configPath = args[++i];\n } else if (arg === '--help' || arg === '-h') {\n printUsage();\n process.exit(0);\n } else if (!command && COMMANDS.includes(arg as Command)) {\n command = arg as Command;\n } else {\n console.error(`Unknown argument: ${arg}`);\n printUsage();\n process.exit(1);\n }\n }\n\n if (!command) {\n printUsage();\n process.exit(1);\n }\n\n return { command: command!, configPath };\n}\n\nconst { command, configPath } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\nconst commands: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AAiCA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;CAC/C,MAAM,SAAS,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;AAQ3D,QAAO;EAAE;EAAS;EAAQ,cANxB,OAAO,gBAAgB,KAAK,KAAK,QAAQ,oBAAoB;EAMvB,YALrB,KAAK,WAAW,OAAO,WAAW,GACjD,OAAO,aACP,KAAK,KAAK,SAAS,OAAO,WAAW;EAGW,iBAF5B,OAAO,mBAAmB;EAEmB;;AAGvE,SAAS,UAAU,QAAoC;CACrD,MAAM,EAAE,SAAS,YAAY,oBAAoB,cAAc,OAAO;AAEtE,QAAO,QAAQ;EACb,OAAO,OAAO;EACd;EACA;EACA,eAAe,OAAO;EACtB;EACA,aAAa,OAAO;EACrB,CAAC;;AAGJ,SAAS,kBAAkB,UAAqC;AAC9D,QAAO,CAAC,GAAG,IAAI,IAAI,SAAS,OAAO,SAAS,UAAU,MAAM,OAAO,CAAC,CAAC,CAAC,MAAM;;;;;AAM9E,SAAS,IAAI,KAAa,OAAuB;AAC/C,QAAO,MAAM,IAAI,OAAO,KAAK,IAAI,GAAG,QAAQ,IAAI,OAAO,CAAC;;;;;AAM1D,SAAS,WACP,SACA,MACM;CACN,MAAM,YAAY,QAAQ,KAAK,GAAG,MAChC,KAAK,IAAI,EAAE,QAAQ,GAAG,KAAK,KAAK,OAAO,EAAE,MAAM,IAAI,OAAO,CAAC,CAC5D;CAED,MAAM,MACJ,MACA,UAAU,KAAK,MAAM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,sEAAsE;AAClF,SAAQ,IAAI,GAAG;AACf,SAAQ,IAAI,WAAW;AACvB,SAAQ,IAAI,qEAAqE;;AAGnF,SAAS,WAAW,YAA+B;CACjD,MAAM,WAAW,KAAK,QAAQ,WAAW;AACzC,KAAI,CAAC,GAAG,WAAW,SAAS,EAAE;AAC5B,UAAQ,MAAM,0BAA0B,WAAW;AACnD,UAAQ,KAAK,EAAE;;CAGjB,MAAM,MAAM,GAAG,aAAa,UAAU,QAAQ;AAC9C,QAAO,KAAK,MAAM,IAAI;;AAGxB,SAAS,UAAU,MAA0D;CAC3E,MAAM,OAAO,KAAK,MAAM,EAAE;CAC1B,IAAI;CACJ,IAAI,aAAa;AAEjB,MAAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;AACjB,MAAI,QAAQ,cAAc,IAAI,IAAI,KAAK,OACrC,cAAa,KAAK,EAAE;WACX,QAAQ,YAAY,QAAQ,MAAM;AAC3C,eAAY;AACZ,WAAQ,KAAK,EAAE;aACN,CAAC,WAAW,SAAS,SAAS,IAAe,CACtD,WAAU;OACL;AACL,WAAQ,MAAM,qBAAqB,MAAM;AACzC,eAAY;AACZ,WAAQ,KAAK,EAAE;;;AAInB,KAAI,CAAC,SAAS;AACZ,cAAY;AACZ,UAAQ,KAAK,EAAE;;AAGjB,QAAO;EAAW;EAAU;EAAY;;AAG1C,IAAM,EAAE,SAAS,eAAe,UAAU,QAAQ,KAAK;AACvD,IAAM,SAAS,WAAW,WAAW;CAEuB;CAC1D;CACA;CACA;CACA;CACA;CACD,EAEQ,SAAS,OAAO"}
@@ -707,15 +707,29 @@ var PACKAGE_NAMES = new Set([
707
707
  ]);
708
708
  /**
709
709
  * Package specifiers recognized as ours.
710
+ *
711
+ * @param specifier - The import module specifier to check.
712
+ * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.
713
+ */
714
+ function isOurPackage(specifier, hookSources) {
715
+ return PACKAGE_NAMES.has(specifier) || specifier.includes("/core/t") || specifier.includes("/react/useI18n") || matchesHookSource(specifier, hookSources);
716
+ }
717
+ /**
718
+ * Checks if a module specifier exports `useI18n`.
719
+ *
720
+ * @param specifier - The import module specifier to check.
721
+ * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.
710
722
  */
711
- function isOurPackage(specifier) {
712
- return PACKAGE_NAMES.has(specifier) || specifier.includes("/core/t") || specifier.includes("/react/useI18n");
723
+ function isUseI18nPackage(specifier, hookSources) {
724
+ return specifier === "vite-bundled-i18n/react" || specifier === "vite-i18n-manager/react" || specifier.includes("/react/useI18n") || matchesHookSource(specifier, hookSources);
713
725
  }
714
726
  /**
715
- * Checks if a module specifier is one that exports `useI18n`.
727
+ * Checks if a specifier matches any configured hook source.
728
+ * Uses exact match or endsWith to handle path alias resolution.
716
729
  */
717
- function isUseI18nPackage(specifier) {
718
- return specifier === "vite-bundled-i18n/react" || specifier === "vite-i18n-manager/react" || specifier.includes("/react/useI18n");
730
+ function matchesHookSource(specifier, hookSources) {
731
+ if (!hookSources || hookSources.length === 0) return false;
732
+ return hookSources.some((source) => specifier === source || specifier.endsWith(source));
719
733
  }
720
734
  /**
721
735
  * Checks if a module specifier is one that exports the global `t`.
@@ -756,7 +770,7 @@ function findTranslationCalls(sourceFile, options) {
756
770
  if (!ts.isImportDeclaration(node)) return;
757
771
  if (!ts.isStringLiteral(node.moduleSpecifier)) return;
758
772
  const specifier = node.moduleSpecifier.text;
759
- if (!isOurPackage(specifier)) return;
773
+ if (!isOurPackage(specifier, options.hookSources)) return;
760
774
  const clause = node.importClause;
761
775
  if (!clause) return;
762
776
  const bindings = clause.namedBindings;
@@ -767,8 +781,8 @@ function findTranslationCalls(sourceFile, options) {
767
781
  if (importedName === "t" && isGlobalTPackage(specifier)) {
768
782
  if (options.scope !== "scoped") trackedNames.set(localName, "global");
769
783
  }
770
- if (importedName === "useI18n" && isUseI18nPackage(specifier)) useI18nNames.add(localName);
771
- if (importedName === "i18nKey" && isOurPackage(specifier)) i18nKeyNames.add(localName);
784
+ if (importedName === "useI18n" && isUseI18nPackage(specifier, options.hookSources)) useI18nNames.add(localName);
785
+ if (importedName === "i18nKey" && isOurPackage(specifier, options.hookSources)) i18nKeyNames.add(localName);
772
786
  }
773
787
  });
774
788
  ts.forEachChild(sourceFile, (node) => {
@@ -929,15 +943,18 @@ function findTranslationCalls(sourceFile, options) {
929
943
  }
930
944
  /**
931
945
  * Extracts scope strings from all useI18n() calls in a source file.
946
+ *
947
+ * @param sourceFile - The parsed TypeScript source file.
948
+ * @param hookSources - Additional module specifiers that export `useI18n`.
932
949
  */
933
- function extractScopes(sourceFile) {
950
+ function extractScopes(sourceFile, hookSources) {
934
951
  const scopes = [];
935
952
  const useI18nNames = /* @__PURE__ */ new Set();
936
953
  ts.forEachChild(sourceFile, (node) => {
937
954
  if (!ts.isImportDeclaration(node)) return;
938
955
  if (!ts.isStringLiteral(node.moduleSpecifier)) return;
939
956
  const specifier = node.moduleSpecifier.text;
940
- if (!isUseI18nPackage(specifier)) return;
957
+ if (!isUseI18nPackage(specifier, hookSources)) return;
941
958
  const clause = node.importClause;
942
959
  if (!clause) return;
943
960
  const bindings = clause.namedBindings;
@@ -999,7 +1016,7 @@ function extractKeys(source, options) {
999
1016
  };
1000
1017
  }
1001
1018
  const keys = findTranslationCalls(sourceFile, opts);
1002
- const scopes = extractScopes(sourceFile);
1019
+ const scopes = extractScopes(sourceFile, opts.hookSources);
1003
1020
  const imports = collectImports(sourceFile);
1004
1021
  return {
1005
1022
  filePath: opts.filePath,
@@ -1138,7 +1155,8 @@ function walkRoute(entryPoint, options) {
1138
1155
  allFiles.push(resolved);
1139
1156
  const result = extractKeys(source, {
1140
1157
  scope: options.extractionScope,
1141
- filePath: resolved
1158
+ filePath: resolved,
1159
+ hookSources: options.hookSources
1142
1160
  });
1143
1161
  for (const key of result.keys) if (!seenKeys.has(key.key)) {
1144
1162
  seenKeys.add(key.key);
@@ -1171,7 +1189,8 @@ function walkAll(options) {
1171
1189
  absolute: true
1172
1190
  }).map((entry) => walkRoute(entry, {
1173
1191
  rootDir,
1174
- extractionScope
1192
+ extractionScope,
1193
+ hookSources: options.hookSources
1175
1194
  }));
1176
1195
  const availableNamespaces = discoverNamespaces(path.isAbsolute(options.localesDir) ? options.localesDir : path.join(rootDir, options.localesDir), options.defaultLocale);
1177
1196
  const allKeysMap = /* @__PURE__ */ new Map();
@@ -1350,4 +1369,4 @@ function compileAll(analysis, options) {
1350
1369
  //#endregion
1351
1370
  export { generateReports as a, flattenKeys as c, keyMatchesPattern as d, normalizeDictionaries as f, generateDictionaryOwnershipReport as i, generateBundles as l, walkAll as n, generateTypes as o, resolveDictionaryOwnership as p, flattenLocaleKeys as r, writeTypes as s, compileAll as t, pruneNamespace as u };
1352
1371
 
1353
- //# sourceMappingURL=compiler-B8vL51ge.js.map
1372
+ //# sourceMappingURL=compiler-76bzcfdD.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compiler-76bzcfdD.js","names":[],"sources":["../src/extractor/dictionary-ownership.ts","../src/extractor/scope-bundles.ts","../src/extractor/bundle-generator.ts","../src/extractor/type-generator.ts","../src/extractor/reports.ts","../src/extractor/ast-utils.ts","../src/extractor/patterns.ts","../src/extractor/extract.ts","../src/extractor/walker.ts","../src/extractor/compiler.ts"],"sourcesContent":["import type { DictionaryConfig } from '../core/types';\n\nexport interface NormalizedDictionaryRule {\n name: string;\n include: string[];\n exclude: string[];\n priority: number;\n pinned: boolean;\n order: number;\n}\n\nexport interface DictionaryOwnership {\n rules: NormalizedDictionaryRule[];\n keyOwner: Map<string, string>;\n dictionaryKeys: Map<string, Set<string>>;\n dictionaryNamespaces: Set<string>;\n}\n\nexport function getDictionaryIncludePatterns(dict: DictionaryConfig): string[] {\n const fromKeys = (dict.keys ?? []).map((key) => `${key}.*`);\n return [...fromKeys, ...(dict.include ?? [])];\n}\n\nexport function normalizeDictionaries(\n dictionaries?: Record<string, DictionaryConfig>,\n): NormalizedDictionaryRule[] {\n if (!dictionaries) return [];\n\n return Object.entries(dictionaries)\n .map(([name, dict], order) => ({\n name,\n include: getDictionaryIncludePatterns(dict),\n exclude: dict.exclude ?? [],\n priority: dict.priority ?? 0,\n pinned: dict.pinned ?? false,\n order,\n }))\n .filter((rule) => rule.include.length > 0)\n .sort((a, b) => b.priority - a.priority || a.order - b.order);\n}\n\nexport function keyMatchesPattern(key: string, pattern: string): boolean {\n if (pattern.includes('.')) {\n if (pattern.endsWith('*')) {\n const prefix = pattern.slice(0, -1);\n return key.startsWith(prefix);\n }\n return key === pattern;\n }\n\n const namespace = key.split('.')[0];\n if (pattern.endsWith('*')) {\n return namespace.startsWith(pattern.slice(0, -1));\n }\n return namespace === pattern;\n}\n\nexport function resolveDictionaryOwnership(\n availableKeys: Iterable<string>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnership {\n const rules = normalizeDictionaries(dictionaries);\n const keyOwner = new Map<string, string>();\n const dictionaryKeys = new Map<string, Set<string>>();\n const dictionaryNamespaces = new Set<string>();\n\n for (const rule of rules) {\n dictionaryKeys.set(rule.name, new Set());\n }\n\n for (const key of availableKeys) {\n for (const rule of rules) {\n const included = rule.include.some((pattern) => keyMatchesPattern(key, pattern));\n const excluded = rule.exclude.some((pattern) => keyMatchesPattern(key, pattern));\n if (included && !excluded) {\n keyOwner.set(key, rule.name);\n dictionaryKeys.get(rule.name)!.add(key);\n const namespace = key.split('.')[0];\n if (namespace) {\n dictionaryNamespaces.add(namespace);\n }\n break;\n }\n }\n }\n\n return {\n rules,\n keyOwner,\n dictionaryKeys,\n dictionaryNamespaces,\n };\n}\n","import type { ProjectAnalysis } from './walker-types';\nimport type { ExtractedKey } from './types';\n\nexport interface ScopeBundlePlan {\n scope: string;\n namespace: string;\n keys: Set<string>;\n routeIds: Set<string>;\n}\n\nexport function inferScopeNamespace(scope: string): string {\n return scope.includes('.') ? scope.slice(0, scope.indexOf('.')) : scope;\n}\n\nfunction keyNamespace(key: ExtractedKey): string | undefined {\n const source = key.dynamic && key.staticPrefix ? key.staticPrefix : key.key;\n if (!source) return undefined;\n const dotIndex = source.indexOf('.');\n return dotIndex === -1 ? undefined : source.slice(0, dotIndex);\n}\n\nexport function buildScopePlans(\n analysis: ProjectAnalysis,\n availableKeys: Iterable<string>,\n): ScopeBundlePlan[] {\n const scopePlans = new Map<string, ScopeBundlePlan>();\n const allAvailableKeys = [...availableKeys];\n\n for (const route of analysis.routes) {\n for (const scope of route.scopes) {\n const namespace = inferScopeNamespace(scope);\n let plan = scopePlans.get(scope);\n if (!plan) {\n plan = {\n scope,\n namespace,\n keys: new Set<string>(),\n routeIds: new Set<string>(),\n };\n scopePlans.set(scope, plan);\n }\n\n plan.routeIds.add(route.routeId);\n\n for (const key of route.keys) {\n if (keyNamespace(key) !== namespace) continue;\n\n if (!key.dynamic) {\n plan.keys.add(key.key);\n continue;\n }\n\n if (!key.staticPrefix) continue;\n for (const availableKey of allAvailableKeys) {\n if (availableKey.startsWith(key.staticPrefix)) {\n plan.keys.add(availableKey);\n }\n }\n }\n }\n }\n\n return [...scopePlans.values()].sort((a, b) => a.scope.localeCompare(b.scope));\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership, keyMatchesPattern } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the bundle generator.\n */\nexport interface BundleGeneratorOptions {\n /** Path to locales directory (absolute). */\n localesDir: string;\n /** Locales to generate bundles for. */\n locales: string[];\n /** Output directory for generated bundles (absolute). */\n outDir: string;\n /** Optional named dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\n/**\n * Metadata about a generated bundle file.\n */\nexport interface GeneratedBundle {\n /** The route ID or dictionary name this bundle is for. */\n name: string;\n /** The locale this bundle is for. */\n locale: string;\n /** The output file path. */\n filePath: string;\n /** Number of keys in this bundle. */\n keyCount: number;\n /** Number of keys pruned (available but not used). */\n prunedCount: number;\n}\n\n/**\n * Flatten a nested object into dot-separated key paths.\n */\nexport function flattenKeys(data: object, prefix?: string): string[] {\n const keys: string[] = [];\n for (const [k, v] of Object.entries(data)) {\n const fullKey = prefix ? `${prefix}.${k}` : k;\n if (v !== null && typeof v === 'object' && !Array.isArray(v)) {\n keys.push(...flattenKeys(v as object, fullKey));\n } else {\n keys.push(fullKey);\n }\n }\n return keys;\n}\n\n/**\n * Set a value at a dot-separated path in a nested object, creating\n * intermediate objects as needed.\n */\nfunction setNestedValue(obj: Record<string, unknown>, keyPath: string, value: unknown): void {\n const parts = keyPath.split('.');\n let current: Record<string, unknown> = obj;\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n if (!(part in current) || typeof current[part] !== 'object' || current[part] === null) {\n current[part] = {};\n }\n current = current[part] as Record<string, unknown>;\n }\n current[parts[parts.length - 1]] = value;\n}\n\n/**\n * Get a value at a dot-separated path in a nested object.\n * Returns undefined if the path does not exist.\n */\nfunction getNestedValue(obj: Record<string, unknown>, keyPath: string): unknown {\n const parts = keyPath.split('.');\n let current: unknown = obj;\n for (const part of parts) {\n if (current === null || typeof current !== 'object') return undefined;\n current = (current as Record<string, unknown>)[part];\n }\n return current;\n}\n\n/**\n * Prune a namespace JSON object to only include the specified key paths.\n *\n * For keys that point to a subtree (object), the entire subtree is included.\n * This supports dynamic keys with a static prefix — the full subtree under\n * the prefix is preserved.\n */\nexport function pruneNamespace(\n fullData: object,\n usedKeyPaths: string[],\n): object {\n const result: Record<string, unknown> = {};\n for (const keyPath of usedKeyPaths) {\n const value = getNestedValue(fullData as Record<string, unknown>, keyPath);\n if (value !== undefined) {\n setNestedValue(result, keyPath, value);\n }\n }\n return result;\n}\n\n/**\n * Read a namespace JSON file for a given locale.\n */\nfunction readNamespaceFile(\n localesDir: string,\n locale: string,\n namespace: string,\n): Record<string, unknown> | null {\n const filePath = path.join(localesDir, locale, `${namespace}.json`);\n if (!fs.existsSync(filePath)) return null;\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content) as Record<string, unknown>;\n}\n\n/**\n * Generate tree-shaken per-route translation bundles from project analysis.\n */\nexport function generateBundles(\n analysis: ProjectAnalysis,\n options: BundleGeneratorOptions,\n): GeneratedBundle[] {\n const { localesDir, locales, outDir, dictionaries } = options;\n const bundles: GeneratedBundle[] = [];\n\n const availableKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n if (!key.dynamic) {\n availableKeys.add(key.key);\n }\n }\n }\n const ownership = resolveDictionaryOwnership(availableKeys, dictionaries);\n const hasNamedDictionaries = ownership.rules.length > 0;\n const sharedNsSet = hasNamedDictionaries ? new Set<string>() : new Set(analysis.sharedNamespaces);\n\n // Generate per-scope bundles keyed by scope string, matching runtime URLs.\n for (const plan of buildScopePlans(analysis, availableKeys)) {\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n let totalPrunedCount = 0;\n const scopeKeys = [...plan.keys].filter((key) => {\n if (ownership.keyOwner.has(key)) return false;\n return !(!hasNamedDictionaries && sharedNsSet.has(plan.namespace));\n });\n const subKeys = scopeKeys\n .filter((key) => key.startsWith(`${plan.namespace}.`))\n .map((key) => key.slice(plan.namespace.length + 1));\n const fullData = readNamespaceFile(localesDir, locale, plan.namespace);\n if (fullData && subKeys.length > 0) {\n const pruned = pruneNamespace(fullData, [...new Set(subKeys)]);\n bundleData[plan.namespace] = pruned;\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n totalKeyCount += keptCount;\n totalPrunedCount += availableCount - keptCount;\n }\n\n const filePath = path.join(outDir, locale, `${plan.scope}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: plan.scope,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: totalPrunedCount,\n });\n }\n }\n\n if (hasNamedDictionaries) {\n for (const rule of ownership.rules) {\n // Dictionary bundles include ALL keys from matching namespaces — no tree-shaking.\n // Dictionaries are the \"preload everything I need\" layer.\n // Only scope bundles are pruned to extracted keys.\n const matchedNamespaces = new Set<string>();\n\n // Find all namespaces that match this dictionary's include patterns (minus exclude)\n const localeDir = path.join(localesDir, locales[0]);\n let nsFiles: string[] = [];\n try {\n nsFiles = fs.readdirSync(localeDir).filter(f => f.endsWith('.json'));\n } catch { /* dir may not exist */ }\n\n for (const file of nsFiles) {\n const ns = file.slice(0, -'.json'.length);\n // Check if any key in this namespace would match the include patterns\n if (rule.include.some(pattern => keyMatchesPattern(`${ns}.x`, pattern) || keyMatchesPattern(`${ns}.`, pattern) || pattern === `${ns}.*` || pattern.startsWith(`${ns}.`) || (pattern.endsWith('*') && ns.startsWith(pattern.slice(0, -1))))) {\n matchedNamespaces.add(ns);\n }\n }\n\n // Also check from the ownership map (covers exact key patterns)\n const ownedKeys = ownership.dictionaryKeys.get(rule.name) ?? new Set<string>();\n for (const key of ownedKeys) {\n const ns = key.split('.')[0];\n if (ns) matchedNamespaces.add(ns);\n }\n\n for (const locale of locales) {\n const bundleData: Record<string, unknown> = {};\n let totalKeyCount = 0;\n\n for (const ns of matchedNamespaces) {\n const fullData = readNamespaceFile(localesDir, locale, ns);\n if (!fullData) continue;\n\n // Include ALL keys from the namespace that match include and don't match exclude\n const allKeys = flattenKeys(fullData);\n const includedKeys = allKeys.filter(subKey => {\n const fullKey = `${ns}.${subKey}`;\n const included = rule.include.some(pattern => keyMatchesPattern(fullKey, pattern));\n const excluded = rule.exclude.length > 0 &&\n rule.exclude.some(pattern => keyMatchesPattern(fullKey, pattern));\n return included && !excluded;\n });\n\n if (includedKeys.length === 0) continue;\n\n const pruned = pruneNamespace(fullData, includedKeys);\n bundleData[ns] = pruned;\n totalKeyCount += flattenKeys(pruned).length;\n }\n\n const filePath = path.join(outDir, locale, '_dict', `${rule.name}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(bundleData, null, 2));\n\n bundles.push({\n name: `_dict/${rule.name}`,\n locale,\n filePath,\n keyCount: totalKeyCount,\n prunedCount: 0,\n });\n }\n }\n\n return bundles;\n }\n\n // Legacy shared-namespace dictionary bundles\n for (const sharedNs of analysis.sharedNamespaces) {\n // Collect ALL keys used across ALL routes for this namespace\n const allSubKeys = new Set<string>();\n for (const route of analysis.routes) {\n for (const key of route.keys) {\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n const ns = key.key.substring(0, dotIndex);\n if (ns === sharedNs) {\n const subKey = key.dynamic && key.staticPrefix\n ? key.staticPrefix.substring(dotIndex + 1)\n : key.key.substring(dotIndex + 1);\n allSubKeys.add(subKey);\n }\n }\n }\n\n for (const locale of locales) {\n const fullData = readNamespaceFile(localesDir, locale, sharedNs);\n if (!fullData) continue;\n\n const uniqueSubKeys = [...allSubKeys];\n const pruned = pruneNamespace(fullData, uniqueSubKeys);\n\n const filePath = path.join(outDir, locale, '_dict', `${sharedNs}.json`);\n fs.mkdirSync(path.dirname(filePath), { recursive: true });\n fs.writeFileSync(filePath, JSON.stringify(pruned, null, 2));\n\n const availableCount = flattenKeys(fullData).length;\n const keptCount = flattenKeys(pruned).length;\n\n bundles.push({\n name: `_dict/${sharedNs}`,\n locale,\n filePath,\n keyCount: keptCount,\n prunedCount: availableCount - keptCount,\n });\n }\n }\n\n return bundles;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\n\nconst PLACEHOLDER_PATTERN = /\\{\\{\\s*(\\w+)\\s*\\}\\}/g;\n\n/**\n * Recursively flattens a nested object to dot-separated leaf key paths.\n *\n * @example\n * flattenToKeyPaths({ show: { title: 'X' }, ok: 'Z' })\n * // → ['show.title', 'ok']\n */\nexport function flattenToKeyPaths(data: object, prefix?: string): string[] {\n const result: string[] = [];\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n result.push(...flattenToKeyPaths(value as object, fullKey));\n } else {\n result.push(fullKey);\n }\n }\n\n return result;\n}\n\n/**\n * Recursively flattens a nested object to a map of dot-separated leaf key paths\n * to their string values.\n */\nexport function flattenToLeafValues(\n data: object,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = prefix !== undefined ? `${prefix}.${key}` : key;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (value !== null && typeof value === 'object' && !Array.isArray(value)) {\n for (const [nestedKey, nestedValue] of flattenToLeafValues(value as object, fullKey)) {\n result.set(nestedKey, nestedValue);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Extracts placeholder names from a translation string.\n */\nexport function extractPlaceholders(text: string): string[] {\n const names = new Set<string>();\n for (const match of text.matchAll(PLACEHOLDER_PATTERN)) {\n if (match[1]) {\n names.add(match[1]);\n }\n }\n return [...names];\n}\n\n/**\n * Builds nested TypeScript interface content from flat dot-separated keys.\n * Each leaf becomes `true`, each branch becomes a nested object.\n */\nfunction buildNestedInterface(keys: string[]): string {\n // Build tree structure\n type TreeNode = { [segment: string]: TreeNode | true };\n const tree: TreeNode = {};\n\n for (const key of keys) {\n const parts = key.split('.');\n let current: TreeNode = tree;\n for (let i = 0; i < parts.length; i++) {\n const part = parts[i];\n if (i === parts.length - 1) {\n current[part] = true;\n } else {\n if (current[part] === true || current[part] === undefined) {\n current[part] = {};\n }\n current = current[part] as TreeNode;\n }\n }\n }\n\n // Serialize to TypeScript\n function serialize(node: TreeNode | true, indent: number): string {\n if (node === true) return 'true';\n const pad = ' '.repeat(indent);\n const entries = Object.entries(node).sort(([a], [b]) => a.localeCompare(b));\n const lines = entries.map(([key, value]) => {\n const serialized = serialize(value, indent + 1);\n if (serialized === 'true') {\n return `${pad}'${key}': true;`;\n }\n return `${pad}'${key}': {\\n${serialized}\\n${pad}};`;\n });\n return lines.join('\\n');\n }\n\n return serialize(tree, 2);\n}\n\n/**\n * Reads all `.json` files in `{localesDir}/{defaultLocale}/`, flattens each to\n * key paths, and returns a TypeScript declaration string that:\n *\n * 1. Augments the `vite-bundled-i18n` module to populate `I18nKeyMap` — this\n * wires autocomplete directly into `t()`, `useI18n().t`, and `hasKey()`.\n * 2. Exports `TranslationKey`, `Namespace`, and `NamespaceKeyPaths<T>` for\n * direct use in application code.\n *\n * When this file is present in the project, `t('shar...')` autocompletes to\n * `t('shared.ok')`. Without it, `t()` accepts any string.\n */\nexport function generateTypes(localesDir: string, defaultLocale: string, scopes?: string[]): string {\n const localeDir = path.join(localesDir, defaultLocale);\n\n let entries: string[];\n try {\n entries = fs.readdirSync(localeDir);\n } catch {\n entries = [];\n }\n\n const jsonFiles = entries.filter((f) => f.endsWith('.json')).sort();\n\n /** Map from namespace name → flat key paths (without namespace prefix) */\n const namespaceMap = new Map<string, string[]>();\n /** Map from fully qualified key → placeholder names */\n const paramsMap = new Map<string, string[]>();\n\n for (const file of jsonFiles) {\n const namespace = file.slice(0, -'.json'.length);\n const raw = fs.readFileSync(path.join(localeDir, file), 'utf-8');\n const data: unknown = JSON.parse(raw);\n const keyPaths =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToKeyPaths(data as object)\n : [];\n namespaceMap.set(namespace, keyPaths);\n\n const leafValues =\n data !== null && typeof data === 'object' && !Array.isArray(data)\n ? flattenToLeafValues(data as object)\n : new Map<string, string>();\n for (const [keyPath, value] of leafValues) {\n paramsMap.set(`${namespace}.${keyPath}`, extractPlaceholders(value));\n }\n }\n\n // Collect all fully qualified keys\n const allQualifiedKeys: string[] = [];\n for (const [ns, paths] of namespaceMap) {\n for (const p of paths) {\n allQualifiedKeys.push(`${ns}.${p}`);\n }\n }\n\n // ---- I18nParamsMap (only keys with placeholders — skip empty {}) -----------\n let paramsMapEntries: string;\n const keysWithParams = allQualifiedKeys.filter(k => (paramsMap.get(k) ?? []).length > 0);\n if (keysWithParams.length === 0) {\n paramsMapEntries = ' // No parameterized keys found';\n } else {\n paramsMapEntries = keysWithParams\n .map((k) => {\n const placeholders = paramsMap.get(k)!;\n const shape = `{ ${placeholders.map((name) => `${name}: TranslationValue`).join('; ')} }`;\n return ` '${k}': ${shape};`;\n })\n .join('\\n');\n }\n\n // ---- I18nNestedKeys (progressive autocomplete) ----------------------------\n let nestedKeysBlock: string;\n if (allQualifiedKeys.length === 0) {\n nestedKeysBlock = ' interface I18nNestedKeys {}';\n } else {\n const nestedBody = buildNestedInterface(allQualifiedKeys);\n nestedKeysBlock = ` interface I18nNestedKeys {\\n${nestedBody}\\n }`;\n }\n\n // ---- I18nScopeMap ----\n let scopeMapEntries: string;\n if (!scopes || scopes.length === 0) {\n scopeMapEntries = ' // No scopes found';\n } else {\n scopeMapEntries = scopes\n .sort()\n .map((s) => ` '${s}': true;`)\n .join('\\n');\n }\n\n // Direct exports — the generated file is imported by src/core/types.ts.\n // No module augmentation. This works for both npm consumers and local dev.\n return [\n '// Auto-generated by vite-bundled-i18n — do not edit.',\n '// Regenerated on: npm run dev (auto), npm run build, npm run i18n -- generate',\n '//',\n '// Add \".i18n\" to your tsconfig include: { \"include\": [\"src\", \".i18n\"] }',\n '',\n 'type TranslationValue = string | number | boolean | bigint | null | undefined;',\n '',\n '// Direct exports — used by the package to populate types',\n `export ${nestedKeysBlock.replace(' interface ', 'interface ')}`,\n '',\n `export interface I18nParamsMap {`,\n paramsMapEntries,\n `}`,\n '',\n `export interface I18nScopeMap {`,\n scopeMapEntries,\n `}`,\n '',\n ].join('\\n');\n}\n\n/**\n * Calls {@link generateTypes} and writes the result to `outPath`.\n */\nexport function writeTypes(\n localesDir: string,\n defaultLocale: string,\n outPath: string,\n scopes?: string[],\n): void {\n const content = generateTypes(localesDir, defaultLocale, scopes);\n fs.mkdirSync(path.dirname(outPath), { recursive: true });\n fs.writeFileSync(outPath, content, 'utf-8');\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport { flattenKeys } from './bundle-generator';\nimport type { DictionaryConfig } from '../core/types';\nimport {\n keyMatchesPattern,\n normalizeDictionaries,\n resolveDictionaryOwnership,\n} from './dictionary-ownership';\n\n/**\n * Read all namespace JSON files for the default locale and return a map of\n * namespace → flattened dot-path key arrays.\n */\nexport function flattenLocaleKeys(\n localesDir: string,\n defaultLocale: string,\n): Map<string, string[]> {\n const result = new Map<string, string[]>();\n const localeDir = path.join(localesDir, defaultLocale);\n\n if (!fs.existsSync(localeDir)) return result;\n\n const entries = fs.readdirSync(localeDir);\n for (const entry of entries) {\n if (!entry.endsWith('.json')) continue;\n const namespace = entry.slice(0, -5);\n const filePath = path.join(localeDir, entry);\n try {\n const data = JSON.parse(fs.readFileSync(filePath, 'utf-8')) as object;\n result.set(namespace, flattenKeys(data));\n } catch {\n // skip malformed files\n }\n }\n\n return result;\n}\n\n/**\n * Generate the manifest report: mapping of routeId → { scopes, keys, files }.\n */\nexport function generateManifest(\n analysis: ProjectAnalysis,\n): Record<string, object> {\n const manifest: Record<string, object> = {};\n\n for (const route of analysis.routes) {\n manifest[route.routeId] = {\n scopes: route.scopes,\n keys: route.keys.map((k) => k.key),\n files: route.files,\n };\n }\n\n return manifest;\n}\n\n/**\n * A single missing-key entry.\n */\nexport interface MissingKeyEntry {\n key: string;\n usedIn: string[];\n line: number;\n}\n\n/**\n * Generate the missing-keys report: keys used in code that don't exist in\n * translation files.\n */\nexport function generateMissing(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { summary?: { total: number; hint: string }; keys: MissingKeyEntry[] } {\n const missing: MissingKeyEntry[] = [];\n\n for (const key of analysis.allKeys) {\n // Skip dynamic keys — they can't be checked statically.\n if (key.dynamic) continue;\n\n const dotIndex = key.key.indexOf('.');\n if (dotIndex === -1) continue;\n\n const namespace = key.key.substring(0, dotIndex);\n const subKey = key.key.substring(dotIndex + 1);\n\n const namespacePaths = availableKeys.get(namespace);\n if (!namespacePaths || !namespacePaths.includes(subKey)) {\n // Collect all files where this key appears across routes.\n const usedIn: string[] = [];\n for (const route of analysis.routes) {\n for (const rk of route.keys) {\n if (rk.key === key.key && rk.line === key.line) {\n for (const file of route.files) {\n if (!usedIn.includes(file)) {\n usedIn.push(file);\n }\n }\n }\n }\n }\n\n missing.push({ key: key.key, usedIn, line: key.line });\n }\n }\n\n if (missing.length > 50) {\n return {\n summary: {\n total: missing.length,\n hint: 'If most keys are missing, verify localesDir structure: {locale}/{namespace}.json',\n },\n keys: missing,\n };\n }\n\n return { keys: missing };\n}\n\n/**\n * A single unused-key entry.\n */\nexport interface UnusedKeyEntry {\n key: string;\n namespace: string;\n}\n\n/**\n * Generate the unused-keys report: keys in translation files that no route\n * uses.\n */\nexport function generateUnused(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): { keys: UnusedKeyEntry[] } {\n const unused: UnusedKeyEntry[] = [];\n\n // Build a set of all fully-qualified keys used across all routes.\n const usedKeys = new Set<string>(analysis.allKeys.map((k) => k.key));\n\n for (const [namespace, keyPaths] of availableKeys) {\n for (const keyPath of keyPaths) {\n const fullKey = `${namespace}.${keyPath}`;\n if (!usedKeys.has(fullKey)) {\n unused.push({ key: fullKey, namespace });\n }\n }\n }\n\n return { keys: unused };\n}\n\n/**\n * Per-route statistics entry.\n */\nexport interface RouteStats {\n routeId: string;\n usedKeys: number;\n availableKeys: number;\n prunedKeys: number;\n}\n\n/**\n * A key that is used by more than one route and whose namespace is not in a\n * dictionary, making it a candidate for extraction.\n */\nexport interface DictionaryCandidate {\n key: string;\n namespace: string;\n usedByRoutes: string[];\n routeCount: number;\n}\n\n/**\n * Per-namespace usage summary.\n */\nexport interface NamespaceUsageEntry {\n namespace: string;\n routeCount: number;\n totalRoutes: number;\n percentage: number;\n inDictionary: boolean;\n}\n\n/**\n * Full overlap analysis result.\n */\nexport interface OverlapAnalysis {\n candidates: DictionaryCandidate[];\n namespaceUsage: NamespaceUsageEntry[];\n}\n\nexport interface DictionaryOwnershipRuleReport {\n name: string;\n priority: number;\n include: string[];\n ownedKeys: string[];\n}\n\nexport interface DictionaryCollisionReport {\n key: string;\n owner: string;\n matchedDictionaries: string[];\n}\n\nexport interface DictionaryOwnershipReport {\n rules: DictionaryOwnershipRuleReport[];\n collisions: DictionaryCollisionReport[];\n unownedKeys: string[];\n}\n\n/**\n * Analyse key and namespace overlap across routes. Keys used by more than one\n * route whose namespace is NOT already a dictionary namespace are returned as\n * candidates. The namespace-level summary describes what fraction of routes\n * use each namespace.\n */\nexport function generateOverlapAnalysis(\n analysis: ProjectAnalysis,\n dictionaryNamespaces?: Set<string>,\n): OverlapAnalysis {\n const dictNs = dictionaryNamespaces ?? new Set<string>();\n const totalRoutes = analysis.routes.length;\n\n // 1. Map each fully-qualified key → set of routeIds that use it.\n const keyToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n if (!keyToRoutes.has(k.key)) {\n keyToRoutes.set(k.key, new Set());\n }\n keyToRoutes.get(k.key)!.add(route.routeId);\n }\n }\n\n // 2. Build candidates: keys used by >1 route whose namespace is not a\n // dictionary namespace.\n const candidates: DictionaryCandidate[] = [];\n for (const [key, routes] of keyToRoutes) {\n if (routes.size <= 1) continue;\n const dotIndex = key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = key.substring(0, dotIndex);\n if (dictNs.has(namespace)) continue;\n const usedByRoutes = Array.from(routes);\n candidates.push({ key, namespace, usedByRoutes, routeCount: usedByRoutes.length });\n }\n\n // Sort for stable output: descending routeCount then alphabetical key.\n candidates.sort((a, b) => b.routeCount - a.routeCount || a.key.localeCompare(b.key));\n\n // 3. Namespace-level analysis: for each namespace, count distinct routes.\n const namespaceToRoutes = new Map<string, Set<string>>();\n for (const route of analysis.routes) {\n for (const k of route.keys) {\n if (k.dynamic) continue;\n const dotIndex = k.key.indexOf('.');\n if (dotIndex === -1) continue;\n const namespace = k.key.substring(0, dotIndex);\n if (!namespaceToRoutes.has(namespace)) {\n namespaceToRoutes.set(namespace, new Set());\n }\n namespaceToRoutes.get(namespace)!.add(route.routeId);\n }\n }\n\n const namespaceUsage: NamespaceUsageEntry[] = [];\n for (const [namespace, routes] of namespaceToRoutes) {\n const routeCount = routes.size;\n const percentage =\n totalRoutes === 0 ? 0 : Math.round((routeCount / totalRoutes) * 100);\n namespaceUsage.push({\n namespace,\n routeCount,\n totalRoutes,\n percentage,\n inDictionary: dictNs.has(namespace),\n });\n }\n\n // Sort descending by routeCount then alphabetically.\n namespaceUsage.sort(\n (a, b) => b.routeCount - a.routeCount || a.namespace.localeCompare(b.namespace),\n );\n\n return { candidates, namespaceUsage };\n}\n\n/**\n * Generate the stats report: summary counts.\n */\nexport function generateStats(\n analysis: ProjectAnalysis,\n availableKeys: Map<string, string[]>,\n): object {\n const totalKeysInFiles = Array.from(availableKeys.values()).reduce(\n (sum, paths) => sum + paths.length,\n 0,\n );\n\n const missingResult = generateMissing(analysis, availableKeys);\n const unusedResult = generateUnused(analysis, availableKeys);\n\n const perRoute: RouteStats[] = analysis.routes.map((route) => ({\n routeId: route.routeId,\n usedKeys: route.keys.filter((k) => !k.dynamic).length,\n availableKeys: totalKeysInFiles,\n prunedKeys: totalKeysInFiles - route.keys.filter((k) => !k.dynamic).length,\n }));\n\n const overlapResult = generateOverlapAnalysis(analysis);\n const sharedKeysCount = new Set(\n overlapResult.candidates.map((c) => c.key),\n ).size;\n const dictionaryCandidates = Array.from(\n new Set(overlapResult.candidates.map((c) => c.namespace)),\n );\n\n return {\n totalKeysInCode: analysis.allKeys.length,\n totalKeysInFiles,\n usedKeys: analysis.allKeys.length,\n missingKeys: missingResult.keys.length,\n unusedKeys: unusedResult.keys.length,\n routes: analysis.routes.length,\n namespaces: analysis.availableNamespaces.length,\n sharedNamespaces: analysis.sharedNamespaces,\n sharedKeysCount,\n dictionaryCandidates,\n perRoute,\n };\n}\n\nexport function generateDictionaryOwnershipReport(\n availableKeys: Map<string, string[]>,\n dictionaries?: Record<string, DictionaryConfig>,\n): DictionaryOwnershipReport {\n const rules = normalizeDictionaries(dictionaries);\n const allKeys = [...availableKeys.entries()].flatMap(([namespace, keys]) =>\n keys.map((key) => `${namespace}.${key}`),\n );\n const ownership = resolveDictionaryOwnership(allKeys, dictionaries);\n\n const collisions: DictionaryCollisionReport[] = [];\n for (const key of allKeys) {\n const matched = rules\n .filter((rule) => rule.include.some((pattern) => keyMatchesPattern(key, pattern)))\n .map((rule) => rule.name);\n if (matched.length > 1) {\n collisions.push({\n key,\n owner: ownership.keyOwner.get(key) ?? matched[0],\n matchedDictionaries: matched,\n });\n }\n }\n\n return {\n rules: rules.map((rule) => ({\n name: rule.name,\n priority: rule.priority,\n include: rule.include,\n ownedKeys: [...(ownership.dictionaryKeys.get(rule.name) ?? new Set())].sort(),\n })),\n collisions: collisions.sort((a, b) => a.key.localeCompare(b.key)),\n unownedKeys: allKeys.filter((key) => !ownership.keyOwner.has(key)).sort(),\n };\n}\n\n/**\n * Orchestrate report generation: flatten locale keys, generate all four\n * reports, and write them as JSON files to outDir.\n */\nexport function generateReports(\n analysis: ProjectAnalysis,\n localesDir: string,\n defaultLocale: string,\n outDir: string,\n dictionaries?: Record<string, DictionaryConfig>,\n): void {\n const availableKeys = flattenLocaleKeys(localesDir, defaultLocale);\n\n const manifest = generateManifest(analysis);\n const missing = generateMissing(analysis, availableKeys);\n const unused = generateUnused(analysis, availableKeys);\n const stats = generateStats(analysis, availableKeys);\n const overlap = generateOverlapAnalysis(analysis);\n const ownership = generateDictionaryOwnershipReport(availableKeys, dictionaries);\n\n fs.mkdirSync(outDir, { recursive: true });\n\n fs.writeFileSync(\n path.join(outDir, 'manifest.json'),\n JSON.stringify(manifest, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'missing.json'),\n JSON.stringify(missing, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'unused.json'),\n JSON.stringify(unused, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'stats.json'),\n JSON.stringify(stats, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'overlap.json'),\n JSON.stringify(overlap, null, 2),\n );\n fs.writeFileSync(\n path.join(outDir, 'ownership.json'),\n JSON.stringify(ownership, null, 2),\n );\n}\n","import ts from 'typescript';\n\n/**\n * Extracts a string value from a node if it's a string literal or\n * a no-substitution template literal. Returns undefined for anything else.\n */\nexport function getStringValue(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n return node.text;\n }\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n return node.text;\n }\n return undefined;\n}\n\n/**\n * Extracts the longest static prefix from an expression.\n *\n * For string literals, returns the full string.\n * For template literals, returns the head text (before the first expression), trimmed of trailing dots.\n * For binary `+` expressions, recursively extracts from the left side.\n * For anything else, returns undefined.\n */\nexport function getStaticPrefix(node: ts.Expression): string | undefined {\n if (ts.isStringLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isNoSubstitutionTemplateLiteral(node)) {\n const text = node.text;\n return text.endsWith('.') ? text.slice(0, -1) : text || undefined;\n }\n\n if (ts.isTemplateExpression(node)) {\n const head = node.head.text;\n return head.endsWith('.') ? head.slice(0, -1) : head || undefined;\n }\n\n if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {\n return getStaticPrefix(node.left);\n }\n\n return undefined;\n}\n\n/**\n * Collects all non-type-only import and export-from specifiers from a source file.\n */\nexport function collectImports(sourceFile: ts.SourceFile): string[] {\n const imports: string[] = [];\n\n ts.forEachChild(sourceFile, (node) => {\n if (ts.isImportDeclaration(node)) {\n if (node.importClause?.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n\n if (ts.isExportDeclaration(node) && node.moduleSpecifier) {\n if (node.isTypeOnly) return;\n if (ts.isStringLiteral(node.moduleSpecifier)) {\n imports.push(node.moduleSpecifier.text);\n }\n }\n });\n\n return imports;\n}\n","import ts from 'typescript';\nimport { getStringValue, getStaticPrefix } from './ast-utils';\nimport type { ExtractionOptions, ExtractedKey } from './types';\n\nconst DEFAULT_KEY_FIELDS = ['labelKey', 'titleKey', 'translationKey'];\n\n/** Function names recognized as translation calls even when not traced to useI18n(). */\nconst TRANSLATION_CALLEE_NAMES = new Set(['t', 'get']);\n\nfunction getKeyFields(options: ExtractionOptions): Set<string> {\n if (!options.keyFields || options.keyFields.length === 0) {\n return new Set(DEFAULT_KEY_FIELDS);\n }\n return new Set([...DEFAULT_KEY_FIELDS, ...options.keyFields]);\n}\nconst PACKAGE_NAMES = new Set([\n 'vite-bundled-i18n',\n 'vite-bundled-i18n/react',\n 'vite-i18n-manager',\n 'vite-i18n-manager/react',\n]);\n\n/**\n * Package specifiers recognized as ours.\n *\n * @param specifier - The import module specifier to check.\n * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.\n */\nfunction isOurPackage(specifier: string, hookSources?: string[]): boolean {\n return (\n PACKAGE_NAMES.has(specifier) ||\n specifier.includes('/core/t') ||\n specifier.includes('/react/useI18n') ||\n matchesHookSource(specifier, hookSources)\n );\n}\n\n/**\n * Checks if a module specifier exports `useI18n`.\n *\n * @param specifier - The import module specifier to check.\n * @param hookSources - Additional module specifiers configured via `extraction.hookSources`.\n */\nfunction isUseI18nPackage(specifier: string, hookSources?: string[]): boolean {\n return (\n specifier === 'vite-bundled-i18n/react' ||\n specifier === 'vite-i18n-manager/react' ||\n specifier.includes('/react/useI18n') ||\n matchesHookSource(specifier, hookSources)\n );\n}\n\n/**\n * Checks if a specifier matches any configured hook source.\n * Uses exact match or endsWith to handle path alias resolution.\n */\nfunction matchesHookSource(specifier: string, hookSources?: string[]): boolean {\n if (!hookSources || hookSources.length === 0) return false;\n return hookSources.some(source => specifier === source || specifier.endsWith(source));\n}\n\n/**\n * Checks if a module specifier is one that exports the global `t`.\n */\nfunction isGlobalTPackage(specifier: string): boolean {\n return (\n specifier === 'vite-bundled-i18n' ||\n specifier === 'vite-i18n-manager' ||\n specifier.includes('/core/t')\n );\n}\n\n/**\n * Extract the fallback string from a t() call's arguments.\n * - t(key, fallback) where fallback is a string literal\n * - t(key, params, fallback) where params is an object literal and fallback is a string literal\n */\nfunction extractFallback(args: ts.NodeArray<ts.Expression>): string | undefined {\n if (args.length >= 2) {\n const second = args[1];\n // t(key, fallbackString)\n const secondStr = getStringValue(second);\n if (secondStr !== undefined) {\n return secondStr;\n }\n // t(key, paramsObject, fallbackString)\n if (args.length >= 3 && ts.isObjectLiteralExpression(second)) {\n const third = args[2];\n const thirdStr = getStringValue(third);\n if (thirdStr !== undefined) {\n return thirdStr;\n }\n }\n }\n return undefined;\n}\n\n/**\n * Finds all t() translation calls in a source file.\n */\nexport function findTranslationCalls(\n sourceFile: ts.SourceFile,\n options: ExtractionOptions,\n): ExtractedKey[] {\n const results: ExtractedKey[] = [];\n const seenStaticFieldKeys = new Set<string>();\n\n // Track which local identifiers map to our global `t`\n // key = local name, value = 'global' | 'useI18n'\n const trackedNames = new Map<string, 'global' | 'useI18n'>();\n\n // Set of local names bound to our `useI18n` import\n const useI18nNames = new Set<string>();\n const i18nKeyNames = new Set<string>();\n const literalConstants = new Map<string, string>();\n /** Tracks `as const` objects and string enums: varName → (propName → stringValue) */\n const constObjectMaps = new Map<string, Map<string, string>>();\n\n // Pass 1: Walk imports\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isOurPackage(specifier, options.hookSources)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n\n if (importedName === 't' && isGlobalTPackage(specifier)) {\n if (options.scope !== 'scoped') {\n trackedNames.set(localName, 'global');\n }\n }\n\n if (importedName === 'useI18n' && isUseI18nPackage(specifier, options.hookSources)) {\n useI18nNames.add(localName);\n }\n\n if (importedName === 'i18nKey' && isOurPackage(specifier, options.hookSources)) {\n i18nKeyNames.add(localName);\n }\n }\n });\n\n // Pass 1b: Collect `as const` objects and string enums\n ts.forEachChild(sourceFile, (node) => {\n // as const objects: const X = { ... } as const\n if (ts.isVariableStatement(node)) {\n for (const decl of node.declarationList.declarations) {\n if (!ts.isIdentifier(decl.name) || !decl.initializer) continue;\n if (!ts.isAsExpression(decl.initializer)) continue;\n const init = decl.initializer.expression;\n if (!ts.isObjectLiteralExpression(init)) continue;\n\n const entries = new Map<string, string>();\n for (const prop of init.properties) {\n if (!ts.isPropertyAssignment(prop)) continue;\n const propName = ts.isIdentifier(prop.name)\n ? prop.name.text\n : ts.isStringLiteral(prop.name)\n ? prop.name.text\n : undefined;\n if (!propName) continue;\n const value = getStringValue(prop.initializer);\n if (value !== undefined) {\n entries.set(propName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(decl.name.text, entries);\n }\n }\n }\n\n // String enums\n if (ts.isEnumDeclaration(node) && ts.isIdentifier(node.name)) {\n const entries = new Map<string, string>();\n for (const member of node.members) {\n const memberName = ts.isIdentifier(member.name)\n ? member.name.text\n : ts.isStringLiteral(member.name)\n ? member.name.text\n : undefined;\n if (!memberName || !member.initializer) continue;\n const value = getStringValue(member.initializer);\n if (value !== undefined) {\n entries.set(memberName, value);\n }\n }\n if (entries.size > 0) {\n constObjectMaps.set(node.name.text, entries);\n }\n }\n });\n\n // Pass 2: Walk entire AST to find useI18n destructuring and t() calls\n const keyFields = getKeyFields(options);\n function visit(node: ts.Node): void {\n if (\n ts.isVariableDeclaration(node) &&\n ts.isIdentifier(node.name) &&\n node.initializer &&\n getStringValue(node.initializer) !== undefined\n ) {\n literalConstants.set(node.name.text, getStringValue(node.initializer)!);\n }\n\n // Look for: const { t } = useI18n(...) or const { t: alias } = useI18n(...)\n if (\n ts.isVariableDeclaration(node) &&\n node.initializer &&\n ts.isCallExpression(node.initializer) &&\n ts.isIdentifier(node.initializer.expression) &&\n useI18nNames.has(node.initializer.expression.text) &&\n node.name &&\n ts.isObjectBindingPattern(node.name)\n ) {\n for (const element of node.name.elements) {\n if (!ts.isIdentifier(element.name)) continue;\n const propName = element.propertyName\n ? ts.isIdentifier(element.propertyName)\n ? element.propertyName.text\n : undefined\n : element.name.text;\n\n if (propName === 't') {\n const localName = element.name.text;\n trackedNames.set(localName, 'useI18n');\n }\n }\n }\n\n // Look for calls to tracked identifiers\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n trackedNames.has(node.expression.text)\n ) {\n const args = node.arguments;\n if (args.length === 0) {\n ts.forEachChild(node, visit);\n return;\n }\n\n const keyArg = args[0];\n let staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n\n // Const object / enum property access: KEYS.active\n if (staticKey === undefined && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n const value = objMap.get(keyArg.name.text);\n if (value !== undefined) {\n staticKey = value;\n }\n }\n }\n\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n // Const object / enum element access with dynamic index: KEYS[status]\n if (staticKey === undefined && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n for (const value of objMap.values()) {\n results.push({\n key: value,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n ts.forEachChild(node, visit);\n return;\n }\n }\n\n if (staticKey !== undefined) {\n // Static key\n results.push({\n key: staticKey,\n fallback: extractFallback(args),\n dynamic: false,\n line: line + 1,\n column: character,\n });\n } else {\n // Dynamic key\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n i18nKeyNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const keyArg = node.arguments[0];\n let staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n\n // Const object / enum property access: KEYS.active\n if (staticKey === undefined && ts.isPropertyAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n const value = objMap.get(keyArg.name.text);\n if (value !== undefined) {\n staticKey = value;\n }\n }\n }\n\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n\n // Const object / enum element access with dynamic index: KEYS[status]\n if (staticKey === undefined && ts.isElementAccessExpression(keyArg) && ts.isIdentifier(keyArg.expression)) {\n const objMap = constObjectMaps.get(keyArg.expression.text);\n if (objMap) {\n for (const value of objMap.values()) {\n results.push({\n key: value,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n ts.forEachChild(node, visit);\n return;\n }\n }\n\n if (staticKey !== undefined) {\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n } else {\n const prefix = getStaticPrefix(keyArg);\n results.push({\n key: prefix ? `${prefix}.*` : '*',\n dynamic: true,\n staticPrefix: prefix || undefined,\n line: line + 1,\n column: character,\n });\n }\n }\n\n // Catch t() / get() calls from untracked sources (e.g., t passed as argument to helpers).\n // Only fires in global extraction mode — scoped mode only tracks traced identifiers.\n if (\n options.scope !== 'scoped' &&\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n !trackedNames.has(node.expression.text) &&\n !i18nKeyNames.has(node.expression.text) &&\n TRANSLATION_CALLEE_NAMES.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const keyArg = node.arguments[0];\n const staticKey = getStringValue(keyArg)\n ?? (ts.isIdentifier(keyArg) ? literalConstants.get(keyArg.text) : undefined);\n // Only extract if it looks like a dotted translation key (has at least one dot)\n if (staticKey !== undefined && staticKey.includes('.')) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n }\n\n if (\n ts.isPropertyAssignment(node) &&\n ((ts.isIdentifier(node.name) && keyFields.has(node.name.text))\n || (ts.isStringLiteral(node.name) && keyFields.has(node.name.text)))\n ) {\n const staticKey = getStringValue(node.initializer)\n ?? (ts.isIdentifier(node.initializer) ? literalConstants.get(node.initializer.text) : undefined);\n if (staticKey !== undefined && !seenStaticFieldKeys.has(staticKey)) {\n const { line, character } = sourceFile.getLineAndCharacterOfPosition(node.getStart());\n seenStaticFieldKeys.add(staticKey);\n results.push({\n key: staticKey,\n dynamic: false,\n line: line + 1,\n column: character,\n });\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return results;\n}\n\n/**\n * Extracts scope strings from all useI18n() calls in a source file.\n *\n * @param sourceFile - The parsed TypeScript source file.\n * @param hookSources - Additional module specifiers that export `useI18n`.\n */\nexport function extractScopes(sourceFile: ts.SourceFile, hookSources?: string[]): string[] {\n const scopes: string[] = [];\n\n // First check that useI18n is actually imported from our package\n const useI18nNames = new Set<string>();\n\n ts.forEachChild(sourceFile, (node) => {\n if (!ts.isImportDeclaration(node)) return;\n if (!ts.isStringLiteral(node.moduleSpecifier)) return;\n const specifier = node.moduleSpecifier.text;\n if (!isUseI18nPackage(specifier, hookSources)) return;\n\n const clause = node.importClause;\n if (!clause) return;\n const bindings = clause.namedBindings;\n if (!bindings || !ts.isNamedImports(bindings)) return;\n\n for (const element of bindings.elements) {\n const importedName = (element.propertyName ?? element.name).text;\n const localName = element.name.text;\n if (importedName === 'useI18n') {\n useI18nNames.add(localName);\n }\n }\n });\n\n function visit(node: ts.Node): void {\n if (\n ts.isCallExpression(node) &&\n ts.isIdentifier(node.expression) &&\n useI18nNames.has(node.expression.text) &&\n node.arguments.length > 0\n ) {\n const scopeArg = node.arguments[0];\n const scopeStr = getStringValue(scopeArg);\n if (scopeStr !== undefined) {\n scopes.push(scopeStr);\n }\n }\n\n ts.forEachChild(node, visit);\n }\n\n visit(sourceFile);\n return scopes;\n}\n","import ts from 'typescript';\nimport { collectImports } from './ast-utils';\nimport { findTranslationCalls, extractScopes } from './patterns';\nimport type { ExtractionOptions, ExtractionResult } from './types';\n\nconst DEFAULT_OPTIONS: ExtractionOptions = {\n scope: 'global',\n filePath: '',\n};\n\n/**\n * Extracts translation keys, scopes, and imports from a TypeScript/TSX source string.\n *\n * Parses the source with the TypeScript compiler, walks the AST to find\n * `t()` and `useI18n()` patterns, and returns structured extraction data.\n *\n * @param source - The TypeScript/TSX source code to analyze\n * @param options - Extraction options (scope mode, file path for metadata)\n * @returns The extraction result with keys, scopes, and imports\n */\nexport function extractKeys(\n source: string,\n options?: Partial<ExtractionOptions>,\n): ExtractionResult {\n const opts: ExtractionOptions = { ...DEFAULT_OPTIONS, ...options };\n\n if (!source.trim()) {\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n let sourceFile: ts.SourceFile;\n try {\n sourceFile = ts.createSourceFile(\n opts.filePath || 'source.tsx',\n source,\n ts.ScriptTarget.Latest,\n true,\n ts.ScriptKind.TSX,\n );\n } catch {\n console.warn('vite-bundled-i18n: Failed to parse ' + opts.filePath);\n return { filePath: opts.filePath, scopes: [], keys: [], imports: [] };\n }\n\n const keys = findTranslationCalls(sourceFile, opts);\n const scopes = extractScopes(sourceFile, opts.hookSources);\n const imports = collectImports(sourceFile);\n\n return {\n filePath: opts.filePath,\n scopes,\n keys,\n imports,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { globSync } from 'tinyglobby';\nimport ts from 'typescript';\nimport { extractKeys } from './extract';\nimport type { ExtractedKey } from './types';\nimport type {\n WalkerOptions,\n RouteAnalysis,\n ProjectAnalysis,\n} from './walker-types';\n\nconst RESOLVE_EXTENSIONS = ['.tsx', '.ts', '.jsx', '.js'];\nconst INDEX_EXTENSIONS = ['/index.tsx', '/index.ts'];\nconst tsconfigPathCache = new Map<string, { baseUrl?: string; paths?: Record<string, string[]> }>();\n\nfunction tryResolveBase(base: string): string | undefined {\n for (const ext of RESOLVE_EXTENSIONS) {\n const candidate = base + ext;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n for (const indexSuffix of INDEX_EXTENSIONS) {\n const candidate = base + indexSuffix;\n if (fs.existsSync(candidate)) {\n return candidate;\n }\n }\n\n return undefined;\n}\n\nfunction readTsconfigPaths(rootDir: string): { baseUrl?: string; paths?: Record<string, string[]> } {\n const cached = tsconfigPathCache.get(rootDir);\n if (cached) return cached;\n\n for (const fileName of ['tsconfig.app.json', 'tsconfig.json']) {\n const fullPath = path.join(rootDir, fileName);\n if (!fs.existsSync(fullPath)) continue;\n\n try {\n const configFile = ts.readConfigFile(fullPath, ts.sys.readFile);\n if (configFile.error) continue;\n const parsed = ts.parseJsonConfigFileContent(configFile.config, ts.sys, rootDir);\n const result = {\n baseUrl: parsed.options.baseUrl,\n paths: parsed.options.paths,\n };\n tsconfigPathCache.set(rootDir, result);\n return result;\n } catch {\n // Ignore malformed tsconfig and continue with default resolution.\n }\n }\n\n const empty = {};\n tsconfigPathCache.set(rootDir, empty);\n return empty;\n}\n\nfunction resolveAliasImport(\n specifier: string,\n rootDir: string,\n): string | undefined {\n const { baseUrl, paths } = readTsconfigPaths(rootDir);\n if (!baseUrl || !paths) return undefined;\n\n for (const [pattern, targets] of Object.entries(paths)) {\n const wildcardIndex = pattern.indexOf('*');\n\n if (wildcardIndex === -1) {\n if (specifier !== pattern) continue;\n for (const target of targets) {\n const candidate = tryResolveBase(path.resolve(baseUrl, target));\n if (candidate) return candidate;\n }\n continue;\n }\n\n const prefix = pattern.slice(0, wildcardIndex);\n const suffix = pattern.slice(wildcardIndex + 1);\n if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) {\n continue;\n }\n\n const matched = specifier.slice(prefix.length, specifier.length - suffix.length);\n for (const target of targets) {\n const resolvedTarget = target.replace('*', matched);\n const candidate = tryResolveBase(path.resolve(baseUrl, resolvedTarget));\n if (candidate) return candidate;\n }\n }\n\n return undefined;\n}\n\n/**\n * Resolves a relative import specifier to an absolute file path.\n *\n * Only handles relative imports (starting with `.` or `..`).\n * Returns undefined for package/bare imports or if no file is found.\n */\nexport function resolveImport(\n specifier: string,\n fromFile: string,\n rootDir?: string,\n): string | undefined {\n if (specifier.startsWith('.')) {\n const base = path.resolve(path.dirname(fromFile), specifier);\n return tryResolveBase(base);\n }\n\n if (rootDir) {\n return resolveAliasImport(specifier, rootDir);\n }\n\n return undefined;\n}\n\n/**\n * Derives a route identifier from the entry point file path.\n *\n * Strips the rootDir prefix and `src/pages/` prefix, then removes the extension.\n * Falls back to stripping just the rootDir prefix if `src/pages/` is not present.\n */\nexport function deriveRouteId(entryPoint: string, rootDir: string): string {\n let rel = path.relative(rootDir, entryPoint);\n\n const pagesPrefix = path.join('src', 'pages') + path.sep;\n if (rel.startsWith(pagesPrefix)) {\n rel = rel.slice(pagesPrefix.length);\n }\n\n // Strip extension\n const ext = path.extname(rel);\n if (ext) {\n rel = rel.slice(0, -ext.length);\n }\n\n return rel;\n}\n\n/**\n * Discovers namespace names from locale JSON files.\n *\n * Reads `{localesDir}/{defaultLocale}/` and returns sorted `.json`\n * filenames without their extension.\n */\nexport function discoverNamespaces(\n localesDir: string,\n defaultLocale: string,\n): string[] {\n const dir = path.join(localesDir, defaultLocale);\n\n try {\n const entries = fs.readdirSync(dir);\n return entries\n .filter((f) => f.endsWith('.json'))\n .map((f) => f.slice(0, -5))\n .sort();\n } catch {\n return [];\n }\n}\n\n/**\n * Walks a single route's import graph starting from the entry point.\n *\n * Reads each file, extracts translation keys and import specifiers,\n * then recursively follows relative imports. Handles circular imports\n * via a visited set and deduplicates keys by key string.\n */\nexport function walkRoute(\n entryPoint: string,\n options: { rootDir: string; extractionScope: 'global' | 'scoped'; hookSources?: string[] },\n): RouteAnalysis {\n const visited = new Set<string>();\n const allKeys: ExtractedKey[] = [];\n const allScopes: string[] = [];\n const allFiles: string[] = [];\n const seenKeys = new Set<string>();\n\n function visit(filePath: string): void {\n const resolved = path.resolve(filePath);\n if (visited.has(resolved)) {\n return;\n }\n visited.add(resolved);\n\n let source: string;\n try {\n source = fs.readFileSync(resolved, 'utf-8');\n } catch {\n return;\n }\n\n allFiles.push(resolved);\n\n const result = extractKeys(source, {\n scope: options.extractionScope,\n filePath: resolved,\n hookSources: options.hookSources,\n });\n\n for (const key of result.keys) {\n if (!seenKeys.has(key.key)) {\n seenKeys.add(key.key);\n allKeys.push(key);\n }\n }\n\n for (const scope of result.scopes) {\n if (!allScopes.includes(scope)) {\n allScopes.push(scope);\n }\n }\n\n for (const imp of result.imports) {\n const importPath = resolveImport(imp, resolved, options.rootDir);\n if (importPath) {\n visit(importPath);\n }\n }\n }\n\n visit(entryPoint);\n\n return {\n entryPoint: path.resolve(entryPoint),\n routeId: deriveRouteId(path.resolve(entryPoint), options.rootDir),\n scopes: allScopes,\n keys: allKeys,\n files: allFiles,\n };\n}\n\n/**\n * Walks the entire project: finds page entry points, analyzes each route,\n * discovers namespaces, and computes shared namespace candidates.\n */\nexport function walkAll(options: WalkerOptions): ProjectAnalysis {\n const rootDir = options.rootDir ?? process.cwd();\n const extractionScope = options.extractionScope ?? 'global';\n\n // Find page entry points\n const entryFiles = globSync(options.pages, { cwd: rootDir, absolute: true });\n\n // Walk each route\n const routes = entryFiles.map((entry) =>\n walkRoute(entry, { rootDir, extractionScope, hookSources: options.hookSources }),\n );\n\n // Discover namespaces\n const localesPath = path.isAbsolute(options.localesDir)\n ? options.localesDir\n : path.join(rootDir, options.localesDir);\n const availableNamespaces = discoverNamespaces(\n localesPath,\n options.defaultLocale,\n );\n\n // Deduplicate all keys across routes\n const allKeysMap = new Map<string, ExtractedKey>();\n for (const route of routes) {\n for (const key of route.keys) {\n if (!allKeysMap.has(key.key)) {\n allKeysMap.set(key.key, key);\n }\n }\n }\n const allKeys = Array.from(allKeysMap.values());\n\n // Compute shared namespaces (used by >50% of routes)\n const sharedNamespaces: string[] = [];\n if (routes.length > 0) {\n const nsCounts = new Map<string, number>();\n for (const route of routes) {\n const routeNamespaces = new Set<string>();\n for (const key of route.keys) {\n const ns = key.key.split('.')[0];\n if (ns) {\n routeNamespaces.add(ns);\n }\n }\n for (const ns of routeNamespaces) {\n nsCounts.set(ns, (nsCounts.get(ns) ?? 0) + 1);\n }\n }\n\n const threshold = routes.length / 2;\n for (const [ns, count] of nsCounts) {\n if (count > threshold) {\n sharedNamespaces.push(ns);\n }\n }\n sharedNamespaces.sort();\n }\n\n return {\n routes,\n availableNamespaces,\n allKeys,\n sharedNamespaces,\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { ProjectAnalysis } from './walker-types';\nimport type { DictionaryConfig } from '../core/types';\nimport { resolveDictionaryOwnership } from './dictionary-ownership';\nimport { buildScopePlans } from './scope-bundles';\n\n/**\n * Options for the module compiler.\n */\nexport interface CompilerOptions {\n /** Absolute path to the locales directory. */\n localesDir: string;\n /** List of locale codes to compile. */\n locales: string[];\n /** Default locale code used for fallback resolution. */\n defaultLocale: string;\n /** Output directory for compiled modules. */\n outDir: string;\n /** Optional dictionary configurations. */\n dictionaries?: Record<string, DictionaryConfig>;\n}\n\n/**\n * Escapes backslashes and single quotes for use in JS string literals.\n */\nfunction escapeValue(value: string): string {\n return value.replace(/\\\\/g, '\\\\\\\\').replace(/'/g, \"\\\\'\");\n}\n\n/**\n * Flattens a nested translation object into a flat Map with fully qualified keys.\n *\n * @param namespace - The namespace prefix (e.g., 'products')\n * @param data - The nested translation object\n * @param prefix - Internal prefix for recursion\n * @returns A Map of fully qualified keys to string values\n */\nexport function flattenNamespace(\n namespace: string,\n data: Record<string, unknown>,\n prefix?: string,\n): Map<string, string> {\n const result = new Map<string, string>();\n const currentPrefix = prefix ? `${prefix}.` : `${namespace}.`;\n\n for (const [key, value] of Object.entries(data)) {\n const fullKey = `${currentPrefix}${key}`;\n if (typeof value === 'string') {\n result.set(fullKey, value);\n } else if (typeof value === 'object' && value !== null) {\n const nested = flattenNamespace(\n namespace,\n value as Record<string, unknown>,\n fullKey,\n );\n for (const [k, v] of nested) {\n result.set(k, v);\n }\n }\n }\n\n return result;\n}\n\n/**\n * Creates a new map with all keys from primary, plus any missing keys filled from fallback.\n */\nexport function preResolveFallbacks(\n primary: Map<string, string>,\n fallback: Map<string, string>,\n): Map<string, string> {\n const result = new Map(primary);\n for (const [key, value] of fallback) {\n if (!result.has(key)) {\n result.set(key, value);\n }\n }\n return result;\n}\n\n/**\n * Generates a JavaScript module exporting a flat Map of translation entries.\n */\nexport function generateCompiledModule(entries: Map<string, string>): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('const m = new Map([');\n for (const [key, value] of entries) {\n lines.push(` ['${escapeValue(key)}','${escapeValue(value)}'],`);\n }\n lines.push(']);');\n lines.push('export default m;');\n lines.push('');\n return lines.join('\\n');\n}\n\n/**\n * Reads namespace JSON files for a locale and returns a combined flattened Map.\n */\nfunction buildLocaleMap(\n localesDir: string,\n locale: string,\n namespaces: string[],\n): Map<string, string> {\n const combined = new Map<string, string>();\n for (const ns of namespaces) {\n const filePath = path.join(localesDir, locale, `${ns}.json`);\n if (!fs.existsSync(filePath)) continue;\n const data = JSON.parse(\n fs.readFileSync(filePath, 'utf-8'),\n ) as Record<string, unknown>;\n const flat = flattenNamespace(ns, data);\n for (const [k, v] of flat) {\n combined.set(k, v);\n }\n }\n return combined;\n}\n\n/**\n * Reads ALL namespace JSON files for a locale directory.\n */\nfunction buildFullLocaleMap(\n localesDir: string,\n locale: string,\n): Map<string, string> {\n const localeDir = path.join(localesDir, locale);\n if (!fs.existsSync(localeDir)) return new Map();\n const files = fs.readdirSync(localeDir).filter((f) => f.endsWith('.json'));\n const namespaces = files.map((f) => f.replace(/\\.json$/, ''));\n return buildLocaleMap(localesDir, locale, namespaces);\n}\n\n/**\n * Filters a map to only include entries whose keys are in the given set.\n */\nfunction filterMap(\n map: Map<string, string>,\n keys: Set<string>,\n): Map<string, string> {\n const result = new Map<string, string>();\n for (const [k, v] of map) {\n if (keys.has(k)) {\n result.set(k, v);\n }\n }\n return result;\n}\n\n/**\n * Generates a dictionary module for a locale by reading all dictionary namespace files,\n * flattening them, and pre-resolving fallbacks against the default locale.\n */\nexport function generateDictionaryModule(\n localesDir: string,\n locale: string,\n defaultLocale: string,\n dictionaries: Record<string, DictionaryConfig>,\n dictionaryName: string,\n): string {\n const fullAvailable = buildFullLocaleMap(localesDir, defaultLocale);\n const ownership = resolveDictionaryOwnership(fullAvailable.keys(), dictionaries);\n const ownedKeys = ownership.dictionaryKeys.get(dictionaryName) ?? new Set<string>();\n\n const localeMap = filterMap(buildFullLocaleMap(localesDir, locale), ownedKeys);\n\n if (locale !== defaultLocale) {\n const defaultMap = filterMap(buildFullLocaleMap(localesDir, defaultLocale), ownedKeys);\n const resolved = preResolveFallbacks(localeMap, defaultMap);\n return generateCompiledModule(resolved);\n }\n\n return generateCompiledModule(localeMap);\n}\n\n/**\n * Generates a manifest module with dynamic import mappings for routes and dictionaries.\n */\nexport function generateManifest(\n scopeIds: string[],\n locales: string[],\n dictionaryNames: string[],\n): string {\n const lines: string[] = [];\n lines.push('// Auto-generated by vite-bundled-i18n. Do not edit.');\n lines.push('export const scopes = {');\n for (const scopeId of scopeIds) {\n lines.push(` '${escapeValue(scopeId)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/${scopeId}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n\n lines.push('export const routes = scopes;');\n lines.push('');\n\n if (dictionaryNames.length > 0) {\n lines.push('export const dictionaries = {');\n for (const name of dictionaryNames) {\n lines.push(` '${escapeValue(name)}': {`);\n for (const locale of locales) {\n lines.push(\n ` '${escapeValue(locale)}': () => import('./${locale}/_dict/${name}.js'),`,\n );\n }\n lines.push(' },');\n }\n lines.push('};');\n lines.push('');\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Orchestrates the full compilation of pre-compiled i18n modules.\n */\nexport function compileAll(\n analysis: ProjectAnalysis,\n options: CompilerOptions,\n): void {\n const { localesDir, locales, defaultLocale, outDir, dictionaries } = options;\n\n fs.mkdirSync(outDir, { recursive: true });\n\n // Build the default locale full map for fallback resolution\n const defaultFullMap = buildFullLocaleMap(localesDir, defaultLocale);\n\n // Determine which namespaces the routes reference\n const ownership = resolveDictionaryOwnership(defaultFullMap.keys(), dictionaries);\n\n // For each scope + locale: collect used keys, filter, resolve fallbacks, write\n const scopePlans = buildScopePlans(analysis, defaultFullMap.keys());\n for (const plan of scopePlans) {\n const usedKeys = new Set(\n [...plan.keys].filter((key) => !ownership.keyOwner.has(key)),\n );\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n fs.mkdirSync(localeDir, { recursive: true });\n\n const localeMap = buildFullLocaleMap(localesDir, locale);\n const filtered = filterMap(localeMap, usedKeys);\n\n const resolved =\n locale !== defaultLocale\n ? preResolveFallbacks(filtered, filterMap(defaultFullMap, usedKeys))\n : filtered;\n\n const moduleSource = generateCompiledModule(resolved);\n fs.writeFileSync(\n path.join(localeDir, `${plan.scope}.js`),\n moduleSource,\n );\n }\n }\n\n // For each locale: generate per-dictionary modules\n if (dictionaries && Object.keys(dictionaries).length > 0) {\n for (const locale of locales) {\n const localeDir = path.join(outDir, locale);\n const dictDir = path.join(localeDir, '_dict');\n fs.mkdirSync(dictDir, { recursive: true });\n\n for (const dictionaryName of Object.keys(dictionaries)) {\n const dictModule = generateDictionaryModule(\n localesDir,\n locale,\n defaultLocale,\n dictionaries,\n dictionaryName,\n );\n fs.writeFileSync(path.join(dictDir, `${dictionaryName}.js`), dictModule);\n }\n }\n }\n\n // Generate manifest\n const scopeIds = scopePlans.map((plan) => plan.scope);\n const dictionaryNames = dictionaries ? Object.keys(dictionaries) : [];\n const manifestSource = generateManifest(scopeIds, locales, dictionaryNames);\n fs.writeFileSync(path.join(outDir, 'manifest.js'), manifestSource);\n}\n"],"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AAE1C,OAAK,MAAM,kBAAkB,OAAO,KAAK,aAAa,EAAE;GACtD,MAAM,aAAa,yBACjB,YACA,QACA,eACA,cACA,eACD;AACD,MAAG,cAAc,KAAK,KAAK,SAAS,GAAG,eAAe,KAAK,EAAE,WAAW;;;CAQ9E,MAAM,iBAAiB,iBAFN,WAAW,KAAK,SAAS,KAAK,MAAM,EAEH,SAD1B,eAAe,OAAO,KAAK,aAAa,GAAG,EAAE,CACM;AAC3E,IAAG,cAAc,KAAK,KAAK,QAAQ,cAAc,EAAE,eAAe"}
@@ -17,6 +17,22 @@ export interface I18nSharedConfig {
17
17
  extraction?: {
18
18
  /** Additional property names to scan as translation key fields. */
19
19
  keyFields?: string[];
20
+ /**
21
+ * Additional module specifiers that export `useI18n`.
22
+ *
23
+ * The extractor only recognizes `useI18n` imported from `vite-bundled-i18n/react`
24
+ * by default. If your app wraps `useI18n` in a custom hook that re-exports it
25
+ * from a different path, add that path here so the extractor can trace scope
26
+ * declarations and `t()` calls through the wrapper.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * extraction: {
31
+ * hookSources: ['@/hooks/use-page-i18n-scope'],
32
+ * }
33
+ * ```
34
+ */
35
+ hookSources?: string[];
20
36
  };
21
37
  }
22
38
  /**
@@ -419,14 +419,20 @@ export interface I18nInstance {
419
419
  */
420
420
  getDictionaryNames: () => string[];
421
421
  /**
422
- * Registers a scope as currently loading. Missing-key warnings for keys
422
+ * Marks a scope as currently loading. Missing-key warnings for keys
423
423
  * belonging to loading scopes are suppressed — calling `t()` before a scope
424
424
  * is ready is an expected transient state, not a real missing translation.
425
425
  *
426
- * Returns an unregister function that must be called when the scope finishes
427
- * loading (or the component unmounts).
426
+ * Idempotent — safe to call during React render (no side effects beyond
427
+ * a Set.add). Use {@link removeLoadingScope} in an effect cleanup.
428
428
  */
429
- registerLoadingScope: (scope: string) => () => void;
429
+ addLoadingScope: (scope: string) => void;
430
+ /**
431
+ * Removes a scope from the loading set. Warnings for keys in that scope's
432
+ * namespace will resume. Call this in effect cleanup or when the scope
433
+ * finishes loading.
434
+ */
435
+ removeLoadingScope: (scope: string) => void;
430
436
  }
431
437
  /**
432
438
  * Records how a translation key was resolved at runtime.
@@ -1245,11 +1245,11 @@ function createI18n(config) {
1245
1245
  onResourcesChange: (callback) => cache.onResourcesChange(callback),
1246
1246
  getKeyUsage: () => keyTracker.getKeyUsage(),
1247
1247
  getResidentKeyCount: (locale) => cache.getResidentKeyCount(locale),
1248
- registerLoadingScope(scope) {
1248
+ addLoadingScope(scope) {
1249
1249
  loadingScopes.add(scope);
1250
- return () => {
1251
- loadingScopes.delete(scope);
1252
- };
1250
+ },
1251
+ removeLoadingScope(scope) {
1252
+ loadingScopes.delete(scope);
1253
1253
  }
1254
1254
  };
1255
1255
  }
@@ -1356,4 +1356,4 @@ function i18nKey(key) {
1356
1356
  //#endregion
1357
1357
  export { clearTranslations as a, mergeTranslations$1 as c, createI18n as i, setTranslations as l, i18nKey as n, compiledHasKey as o, defineI18nConfig as r, compiledTranslate as s, defineI18nData as t };
1358
1358
 
1359
- //# sourceMappingURL=data-BtBbelxk.js.map
1359
+ //# sourceMappingURL=data-BQSxm6Hf.js.map