vite-bundled-i18n 0.2.13 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -70,13 +70,24 @@ export default defineConfig({
70
70
  locales: ['en', 'bg'],
71
71
  defaultLocale: 'en',
72
72
  generatedOutDir: '.i18n',
73
- // types are generated to src/core/i18n-generated.ts by default
73
+ // types are generated to .i18n/i18n-generated.ts by default
74
74
  }),
75
75
  ],
76
76
  })
77
77
  ```
78
78
 
79
- Types are generated automatically on `npm run dev` (on server start and when locale files change) and during `npm run build`. No manual step needed.
79
+ Types are generated automatically on `npm run dev` (on server start and when locale files change) and during `npm run build`. To enable autocomplete and type validation, add to your `tsconfig.json`:
80
+
81
+ ```json
82
+ {
83
+ "compilerOptions": {
84
+ "paths": {
85
+ "vite-bundled-i18n/generated": ["./.i18n/i18n-generated.ts"]
86
+ }
87
+ },
88
+ "include": ["src", ".i18n"]
89
+ }
90
+ ```
80
91
 
81
92
  ### React
82
93
 
package/dist/cli/index.js CHANGED
@@ -5,10 +5,11 @@ import path from "node:path";
5
5
  //#region src/cli/commands.ts
6
6
  function resolveConfig(config) {
7
7
  const rootDir = config.rootDir ?? process.cwd();
8
+ const outDir = config.outDir ?? path.join(rootDir, ".i18n");
8
9
  return {
9
10
  rootDir,
10
- outDir: config.outDir ?? path.join(rootDir, ".i18n"),
11
- typesOutPath: config.typesOutPath ?? path.join(rootDir, "src", "core", "i18n-generated.ts"),
11
+ outDir,
12
+ typesOutPath: config.typesOutPath ?? path.join(outDir, "i18n-generated.ts"),
12
13
  localesDir: path.isAbsolute(config.localesDir) ? config.localesDir : path.join(rootDir, config.localesDir),
13
14
  extractionScope: config.extractionScope ?? "global"
14
15
  };
@@ -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(rootDir, 'src', 'core', '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\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);\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);\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;AAS/C,QAAO;EAAE;EAAS,QARH,OAAO,UAAU,KAAK,KAAK,SAAS,QAAQ;EAQjC,cANxB,OAAO,gBAAgB,KAAK,KAAK,SAAS,OAAO,QAAQ,oBAAoB;EAMvC,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;;;;;AAMJ,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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AAW,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"}
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\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);\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);\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;;;;;AAMJ,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,KAAK,IAAS,GAC3D;CACF,MAAM,MACJ,MACA,UAAU,KAAK,MAAM,IAAS,OAAO,IAAI,EAAE,CAAC,CAAC,KAAK,IAAS,GAC3D;CAEF,MAAM,aAAa,UACjB,MACA,MAAM,KAAK,GAAG,MAAM,MAAM,IA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,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,231 +1,5 @@
1
- type TranslationValue = string | number | boolean | bigint | null | undefined;
2
- export interface I18nNestedKeys {
3
- 'account': {
4
- 'addresses': {
5
- 'addNew': true;
6
- 'default': true;
7
- 'heading': true;
8
- 'setDefault': true;
9
- };
10
- 'orders': {
11
- 'empty': true;
12
- 'heading': true;
13
- 'orderNumber': true;
14
- 'placedOn': true;
15
- 'reorder': true;
16
- 'status': {
17
- 'cancelled': true;
18
- 'delivered': true;
19
- 'pending': true;
20
- 'processing': true;
21
- 'shipped': true;
22
- };
23
- 'trackOrder': true;
24
- };
25
- 'profile': {
26
- 'changePassword': true;
27
- 'confirmPassword': true;
28
- 'currentPassword': true;
29
- 'email': true;
30
- 'heading': true;
31
- 'name': true;
32
- 'newPassword': true;
33
- 'personalInfo': true;
34
- 'phone': true;
35
- 'updated': true;
36
- };
37
- };
38
- 'actions': {
39
- 'addToCart': true;
40
- 'applyFilter': true;
41
- 'checkout': true;
42
- 'clearFilters': true;
43
- 'create': true;
44
- 'delete': true;
45
- 'edit': true;
46
- 'register': true;
47
- 'removeFromCart': true;
48
- 'save': true;
49
- 'signIn': true;
50
- 'signOut': true;
51
- 'sortBy': true;
52
- 'submit': true;
53
- 'update': true;
54
- 'viewDetails': true;
55
- };
56
- 'cart': {
57
- 'empty': true;
58
- 'emptyAction': true;
59
- 'item': {
60
- 'moveToWishlist': true;
61
- 'priceEach': true;
62
- 'quantity': true;
63
- 'remove': true;
64
- };
65
- 'promoCode': {
66
- 'applied': true;
67
- 'apply': true;
68
- 'invalid': true;
69
- 'label': true;
70
- 'placeholder': true;
71
- };
72
- 'summary': {
73
- 'estimatedDelivery': true;
74
- 'freeShipping': true;
75
- 'shipping': true;
76
- 'subtotal': true;
77
- 'tax': true;
78
- 'total': true;
79
- };
80
- 'title': true;
81
- };
82
- 'global': {
83
- 'appName': true;
84
- 'footer': {
85
- 'contact': true;
86
- 'madeWith': true;
87
- 'privacy': true;
88
- 'terms': true;
89
- 'version': true;
90
- };
91
- 'meta': {
92
- 'description': true;
93
- 'title': true;
94
- };
95
- 'nav': {
96
- 'about': true;
97
- 'account': true;
98
- 'cart': true;
99
- 'home': true;
100
- 'products': true;
101
- };
102
- 'tagline': true;
103
- };
104
- 'products': {
105
- 'index': {
106
- 'empty': true;
107
- 'filters': {
108
- 'category': true;
109
- 'featured': true;
110
- 'inStock': true;
111
- 'priceRange': true;
112
- };
113
- 'heading': true;
114
- 'sort': {
115
- 'newest': true;
116
- 'popular': true;
117
- 'priceAsc': true;
118
- 'priceDesc': true;
119
- };
120
- 'subheading': true;
121
- };
122
- 'reviews': {
123
- 'averageRating': true;
124
- 'heading': true;
125
- 'helpful': true;
126
- 'noReviews': true;
127
- 'reported': true;
128
- 'reviewCount': true;
129
- 'writeReview': true;
130
- };
131
- 'show': {
132
- 'availability': {
133
- 'backorder': true;
134
- 'inStock': true;
135
- 'outOfStock': true;
136
- };
137
- 'description': true;
138
- 'discount': true;
139
- 'originalPrice': true;
140
- 'price': true;
141
- 'relatedProducts': true;
142
- 'sku': true;
143
- 'tabs': {
144
- 'description': true;
145
- 'reviews': true;
146
- 'specifications': true;
147
- };
148
- 'title': true;
149
- };
150
- };
151
- 'shared': {
152
- 'backToHome': true;
153
- 'cancel': true;
154
- 'close': true;
155
- 'confirm': true;
156
- 'copyright': true;
157
- 'error': true;
158
- 'loading': true;
159
- 'next': true;
160
- 'no': true;
161
- 'noResults': true;
162
- 'ok': true;
163
- 'previous': true;
164
- 'retry': true;
165
- 'search': true;
166
- 'yes': true;
167
- };
168
- }
169
- export interface I18nParamsMap {
170
- 'account.orders.orderNumber': {
171
- number: TranslationValue;
172
- };
173
- 'account.orders.placedOn': {
174
- date: TranslationValue;
175
- };
176
- 'actions.sortBy': {
177
- field: TranslationValue;
178
- };
179
- 'cart.summary.estimatedDelivery': {
180
- date: TranslationValue;
181
- };
182
- 'cart.item.quantity': {
183
- count: TranslationValue;
184
- };
185
- 'cart.item.priceEach': {
186
- amount: TranslationValue;
187
- };
188
- 'cart.promoCode.applied': {
189
- code: TranslationValue;
190
- discount: TranslationValue;
191
- };
192
- 'global.footer.madeWith': {
193
- framework: TranslationValue;
194
- };
195
- 'global.footer.version': {
196
- version: TranslationValue;
197
- };
198
- 'global.meta.title': {
199
- page: TranslationValue;
200
- };
201
- 'products.index.subheading': {
202
- count: TranslationValue;
203
- };
204
- 'products.show.price': {
205
- amount: TranslationValue;
206
- };
207
- 'products.show.originalPrice': {
208
- amount: TranslationValue;
209
- };
210
- 'products.show.discount': {
211
- percent: TranslationValue;
212
- };
213
- 'products.show.sku': {
214
- code: TranslationValue;
215
- };
216
- 'products.show.availability.inStock': {
217
- count: TranslationValue;
218
- };
219
- 'products.show.tabs.reviews': {
220
- count: TranslationValue;
221
- };
222
- 'products.reviews.averageRating': {
223
- rating: TranslationValue;
224
- };
225
- 'products.reviews.reviewCount': {
226
- count: TranslationValue;
227
- };
228
- }
229
- export interface I18nScopeMap {
230
- }
231
- export {};
1
+ // Empty stubs — consumers generate their own via the vite-bundled-i18n plugin.
2
+ // Override with tsconfig paths: "vite-bundled-i18n/generated": ["./path/to/generated"]
3
+ export interface I18nNestedKeys {}
4
+ export interface I18nParamsMap {}
5
+ export interface I18nScopeMap {}
@@ -1,5 +1,5 @@
1
1
  import type { CompiledManifestModule } from './compiled-runtime';
2
- import type { I18nNestedKeys, I18nParamsMap, I18nScopeMap } from './i18n-generated';
2
+ import type { I18nNestedKeys, I18nParamsMap, I18nScopeMap } from 'vite-bundled-i18n/generated';
3
3
  export type { I18nNestedKeys, I18nParamsMap, I18nScopeMap, };
4
4
  /**
5
5
  * Recursive type representing nested translation JSON.
@@ -86,10 +86,10 @@ export type ParamsOf<K extends TranslationKey> = K extends keyof I18nParamsMap ?
86
86
  * Params are type-checked per key: `t('cart.total', { amount: 9 })` enforces `{ amount }`.
87
87
  */
88
88
  export type TFunction = {
89
- <K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string;
90
- <K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K], fallback: string): string;
91
89
  (key: TranslationKey): string;
92
90
  (key: TranslationKey, fallback: string): string;
91
+ (key: TranslationKey, params: Record<string, unknown>): string;
92
+ (key: TranslationKey, params: Record<string, unknown>, fallback: string): string;
93
93
  };
94
94
  /**
95
95
  * Translation function for scoped/namespace-relative keys.
@@ -110,8 +110,8 @@ export type ScopedTFunction = {
110
110
  * and does not degrade to key-as-value.
111
111
  */
112
112
  export type TryTFunction = {
113
- <K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string | undefined;
114
113
  (key: TranslationKey): string | undefined;
114
+ (key: TranslationKey, params: Record<string, unknown>): string | undefined;
115
115
  };
116
116
  /**
117
117
  * Namespace-relative version of {@link TryTFunction}.
@@ -126,8 +126,8 @@ export type ScopedTryTFunction = {
126
126
  * Like {@link TryTFunction}, this function does not accept fallback strings.
127
127
  */
128
128
  export type RequireTFunction = {
129
- <K extends keyof I18nParamsMap>(key: K, params: I18nParamsMap[K]): string;
130
129
  (key: TranslationKey): string;
130
+ (key: TranslationKey, params: Record<string, unknown>): string;
131
131
  };
132
132
  /**
133
133
  * Namespace-relative version of {@link RequireTFunction}.
package/dist/plugin.js CHANGED
@@ -66,7 +66,8 @@ function i18nDevPlugin(config, options) {
66
66
  configureServer(server) {
67
67
  const localesPath = path.join(projectRoot, config.localesDir);
68
68
  const defaultLocale = options?.defaultLocale ?? "en";
69
- const typesOutPath = options?.typesOutPath ? path.resolve(projectRoot, options.typesOutPath) : path.join(projectRoot, "src", "core", "i18n-generated.ts");
69
+ const generatedOutDir = path.join(projectRoot, ".i18n");
70
+ const typesOutPath = options?.typesOutPath ? path.resolve(projectRoot, options.typesOutPath) : path.join(generatedOutDir, "i18n-generated.ts");
70
71
  function regenerateTypes() {
71
72
  try {
72
73
  writeTypes(localesPath, defaultLocale, typesOutPath);
@@ -112,10 +113,12 @@ function i18nDevPlugin(config, options) {
112
113
  //#region src/plugin/buildPlugin.ts
113
114
  function resolveBuildPaths(options) {
114
115
  const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;
116
+ const localesDir = path.isAbsolute(sharedConfig.localesDir) ? sharedConfig.localesDir : path.join(rootDir, sharedConfig.localesDir);
117
+ const generatedOutDir = buildConfig.generatedOutDir ? path.resolve(rootDir, buildConfig.generatedOutDir) : path.join(rootDir, ".i18n");
115
118
  return {
116
- localesDir: path.isAbsolute(sharedConfig.localesDir) ? sharedConfig.localesDir : path.join(rootDir, sharedConfig.localesDir),
117
- generatedOutDir: buildConfig.generatedOutDir ? path.resolve(rootDir, buildConfig.generatedOutDir) : path.join(rootDir, ".i18n"),
118
- typesOutPath: buildConfig.typesOutPath ? path.resolve(rootDir, buildConfig.typesOutPath) : path.join(rootDir, "src", "core", "i18n-generated.ts"),
119
+ localesDir,
120
+ generatedOutDir,
121
+ typesOutPath: buildConfig.typesOutPath ? path.resolve(rootDir, buildConfig.typesOutPath) : path.join(generatedOutDir, "i18n-generated.ts"),
119
122
  assetsOutDir: path.join(viteOutDir, buildConfig.assetsDir ?? "__i18n"),
120
123
  extractionScope: buildConfig.extractionScope ?? "global"
121
124
  };
@@ -1 +1 @@
1
- {"version":3,"file":"plugin.js","names":[],"sources":["../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport { writeTypes } from '../extractor/type-generator';\nimport type { I18nSharedConfig } from '../core/config';\n\n/**\n * Configuration for the i18n dev plugin.\n */\nexport type I18nDevPluginConfig = I18nSharedConfig;\n\n/**\n * Vite dev plugin that serves combined translation bundles.\n *\n * Instead of the browser making N separate HTTP requests for N namespace\n * files, this plugin intercepts requests to `/__i18n/` and serves all\n * requested namespaces combined into a single JSON response.\n *\n * Three types of bundles:\n *\n * **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):\n * Loads only the namespaces belonging to a specific named dictionary.\n * Each dictionary is loaded independently with its own priority.\n *\n * **Scope bundle** (`/__i18n/{locale}/{scope}.json`):\n * Loads the namespace inferred from the scope's first segment. For example,\n * `/__i18n/en/products.show.json` reads `locales/en/products.json` and\n * returns `{ \"products\": { ... } }`.\n *\n * In production (Group 2+), the Vite build plugin will generate these bundles\n * statically with tree-shaking. This dev plugin is the runtime equivalent —\n * same URL pattern, no tree-shaking, but demonstrates the loading strategy.\n *\n * @param config - Plugin configuration\n * @returns A Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { i18nDevPlugin } from './src/plugin/devPlugin';\n *\n * export default defineConfig({\n * plugins: [\n * react(),\n * i18nDevPlugin({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport interface I18nDevPluginOptions {\n assetsDir?: string;\n /** Default locale for type generation. Required for dev-time autocomplete. */\n defaultLocale?: string;\n /** Path to write generated types. Defaults to `.i18n/i18n.d.ts`. */\n typesOutPath?: string;\n}\n\nexport function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin {\n let projectRoot = '';\n const assetsPrefix = `/${options?.assetsDir ?? '__i18n'}/`;\n\n /**\n * Reads a namespace JSON file from the locales directory.\n * Returns the parsed JSON, or undefined if the file doesn't exist.\n */\n function readNamespaceFile(\n locale: string,\n namespace: string,\n ): Record<string, unknown> | undefined {\n const filePath = path.join(\n projectRoot,\n config.localesDir,\n locale,\n `${namespace}.json`,\n );\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Builds a named dictionary bundle — only the namespaces belonging\n * to a specific dictionary, keyed by namespace name.\n */\n function buildDictionaryBundle(\n locale: string,\n dictName: string,\n ): Record<string, unknown> {\n const rule = normalizeDictionaries(config.dictionaries).find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(projectRoot, config.localesDir, locale);\n let files: string[] = [];\n try {\n files = fs.readdirSync(localeDir).filter((file) => file.endsWith('.json'));\n } catch {\n return {};\n }\n\n const bundle: Record<string, unknown> = {};\n for (const file of files) {\n const ns = file.slice(0, -'.json'.length);\n const data = readNamespaceFile(locale, ns);\n if (!data) continue;\n\n const matchedSubKeys = flattenKeys(data)\n .filter((subKey) => rule.include.some((pattern) => keyMatchesPattern(`${ns}.${subKey}`, pattern)));\n if (matchedSubKeys.length === 0) continue;\n\n bundle[ns] = pruneNamespace(data, matchedSubKeys);\n }\n return bundle;\n }\n\n /**\n * Builds a scope bundle — reads the namespace file(s) inferred from\n * the scope and returns them keyed by namespace name.\n *\n * The first segment of the scope is the namespace:\n * 'products.show' → reads products.json → { products: { ... } }\n */\n function buildScopeBundle(\n locale: string,\n scope: string,\n ): Record<string, unknown> {\n const namespace = scope.indexOf('.') === -1\n ? scope\n : scope.slice(0, scope.indexOf('.'));\n\n const bundle: Record<string, unknown> = {};\n const data = readNamespaceFile(locale, namespace);\n if (data) {\n bundle[namespace] = data;\n }\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n },\n configureServer(server) {\n const localesPath = path.join(projectRoot, config.localesDir);\n const defaultLocale = options?.defaultLocale ?? 'en';\n const typesOutPath = options?.typesOutPath\n ? path.resolve(projectRoot, options.typesOutPath)\n : path.join(projectRoot, 'src', 'core', 'i18n-generated.ts');\n\n // Generate types on server start for dev-time autocomplete\n function regenerateTypes() {\n try {\n writeTypes(localesPath, defaultLocale, typesOutPath);\n } catch {\n // Silently skip if locales dir doesn't exist yet\n }\n }\n\n regenerateTypes();\n\n // Watch locale files: regenerate types + reload page\n server.watcher.add(localesPath);\n\n server.watcher.on('change', (filePath) => {\n if (filePath.startsWith(localesPath) && filePath.endsWith('.json')) {\n regenerateTypes();\n server.ws.send({ type: 'full-reload' });\n }\n });\n\n server.middlewares.use((req, res, next) => {\n if (!req.url?.startsWith(assetsPrefix)) {\n return next();\n }\n\n const relativePath = req.url.slice(assetsPrefix.length);\n\n // Named dictionary: {locale}/_dict/{name}.json\n const dictMatch = relativePath.match(\n /^([^/]+)\\/_dict\\/([^/]+)\\.json$/,\n );\n if (dictMatch) {\n const [, locale, dictName] = dictMatch;\n const bundle = buildDictionaryBundle(locale, dictName);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // Scope bundle: {locale}/{scope}.json\n const scopeMatch = relativePath.match(\n /^([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, scope);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n next();\n });\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { I18nSharedConfig } from '../core/config';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { compileAll } from '../extractor/compiler';\nimport { walkAll } from '../extractor/walker';\n\nexport interface I18nBuildPluginConfig {\n /** Glob patterns for route/page entry points. */\n pages: string[];\n /** All supported locale codes. */\n locales: string[];\n /** Default locale used for fallback resolution. */\n defaultLocale: string;\n /** Where to write internal artifacts like reports and compiled modules. */\n generatedOutDir?: string;\n /** Where to write generated type declarations. */\n typesOutPath?: string;\n /** Extraction scope for the walker. */\n extractionScope?: 'global' | 'scoped';\n /** Public asset directory emitted into the Vite build output. */\n assetsDir?: string;\n /** Disable writing generated types during `vite build`. */\n emitTypes?: boolean;\n /** Disable writing reports during `vite build`. */\n emitReports?: boolean;\n /** Disable writing compiled modules during `vite build`. */\n emitCompiled?: boolean;\n}\n\nexport interface EmitI18nBuildArtifactsOptions {\n rootDir: string;\n viteOutDir: string;\n sharedConfig: I18nSharedConfig;\n buildConfig: I18nBuildPluginConfig;\n}\n\nexport interface EmitI18nBuildArtifactsResult {\n assetBundles: number;\n assetsOutDir: string;\n generatedOutDir: string;\n compiledOutDir?: string;\n typesOutPath?: string;\n warnings: string[];\n}\n\nfunction resolveBuildPaths(options: EmitI18nBuildArtifactsOptions) {\n const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;\n\n const localesDir = path.isAbsolute(sharedConfig.localesDir)\n ? sharedConfig.localesDir\n : path.join(rootDir, sharedConfig.localesDir);\n const generatedOutDir = buildConfig.generatedOutDir\n ? path.resolve(rootDir, buildConfig.generatedOutDir)\n : path.join(rootDir, '.i18n');\n const typesOutPath = buildConfig.typesOutPath\n ? path.resolve(rootDir, buildConfig.typesOutPath)\n : path.join(rootDir, 'src', 'core', 'i18n-generated.ts');\n const assetsOutDir = path.join(viteOutDir, buildConfig.assetsDir ?? '__i18n');\n const extractionScope = buildConfig.extractionScope ?? 'global';\n\n return {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n };\n}\n\nfunction joinPublicPath(base: string, relativePath: string): string {\n const normalizedBase = base.endsWith('/') ? base : `${base}/`;\n const normalizedRelative = relativePath.replace(/^\\/+/, '');\n return `${normalizedBase}${normalizedRelative}`;\n}\n\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const { rootDir, sharedConfig, buildConfig } = options;\n const {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n } = resolveBuildPaths(options);\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n });\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n\n if (buildConfig.emitTypes !== false) {\n const scopeNames = analysis.routes.map(r => r.routeId);\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);\n }\n\n let compiledOutDir: string | undefined;\n if (buildConfig.emitCompiled !== false) {\n compiledOutDir = path.join(assetsOutDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: buildConfig.locales,\n defaultLocale: buildConfig.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n }\n\n const warnings: string[] = [];\n\n // Count extracted keys vs bundled keys\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try {\n foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json'));\n } catch { /* dir doesn't exist */ }\n\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n\n warnings.push(\n `vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\\n` +\n ` Expected structure: ${localesDir}/{locale}/{namespace}.json\\n` +\n ` ${hint}\\n` +\n ` Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`\n );\n }\n\n return {\n assetBundles: bundles.length,\n assetsOutDir,\n generatedOutDir,\n compiledOutDir,\n typesOutPath: buildConfig.emitTypes === false ? undefined : typesOutPath,\n warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n // enforce: 'post' ensures config() runs AFTER other plugins (e.g. Laravel's\n // Vite plugin) that set `base` in their own config() hooks.\n enforce: 'post',\n config(config) {\n const base = config.base ?? '/';\n const i18nBase = joinPublicPath(base, assetsDir).replace(/\\/$/, '');\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n return {\n define: {\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const result = emitI18nBuildArtifacts({\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n });\n\n for (const warning of result.warnings) {\n resolvedConfig.logger.warn(warning);\n }\n\n resolvedConfig.logger.info(\n `vite-bundled-i18n: emitted ${result.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.assetsOutDir)}`,\n );\n if (result.compiledOutDir) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`,\n );\n }\n if (result.typesOutPath) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`,\n );\n }\n },\n };\n}\n","/**\n * Vite plugin entry point for vite-bundled-i18n.\n *\n * `i18nPlugin()` unifies:\n * - dev-time bundle serving via `/__i18n/...`\n * - build-time generation of static `/__i18n/...` assets, reports, types, and compiled modules\n */\nimport type { PluginOption } from 'vite';\nimport type { I18nSharedConfig } from './core/config';\nimport { i18nDevPlugin } from './plugin/devPlugin';\nimport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n} from './plugin/buildPlugin';\nimport type {\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport type {\n I18nDevPluginConfig,\n} from './plugin/devPlugin';\nexport type {\n EmitI18nBuildArtifactsOptions,\n EmitI18nBuildArtifactsResult,\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n i18nDevPlugin,\n};\n\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig?: I18nBuildPluginConfig,\n): PluginOption[] {\n const plugins: PluginOption[] = [\n i18nDevPlugin(sharedConfig, {\n assetsDir: buildConfig?.assetsDir,\n defaultLocale: buildConfig?.defaultLocale,\n typesOutPath: buildConfig?.typesOutPath,\n }),\n ];\n\n if (buildConfig) {\n plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));\n }\n\n return plugins;\n}\n"],"mappings":";;;;AAiEA,SAAgB,cAAc,QAA6B,SAAwC;CACjG,IAAI,cAAc;CAClB,MAAM,eAAe,IAAI,SAA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OAAO;IAC1E;IACA;IACD,CAAC;AAEF,QAAK,MAAM,WAAW,OAAO,SAC3B,gBAAe,OAAO,KAAK,QAAQ;AAGrC,kBAAe,OAAO,KACpB,8BAA8B,OAAO,aAAa,2BAA2B,KAAK,SAAS,eAAe,MAAM,OAAO,aAAa,GACrI;AACD,OAAI,OAAO,eACT,gBAAe,OAAO,KACpB,0DAA0D,KAAK,SAAS,eAAe,MAAM,OAAO,eAAe,GACpH;AAEH,OAAI,OAAO,aACT,gBAAe,OAAO,KACpB,uCAAuC,KAAK,SAAS,eAAe,MAAM,OAAO,aAAa,GAC/F;;EAGN;;;;AC9LH,SAAgB,WACd,cACA,aACgB;CAChB,MAAM,UAA0B,CAC9B,cAAc,cAAc;EAC1B,WAAW,aAAa;EACxB,eAAe,aAAa;EAC5B,cAAc,aAAa;EAC5B,CAAC,CACH;AAED,KAAI,YACF,SAAQ,KAAK,gBAAgB,cAAc,YAAY,CAAC;AAG1D,QAAO"}
1
+ {"version":3,"file":"plugin.js","names":[],"sources":["../src/plugin/devPlugin.ts","../src/plugin/buildPlugin.ts","../src/plugin.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin } from 'vite';\nimport { flattenKeys, pruneNamespace } from '../extractor/bundle-generator';\nimport { keyMatchesPattern, normalizeDictionaries } from '../extractor/dictionary-ownership';\nimport { writeTypes } from '../extractor/type-generator';\nimport type { I18nSharedConfig } from '../core/config';\n\n/**\n * Configuration for the i18n dev plugin.\n */\nexport type I18nDevPluginConfig = I18nSharedConfig;\n\n/**\n * Vite dev plugin that serves combined translation bundles.\n *\n * Instead of the browser making N separate HTTP requests for N namespace\n * files, this plugin intercepts requests to `/__i18n/` and serves all\n * requested namespaces combined into a single JSON response.\n *\n * Three types of bundles:\n *\n * **Named dictionary bundle** (`/__i18n/{locale}/_dict/{name}.json`):\n * Loads only the namespaces belonging to a specific named dictionary.\n * Each dictionary is loaded independently with its own priority.\n *\n * **Scope bundle** (`/__i18n/{locale}/{scope}.json`):\n * Loads the namespace inferred from the scope's first segment. For example,\n * `/__i18n/en/products.show.json` reads `locales/en/products.json` and\n * returns `{ \"products\": { ... } }`.\n *\n * In production (Group 2+), the Vite build plugin will generate these bundles\n * statically with tree-shaking. This dev plugin is the runtime equivalent —\n * same URL pattern, no tree-shaking, but demonstrates the loading strategy.\n *\n * @param config - Plugin configuration\n * @returns A Vite plugin\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { i18nDevPlugin } from './src/plugin/devPlugin';\n *\n * export default defineConfig({\n * plugins: [\n * react(),\n * i18nDevPlugin({\n * localesDir: 'locales',\n * dictionaries: {\n * global: { keys: ['shared', 'global', 'actions'] },\n * admin: { keys: ['admin'] },\n * },\n * }),\n * ],\n * });\n * ```\n */\nexport interface I18nDevPluginOptions {\n assetsDir?: string;\n /** Default locale for type generation. Required for dev-time autocomplete. */\n defaultLocale?: string;\n /** Path to write generated types. Defaults to `.i18n/i18n.d.ts`. */\n typesOutPath?: string;\n}\n\nexport function i18nDevPlugin(config: I18nDevPluginConfig, options?: I18nDevPluginOptions): Plugin {\n let projectRoot = '';\n const assetsPrefix = `/${options?.assetsDir ?? '__i18n'}/`;\n\n /**\n * Reads a namespace JSON file from the locales directory.\n * Returns the parsed JSON, or undefined if the file doesn't exist.\n */\n function readNamespaceFile(\n locale: string,\n namespace: string,\n ): Record<string, unknown> | undefined {\n const filePath = path.join(\n projectRoot,\n config.localesDir,\n locale,\n `${namespace}.json`,\n );\n\n try {\n const content = fs.readFileSync(filePath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n }\n\n /**\n * Builds a named dictionary bundle — only the namespaces belonging\n * to a specific dictionary, keyed by namespace name.\n */\n function buildDictionaryBundle(\n locale: string,\n dictName: string,\n ): Record<string, unknown> {\n const rule = normalizeDictionaries(config.dictionaries).find((entry) => entry.name === dictName);\n if (!rule) return {};\n\n const localeDir = path.join(projectRoot, config.localesDir, locale);\n let files: string[] = [];\n try {\n files = fs.readdirSync(localeDir).filter((file) => file.endsWith('.json'));\n } catch {\n return {};\n }\n\n const bundle: Record<string, unknown> = {};\n for (const file of files) {\n const ns = file.slice(0, -'.json'.length);\n const data = readNamespaceFile(locale, ns);\n if (!data) continue;\n\n const matchedSubKeys = flattenKeys(data)\n .filter((subKey) => rule.include.some((pattern) => keyMatchesPattern(`${ns}.${subKey}`, pattern)));\n if (matchedSubKeys.length === 0) continue;\n\n bundle[ns] = pruneNamespace(data, matchedSubKeys);\n }\n return bundle;\n }\n\n /**\n * Builds a scope bundle — reads the namespace file(s) inferred from\n * the scope and returns them keyed by namespace name.\n *\n * The first segment of the scope is the namespace:\n * 'products.show' → reads products.json → { products: { ... } }\n */\n function buildScopeBundle(\n locale: string,\n scope: string,\n ): Record<string, unknown> {\n const namespace = scope.indexOf('.') === -1\n ? scope\n : scope.slice(0, scope.indexOf('.'));\n\n const bundle: Record<string, unknown> = {};\n const data = readNamespaceFile(locale, namespace);\n if (data) {\n bundle[namespace] = data;\n }\n return bundle;\n }\n\n return {\n name: 'vite-bundled-i18n-dev',\n apply: 'serve',\n configResolved(resolvedConfig) {\n projectRoot = resolvedConfig.root;\n },\n configureServer(server) {\n const localesPath = path.join(projectRoot, config.localesDir);\n const defaultLocale = options?.defaultLocale ?? 'en';\n const generatedOutDir = path.join(projectRoot, '.i18n');\n const typesOutPath = options?.typesOutPath\n ? path.resolve(projectRoot, options.typesOutPath)\n : path.join(generatedOutDir, 'i18n-generated.ts');\n\n // Generate types on server start for dev-time autocomplete\n function regenerateTypes() {\n try {\n writeTypes(localesPath, defaultLocale, typesOutPath);\n } catch {\n // Silently skip if locales dir doesn't exist yet\n }\n }\n\n regenerateTypes();\n\n // Watch locale files: regenerate types + reload page\n server.watcher.add(localesPath);\n\n server.watcher.on('change', (filePath) => {\n if (filePath.startsWith(localesPath) && filePath.endsWith('.json')) {\n regenerateTypes();\n server.ws.send({ type: 'full-reload' });\n }\n });\n\n server.middlewares.use((req, res, next) => {\n if (!req.url?.startsWith(assetsPrefix)) {\n return next();\n }\n\n const relativePath = req.url.slice(assetsPrefix.length);\n\n // Named dictionary: {locale}/_dict/{name}.json\n const dictMatch = relativePath.match(\n /^([^/]+)\\/_dict\\/([^/]+)\\.json$/,\n );\n if (dictMatch) {\n const [, locale, dictName] = dictMatch;\n const bundle = buildDictionaryBundle(locale, dictName);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n // Scope bundle: {locale}/{scope}.json\n const scopeMatch = relativePath.match(\n /^([^/]+)\\/(.+)\\.json$/,\n );\n if (scopeMatch) {\n const [, locale, scope] = scopeMatch;\n const bundle = buildScopeBundle(locale, scope);\n const json = JSON.stringify(bundle);\n res.setHeader('Content-Type', 'application/json');\n res.setHeader('Cache-Control', 'no-cache');\n res.end(json);\n return;\n }\n\n next();\n });\n },\n };\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport type { Plugin, ResolvedConfig } from 'vite';\nimport type { I18nSharedConfig } from '../core/config';\nimport { writeTypes } from '../extractor/type-generator';\nimport { generateReports } from '../extractor/reports';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { compileAll } from '../extractor/compiler';\nimport { walkAll } from '../extractor/walker';\n\nexport interface I18nBuildPluginConfig {\n /** Glob patterns for route/page entry points. */\n pages: string[];\n /** All supported locale codes. */\n locales: string[];\n /** Default locale used for fallback resolution. */\n defaultLocale: string;\n /** Where to write internal artifacts like reports and compiled modules. */\n generatedOutDir?: string;\n /** Where to write generated type declarations. */\n typesOutPath?: string;\n /** Extraction scope for the walker. */\n extractionScope?: 'global' | 'scoped';\n /** Public asset directory emitted into the Vite build output. */\n assetsDir?: string;\n /** Disable writing generated types during `vite build`. */\n emitTypes?: boolean;\n /** Disable writing reports during `vite build`. */\n emitReports?: boolean;\n /** Disable writing compiled modules during `vite build`. */\n emitCompiled?: boolean;\n}\n\nexport interface EmitI18nBuildArtifactsOptions {\n rootDir: string;\n viteOutDir: string;\n sharedConfig: I18nSharedConfig;\n buildConfig: I18nBuildPluginConfig;\n}\n\nexport interface EmitI18nBuildArtifactsResult {\n assetBundles: number;\n assetsOutDir: string;\n generatedOutDir: string;\n compiledOutDir?: string;\n typesOutPath?: string;\n warnings: string[];\n}\n\nfunction resolveBuildPaths(options: EmitI18nBuildArtifactsOptions) {\n const { rootDir, viteOutDir, sharedConfig, buildConfig } = options;\n\n const localesDir = path.isAbsolute(sharedConfig.localesDir)\n ? sharedConfig.localesDir\n : path.join(rootDir, sharedConfig.localesDir);\n const generatedOutDir = buildConfig.generatedOutDir\n ? path.resolve(rootDir, buildConfig.generatedOutDir)\n : path.join(rootDir, '.i18n');\n const typesOutPath = buildConfig.typesOutPath\n ? path.resolve(rootDir, buildConfig.typesOutPath)\n : path.join(generatedOutDir, 'i18n-generated.ts');\n const assetsOutDir = path.join(viteOutDir, buildConfig.assetsDir ?? '__i18n');\n const extractionScope = buildConfig.extractionScope ?? 'global';\n\n return {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n };\n}\n\nfunction joinPublicPath(base: string, relativePath: string): string {\n const normalizedBase = base.endsWith('/') ? base : `${base}/`;\n const normalizedRelative = relativePath.replace(/^\\/+/, '');\n return `${normalizedBase}${normalizedRelative}`;\n}\n\nexport function emitI18nBuildArtifacts(\n options: EmitI18nBuildArtifactsOptions,\n): EmitI18nBuildArtifactsResult {\n const { rootDir, sharedConfig, buildConfig } = options;\n const {\n localesDir,\n generatedOutDir,\n typesOutPath,\n assetsOutDir,\n extractionScope,\n } = resolveBuildPaths(options);\n\n const analysis = walkAll({\n pages: buildConfig.pages,\n rootDir,\n localesDir,\n defaultLocale: buildConfig.defaultLocale,\n extractionScope,\n });\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: buildConfig.locales,\n outDir: assetsOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n\n if (buildConfig.emitTypes !== false) {\n const scopeNames = analysis.routes.map(r => r.routeId);\n writeTypes(localesDir, buildConfig.defaultLocale, typesOutPath, scopeNames);\n }\n\n let compiledOutDir: string | undefined;\n if (buildConfig.emitCompiled !== false) {\n compiledOutDir = path.join(assetsOutDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: buildConfig.locales,\n defaultLocale: buildConfig.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: sharedConfig.dictionaries,\n });\n }\n\n if (buildConfig.emitReports !== false) {\n generateReports(\n analysis,\n localesDir,\n buildConfig.defaultLocale,\n generatedOutDir,\n sharedConfig.dictionaries,\n );\n }\n\n const warnings: string[] = [];\n\n // Count extracted keys vs bundled keys\n const totalExtractedKeys = analysis.allKeys.filter(k => !k.dynamic).length;\n const totalBundledKeys = bundles.reduce((sum, b) => sum + b.keyCount, 0);\n\n if (totalExtractedKeys > 0 && totalBundledKeys === 0) {\n const localeCheckDir = path.join(localesDir, buildConfig.defaultLocale);\n let foundFiles: string[] = [];\n try {\n foundFiles = fs.readdirSync(localeCheckDir).filter(f => f.endsWith('.json'));\n } catch { /* dir doesn't exist */ }\n\n const hint = foundFiles.length === 0\n ? `No JSON files found in ${localeCheckDir}`\n : `Found ${foundFiles.length} file(s) but 0 keys matched`;\n\n warnings.push(\n `vite-bundled-i18n: 0 of ${totalExtractedKeys} extracted keys found in translation files.\\n` +\n ` Expected structure: ${localesDir}/{locale}/{namespace}.json\\n` +\n ` ${hint}\\n` +\n ` Hint: Subdirectories are not supported. Each namespace must be a single flat JSON file.`\n );\n }\n\n return {\n assetBundles: bundles.length,\n assetsOutDir,\n generatedOutDir,\n compiledOutDir,\n typesOutPath: buildConfig.emitTypes === false ? undefined : typesOutPath,\n warnings,\n };\n}\n\nexport function i18nBuildPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig: I18nBuildPluginConfig,\n): Plugin {\n let resolvedConfig: ResolvedConfig | undefined;\n const assetsDir = buildConfig.assetsDir ?? '__i18n';\n\n return {\n name: 'vite-bundled-i18n-build',\n apply: 'build',\n // enforce: 'post' ensures config() runs AFTER other plugins (e.g. Laravel's\n // Vite plugin) that set `base` in their own config() hooks.\n enforce: 'post',\n config(config) {\n const base = config.base ?? '/';\n const i18nBase = joinPublicPath(base, assetsDir).replace(/\\/$/, '');\n const manifestUrl = joinPublicPath(base, `${assetsDir}/compiled/manifest.js`);\n return {\n define: {\n __VITE_I18N_COMPILED_MANIFEST__: JSON.stringify(manifestUrl),\n __VITE_I18N_BASE__: JSON.stringify(i18nBase),\n },\n };\n },\n configResolved(config) {\n resolvedConfig = config;\n },\n closeBundle() {\n if (!resolvedConfig) return;\n\n const result = emitI18nBuildArtifacts({\n rootDir: resolvedConfig.root,\n viteOutDir: path.resolve(resolvedConfig.root, resolvedConfig.build.outDir),\n sharedConfig,\n buildConfig,\n });\n\n for (const warning of result.warnings) {\n resolvedConfig.logger.warn(warning);\n }\n\n resolvedConfig.logger.info(\n `vite-bundled-i18n: emitted ${result.assetBundles} i18n asset bundle(s) to ${path.relative(resolvedConfig.root, result.assetsOutDir)}`,\n );\n if (result.compiledOutDir) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: compiled runtime modules written to ${path.relative(resolvedConfig.root, result.compiledOutDir)}`,\n );\n }\n if (result.typesOutPath) {\n resolvedConfig.logger.info(\n `vite-bundled-i18n: types written to ${path.relative(resolvedConfig.root, result.typesOutPath)}`,\n );\n }\n },\n };\n}\n","/**\n * Vite plugin entry point for vite-bundled-i18n.\n *\n * `i18nPlugin()` unifies:\n * - dev-time bundle serving via `/__i18n/...`\n * - build-time generation of static `/__i18n/...` assets, reports, types, and compiled modules\n */\nimport type { PluginOption } from 'vite';\nimport type { I18nSharedConfig } from './core/config';\nimport { i18nDevPlugin } from './plugin/devPlugin';\nimport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n} from './plugin/buildPlugin';\nimport type {\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport type {\n I18nDevPluginConfig,\n} from './plugin/devPlugin';\nexport type {\n EmitI18nBuildArtifactsOptions,\n EmitI18nBuildArtifactsResult,\n I18nBuildPluginConfig,\n} from './plugin/buildPlugin';\n\nexport {\n emitI18nBuildArtifacts,\n i18nBuildPlugin,\n i18nDevPlugin,\n};\n\nexport function i18nPlugin(\n sharedConfig: I18nSharedConfig,\n buildConfig?: I18nBuildPluginConfig,\n): PluginOption[] {\n const plugins: PluginOption[] = [\n i18nDevPlugin(sharedConfig, {\n assetsDir: buildConfig?.assetsDir,\n defaultLocale: buildConfig?.defaultLocale,\n typesOutPath: buildConfig?.typesOutPath,\n }),\n ];\n\n if (buildConfig) {\n plugins.push(i18nBuildPlugin(sharedConfig, buildConfig));\n }\n\n return plugins;\n}\n"],"mappings":";;;;AAiEA,SAAgB,cAAc,QAA6B,SAAwC;CACjG,IAAI,cAAc;CAClB,MAAM,eAAe,IAAI,SAAS,aAAa,SAAS;;;;;CAMxD,SAAS,kBACP,QACA,WACqC;EACrC,MAAM,WAAW,KAAK,KACpB,aACA,OAAO,YACP,QACA,GAAG,UAAU,OACd;AAED,MAAI;GACF,MAAM,UAAU,GAAG,aAAa,UAAU,QAAQ;AAClD,UAAO,KAAK,MAAM,QAAQ;UACpB;AACN;;;;;;;CAQJ,SAAS,sBACP,QACA,UACyB;EACzB,MAAM,OAAO,sBAAsB,OAAO,aAAa,CAAC,MAAM,UAAU,MAAM,SAAS,SAAS;AAChG,MAAI,CAAC,KAAM,QAAO,EAAE;EAEpB,MAAM,YAAY,KAAK,KAAK,aAAa,OAAO,YAAY,OAAO;EACnE,IAAI,QAAkB,EAAE;AACxB,MAAI;AACF,WAAQ,GAAG,YAAY,UAAU,CAAC,QAAQ,SAAS,KAAK,SAAS,QAAQ,CAAC;UACpE;AACN,UAAO,EAAE;;EAGX,MAAM,SAAkC,EAAE;AAC1C,OAAK,MAAM,QAAQ,OAAO;GACxB,MAAM,KAAK,KAAK,MAAM,GAAG,GAAgB;GACzC,MAAM,OAAO,kBAAkB,QAAQ,GAAG;AAC1C,OAAI,CAAC,KAAM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BTn.js";
2
2
  import { i as setGlobalInstance } from "./t-Bfb3ut7N.js";
3
3
  import { createContext, useContext, useEffect, useMemo, useState } from "react";
4
- //#region \0rolldown/runtime.js
5
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
6
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
7
- if (typeof require !== "undefined") return require.apply(this, arguments);
8
- throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
9
- });
10
- //#endregion
4
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
11
5
  //#region src/react/context.ts
