vite-bundled-i18n 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -515,6 +515,116 @@ cache: {
515
515
  }
516
516
  ```
517
517
 
518
+ ### Build artifacts and the build-stamp
519
+
520
+ Every successful build writes `.i18n/build-stamp.json` recording the plugin version, config hash, and an analysis fingerprint (route ids → scopes + sorted extracted keys). The next build reads this stamp and warns when:
521
+
522
+ - the extraction cache exists but no stamp does (a previous build never finished),
523
+ - the plugin version recorded in the stamp differs from the current version,
524
+ - the extraction-relevant config has changed since the stamp was written, or
525
+ - the extraction cache file is materially newer than the stamp (dev-mode edits have advanced the cache without a corresponding production build).
526
+
527
+ The warning is one line, surfaced through Vite's logger, and never blocks the build. It exists so a stale `.i18n/` is loud rather than silent.
528
+
529
+ ### Troubleshooting: "a key is missing from a per-scope bundle"
530
+
531
+ After large refactors (mass `t.dynamic` migrations, sweeping renames, hook restructures), the per-file extraction cache and the downstream artifacts in `.i18n/` can drift if a build was interrupted partway through. The reliable recovery move:
532
+
533
+ ```bash
534
+ npx vite-bundled-i18n clean # rm -rf .i18n/
535
+ # then your build command, e.g.
536
+ npm run build
537
+ ```
538
+
539
+ …or in one step:
540
+
541
+ ```bash
542
+ npx vite-bundled-i18n rebuild --config i18n.config.json
543
+ ```
544
+
545
+ If after that the key is _still_ missing, the issue is in the source — not the cache — and the bundle output reflects the truth. File a bug.
546
+
547
+ The CLI's `clean` command accepts repeatable `--extra-path` flags for project layouts that emit assets outside `.i18n/` (e.g. `--extra-path public/__i18n --extra-path public/build/__i18n`).
548
+
549
+ ## ESLint plugin
550
+
551
+ `vite-bundled-i18n/eslint` ships five rules that catch the patterns the extractor cannot see — keys reached through aliases, props, member access, or runtime concatenation. Same package, optional peer dep on `eslint >= 8`, opt in via the subpath:
552
+
553
+ ```ts
554
+ // eslint.config.js (flat, ESLint 9+)
555
+ import i18n from 'vite-bundled-i18n/eslint';
556
+
557
+ export default [
558
+ i18n.flatConfigs.recommended, // four rules at 'warn'
559
+ ];
560
+ ```
561
+
562
+ ```js
563
+ // .eslintrc.cjs (legacy, ESLint 8)
564
+ module.exports = {
565
+ extends: ['plugin:vite-bundled-i18n/recommended'],
566
+ };
567
+ ```
568
+
569
+ The rules:
570
+
571
+ | Rule | Catches |
572
+ |------|---------|
573
+ | `no-t-dynamic` | Every `t.dynamic(...)` call — escape hatch should be the exception, not the default |
574
+ | `no-non-literal-t-arg` | `t(variable)`, `t(\`tpl\`)`, `t(cond ? a : b)` — argument must be a string literal |
575
+ | `no-renamed-t` | `const { t: translate } = useI18n()` and aliases (autofixes the destructure) |
576
+ | `no-member-access-t` | `props.t(...)`, `this.i18n.t(...)`, any `<expr>.t()` — extractor only sees bare `t` |
577
+ | `t-arg-must-exist-in-types` | `t('typo.in.namespace')` — verifies the literal against your locale JSON files |
578
+
579
+ The `recommended` preset turns the first four to `warn`. The `strict` preset turns every rule to `error` AND enables `t-arg-must-exist-in-types` (with `localesDir: 'locales'`, `defaultLocale: 'en'` defaults — override per-rule if your layout differs):
580
+
581
+ ```ts
582
+ import i18n from 'vite-bundled-i18n/eslint';
583
+ export default [
584
+ i18n.flatConfigs.strict,
585
+ // Override the locale paths if needed:
586
+ {
587
+ rules: {
588
+ 'vite-bundled-i18n/t-arg-must-exist-in-types': ['error', {
589
+ localesDir: 'i18n',
590
+ defaultLocale: 'en-US',
591
+ }],
592
+ },
593
+ },
594
+ ];
595
+ ```
596
+
597
+ > **Parser config.** The presets carry only `plugins` and `rules` — they don't set `languageOptions`. Pair them with your existing parser config (e.g. `@typescript-eslint/parser` for TS/TSX) the same way you would for any other ESLint plugin. The presets stay parser-agnostic so they don't force an extra peer dep on consumers who already wire up their own parser.
598
+
599
+ ## Strict extraction
600
+
601
+ `bundling.strictExtraction` (v0.7+) gates the build on extraction-correctness checks. Pair it with the ESLint plugin: the lint rules block the patterns at edit time; `strictExtraction` is the CI safety net for what slipped through.
602
+
603
+ ```ts
604
+ defineI18nConfig({
605
+ bundling: {
606
+ // Shorthand: every check at the same level.
607
+ strictExtraction: 'warn',
608
+
609
+ // OR: object form for per-check control.
610
+ strictExtraction: {
611
+ mode: 'warn',
612
+ scopeRegistration: 'error', // page registers no useI18n('<scope>')
613
+ missingKeys: 'error', // t('foo.bar') references a missing locale key
614
+ unusedKeys: 'off', // locale key never referenced (noise on bootstrap)
615
+ orphanDynamic: 'warn', // dynamicKeys entry matches no route or dictionary
616
+ // reportPath: '.i18n/strict-extraction-report.json' (default)
617
+ },
618
+ },
619
+ })
620
+ ```
621
+
622
+ Every build writes a structured JSON report at `<generatedOutDir>/strict-extraction-report.json` regardless of severity — CI tooling can parse `findings[]` without scraping logs. Each finding records `check`, `severity`, `message`, and a free-form `details` payload (file paths, key names, etc.).
623
+
624
+ The legacy `bundling.strictScopeRegistration` field is honored as a fallback when `strictExtraction` is not set, so existing configs keep working without changes.
625
+
626
+ > **Build-time only.** `strictExtraction` runs during `vite build` and the CLI's `vite-bundled-i18n build` (and friends). `vite dev` does not run it — to keep dev startup fast and HMR latency low, no on-edit re-audit fires. Pair `strictExtraction` with the ESLint plugin to get most of the same coverage at edit time.
627
+
518
628
  ## Testing
519
629
 
520
630
  Unit tests and integration tests import from `vite-bundled-i18n/testing`. `createTestI18n` returns a synchronous instance seeded with translations you supply — no network, no pending promises, gate starts ready:
@@ -563,6 +673,7 @@ app.use(createI18nTestPlugin(i18n))
563
673
  | `vite-bundled-i18n/plugin` | Vite plugin (`i18nPlugin`) |
564
674
  | `vite-bundled-i18n/generated` | Generated types + `PAGE_SCOPE_MAP` / `I18nPageIdentifier` |
565
675
  | `vite-bundled-i18n/testing` | `createTestI18n`, `I18nTestProvider`, `createI18nTestPlugin` |
676
+ | `vite-bundled-i18n/eslint` | ESLint plugin + `recommended` / `strict` presets (5 rules) |
566
677
 
567
678
  ## Documentation
568
679
 
@@ -572,7 +683,13 @@ app.use(createI18nTestPlugin(i18n))
572
683
 
573
684
  ## Releases
574
685
 
575
- Current release: **v0.6.1** — lean dev bundles (dev responses tree-shaken by default, ~95% smaller on large apps). Built on v0.6.0's framework-agnostic readiness gate (`i18n.gate`, `<GateBoundary>`, `useGate()`), runtime `createScopeMapClient()`, `t.dynamic()` escape hatch, `bundling.dynamicKeys` + `strictScopeRegistration`, `vite-bundled-i18n/testing` subpackage. Breaking in v0.6.0: `loadScope` auto-registers with the gate by default — opt out via `{ trackReadiness: false }`.
686
+ Current release: **v0.7.0** — three loosely-related shipments:
687
+
688
+ - **Build-stamp + staleness detection.** Every successful build writes `.i18n/build-stamp.json` recording the cache mtime it observed; the next build compares against that anchor (not against the stamp file's own mtime, so multi-minute builds and dev sessions no longer look stale). Cache schema bumped v1 → v2 (one-time auto-invalidation on upgrade). New CLI commands `clean` and `rebuild` formalize the recovery path; `--extra-path` is constrained to paths inside `rootDir` unless `--allow-outside-root` is set.
689
+ - **ESLint plugin.** `vite-bundled-i18n/eslint` ships 5 rules (`no-t-dynamic`, `no-non-literal-t-arg`, `no-renamed-t`, `no-member-access-t`, `t-arg-must-exist-in-types`) with both `recommended` (warn) and `strict` (error + `t-arg-must-exist-in-types` enabled) presets. Both flat-config (ESLint 9+) and legacy (ESLint 8) shapes. Bracket-access variants (`t['dynamic']`, `props['t']`) are covered alongside dot access.
690
+ - **`bundling.strictExtraction`.** Unified extraction-correctness audit. Subsumes the legacy `strictScopeRegistration` (still honored as a fallback). Adds `missingKeys` / `unusedKeys` / `orphanDynamic` checks. Always writes a structured JSON report at `<generatedOutDir>/strict-extraction-report.json` for CI consumption. Build-time only — pair with the ESLint plugin for edit-time coverage.
691
+
692
+ Built on v0.6.2's dev/prod parity for scope-bundle filtering, v0.6.1's lean dev bundles, and v0.6.0's framework-agnostic readiness gate.
576
693
 
577
694
  Version history lives in the [git log](https://github.com/nicolasvlachos/vite-bundled-i18n/commits/main) — each release is a `feat: v{version}` commit with a summary of the changes.
578
695
 
@@ -1294,7 +1294,8 @@ function walkRoute(entryPoint, options) {
1294
1294
  const result = extractKeys(source, {
1295
1295
  scope: options.extractionScope,
1296
1296
  filePath: resolved,
1297
- hookSources: options.hookSources
1297
+ hookSources: options.hookSources,
1298
+ keyFields: options.keyFields
1298
1299
  });
1299
1300
  if (isEntry) {
1300
1301
  entryVisited = true;
@@ -1338,6 +1339,7 @@ function walkAll(options) {
1338
1339
  rootDir,
1339
1340
  extractionScope,
1340
1341
  hookSources: options.hookSources,
1342
+ keyFields: options.keyFields,
1341
1343
  cache: options.cache
1342
1344
  }));
1343
1345
  const availableNamespaces = discoverNamespaces(path.isAbsolute(options.localesDir) ? options.localesDir : path.join(rootDir, options.localesDir), options.defaultLocale);
@@ -1366,8 +1368,8 @@ function walkAll(options) {
1366
1368
  sharedNamespaces
1367
1369
  };
1368
1370
  }
1369
- /** Relative filename inside the configured cache directory. */
1370
- var CACHE_FILE_NAME = "extraction-v1.json";
1371
+ /** Relative filename inside the configured cache directory. Encodes the schema version so a v2 build never accidentally loads a v1 file. */
1372
+ var CACHE_FILE_NAME = "extraction-v2.json";
1371
1373
  /**
1372
1374
  * Create a cache instance, eagerly loading from disk if a valid snapshot
1373
1375
  * exists at `{dir}/{CACHE_FILE_NAME}`. A missing, unreadable, or
@@ -1383,9 +1385,27 @@ function createExtractionCache(options) {
1383
1385
  nodeVersion,
1384
1386
  debug: options.debug
1385
1387
  });
1386
- function debugLog(message) {
1387
- if (options.debug) console.warn(`[i18n-cache] ${message}`);
1388
+ /**
1389
+ * Structured-format debug logger. Every line carries the PID and an
1390
+ * ISO-8601 timestamp so a future investigation can correlate cache
1391
+ * activity across processes (e.g. `vite dev` running while
1392
+ * `npm run build` fires) without guessing.
1393
+ *
1394
+ * Enabled by `VITE_I18N_CACHE_DEBUG=1` (resolved upstream into
1395
+ * `options.debug`). Off by default — production builds are silent.
1396
+ */
1397
+ function debugLog(action, detail = {}) {
1398
+ if (!options.debug) return;
1399
+ const stamp = (/* @__PURE__ */ new Date()).toISOString();
1400
+ const fields = Object.entries(detail).map(([k, v]) => `${k}=${typeof v === "string" ? v : JSON.stringify(v)}`).join(" ");
1401
+ console.warn(`[i18n-cache pid=${process.pid} ${stamp}] ${action}${fields ? " " + fields : ""}`);
1388
1402
  }
1403
+ debugLog("init", {
1404
+ file: filePath,
1405
+ loadedEntries: entries.size,
1406
+ pluginVersion: options.pluginVersion,
1407
+ configHash: options.configHash.slice(0, 12)
1408
+ });
1389
1409
  return {
1390
1410
  get(filePath) {
1391
1411
  return entries.get(filePath);
@@ -1395,16 +1415,19 @@ function createExtractionCache(options) {
1395
1415
  },
1396
1416
  invalidate(filePath) {
1397
1417
  entries.delete(filePath);
1418
+ debugLog("invalidate", { file: filePath });
1398
1419
  },
1399
1420
  clear() {
1421
+ const before = entries.size;
1400
1422
  entries.clear();
1423
+ debugLog("clear", { droppedEntries: before });
1401
1424
  },
1402
1425
  size() {
1403
1426
  return entries.size;
1404
1427
  },
1405
1428
  persistToDisk() {
1406
1429
  const payload = {
1407
- schemaVersion: 1,
1430
+ schemaVersion: 2,
1408
1431
  pluginVersion: options.pluginVersion,
1409
1432
  configHash: options.configHash,
1410
1433
  nodeVersion,
@@ -1414,16 +1437,31 @@ function createExtractionCache(options) {
1414
1437
  try {
1415
1438
  fs.mkdirSync(options.dir, { recursive: true });
1416
1439
  } catch (error) {
1417
- debugLog(`mkdir failed at ${options.dir}: ${error.message}`);
1440
+ debugLog("persist-failed", {
1441
+ stage: "mkdir",
1442
+ dir: options.dir,
1443
+ error: error.message
1444
+ });
1418
1445
  return;
1419
1446
  }
1420
1447
  const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
1421
1448
  try {
1422
1449
  fs.writeFileSync(tmpPath, JSON.stringify(payload));
1423
1450
  fs.renameSync(tmpPath, filePath);
1424
- debugLog(`persisted ${entries.size} entries to ${filePath}`);
1451
+ let mtimeMs = null;
1452
+ try {
1453
+ mtimeMs = fs.statSync(filePath).mtimeMs;
1454
+ } catch {}
1455
+ debugLog("persist", {
1456
+ file: filePath,
1457
+ entries: entries.size,
1458
+ mtimeMs
1459
+ });
1425
1460
  } catch (error) {
1426
- debugLog(`write failed: ${error.message}`);
1461
+ debugLog("persist-failed", {
1462
+ stage: "write",
1463
+ error: error.message
1464
+ });
1427
1465
  try {
1428
1466
  fs.rmSync(tmpPath, { force: true });
1429
1467
  } catch {}
@@ -1449,15 +1487,19 @@ function loadEntriesOrEmpty(filePath, context) {
1449
1487
  try {
1450
1488
  parsed = JSON.parse(raw);
1451
1489
  } catch {
1452
- if (context.debug) console.warn(`[i18n-cache] corrupt cache file at ${filePath}; starting empty`);
1490
+ if (context.debug) console.warn(`[i18n-cache pid=${process.pid} ${(/* @__PURE__ */ new Date()).toISOString()}] load-rejected reason=corrupt-json file=${filePath}`);
1453
1491
  return empty;
1454
1492
  }
1455
- if (!parsed || typeof parsed !== "object") return empty;
1456
- if (parsed.schemaVersion !== 1) return empty;
1457
- if (parsed.pluginVersion !== context.pluginVersion) return empty;
1458
- if (parsed.configHash !== context.configHash) return empty;
1459
- if (!isCompatibleNodeVersion(parsed.nodeVersion, context.nodeVersion)) return empty;
1460
- if (!parsed.files || typeof parsed.files !== "object") return empty;
1493
+ function reject(reason) {
1494
+ if (context.debug) console.warn(`[i18n-cache pid=${process.pid} ${(/* @__PURE__ */ new Date()).toISOString()}] load-rejected reason=${reason} file=${filePath}`);
1495
+ return empty;
1496
+ }
1497
+ if (!parsed || typeof parsed !== "object") return reject("not-object");
1498
+ if (parsed.schemaVersion !== 2) return reject(`schema-version-mismatch (got=${String(parsed.schemaVersion)} want=2)`);
1499
+ if (parsed.pluginVersion !== context.pluginVersion) return reject(`plugin-version-mismatch (got=${String(parsed.pluginVersion)} want=${context.pluginVersion})`);
1500
+ if (parsed.configHash !== context.configHash) return reject("config-hash-mismatch");
1501
+ if (!isCompatibleNodeVersion(parsed.nodeVersion, context.nodeVersion)) return reject(`node-version-mismatch (got=${String(parsed.nodeVersion)} want=${context.nodeVersion})`);
1502
+ if (!parsed.files || typeof parsed.files !== "object") return reject("no-files");
1461
1503
  const map = /* @__PURE__ */ new Map();
1462
1504
  for (const [key, value] of Object.entries(parsed.files)) if (value && typeof value === "object") map.set(key, value);
1463
1505
  return map;
@@ -1546,7 +1588,7 @@ function resolveCacheConfig(input, context) {
1546
1588
  * back to a development placeholder during tests and direct imports before
1547
1589
  * the build step runs.
1548
1590
  */
1549
- var PLUGIN_VERSION = "0.6.2";
1591
+ var PLUGIN_VERSION = "0.7.0";
1550
1592
  //#endregion
1551
1593
  //#region src/extractor/scope-map.ts
1552
1594
  var COMPOSITE_PAGE_SUFFIXES = [
@@ -1920,6 +1962,311 @@ function formatMessage(violation) {
1920
1962
  ].join("\n");
1921
1963
  }
1922
1964
  //#endregion
1923
- export { inferScopeNamespace as C, resolveDictionaryOwnership as E, buildScopePlans as S, normalizeDictionaries as T, writeRuntimeConst as _, PLUGIN_VERSION as a, generateBundles as b, createExtractionCache as c, extractKeys as d, flattenLocaleKeys as f, runtimePathFromTypesPath as g, generateTypes as h, buildScopeMap as i, resolveImport as l, generateReports as m, compileAll as n, resolveCacheConfig as o, generateDictionaryOwnershipReport as p, applyDynamicKeys as r, computeConfigHash as s, checkScopeRegistration as t, walkAll as u, writeTypes as v, keyMatchesPattern as w, pruneNamespace as x, flattenKeys as y };
1965
+ //#region src/extractor/strict-extraction.ts
1966
+ /**
1967
+ * Resolve the user's config (any of: undefined, shorthand string, full
1968
+ * object) into a uniform `ResolvedStrictExtractionChecks` plus a
1969
+ * `reportPath`. Honors backward-compat with `strictScopeRegistration`.
1970
+ *
1971
+ * Subtle rule: `orphanDynamic` defaults to `'warn'` when the user
1972
+ * didn't explicitly opt out. Pre-v0.7 `applyDynamicKeys` always
1973
+ * emitted these warnings; making the unified shorthand `'off'`
1974
+ * silently kill them would be a surprising regression. Operators who
1975
+ * truly want silence pass `{ orphanDynamic: 'off' }` explicitly.
1976
+ */
1977
+ function resolveStrictExtractionConfig(config, fallbacks) {
1978
+ let mode;
1979
+ let perCheck = {};
1980
+ let reportPath = fallbacks.defaultReportPath;
1981
+ if (typeof config === "string") mode = config;
1982
+ else if (config && typeof config === "object") {
1983
+ mode = config.mode ?? "warn";
1984
+ perCheck = config;
1985
+ if (config.reportPath) reportPath = config.reportPath;
1986
+ } else return {
1987
+ checks: {
1988
+ scopeRegistration: fallbacks.legacyStrictScopeRegistration ?? "warn",
1989
+ missingKeys: "off",
1990
+ unusedKeys: "off",
1991
+ orphanDynamic: "warn"
1992
+ },
1993
+ reportPath
1994
+ };
1995
+ const orphanDefault = mode === "off" ? "warn" : mode;
1996
+ return {
1997
+ checks: {
1998
+ scopeRegistration: perCheck.scopeRegistration ?? mode,
1999
+ missingKeys: perCheck.missingKeys ?? mode,
2000
+ unusedKeys: perCheck.unusedKeys ?? mode,
2001
+ orphanDynamic: perCheck.orphanDynamic ?? orphanDefault
2002
+ },
2003
+ reportPath
2004
+ };
2005
+ }
2006
+ function pushScopeRegistrationFindings(violations, severity, out) {
2007
+ for (const v of violations) out.push({
2008
+ check: "scopeRegistration",
2009
+ severity,
2010
+ message: `${v.relativePath} registers no scope (no useI18n('<scope>') in entry or imports).`,
2011
+ details: {
2012
+ entryPoint: v.entryPoint,
2013
+ relativePath: v.relativePath
2014
+ }
2015
+ });
2016
+ }
2017
+ function pushMissingKeyFindings(analysis, available, defaultLocale, severity, out) {
2018
+ const missing = generateMissing(analysis, available);
2019
+ for (const entry of missing.keys) out.push({
2020
+ check: "missingKeys",
2021
+ severity,
2022
+ message: `Translation key "${entry.key}" used in code but absent from ${defaultLocale} locale files.`,
2023
+ details: {
2024
+ key: entry.key,
2025
+ line: entry.line,
2026
+ files: entry.usedIn
2027
+ }
2028
+ });
2029
+ }
2030
+ function pushUnusedKeyFindings(analysis, available, severity, out) {
2031
+ const unused = generateUnused(analysis, available);
2032
+ for (const entry of unused.keys) out.push({
2033
+ check: "unusedKeys",
2034
+ severity,
2035
+ message: `Locale key "${entry.key}" is defined but never referenced by any route.`,
2036
+ details: {
2037
+ key: entry.key,
2038
+ namespace: entry.namespace
2039
+ }
2040
+ });
2041
+ }
2042
+ function pushOrphanDynamicFindings(analysis, dynamicKeys, dictionaries, severity, out) {
2043
+ if (!dynamicKeys || dynamicKeys.length === 0) return;
2044
+ const routeNamespaces = /* @__PURE__ */ new Set();
2045
+ for (const route of analysis.routes) for (const scope of route.scopes) {
2046
+ const ns = scope.split(".")[0];
2047
+ if (ns) routeNamespaces.add(ns);
2048
+ }
2049
+ const ownership = resolveDictionaryOwnership(new Set(dynamicKeys), dictionaries);
2050
+ for (const key of dynamicKeys) {
2051
+ const ns = key.split(".")[0];
2052
+ if (!ns) continue;
2053
+ if (routeNamespaces.has(ns)) continue;
2054
+ if (ownership.keyOwner.has(key)) continue;
2055
+ let inDict = false;
2056
+ for (const rule of ownership.rules) if (rule.include.some((pat) => keyMatchesPattern(key, pat))) {
2057
+ inDict = true;
2058
+ break;
2059
+ }
2060
+ if (inDict) continue;
2061
+ out.push({
2062
+ check: "orphanDynamic",
2063
+ severity,
2064
+ message: `dynamicKeys entry "${key}" matches no route and no dictionary — it won't ship anywhere.`,
2065
+ details: {
2066
+ key,
2067
+ namespace: ns
2068
+ }
2069
+ });
2070
+ }
2071
+ }
2072
+ /**
2073
+ * Run every enabled check and return the aggregated report. Pure — no
2074
+ * disk side effects (call {@link writeStrictExtractionReport} for that).
2075
+ */
2076
+ function runStrictExtraction(input) {
2077
+ const { checks } = resolveStrictExtractionConfig(input.config, {
2078
+ legacyStrictScopeRegistration: input.legacyStrictScopeRegistration,
2079
+ defaultReportPath: input.defaultReportPath
2080
+ });
2081
+ const findings = [];
2082
+ if (checks.scopeRegistration !== "off") pushScopeRegistrationFindings(checkScopeRegistration(input.analysis, {
2083
+ rootDir: input.rootDir,
2084
+ mode: checks.scopeRegistration
2085
+ }).violations, checks.scopeRegistration, findings);
2086
+ const available = checks.missingKeys !== "off" || checks.unusedKeys !== "off" ? flattenLocaleKeys(input.localesDir, input.defaultLocale) : null;
2087
+ if (checks.missingKeys !== "off" && available) pushMissingKeyFindings(input.analysis, available, input.defaultLocale, checks.missingKeys, findings);
2088
+ if (checks.unusedKeys !== "off" && available) pushUnusedKeyFindings(input.analysis, available, checks.unusedKeys, findings);
2089
+ if (checks.orphanDynamic !== "off") pushOrphanDynamicFindings(input.analysis, input.dynamicKeys, input.dictionaries, checks.orphanDynamic, findings);
2090
+ const summary = {
2091
+ scopeRegistration: {
2092
+ warn: 0,
2093
+ error: 0
2094
+ },
2095
+ missingKeys: {
2096
+ warn: 0,
2097
+ error: 0
2098
+ },
2099
+ unusedKeys: {
2100
+ warn: 0,
2101
+ error: 0
2102
+ },
2103
+ orphanDynamic: {
2104
+ warn: 0,
2105
+ error: 0
2106
+ }
2107
+ };
2108
+ for (const f of findings) summary[f.check][f.severity]++;
2109
+ return {
2110
+ resolvedChecks: checks,
2111
+ findings,
2112
+ hasErrors: findings.some((f) => f.severity === "error"),
2113
+ summary
2114
+ };
2115
+ }
2116
+ /**
2117
+ * Persist the report to disk as a structured JSON document. CI tooling
2118
+ * can parse this without needing to scrape stdout. Atomic write —
2119
+ * temp file + rename. Failure is swallowed; the report is observability,
2120
+ * never correctness.
2121
+ */
2122
+ function writeStrictExtractionReport(reportPath, report) {
2123
+ const dir = path.dirname(reportPath);
2124
+ try {
2125
+ fs.mkdirSync(dir, { recursive: true });
2126
+ } catch {
2127
+ return;
2128
+ }
2129
+ const payload = {
2130
+ ...report,
2131
+ writtenAt: (/* @__PURE__ */ new Date()).toISOString()
2132
+ };
2133
+ const tmp = `${reportPath}.${process.pid}.${Date.now()}.tmp`;
2134
+ try {
2135
+ fs.writeFileSync(tmp, JSON.stringify(payload, null, 2));
2136
+ fs.renameSync(tmp, reportPath);
2137
+ } catch {
2138
+ try {
2139
+ fs.rmSync(tmp, { force: true });
2140
+ } catch {}
2141
+ }
2142
+ }
2143
+ /**
2144
+ * Convenience: throw if any finding has severity `'error'`. Used by the
2145
+ * build plugin to fail CI when strict mode is set to `'error'`.
2146
+ */
2147
+ function assertNoStrictExtractionErrors(report) {
2148
+ if (!report.hasErrors) return;
2149
+ const lines = report.findings.filter((f) => f.severity === "error").map((f) => ` - [${f.check}] ${f.message}`);
2150
+ throw new Error(`vite-bundled-i18n: strictExtraction failed with ${lines.length} error(s):\n\n${lines.join("\n")}\n\nSee the structured report for details.`);
2151
+ }
2152
+ /** Filename written under `generatedOutDir` (`.i18n/` by default). */
2153
+ var BUILD_STAMP_FILE_NAME = "build-stamp.json";
2154
+ /**
2155
+ * Stable hash of the analysis. Fingerprints route ids → scopes + sorted
2156
+ * extracted key names (NOT call-site metadata like line/column, which
2157
+ * shouldn't gate downstream regeneration).
2158
+ *
2159
+ * Stable across reorderings — routes, scopes, and keys are sorted before
2160
+ * hashing.
2161
+ */
2162
+ function computeAnalysisFingerprint(analysis) {
2163
+ const routes = [...analysis.routes].map((route) => ({
2164
+ id: route.routeId,
2165
+ scopes: [...route.scopes].sort(),
2166
+ keys: [...new Set(route.keys.map((k) => k.key))].sort()
2167
+ })).sort((a, b) => a.id.localeCompare(b.id));
2168
+ const sharedNs = [...analysis.sharedNamespaces].sort();
2169
+ const availableNs = [...analysis.availableNamespaces].sort();
2170
+ const payload = JSON.stringify({
2171
+ routes,
2172
+ sharedNs,
2173
+ availableNs
2174
+ });
2175
+ return crypto.createHash("sha256").update(payload).digest("hex");
2176
+ }
2177
+ /**
2178
+ * Read the stamp at `dir/build-stamp.json` if present and parseable. Returns
2179
+ * `null` for missing/corrupt files — every consumer treats those identically
2180
+ * (no point distinguishing).
2181
+ */
2182
+ function readBuildStamp(dir) {
2183
+ const filePath = path.join(dir, BUILD_STAMP_FILE_NAME);
2184
+ let raw;
2185
+ try {
2186
+ raw = fs.readFileSync(filePath, "utf-8");
2187
+ } catch {
2188
+ return null;
2189
+ }
2190
+ let parsed;
2191
+ try {
2192
+ parsed = JSON.parse(raw);
2193
+ } catch {
2194
+ return null;
2195
+ }
2196
+ if (!parsed || typeof parsed !== "object") return null;
2197
+ if (parsed.schemaVersion !== 1) return null;
2198
+ if (typeof parsed.pluginVersion !== "string") return null;
2199
+ if (typeof parsed.configHash !== "string") return null;
2200
+ if (typeof parsed.analysisFingerprint !== "string") return null;
2201
+ const cm = parsed.cacheMtimeAtStampWrite;
2202
+ if (cm !== null && typeof cm !== "number") return null;
2203
+ return parsed;
2204
+ }
2205
+ /**
2206
+ * Write the stamp atomically (`writeFileSync` to a temp path, then rename).
2207
+ * Creates the parent directory if it doesn't exist. All failures are
2208
+ * swallowed — the stamp is observability, not correctness, so a failed
2209
+ * write must never break the build.
2210
+ */
2211
+ function writeBuildStamp(dir, stamp) {
2212
+ try {
2213
+ fs.mkdirSync(dir, { recursive: true });
2214
+ } catch {
2215
+ return;
2216
+ }
2217
+ const filePath = path.join(dir, BUILD_STAMP_FILE_NAME);
2218
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.tmp`;
2219
+ try {
2220
+ fs.writeFileSync(tmpPath, JSON.stringify(stamp, null, 2));
2221
+ fs.renameSync(tmpPath, filePath);
2222
+ } catch {
2223
+ try {
2224
+ fs.rmSync(tmpPath, { force: true });
2225
+ } catch {}
2226
+ }
2227
+ }
2228
+ function detectStaleness(options) {
2229
+ const { generatedOutDir, cacheFilePath, pluginVersion, configHash } = options;
2230
+ const grace = options.gracePeriodMs ?? 300 * 1e3;
2231
+ let cacheStat;
2232
+ try {
2233
+ cacheStat = fs.statSync(cacheFilePath);
2234
+ } catch {
2235
+ cacheStat = null;
2236
+ }
2237
+ const stamp = readBuildStamp(generatedOutDir);
2238
+ if (cacheStat && !stamp) return {
2239
+ reason: "cache-without-stamp",
2240
+ message: `vite-bundled-i18n: extraction cache exists at ${cacheFilePath} but no build-stamp at ${path.join(generatedOutDir, BUILD_STAMP_FILE_NAME)}. Previous build may not have completed. If your prod bundles look stale, run: npx vite-bundled-i18n clean && <your-build-cmd>`
2241
+ };
2242
+ if (!stamp) return null;
2243
+ if (stamp.pluginVersion !== pluginVersion) return {
2244
+ reason: "plugin-version-changed",
2245
+ message: `vite-bundled-i18n: build-stamp records previous plugin version ${stamp.pluginVersion}, current is ${pluginVersion}. Downstream artifacts in ${generatedOutDir} may be stale until the next full build completes.`
2246
+ };
2247
+ if (stamp.configHash !== configHash) return {
2248
+ reason: "config-changed",
2249
+ message: "vite-bundled-i18n: extraction-relevant config changed since the last build-stamp. If your prod bundles look stale, run: npx vite-bundled-i18n clean && <your-build-cmd>"
2250
+ };
2251
+ if (cacheStat && stamp.cacheMtimeAtStampWrite !== null) {
2252
+ const drift = cacheStat.mtimeMs - stamp.cacheMtimeAtStampWrite;
2253
+ if (drift > grace) {
2254
+ const summary = stamp.routeCount && stamp.keyCount ? ` (last build saw ${stamp.routeCount} route(s), ${stamp.keyCount} key(s))` : "";
2255
+ return {
2256
+ reason: "cache-newer-than-stamp",
2257
+ message: `vite-bundled-i18n: extraction cache has advanced ${formatDuration(drift)} since the last successful production build${summary}. If you've only been running \`vite dev\`, this is expected — the next \`vite build\` will reconcile. If you're seeing stale prod bundles, run: npx vite-bundled-i18n clean && <your-build-cmd>.`
2258
+ };
2259
+ }
2260
+ }
2261
+ return null;
2262
+ }
2263
+ function formatDuration(ms) {
2264
+ if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
2265
+ if (ms < 36e5) return `${Math.round(ms / 6e4)}m`;
2266
+ if (ms < 864e5) return `${Math.round(ms / 36e5)}h`;
2267
+ return `${Math.round(ms / 864e5)}d`;
2268
+ }
2269
+ //#endregion
2270
+ export { keyMatchesPattern as A, writeRuntimeConst as C, pruneNamespace as D, generateBundles as E, resolveDictionaryOwnership as M, buildScopePlans as O, runtimePathFromTypesPath as S, flattenKeys as T, extractKeys as _, runStrictExtraction as a, generateReports as b, applyDynamicKeys as c, resolveCacheConfig as d, CACHE_FILE_NAME as f, walkAll as g, resolveImport as h, assertNoStrictExtractionErrors as i, normalizeDictionaries as j, inferScopeNamespace as k, buildScopeMap as l, createExtractionCache as m, detectStaleness as n, writeStrictExtractionReport as o, computeConfigHash as p, writeBuildStamp as r, compileAll as s, computeAnalysisFingerprint as t, PLUGIN_VERSION as u, flattenLocaleKeys as v, writeTypes as w, generateTypes as x, generateDictionaryOwnershipReport as y };
1924
2271
 
1925
- //# sourceMappingURL=scope-registration-xea-PWbh.js.map
2272
+ //# sourceMappingURL=build-stamp-CwD2KxEn.js.map