12
6
  /**
13
7
  * React context for the i18n instance.
@@ -18,244 +12,7 @@ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require
18
12
  */
19
13
  var I18nContext = createContext(null);
20
14
  //#endregion
21
- //#region node_modules/react/cjs/react-jsx-runtime.production.js
22
- /**
23
- * @license React
24
- * react-jsx-runtime.production.js
25
- *
26
- * Copyright (c) Meta Platforms, Inc. and affiliates.
27
- *
28
- * This source code is licensed under the MIT license found in the
29
- * LICENSE file in the root directory of this source tree.
30
- */
31
- var require_react_jsx_runtime_production = /* @__PURE__ */ __commonJSMin(((exports) => {
32
- var REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment");
33
- function jsxProd(type, config, maybeKey) {
34
- var key = null;
35
- void 0 !== maybeKey && (key = "" + maybeKey);
36
- void 0 !== config.key && (key = "" + config.key);
37
- if ("key" in config) {
38
- maybeKey = {};
39
- for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
40
- } else maybeKey = config;
41
- config = maybeKey.ref;
42
- return {
43
- $$typeof: REACT_ELEMENT_TYPE,
44
- type,
45
- key,
46
- ref: void 0 !== config ? config : null,
47
- props: maybeKey
48
- };
49
- }
50
- exports.Fragment = REACT_FRAGMENT_TYPE;
51
- exports.jsx = jsxProd;
52
- exports.jsxs = jsxProd;
53
- }));
54
- //#endregion
55
- //#region node_modules/react/cjs/react-jsx-runtime.development.js
56
- /**
57
- * @license React
58
- * react-jsx-runtime.development.js
59
- *
60
- * Copyright (c) Meta Platforms, Inc. and affiliates.
61
- *
62
- * This source code is licensed under the MIT license found in the
63
- * LICENSE file in the root directory of this source tree.
64
- */
65
- var require_react_jsx_runtime_development = /* @__PURE__ */ __commonJSMin(((exports) => {
66
- "production" !== process.env.NODE_ENV && (function() {
67
- function getComponentNameFromType(type) {
68
- if (null == type) return null;
69
- if ("function" === typeof type) return type.$$typeof === REACT_CLIENT_REFERENCE ? null : type.displayName || type.name || null;
70
- if ("string" === typeof type) return type;
71
- switch (type) {
72
- case REACT_FRAGMENT_TYPE: return "Fragment";
73
- case REACT_PROFILER_TYPE: return "Profiler";
74
- case REACT_STRICT_MODE_TYPE: return "StrictMode";
75
- case REACT_SUSPENSE_TYPE: return "Suspense";
76
- case REACT_SUSPENSE_LIST_TYPE: return "SuspenseList";
77
- case REACT_ACTIVITY_TYPE: return "Activity";
78
- }
79
- if ("object" === typeof type) switch ("number" === typeof type.tag && console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), type.$$typeof) {
80
- case REACT_PORTAL_TYPE: return "Portal";
81
- case REACT_CONTEXT_TYPE: return type.displayName || "Context";
82
- case REACT_CONSUMER_TYPE: return (type._context.displayName || "Context") + ".Consumer";
83
- case REACT_FORWARD_REF_TYPE:
84
- var innerType = type.render;
85
- type = type.displayName;
86
- type || (type = innerType.displayName || innerType.name || "", type = "" !== type ? "ForwardRef(" + type + ")" : "ForwardRef");
87
- return type;
88
- case REACT_MEMO_TYPE: return innerType = type.displayName || null, null !== innerType ? innerType : getComponentNameFromType(type.type) || "Memo";
89
- case REACT_LAZY_TYPE:
90
- innerType = type._payload;
91
- type = type._init;
92
- try {
93
- return getComponentNameFromType(type(innerType));
94
- } catch (x) {}
95
- }
96
- return null;
97
- }
98
- function testStringCoercion(value) {
99
- return "" + value;
100
- }
101
- function checkKeyStringCoercion(value) {
102
- try {
103
- testStringCoercion(value);
104
- var JSCompiler_inline_result = !1;
105
- } catch (e) {
106
- JSCompiler_inline_result = !0;
107
- }
108
- if (JSCompiler_inline_result) {
109
- JSCompiler_inline_result = console;
110
- var JSCompiler_temp_const = JSCompiler_inline_result.error;
111
- var JSCompiler_inline_result$jscomp$0 = "function" === typeof Symbol && Symbol.toStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object";
112
- JSCompiler_temp_const.call(JSCompiler_inline_result, "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.", JSCompiler_inline_result$jscomp$0);
113
- return testStringCoercion(value);
114
- }
115
- }
116
- function getTaskName(type) {
117
- if (type === REACT_FRAGMENT_TYPE) return "<>";
118
- if ("object" === typeof type && null !== type && type.$$typeof === REACT_LAZY_TYPE) return "<...>";
119
- try {
120
- var name = getComponentNameFromType(type);
121
- return name ? "<" + name + ">" : "<...>";
122
- } catch (x) {
123
- return "<...>";
124
- }
125
- }
126
- function getOwner() {
127
- var dispatcher = ReactSharedInternals.A;
128
- return null === dispatcher ? null : dispatcher.getOwner();
129
- }
130
- function UnknownOwner() {
131
- return Error("react-stack-top-frame");
132
- }
133
- function hasValidKey(config) {
134
- if (hasOwnProperty.call(config, "key")) {
135
- var getter = Object.getOwnPropertyDescriptor(config, "key").get;
136
- if (getter && getter.isReactWarning) return !1;
137
- }
138
- return void 0 !== config.key;
139
- }
140
- function defineKeyPropWarningGetter(props, displayName) {
141
- function warnAboutAccessingKey() {
142
- specialPropKeyWarningShown || (specialPropKeyWarningShown = !0, console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)", displayName));
143
- }
144
- warnAboutAccessingKey.isReactWarning = !0;
145
- Object.defineProperty(props, "key", {
146
- get: warnAboutAccessingKey,
147
- configurable: !0
148
- });
149
- }
150
- function elementRefGetterWithDeprecationWarning() {
151
- var componentName = getComponentNameFromType(this.type);
152
- didWarnAboutElementRef[componentName] || (didWarnAboutElementRef[componentName] = !0, console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."));
153
- componentName = this.props.ref;
154
- return void 0 !== componentName ? componentName : null;
155
- }
156
- function ReactElement(type, key, props, owner, debugStack, debugTask) {
157
- var refProp = props.ref;
158
- type = {
159
- $$typeof: REACT_ELEMENT_TYPE,
160
- type,
161
- key,
162
- props,
163
- _owner: owner
164
- };
165
- null !== (void 0 !== refProp ? refProp : null) ? Object.defineProperty(type, "ref", {
166
- enumerable: !1,
167
- get: elementRefGetterWithDeprecationWarning
168
- }) : Object.defineProperty(type, "ref", {
169
- enumerable: !1,
170
- value: null
171
- });
172
- type._store = {};
173
- Object.defineProperty(type._store, "validated", {
174
- configurable: !1,
175
- enumerable: !1,
176
- writable: !0,
177
- value: 0
178
- });
179
- Object.defineProperty(type, "_debugInfo", {
180
- configurable: !1,
181
- enumerable: !1,
182
- writable: !0,
183
- value: null
184
- });
185
- Object.defineProperty(type, "_debugStack", {
186
- configurable: !1,
187
- enumerable: !1,
188
- writable: !0,
189
- value: debugStack
190
- });
191
- Object.defineProperty(type, "_debugTask", {
192
- configurable: !1,
193
- enumerable: !1,
194
- writable: !0,
195
- value: debugTask
196
- });
197
- Object.freeze && (Object.freeze(type.props), Object.freeze(type));
198
- return type;
199
- }
200
- function jsxDEVImpl(type, config, maybeKey, isStaticChildren, debugStack, debugTask) {
201
- var children = config.children;
202
- if (void 0 !== children) if (isStaticChildren) if (isArrayImpl(children)) {
203
- for (isStaticChildren = 0; isStaticChildren < children.length; isStaticChildren++) validateChildKeys(children[isStaticChildren]);
204
- Object.freeze && Object.freeze(children);
205
- } else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");
206
- else validateChildKeys(children);
207
- if (hasOwnProperty.call(config, "key")) {
208
- children = getComponentNameFromType(type);
209
- var keys = Object.keys(config).filter(function(k) {
210
- return "key" !== k;
211
- });
212
- isStaticChildren = 0 < keys.length ? "{key: someKey, " + keys.join(": ..., ") + ": ...}" : "{key: someKey}";
213
- didWarnAboutKeySpread[children + isStaticChildren] || (keys = 0 < keys.length ? "{" + keys.join(": ..., ") + ": ...}" : "{}", console.error("A props object containing a \"key\" prop is being spread into JSX:\n let props = %s;\n <%s {...props} />\nReact keys must be passed directly to JSX without using spread:\n let props = %s;\n <%s key={someKey} {...props} />", isStaticChildren, children, keys, children), didWarnAboutKeySpread[children + isStaticChildren] = !0);
214
- }
215
- children = null;
216
- void 0 !== maybeKey && (checkKeyStringCoercion(maybeKey), children = "" + maybeKey);
217
- hasValidKey(config) && (checkKeyStringCoercion(config.key), children = "" + config.key);
218
- if ("key" in config) {
219
- maybeKey = {};
220
- for (var propName in config) "key" !== propName && (maybeKey[propName] = config[propName]);
221
- } else maybeKey = config;
222
- children && defineKeyPropWarningGetter(maybeKey, "function" === typeof type ? type.displayName || type.name || "Unknown" : type);
223
- return ReactElement(type, children, maybeKey, getOwner(), debugStack, debugTask);
224
- }
225
- function validateChildKeys(node) {
226
- isValidElement(node) ? node._store && (node._store.validated = 1) : "object" === typeof node && null !== node && node.$$typeof === REACT_LAZY_TYPE && ("fulfilled" === node._payload.status ? isValidElement(node._payload.value) && node._payload.value._store && (node._payload.value._store.validated = 1) : node._store && (node._store.validated = 1));
227
- }
228
- function isValidElement(object) {
229
- return "object" === typeof object && null !== object && object.$$typeof === REACT_ELEMENT_TYPE;
230
- }
231
- var React = __require("react"), REACT_ELEMENT_TYPE = Symbol.for("react.transitional.element"), REACT_PORTAL_TYPE = Symbol.for("react.portal"), REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"), REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"), REACT_PROFILER_TYPE = Symbol.for("react.profiler"), REACT_CONSUMER_TYPE = Symbol.for("react.consumer"), REACT_CONTEXT_TYPE = Symbol.for("react.context"), REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"), REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"), REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"), REACT_MEMO_TYPE = Symbol.for("react.memo"), REACT_LAZY_TYPE = Symbol.for("react.lazy"), REACT_ACTIVITY_TYPE = Symbol.for("react.activity"), REACT_CLIENT_REFERENCE = Symbol.for("react.client.reference"), ReactSharedInternals = React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, hasOwnProperty = Object.prototype.hasOwnProperty, isArrayImpl = Array.isArray, createTask = console.createTask ? console.createTask : function() {
232
- return null;
233
- };
234
- React = { react_stack_bottom_frame: function(callStackForError) {
235
- return callStackForError();
236
- } };
237
- var specialPropKeyWarningShown;
238
- var didWarnAboutElementRef = {};
239
- var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(React, UnknownOwner)();
240
- var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));
241
- var didWarnAboutKeySpread = {};
242
- exports.Fragment = REACT_FRAGMENT_TYPE;
243
- exports.jsx = function(type, config, maybeKey) {
244
- var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
245
- return jsxDEVImpl(type, config, maybeKey, !1, trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
246
- };
247
- exports.jsxs = function(type, config, maybeKey) {
248
- var trackActualOwner = 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;
249
- return jsxDEVImpl(type, config, maybeKey, !0, trackActualOwner ? Error("react-stack-top-frame") : unknownOwnerDebugStack, trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask);
250
- };
251
- })();
252
- }));
253
- //#endregion
254
15
  //#region src/react/I18nProvider.tsx
255
- var import_jsx_runtime = (/* @__PURE__ */ __commonJSMin(((exports, module) => {
256
- if (process.env.NODE_ENV === "production") module.exports = require_react_jsx_runtime_production();
257
- else module.exports = require_react_jsx_runtime_development();
258
- })))();
259
16
  function I18nProvider({ instance, children, serverResources }) {
260
17
  const [hydrated] = useState(() => {
261
18
  if (serverResources) return true;
@@ -293,7 +50,7 @@ function I18nProvider({ instance, children, serverResources }) {
293
50
  instance,
294
51
  version
295
52
  }), [instance, version]);
296
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(I18nContext.Provider, {
53
+ return /* @__PURE__ */ jsx(I18nContext.Provider, {
297
54
  value: contextValue,
298
55
  children
299
56
  });
@@ -457,7 +214,7 @@ function DevToolbar() {
457
214
  const fallbackCount = groups[1].entries.length + groups[2].entries.length;
458
215
  const missingCount = groups[3].entries.length;
459
216
  const totalKeys = uniqueKeys.size;
460
- return /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(import_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("button", {
217
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("button", {
461
218
  "data-testid": "i18n-toolbar-toggle",
462
219
  onClick: () => setOpen((v) => !v),
463
220
  style: {
@@ -482,7 +239,7 @@ function DevToolbar() {
482
239
  },
483
240
  "aria-label": open ? "Close i18n toolbar" : "Open i18n toolbar",
484
241
  children: totalKeys
485
- }), open && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
242
+ }), open && /* @__PURE__ */ jsxs("div", {
486
243
  "data-testid": "i18n-toolbar-panel",
487
244
  style: {
488
245
  position: "fixed",
@@ -502,7 +259,7 @@ function DevToolbar() {
502
259
  flexDirection: "column"
503
260
  },
504
261
  children: [
505
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
262
+ /* @__PURE__ */ jsxs("div", {
506
263
  style: {
507
264
  padding: "12px 16px",
508
265
  borderBottom: "1px solid rgba(255,255,255,0.1)",
@@ -510,13 +267,13 @@ function DevToolbar() {
510
267
  alignItems: "center",
511
268
  justifyContent: "space-between"
512
269
  },
513
- children: [/* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
270
+ children: [/* @__PURE__ */ jsx("span", {
514
271
  style: {
515
272
  fontWeight: 600,
516
273
  fontSize: 14
517
274
  },
518
275
  children: "i18n DevToolbar"
519
- }), /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
276
+ }), /* @__PURE__ */ jsx("span", {
520
277
  style: {
521
278
  background: "#2563eb",
522
279
  color: "#fff",
@@ -528,7 +285,7 @@ function DevToolbar() {
528
285
  children: locale
529
286
  })]
530
287
  }),
531
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
288
+ /* @__PURE__ */ jsxs("div", {
532
289
  style: {
533
290
  padding: "10px 16px",
534
291
  borderBottom: "1px solid rgba(255,255,255,0.1)",
@@ -538,30 +295,30 @@ function DevToolbar() {
538
295
  fontSize: 12
539
296
  },
540
297
  children: [
541
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", { children: ["Total: ", /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: totalKeys })] }),
542
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
298
+ /* @__PURE__ */ jsxs("span", { children: ["Total: ", /* @__PURE__ */ jsx("strong", { children: totalKeys })] }),
299
+ /* @__PURE__ */ jsxs("span", {
543
300
  style: { color: RESOLUTION_COLORS.primary },
544
- children: ["Primary: ", /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: primaryCount })]
301
+ children: ["Primary: ", /* @__PURE__ */ jsx("strong", { children: primaryCount })]
545
302
  }),
546
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
303
+ /* @__PURE__ */ jsxs("span", {
547
304
  style: { color: RESOLUTION_COLORS["fallback-locale"] },
548
- children: ["Fallback: ", /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: fallbackCount })]
305
+ children: ["Fallback: ", /* @__PURE__ */ jsx("strong", { children: fallbackCount })]
549
306
  }),
550
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
307
+ /* @__PURE__ */ jsxs("span", {
551
308
  style: { color: RESOLUTION_COLORS["key-as-value"] },
552
- children: ["Missing: ", /* @__PURE__ */ (0, import_jsx_runtime.jsx)("strong", { children: missingCount })]
309
+ children: ["Missing: ", /* @__PURE__ */ jsx("strong", { children: missingCount })]
553
310
  })
554
311
  ]
555
312
  }),
556
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
313
+ /* @__PURE__ */ jsxs("div", {
557
314
  style: {
558
315
  overflowY: "auto",
559
316
  flex: 1,
560
317
  padding: "8px 0"
561
318
  },
562
- children: [groups.map((group) => group.entries.length > 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
319
+ children: [groups.map((group) => group.entries.length > 0 && /* @__PURE__ */ jsxs("div", {
563
320
  style: { marginBottom: 8 },
564
- children: [/* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
321
+ children: [/* @__PURE__ */ jsxs("div", {
565
322
  style: {
566
323
  padding: "4px 16px",
567
324
  fontSize: 11,
@@ -576,7 +333,7 @@ function DevToolbar() {
576
333
  group.entries.length,
577
334
  ")"
578
335
  ]
579
- }), group.entries.map((entry) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("div", {
336
+ }), group.entries.map((entry) => /* @__PURE__ */ jsxs("div", {
580
337
  style: {
581
338
  padding: "4px 16px 4px 24px",
582
339
  display: "flex",
@@ -584,7 +341,7 @@ function DevToolbar() {
584
341
  gap: 8
585
342
  },
586
343
  children: [
587
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", { style: {
344
+ /* @__PURE__ */ jsx("span", { style: {
588
345
  width: 6,
589
346
  height: 6,
590
347
  borderRadius: 3,
@@ -592,7 +349,7 @@ function DevToolbar() {
592
349
  flexShrink: 0,
593
350
  alignSelf: "center"
594
351
  } }),
595
- /* @__PURE__ */ (0, import_jsx_runtime.jsx)("span", {
352
+ /* @__PURE__ */ jsx("span", {
596
353
  style: {
597
354
  fontFamily: "ui-monospace, monospace",
598
355
  fontSize: 12,
@@ -600,7 +357,7 @@ function DevToolbar() {
600
357
  },
601
358
  children: entry.key
602
359
  }),
603
- /* @__PURE__ */ (0, import_jsx_runtime.jsxs)("span", {
360
+ /* @__PURE__ */ jsxs("span", {
604
361
  style: {
605
362
  fontSize: 11,
606
363
  color: "#94a3b8",
@@ -611,7 +368,7 @@ function DevToolbar() {
611
368
  })
612
369
  ]
613
370
  }, `${entry.key}-${entry.namespace}-${entry.scope ?? ""}`))]
614
- }, group.type)), totalKeys === 0 && /* @__PURE__ */ (0, import_jsx_runtime.jsx)("div", {
371
+ }, group.type)), totalKeys === 0 && /* @__PURE__ */ jsx("div", {
615
372
  style: {
616
373
  padding: "16px",
617
374
  textAlign: "center",
@@ -639,8 +396,8 @@ function DevToolbar() {
639
396
  */
640
397
  function I18nBoundary({ scope, fallback = null, children }) {
641
398
  const { ready } = useI18n(scope);
642
- if (!ready) return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children: fallback });
643
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_jsx_runtime.Fragment, { children });
399
+ if (!ready) return /* @__PURE__ */ jsx(Fragment, { children: fallback });
400
+ return /* @__PURE__ */ jsx(Fragment, { children });
644
401
  }
645
402
  //#endregion
646
403
  export { DevToolbar, I18nBoundary, I18nProvider, useI18n };
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"react.js","names":[],"sources":["../src/react/context.ts","../node_modules/react/cjs/react-jsx-runtime.production.js","../node_modules/react/cjs/react-jsx-runtime.development.js","../node_modules/react/jsx-runtime.js","../src/react/I18nProvider.tsx","../src/react/useI18n.ts","../src/react/DevToolbar.tsx","../src/react/I18nBoundary.tsx"],"sourcesContent":["import { createContext } from 'react';\nimport type { I18nInstance } from '../core/types';\n\n/**\n * Context value passed from I18nProvider to consumers.\n * Includes the i18n instance and a version counter that increments\n * whenever the store is updated (dictionaries loaded, locale changed).\n * The version forces useMemo in useI18n to re-create the t function.\n */\nexport interface I18nContextValue {\n instance: I18nInstance;\n version: number;\n}\n\n/**\n * React context for the i18n instance.\n *\n * Provided by `I18nProvider`, consumed by `useI18n`.\n * The default value is `null` — using `useI18n` outside of a provider\n * will throw a descriptive error.\n */\nexport const I18nContext = createContext<I18nContextValue | null>(null);\n","/**\n * @license React\n * react-jsx-runtime.production.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\nvar REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\");\nfunction jsxProd(type, config, maybeKey) {\n var key = null;\n void 0 !== maybeKey && (key = \"\" + maybeKey);\n void 0 !== config.key && (key = \"\" + config.key);\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n config = maybeKey.ref;\n return {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n ref: void 0 !== config ? config : null,\n props: maybeKey\n };\n}\nexports.Fragment = REACT_FRAGMENT_TYPE;\nexports.jsx = jsxProd;\nexports.jsxs = jsxProd;\n","/**\n * @license React\n * react-jsx-runtime.development.js\n *\n * Copyright (c) Meta Platforms, Inc. and affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n */\n\n\"use strict\";\n\"production\" !== process.env.NODE_ENV &&\n (function () {\n function getComponentNameFromType(type) {\n if (null == type) return null;\n if (\"function\" === typeof type)\n return type.$$typeof === REACT_CLIENT_REFERENCE\n ? null\n : type.displayName || type.name || null;\n if (\"string\" === typeof type) return type;\n switch (type) {\n case REACT_FRAGMENT_TYPE:\n return \"Fragment\";\n case REACT_PROFILER_TYPE:\n return \"Profiler\";\n case REACT_STRICT_MODE_TYPE:\n return \"StrictMode\";\n case REACT_SUSPENSE_TYPE:\n return \"Suspense\";\n case REACT_SUSPENSE_LIST_TYPE:\n return \"SuspenseList\";\n case REACT_ACTIVITY_TYPE:\n return \"Activity\";\n }\n if (\"object\" === typeof type)\n switch (\n (\"number\" === typeof type.tag &&\n console.error(\n \"Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue.\"\n ),\n type.$$typeof)\n ) {\n case REACT_PORTAL_TYPE:\n return \"Portal\";\n case REACT_CONTEXT_TYPE:\n return type.displayName || \"Context\";\n case REACT_CONSUMER_TYPE:\n return (type._context.displayName || \"Context\") + \".Consumer\";\n case REACT_FORWARD_REF_TYPE:\n var innerType = type.render;\n type = type.displayName;\n type ||\n ((type = innerType.displayName || innerType.name || \"\"),\n (type = \"\" !== type ? \"ForwardRef(\" + type + \")\" : \"ForwardRef\"));\n return type;\n case REACT_MEMO_TYPE:\n return (\n (innerType = type.displayName || null),\n null !== innerType\n ? innerType\n : getComponentNameFromType(type.type) || \"Memo\"\n );\n case REACT_LAZY_TYPE:\n innerType = type._payload;\n type = type._init;\n try {\n return getComponentNameFromType(type(innerType));\n } catch (x) {}\n }\n return null;\n }\n function testStringCoercion(value) {\n return \"\" + value;\n }\n function checkKeyStringCoercion(value) {\n try {\n testStringCoercion(value);\n var JSCompiler_inline_result = !1;\n } catch (e) {\n JSCompiler_inline_result = !0;\n }\n if (JSCompiler_inline_result) {\n JSCompiler_inline_result = console;\n var JSCompiler_temp_const = JSCompiler_inline_result.error;\n var JSCompiler_inline_result$jscomp$0 =\n (\"function\" === typeof Symbol &&\n Symbol.toStringTag &&\n value[Symbol.toStringTag]) ||\n value.constructor.name ||\n \"Object\";\n JSCompiler_temp_const.call(\n JSCompiler_inline_result,\n \"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.\",\n JSCompiler_inline_result$jscomp$0\n );\n return testStringCoercion(value);\n }\n }\n function getTaskName(type) {\n if (type === REACT_FRAGMENT_TYPE) return \"<>\";\n if (\n \"object\" === typeof type &&\n null !== type &&\n type.$$typeof === REACT_LAZY_TYPE\n )\n return \"<...>\";\n try {\n var name = getComponentNameFromType(type);\n return name ? \"<\" + name + \">\" : \"<...>\";\n } catch (x) {\n return \"<...>\";\n }\n }\n function getOwner() {\n var dispatcher = ReactSharedInternals.A;\n return null === dispatcher ? null : dispatcher.getOwner();\n }\n function UnknownOwner() {\n return Error(\"react-stack-top-frame\");\n }\n function hasValidKey(config) {\n if (hasOwnProperty.call(config, \"key\")) {\n var getter = Object.getOwnPropertyDescriptor(config, \"key\").get;\n if (getter && getter.isReactWarning) return !1;\n }\n return void 0 !== config.key;\n }\n function defineKeyPropWarningGetter(props, displayName) {\n function warnAboutAccessingKey() {\n specialPropKeyWarningShown ||\n ((specialPropKeyWarningShown = !0),\n console.error(\n \"%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)\",\n displayName\n ));\n }\n warnAboutAccessingKey.isReactWarning = !0;\n Object.defineProperty(props, \"key\", {\n get: warnAboutAccessingKey,\n configurable: !0\n });\n }\n function elementRefGetterWithDeprecationWarning() {\n var componentName = getComponentNameFromType(this.type);\n didWarnAboutElementRef[componentName] ||\n ((didWarnAboutElementRef[componentName] = !0),\n console.error(\n \"Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.\"\n ));\n componentName = this.props.ref;\n return void 0 !== componentName ? componentName : null;\n }\n function ReactElement(type, key, props, owner, debugStack, debugTask) {\n var refProp = props.ref;\n type = {\n $$typeof: REACT_ELEMENT_TYPE,\n type: type,\n key: key,\n props: props,\n _owner: owner\n };\n null !== (void 0 !== refProp ? refProp : null)\n ? Object.defineProperty(type, \"ref\", {\n enumerable: !1,\n get: elementRefGetterWithDeprecationWarning\n })\n : Object.defineProperty(type, \"ref\", { enumerable: !1, value: null });\n type._store = {};\n Object.defineProperty(type._store, \"validated\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: 0\n });\n Object.defineProperty(type, \"_debugInfo\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: null\n });\n Object.defineProperty(type, \"_debugStack\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugStack\n });\n Object.defineProperty(type, \"_debugTask\", {\n configurable: !1,\n enumerable: !1,\n writable: !0,\n value: debugTask\n });\n Object.freeze && (Object.freeze(type.props), Object.freeze(type));\n return type;\n }\n function jsxDEVImpl(\n type,\n config,\n maybeKey,\n isStaticChildren,\n debugStack,\n debugTask\n ) {\n var children = config.children;\n if (void 0 !== children)\n if (isStaticChildren)\n if (isArrayImpl(children)) {\n for (\n isStaticChildren = 0;\n isStaticChildren < children.length;\n isStaticChildren++\n )\n validateChildKeys(children[isStaticChildren]);\n Object.freeze && Object.freeze(children);\n } else\n console.error(\n \"React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.\"\n );\n else validateChildKeys(children);\n if (hasOwnProperty.call(config, \"key\")) {\n children = getComponentNameFromType(type);\n var keys = Object.keys(config).filter(function (k) {\n return \"key\" !== k;\n });\n isStaticChildren =\n 0 < keys.length\n ? \"{key: someKey, \" + keys.join(\": ..., \") + \": ...}\"\n : \"{key: someKey}\";\n didWarnAboutKeySpread[children + isStaticChildren] ||\n ((keys =\n 0 < keys.length ? \"{\" + keys.join(\": ..., \") + \": ...}\" : \"{}\"),\n console.error(\n 'A props object containing a \"key\" prop is being spread into JSX:\\n let props = %s;\\n <%s {...props} />\\nReact keys must be passed directly to JSX without using spread:\\n let props = %s;\\n <%s key={someKey} {...props} />',\n isStaticChildren,\n children,\n keys,\n children\n ),\n (didWarnAboutKeySpread[children + isStaticChildren] = !0));\n }\n children = null;\n void 0 !== maybeKey &&\n (checkKeyStringCoercion(maybeKey), (children = \"\" + maybeKey));\n hasValidKey(config) &&\n (checkKeyStringCoercion(config.key), (children = \"\" + config.key));\n if (\"key\" in config) {\n maybeKey = {};\n for (var propName in config)\n \"key\" !== propName && (maybeKey[propName] = config[propName]);\n } else maybeKey = config;\n children &&\n defineKeyPropWarningGetter(\n maybeKey,\n \"function\" === typeof type\n ? type.displayName || type.name || \"Unknown\"\n : type\n );\n return ReactElement(\n type,\n children,\n maybeKey,\n getOwner(),\n debugStack,\n debugTask\n );\n }\n function validateChildKeys(node) {\n isValidElement(node)\n ? node._store && (node._store.validated = 1)\n : \"object\" === typeof node &&\n null !== node &&\n node.$$typeof === REACT_LAZY_TYPE &&\n (\"fulfilled\" === node._payload.status\n ? isValidElement(node._payload.value) &&\n node._payload.value._store &&\n (node._payload.value._store.validated = 1)\n : node._store && (node._store.validated = 1));\n }\n function isValidElement(object) {\n return (\n \"object\" === typeof object &&\n null !== object &&\n object.$$typeof === REACT_ELEMENT_TYPE\n );\n }\n var React = require(\"react\"),\n REACT_ELEMENT_TYPE = Symbol.for(\"react.transitional.element\"),\n REACT_PORTAL_TYPE = Symbol.for(\"react.portal\"),\n REACT_FRAGMENT_TYPE = Symbol.for(\"react.fragment\"),\n REACT_STRICT_MODE_TYPE = Symbol.for(\"react.strict_mode\"),\n REACT_PROFILER_TYPE = Symbol.for(\"react.profiler\"),\n REACT_CONSUMER_TYPE = Symbol.for(\"react.consumer\"),\n REACT_CONTEXT_TYPE = Symbol.for(\"react.context\"),\n REACT_FORWARD_REF_TYPE = Symbol.for(\"react.forward_ref\"),\n REACT_SUSPENSE_TYPE = Symbol.for(\"react.suspense\"),\n REACT_SUSPENSE_LIST_TYPE = Symbol.for(\"react.suspense_list\"),\n REACT_MEMO_TYPE = Symbol.for(\"react.memo\"),\n REACT_LAZY_TYPE = Symbol.for(\"react.lazy\"),\n REACT_ACTIVITY_TYPE = Symbol.for(\"react.activity\"),\n REACT_CLIENT_REFERENCE = Symbol.for(\"react.client.reference\"),\n ReactSharedInternals =\n React.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,\n hasOwnProperty = Object.prototype.hasOwnProperty,\n isArrayImpl = Array.isArray,\n createTask = console.createTask\n ? console.createTask\n : function () {\n return null;\n };\n React = {\n react_stack_bottom_frame: function (callStackForError) {\n return callStackForError();\n }\n };\n var specialPropKeyWarningShown;\n var didWarnAboutElementRef = {};\n var unknownOwnerDebugStack = React.react_stack_bottom_frame.bind(\n React,\n UnknownOwner\n )();\n var unknownOwnerDebugTask = createTask(getTaskName(UnknownOwner));\n var didWarnAboutKeySpread = {};\n exports.Fragment = REACT_FRAGMENT_TYPE;\n exports.jsx = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !1,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n exports.jsxs = function (type, config, maybeKey) {\n var trackActualOwner =\n 1e4 > ReactSharedInternals.recentlyCreatedOwnerStacks++;\n return jsxDEVImpl(\n type,\n config,\n maybeKey,\n !0,\n trackActualOwner\n ? Error(\"react-stack-top-frame\")\n : unknownOwnerDebugStack,\n trackActualOwner ? createTask(getTaskName(type)) : unknownOwnerDebugTask\n );\n };\n })();\n","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/react-jsx-runtime.production.js');\n} else {\n module.exports = require('./cjs/react-jsx-runtime.development.js');\n}\n","import { useEffect, useState, useMemo, type ReactNode } from 'react';\nimport { I18nContext } from './context';\nimport { setGlobalInstance } from '../core/t';\nimport type { I18nInstance, NestedTranslations } from '../core/types';\n\n/**\n * Props for the {@link I18nProvider} component.\n */\ninterface I18nProviderProps {\n /** The i18n instance returned by `createI18n()`. */\n instance: I18nInstance;\n /** Child components that will have access to translations. */\n children: ReactNode;\n /**\n * Pre-loaded translations from SSR. When provided, the provider adds these\n * resources to the store immediately and skips dictionary fetching.\n * Format: Record<namespace, NestedTranslations>\n * Example: { shared: { ok: 'OK' }, global: { appName: 'Store' } }\n */\n serverResources?: Record<string, NestedTranslations>;\n}\n\n/**\n * React context provider for translations.\n *\n * On mount, it sets the global i18n instance and loads all dictionary\n * bundles (one HTTP request per named dictionary, in declaration order).\n * Re-renders children when dictionaries finish loading and when the\n * locale changes.\n *\n * @example\n * ```tsx\n * import { createI18n } from 'vite-bundled-i18n';\n * import { I18nProvider } from 'vite-bundled-i18n/react';\n *\n * const i18n = createI18n({ ... });\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * </I18nProvider>\n * );\n * }\n * ```\n */\ninterface WindowWithI18n extends Window {\n __I18N_RESOURCES__?: {\n locale: string;\n resources: Record<string, NestedTranslations>;\n };\n}\n\nexport function I18nProvider({ instance, children, serverResources }: I18nProviderProps) {\n const [hydrated] = useState(() => {\n if (serverResources) {\n return true;\n }\n if (typeof window !== 'undefined' && (window as WindowWithI18n).__I18N_RESOURCES__) {\n return true;\n }\n return false;\n });\n\n const [version, setVersion] = useState(() => {\n if (serverResources) {\n const locale = instance.getLocale();\n for (const [namespace, data] of Object.entries(serverResources)) {\n instance.addResources(locale, namespace, data);\n }\n return 1;\n }\n\n // Auto-hydrate from server-injected global\n const win = typeof window !== 'undefined' ? (window as WindowWithI18n) : undefined;\n if (win?.__I18N_RESOURCES__) {\n const serverData = win.__I18N_RESOURCES__;\n for (const [namespace, data] of Object.entries(serverData.resources)) {\n instance.addResources(serverData.locale, namespace, data);\n }\n delete win.__I18N_RESOURCES__;\n return 1;\n }\n\n return 0;\n });\n\n useEffect(() => {\n setGlobalInstance(instance);\n\n const unsub = instance.onLocaleChange(() => {\n setVersion((v) => v + 1);\n });\n\n if (!hydrated) {\n const hasDicts = instance.getDictionaryNames().length > 0;\n if (hasDicts) {\n instance.loadAllDictionaries(instance.getLocale()).then(() => {\n setVersion((v) => v + 1);\n });\n }\n }\n\n return unsub;\n }, [instance, hydrated]);\n\n const contextValue = useMemo(\n () => ({ instance, version }),\n [instance, version],\n );\n\n return (\n <I18nContext.Provider value={contextValue}>\n {children}\n </I18nContext.Provider>\n );\n}\n","import { useContext, useEffect, useState, useMemo } from 'react';\nimport { I18nContext } from './context';\nimport { createTranslations } from '../core/getTranslations';\nimport type { UseI18nResult, ValidScope } from '../core/types';\n\n/**\n * React hook for accessing translations.\n *\n * Can be called with or without a scope:\n *\n * **Without scope** — accesses only dictionary translations (shared, global, etc.).\n * Use this in layout components, navigation, footers, and other app-wide UI.\n *\n * **With scope** — triggers loading of the scope bundle (one HTTP request for all\n * namespaces that page needs). Use this in route/page components.\n *\n * Keys are always fully qualified (e.g., `'products.show.title'`), regardless of scope.\n *\n * @param scope - Optional bundle identifier (e.g., `'products.show'`).\n * Triggers loading of the scope bundle via `/__i18n/{locale}/{scope}.json`.\n * @returns An object with `t` (translation function), `ready` (loading state),\n * and `locale` (current locale code)\n * @throws If called outside of an `I18nProvider`\n *\n * @example\n * ```tsx\n * // Dictionary-only access\n * const { t, ready } = useI18n();\n * t('shared.ok', 'OK');\n *\n * // Bundle + dictionary access\n * const { t, ready } = useI18n('products.show');\n * t('products.show.title', 'Product Details');\n * t('shared.ok', 'OK'); // dictionaries still work\n * ```\n */\nexport function useI18n(scope?: ValidScope): UseI18nResult {\n const ctx = useContext(I18nContext);\n\n if (!ctx) {\n throw new Error(\n 'vite-bundled-i18n: useI18n() must be used within an <I18nProvider>. ' +\n 'Wrap your app with <I18nProvider instance={...}>.',\n );\n }\n\n const { instance, version } = ctx;\n const locale = instance.getLocale();\n const [scopeReady, setScopeReady] = useState(() => {\n if (!scope) return true;\n return instance.isScopeLoaded(locale, scope);\n });\n const [loadedScopeKey, setLoadedScopeKey] = useState<string | null>(null);\n\n // Load scope bundle if needed — one HTTP request per scope\n const scopeKey = scope ? `${locale}:${scope}` : null;\n useEffect(() => {\n if (!scopeKey || !scope) return;\n if (scopeKey === loadedScopeKey) return;\n\n let cancelled = false;\n instance.loadScope(locale, scope).then(() => {\n if (!cancelled) {\n setLoadedScopeKey(scopeKey);\n setScopeReady(true);\n }\n });\n\n return () => { cancelled = true; };\n }, [scopeKey, scope, locale, instance, loadedScopeKey]);\n\n // Re-create the translator object whenever locale or loaded resources change.\n const translations = useMemo(\n () => createTranslations(instance, locale),\n // version is not read directly here, but it must participate so the\n // translator object is recreated after dictionary/scope loads.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [instance, locale, version],\n );\n\n return {\n t: translations.t,\n get: translations.get,\n has: translations.has,\n exists: translations.exists,\n tryGet: translations.tryGet,\n require: translations.require,\n translations,\n ready: scopeReady,\n locale,\n };\n}\n","import { useContext, useState } from 'react';\nimport { I18nContext } from './context';\nimport type { KeyUsageEntry } from '../core/types';\n\nconst RESOLUTION_COLORS: Record<KeyUsageEntry['resolvedFrom'], string> = {\n primary: '#4ade80',\n 'fallback-locale': '#facc15',\n 'fallback-string': '#fb923c',\n 'key-as-value': '#f87171',\n};\n\nconst RESOLUTION_LABELS: Record<KeyUsageEntry['resolvedFrom'], string> = {\n primary: 'Primary',\n 'fallback-locale': 'Fallback Locale',\n 'fallback-string': 'Fallback String',\n 'key-as-value': 'Key as Value',\n};\n\n/**\n * Dev-only toolbar overlay that displays translation diagnostics\n * for the current page. Reads key usage data from the i18n instance\n * via {@link I18nContext}.\n *\n * Renders nothing in production or when used outside an `I18nProvider`.\n *\n * @example\n * ```tsx\n * import { DevToolbar } from 'vite-bundled-i18n/react';\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * <DevToolbar />\n * </I18nProvider>\n * );\n * }\n * ```\n */\nexport function DevToolbar() {\n // Skip in production — always render in test (import.meta.env may not exist)\n const isDev =\n typeof import.meta !== 'undefined' && import.meta.env\n ? import.meta.env.DEV\n : true;\n\n const ctx = useContext(I18nContext);\n\n const [open, setOpen] = useState(false);\n\n if (!isDev) return null;\n if (!ctx) return null;\n\n const { instance } = ctx;\n const usage = instance.getKeyUsage();\n const locale = instance.getLocale();\n\n // Deduplicate keys for display — keep the first occurrence\n const uniqueKeys = new Map<string, KeyUsageEntry>();\n for (const entry of usage) {\n if (!uniqueKeys.has(entry.key)) {\n uniqueKeys.set(entry.key, entry);\n }\n }\n\n const groups: Array<{ type: KeyUsageEntry['resolvedFrom']; entries: KeyUsageEntry[] }> = [\n { type: 'primary', entries: [] },\n { type: 'fallback-locale', entries: [] },\n { type: 'fallback-string', entries: [] },\n { type: 'key-as-value', entries: [] },\n ];\n\n for (const entry of uniqueKeys.values()) {\n const group = groups.find((g) => g.type === entry.resolvedFrom);\n if (group) group.entries.push(entry);\n }\n\n const primaryCount = groups[0].entries.length;\n const fallbackCount =\n groups[1].entries.length + groups[2].entries.length;\n const missingCount = groups[3].entries.length;\n const totalKeys = uniqueKeys.size;\n\n return (\n <>\n {/* Toggle button */}\n <button\n data-testid=\"i18n-toolbar-toggle\"\n onClick={() => setOpen((v) => !v)}\n style={{\n position: 'fixed',\n bottom: 16,\n right: 16,\n zIndex: 99999,\n width: 44,\n height: 44,\n borderRadius: 22,\n border: 'none',\n background: missingCount > 0 ? '#dc2626' : '#2563eb',\n color: '#fff',\n fontSize: 14,\n fontWeight: 700,\n cursor: 'pointer',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n boxShadow: '0 2px 8px rgba(0,0,0,0.3)',\n fontFamily: 'system-ui, sans-serif',\n }}\n aria-label={open ? 'Close i18n toolbar' : 'Open i18n toolbar'}\n >\n {totalKeys}\n </button>\n\n {/* Panel */}\n {open && (\n <div\n data-testid=\"i18n-toolbar-panel\"\n style={{\n position: 'fixed',\n bottom: 68,\n right: 16,\n zIndex: 99999,\n width: 380,\n maxHeight: 480,\n background: 'rgba(0, 0, 0, 0.92)',\n color: '#f1f5f9',\n borderRadius: 10,\n boxShadow: '0 4px 24px rgba(0,0,0,0.4)',\n fontFamily: 'system-ui, sans-serif',\n fontSize: 13,\n overflow: 'hidden',\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n {/* Header */}\n <div\n style={{\n padding: '12px 16px',\n borderBottom: '1px solid rgba(255,255,255,0.1)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n }}\n >\n <span style={{ fontWeight: 600, fontSize: 14 }}>i18n DevToolbar</span>\n <span\n style={{\n background: '#2563eb',\n color: '#fff',\n padding: '2px 10px',\n borderRadius: 12,\n fontSize: 12,\n fontWeight: 600,\n }}\n >\n {locale}\n </span>\n </div>\n\n {/* Summary */}\n <div\n style={{\n padding: '10px 16px',\n borderBottom: '1px solid rgba(255,255,255,0.1)',\n display: 'flex',\n gap: 16,\n flexWrap: 'wrap',\n fontSize: 12,\n }}\n >\n <span>\n Total: <strong>{totalKeys}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS.primary }}>\n Primary: <strong>{primaryCount}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS['fallback-locale'] }}>\n Fallback: <strong>{fallbackCount}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS['key-as-value'] }}>\n Missing: <strong>{missingCount}</strong>\n </span>\n </div>\n\n {/* Key list */}\n <div style={{ overflowY: 'auto', flex: 1, padding: '8px 0' }}>\n {groups.map(\n (group) =>\n group.entries.length > 0 && (\n <div key={group.type} style={{ marginBottom: 8 }}>\n <div\n style={{\n padding: '4px 16px',\n fontSize: 11,\n fontWeight: 700,\n textTransform: 'uppercase',\n letterSpacing: '0.05em',\n color: RESOLUTION_COLORS[group.type],\n }}\n >\n {RESOLUTION_LABELS[group.type]} ({group.entries.length})\n </div>\n {group.entries.map((entry) => (\n <div\n key={`${entry.key}-${entry.namespace}-${entry.scope ?? ''}`}\n style={{\n padding: '4px 16px 4px 24px',\n display: 'flex',\n alignItems: 'baseline',\n gap: 8,\n }}\n >\n <span\n style={{\n width: 6,\n height: 6,\n borderRadius: 3,\n background: RESOLUTION_COLORS[entry.resolvedFrom],\n flexShrink: 0,\n alignSelf: 'center',\n }}\n />\n <span\n style={{\n fontFamily: 'ui-monospace, monospace',\n fontSize: 12,\n wordBreak: 'break-all',\n }}\n >\n {entry.key}\n </span>\n <span\n style={{\n fontSize: 11,\n color: '#94a3b8',\n marginLeft: 'auto',\n flexShrink: 0,\n }}\n >\n {entry.namespace}\n {entry.scope ? ` / ${entry.scope}` : ''}\n </span>\n </div>\n ))}\n </div>\n ),\n )}\n {totalKeys === 0 && (\n <div style={{ padding: '16px', textAlign: 'center', color: '#64748b' }}>\n No keys used yet\n </div>\n )}\n </div>\n </div>\n )}\n </>\n );\n}\n","import { type ReactNode } from 'react';\nimport { useI18n } from './useI18n';\n\nexport interface I18nBoundaryProps {\n /** Scope to load (e.g., 'products.index') */\n scope: string;\n /** Rendered while translations are loading */\n fallback?: ReactNode;\n /** Rendered once translations are ready */\n children: ReactNode;\n}\n\n/**\n * Boundary component that handles translation loading.\n * Children only render once the scope is ready, avoiding\n * rules-of-hooks violations from early returns in child components.\n *\n * @example\n * ```tsx\n * <I18nBoundary scope=\"products.index\" fallback={<Spinner />}>\n * <ProductsPage />\n * </I18nBoundary>\n * ```\n */\nexport function I18nBoundary({ scope, fallback = null, children }: I18nBoundaryProps) {\n const { ready } = useI18n(scope);\n\n if (!ready) return <>{fallback}</>;\n return <>{children}</>;\n}\n"],"x_google_ignoreList":[1,2,3],"mappings":";;;;;;;;;;;;;;;;;;AAqBA,IAAa,cAAc,cAAuC,KAAK;;;;;;;;;;;;;CCVvE,IAAI,qBAAqB,OAAO,IAAI,6BAA6B,EAC/D,sBAAsB,OAAO,IAAI,iBAAiB;CACpD,SAAS,QAAQ,MAAM,QAAQ,UAAU;EACvC,IAAI,MAAM;AACV,OAAK,MAAM,aAAa,MAAM,KAAK;AACnC,OAAK,MAAM,OAAO,QAAQ,MAAM,KAAK,OAAO;AAC5C,MAAI,SAAS,QAAQ;AACnB,cAAW,EAAE;AACb,QAAK,IAAI,YAAY,OACnB,WAAU,aAAa,SAAS,YAAY,OAAO;QAChD,YAAW;AAClB,WAAS,SAAS;AAClB,SAAO;GACL,UAAU;GACJ;GACD;GACL,KAAK,KAA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,UAAU,QAAQ,MAAM;AAEhC,KAAI,CAAC,MAAO,QAAO,iBAAA,GAAA,mBAAA,KAAA,mBAAA,UAAA,EAAA,UAAG,UAAY,CAAA;AAClC,QAAO,iBAAA,GAAA,mBAAA,KAAA,mBAAA,UAAA,EAAG,UAAY,CAAA"}
1
+ {"version":3,"file":"react.js","names":[],"sources":["../src/react/context.ts","../src/react/I18nProvider.tsx","../src/react/useI18n.ts","../src/react/DevToolbar.tsx","../src/react/I18nBoundary.tsx"],"sourcesContent":["import { createContext } from 'react';\nimport type { I18nInstance } from '../core/types';\n\n/**\n * Context value passed from I18nProvider to consumers.\n * Includes the i18n instance and a version counter that increments\n * whenever the store is updated (dictionaries loaded, locale changed).\n * The version forces useMemo in useI18n to re-create the t function.\n */\nexport interface I18nContextValue {\n instance: I18nInstance;\n version: number;\n}\n\n/**\n * React context for the i18n instance.\n *\n * Provided by `I18nProvider`, consumed by `useI18n`.\n * The default value is `null` — using `useI18n` outside of a provider\n * will throw a descriptive error.\n */\nexport const I18nContext = createContext<I18nContextValue | null>(null);\n","import { useEffect, useState, useMemo, type ReactNode } from 'react';\nimport { I18nContext } from './context';\nimport { setGlobalInstance } from '../core/t';\nimport type { I18nInstance, NestedTranslations } from '../core/types';\n\n/**\n * Props for the {@link I18nProvider} component.\n */\ninterface I18nProviderProps {\n /** The i18n instance returned by `createI18n()`. */\n instance: I18nInstance;\n /** Child components that will have access to translations. */\n children: ReactNode;\n /**\n * Pre-loaded translations from SSR. When provided, the provider adds these\n * resources to the store immediately and skips dictionary fetching.\n * Format: Record<namespace, NestedTranslations>\n * Example: { shared: { ok: 'OK' }, global: { appName: 'Store' } }\n */\n serverResources?: Record<string, NestedTranslations>;\n}\n\n/**\n * React context provider for translations.\n *\n * On mount, it sets the global i18n instance and loads all dictionary\n * bundles (one HTTP request per named dictionary, in declaration order).\n * Re-renders children when dictionaries finish loading and when the\n * locale changes.\n *\n * @example\n * ```tsx\n * import { createI18n } from 'vite-bundled-i18n';\n * import { I18nProvider } from 'vite-bundled-i18n/react';\n *\n * const i18n = createI18n({ ... });\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * </I18nProvider>\n * );\n * }\n * ```\n */\ninterface WindowWithI18n extends Window {\n __I18N_RESOURCES__?: {\n locale: string;\n resources: Record<string, NestedTranslations>;\n };\n}\n\nexport function I18nProvider({ instance, children, serverResources }: I18nProviderProps) {\n const [hydrated] = useState(() => {\n if (serverResources) {\n return true;\n }\n if (typeof window !== 'undefined' && (window as WindowWithI18n).__I18N_RESOURCES__) {\n return true;\n }\n return false;\n });\n\n const [version, setVersion] = useState(() => {\n if (serverResources) {\n const locale = instance.getLocale();\n for (const [namespace, data] of Object.entries(serverResources)) {\n instance.addResources(locale, namespace, data);\n }\n return 1;\n }\n\n // Auto-hydrate from server-injected global\n const win = typeof window !== 'undefined' ? (window as WindowWithI18n) : undefined;\n if (win?.__I18N_RESOURCES__) {\n const serverData = win.__I18N_RESOURCES__;\n for (const [namespace, data] of Object.entries(serverData.resources)) {\n instance.addResources(serverData.locale, namespace, data);\n }\n delete win.__I18N_RESOURCES__;\n return 1;\n }\n\n return 0;\n });\n\n useEffect(() => {\n setGlobalInstance(instance);\n\n const unsub = instance.onLocaleChange(() => {\n setVersion((v) => v + 1);\n });\n\n if (!hydrated) {\n const hasDicts = instance.getDictionaryNames().length > 0;\n if (hasDicts) {\n instance.loadAllDictionaries(instance.getLocale()).then(() => {\n setVersion((v) => v + 1);\n });\n }\n }\n\n return unsub;\n }, [instance, hydrated]);\n\n const contextValue = useMemo(\n () => ({ instance, version }),\n [instance, version],\n );\n\n return (\n <I18nContext.Provider value={contextValue}>\n {children}\n </I18nContext.Provider>\n );\n}\n","import { useContext, useEffect, useState, useMemo } from 'react';\nimport { I18nContext } from './context';\nimport { createTranslations } from '../core/getTranslations';\nimport type { UseI18nResult, ValidScope } from '../core/types';\n\n/**\n * React hook for accessing translations.\n *\n * Can be called with or without a scope:\n *\n * **Without scope** — accesses only dictionary translations (shared, global, etc.).\n * Use this in layout components, navigation, footers, and other app-wide UI.\n *\n * **With scope** — triggers loading of the scope bundle (one HTTP request for all\n * namespaces that page needs). Use this in route/page components.\n *\n * Keys are always fully qualified (e.g., `'products.show.title'`), regardless of scope.\n *\n * @param scope - Optional bundle identifier (e.g., `'products.show'`).\n * Triggers loading of the scope bundle via `/__i18n/{locale}/{scope}.json`.\n * @returns An object with `t` (translation function), `ready` (loading state),\n * and `locale` (current locale code)\n * @throws If called outside of an `I18nProvider`\n *\n * @example\n * ```tsx\n * // Dictionary-only access\n * const { t, ready } = useI18n();\n * t('shared.ok', 'OK');\n *\n * // Bundle + dictionary access\n * const { t, ready } = useI18n('products.show');\n * t('products.show.title', 'Product Details');\n * t('shared.ok', 'OK'); // dictionaries still work\n * ```\n */\nexport function useI18n(scope?: ValidScope): UseI18nResult {\n const ctx = useContext(I18nContext);\n\n if (!ctx) {\n throw new Error(\n 'vite-bundled-i18n: useI18n() must be used within an <I18nProvider>. ' +\n 'Wrap your app with <I18nProvider instance={...}>.',\n );\n }\n\n const { instance, version } = ctx;\n const locale = instance.getLocale();\n const [scopeReady, setScopeReady] = useState(() => {\n if (!scope) return true;\n return instance.isScopeLoaded(locale, scope);\n });\n const [loadedScopeKey, setLoadedScopeKey] = useState<string | null>(null);\n\n // Load scope bundle if needed — one HTTP request per scope\n const scopeKey = scope ? `${locale}:${scope}` : null;\n useEffect(() => {\n if (!scopeKey || !scope) return;\n if (scopeKey === loadedScopeKey) return;\n\n let cancelled = false;\n instance.loadScope(locale, scope).then(() => {\n if (!cancelled) {\n setLoadedScopeKey(scopeKey);\n setScopeReady(true);\n }\n });\n\n return () => { cancelled = true; };\n }, [scopeKey, scope, locale, instance, loadedScopeKey]);\n\n // Re-create the translator object whenever locale or loaded resources change.\n const translations = useMemo(\n () => createTranslations(instance, locale),\n // version is not read directly here, but it must participate so the\n // translator object is recreated after dictionary/scope loads.\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [instance, locale, version],\n );\n\n return {\n t: translations.t,\n get: translations.get,\n has: translations.has,\n exists: translations.exists,\n tryGet: translations.tryGet,\n require: translations.require,\n translations,\n ready: scopeReady,\n locale,\n };\n}\n","import { useContext, useState } from 'react';\nimport { I18nContext } from './context';\nimport type { KeyUsageEntry } from '../core/types';\n\nconst RESOLUTION_COLORS: Record<KeyUsageEntry['resolvedFrom'], string> = {\n primary: '#4ade80',\n 'fallback-locale': '#facc15',\n 'fallback-string': '#fb923c',\n 'key-as-value': '#f87171',\n};\n\nconst RESOLUTION_LABELS: Record<KeyUsageEntry['resolvedFrom'], string> = {\n primary: 'Primary',\n 'fallback-locale': 'Fallback Locale',\n 'fallback-string': 'Fallback String',\n 'key-as-value': 'Key as Value',\n};\n\n/**\n * Dev-only toolbar overlay that displays translation diagnostics\n * for the current page. Reads key usage data from the i18n instance\n * via {@link I18nContext}.\n *\n * Renders nothing in production or when used outside an `I18nProvider`.\n *\n * @example\n * ```tsx\n * import { DevToolbar } from 'vite-bundled-i18n/react';\n *\n * function App() {\n * return (\n * <I18nProvider instance={i18n}>\n * <Router />\n * <DevToolbar />\n * </I18nProvider>\n * );\n * }\n * ```\n */\nexport function DevToolbar() {\n // Skip in production — always render in test (import.meta.env may not exist)\n const isDev =\n typeof import.meta !== 'undefined' && import.meta.env\n ? import.meta.env.DEV\n : true;\n\n const ctx = useContext(I18nContext);\n\n const [open, setOpen] = useState(false);\n\n if (!isDev) return null;\n if (!ctx) return null;\n\n const { instance } = ctx;\n const usage = instance.getKeyUsage();\n const locale = instance.getLocale();\n\n // Deduplicate keys for display — keep the first occurrence\n const uniqueKeys = new Map<string, KeyUsageEntry>();\n for (const entry of usage) {\n if (!uniqueKeys.has(entry.key)) {\n uniqueKeys.set(entry.key, entry);\n }\n }\n\n const groups: Array<{ type: KeyUsageEntry['resolvedFrom']; entries: KeyUsageEntry[] }> = [\n { type: 'primary', entries: [] },\n { type: 'fallback-locale', entries: [] },\n { type: 'fallback-string', entries: [] },\n { type: 'key-as-value', entries: [] },\n ];\n\n for (const entry of uniqueKeys.values()) {\n const group = groups.find((g) => g.type === entry.resolvedFrom);\n if (group) group.entries.push(entry);\n }\n\n const primaryCount = groups[0].entries.length;\n const fallbackCount =\n groups[1].entries.length + groups[2].entries.length;\n const missingCount = groups[3].entries.length;\n const totalKeys = uniqueKeys.size;\n\n return (\n <>\n {/* Toggle button */}\n <button\n data-testid=\"i18n-toolbar-toggle\"\n onClick={() => setOpen((v) => !v)}\n style={{\n position: 'fixed',\n bottom: 16,\n right: 16,\n zIndex: 99999,\n width: 44,\n height: 44,\n borderRadius: 22,\n border: 'none',\n background: missingCount > 0 ? '#dc2626' : '#2563eb',\n color: '#fff',\n fontSize: 14,\n fontWeight: 700,\n cursor: 'pointer',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'center',\n boxShadow: '0 2px 8px rgba(0,0,0,0.3)',\n fontFamily: 'system-ui, sans-serif',\n }}\n aria-label={open ? 'Close i18n toolbar' : 'Open i18n toolbar'}\n >\n {totalKeys}\n </button>\n\n {/* Panel */}\n {open && (\n <div\n data-testid=\"i18n-toolbar-panel\"\n style={{\n position: 'fixed',\n bottom: 68,\n right: 16,\n zIndex: 99999,\n width: 380,\n maxHeight: 480,\n background: 'rgba(0, 0, 0, 0.92)',\n color: '#f1f5f9',\n borderRadius: 10,\n boxShadow: '0 4px 24px rgba(0,0,0,0.4)',\n fontFamily: 'system-ui, sans-serif',\n fontSize: 13,\n overflow: 'hidden',\n display: 'flex',\n flexDirection: 'column',\n }}\n >\n {/* Header */}\n <div\n style={{\n padding: '12px 16px',\n borderBottom: '1px solid rgba(255,255,255,0.1)',\n display: 'flex',\n alignItems: 'center',\n justifyContent: 'space-between',\n }}\n >\n <span style={{ fontWeight: 600, fontSize: 14 }}>i18n DevToolbar</span>\n <span\n style={{\n background: '#2563eb',\n color: '#fff',\n padding: '2px 10px',\n borderRadius: 12,\n fontSize: 12,\n fontWeight: 600,\n }}\n >\n {locale}\n </span>\n </div>\n\n {/* Summary */}\n <div\n style={{\n padding: '10px 16px',\n borderBottom: '1px solid rgba(255,255,255,0.1)',\n display: 'flex',\n gap: 16,\n flexWrap: 'wrap',\n fontSize: 12,\n }}\n >\n <span>\n Total: <strong>{totalKeys}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS.primary }}>\n Primary: <strong>{primaryCount}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS['fallback-locale'] }}>\n Fallback: <strong>{fallbackCount}</strong>\n </span>\n <span style={{ color: RESOLUTION_COLORS['key-as-value'] }}>\n Missing: <strong>{missingCount}</strong>\n </span>\n </div>\n\n {/* Key list */}\n <div style={{ overflowY: 'auto', flex: 1, padding: '8px 0' }}>\n {groups.map(\n (group) =>\n group.entries.length > 0 && (\n <div key={group.type} style={{ marginBottom: 8 }}>\n <div\n style={{\n padding: '4px 16px',\n fontSize: 11,\n fontWeight: 700,\n textTransform: 'uppercase',\n letterSpacing: '0.05em',\n color: RESOLUTION_COLORS[group.type],\n }}\n >\n {RESOLUTION_LABELS[group.type]} ({group.entries.length})\n </div>\n {group.entries.map((entry) => (\n <div\n key={`${entry.key}-${entry.namespace}-${entry.scope ?? ''}`}\n style={{\n padding: '4px 16px 4px 24px',\n display: 'flex',\n alignItems: 'baseline',\n gap: 8,\n }}\n >\n <span\n style={{\n width: 6,\n height: 6,\n borderRadius: 3,\n background: RESOLUTION_COLORS[entry.resolvedFrom],\n flexShrink: 0,\n alignSelf: 'center',\n }}\n />\n <span\n style={{\n fontFamily: 'ui-monospace, monospace',\n fontSize: 12,\n wordBreak: 'break-all',\n }}\n >\n {entry.key}\n </span>\n <span\n style={{\n fontSize: 11,\n color: '#94a3b8',\n marginLeft: 'auto',\n flexShrink: 0,\n }}\n >\n {entry.namespace}\n {entry.scope ? ` / ${entry.scope}` : ''}\n </span>\n </div>\n ))}\n </div>\n ),\n )}\n {totalKeys === 0 && (\n <div style={{ padding: '16px', textAlign: 'center', color: '#64748b' }}>\n No keys used yet\n </div>\n )}\n </div>\n </div>\n )}\n </>\n );\n}\n","import { type ReactNode } from 'react';\nimport { useI18n } from './useI18n';\n\nexport interface I18nBoundaryProps {\n /** Scope to load (e.g., 'products.index') */\n scope: string;\n /** Rendered while translations are loading */\n fallback?: ReactNode;\n /** Rendered once translations are ready */\n children: ReactNode;\n}\n\n/**\n * Boundary component that handles translation loading.\n * Children only render once the scope is ready, avoiding\n * rules-of-hooks violations from early returns in child components.\n *\n * @example\n * ```tsx\n * <I18nBoundary scope=\"products.index\" fallback={<Spinner />}>\n * <ProductsPage />\n * </I18nBoundary>\n * ```\n */\nexport function I18nBoundary({ scope, fallback = null, children }: I18nBoundaryProps) {\n const { ready } = useI18n(scope);\n\n if (!ready) return <>{fallback}</>;\n return <>{children}</>;\n}\n"],"mappings":";;;;;;;;;;;;AAqBA,IAAa,cAAc,cAAuC,KAAK;;;ACgCvE,SAAgB,aAAa,EAAE,UAAU,UAAU,mBAAsC;CACvF,MAAM,CAAC,YAAY,eAAe;AAChC,MAAI,gBACF,QAAO;AAET,MAAI,OAAO,WAAW,eAAgB,OAA0B,mBAC9D,QAAO;AAET,SAAO;GACP;CAEF,MAAM,CAAC,SAAS,cAAc,eAAe;AAC3C,MAAI,iBAAiB;GACnB,MAAM,SAAS,SAAS,WAAW;AACnC,QAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,gBAAgB,CAC7D,UAAS,aAAa,QAAQ,WAAW,KAAK;AAEhD,UAAO;;EAIT,MAAM,MAAM,OAAO,WAAW,cAAe,SAA4B,KAAA;AACzE,MAAI,KAAK,oBAAoB;GAC3B,MAAM,aAAa,IAAI;AACvB,QAAK,MAAM,CAAC,WAAW,SAAS,OAAO,QAAQ,WAAW,UAAU,CAClE,UAAS,aAAa,WAAW,QAAQ,WAAW,KAAK;AAE3D,UAAO,IAAI;AACX,UAAO;;AAGT,SAAO;GACP;AAEF,iBAAgB;AACd,oBAAkB,SAAS;EAE3B,MAAM,QAAQ,SAAS,qBAAqB;AAC1C,eAAY,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,WAAW;MAAU,OAAO;MAAW;eAAE;KAElE,CAAA,CAEJ;;GACF;IAEP,EAAA,CAAA;;;;;;;;;;;;;;;;ACzOP,SAAgB,aAAa,EAAE,OAAO,WAAW,MAAM,YAA+B;CACpF,MAAM,EAAE,UAAU,QAAQ,MAAM;AAEhC,KAAI,CAAC,MAAO,QAAO,oBAAA,UAAA,EAAA,UAAG,UAAY,CAAA;AAClC,QAAO,oBAAA,UAAA,EAAG,UAAY,CAAA"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "vite-bundled-i18n",
3
3
  "private": false,
4
- "version": "0.2.13",
4
+ "version": "0.2.14",
5
5
  "description": "Route-aware i18n for Vite apps with typed keys, scope bundles, dictionary ownership, and compiled production output.",
6
6
  "type": "module",
7
7
  "types": "./dist/index.d.ts",
@@ -68,6 +68,9 @@
68
68
  "./plugin": {
69
69
  "types": "./dist/plugin.d.ts",
70
70
  "default": "./dist/plugin.js"
71
+ },
72
+ "./generated": {
73
+ "types": "./dist/core/i18n-generated.d.ts"
71
74
  }
72
75
  },
73
76
  "scripts": {