vite-bundled-i18n 0.4.0 → 0.6.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 +125 -16
- package/dist/cli/commands.d.ts +22 -0
- package/dist/cli/index.js +107 -19
- package/dist/cli/index.js.map +1 -1
- package/dist/context-B66VMNFr.js +14 -0
- package/dist/context-B66VMNFr.js.map +1 -0
- package/dist/core/config.d.ts +34 -0
- package/dist/core/i18n-generated-shim.d.ts +18 -0
- package/dist/core/i18n-generated-shim.js +23 -0
- package/dist/core/i18n-generated-shim.js.map +1 -0
- package/dist/core/scope-map-client.d.ts +79 -0
- package/dist/core/services/readiness-gate.d.ts +57 -0
- package/dist/core/types.d.ts +42 -2
- package/dist/{data-Yv_f3OCA.js → data-DtpMCpiZ.js} +85 -7
- package/dist/data-DtpMCpiZ.js.map +1 -0
- package/dist/extractor/bundle-generator.d.ts +4 -2
- package/dist/extractor/cache-config.d.ts +58 -0
- package/dist/extractor/dynamic-keys.d.ts +41 -0
- package/dist/extractor/extraction-cache.d.ts +87 -0
- package/dist/extractor/scope-map.d.ts +64 -0
- package/dist/extractor/scope-registration.d.ts +50 -0
- package/dist/extractor/type-generator.d.ts +31 -4
- package/dist/extractor/walker-types.d.ts +13 -0
- package/dist/extractor/walker.d.ts +2 -0
- package/dist/{getTranslations-BdfteEhG.js → getTranslations-htem-Z8C.js} +9 -1
- package/dist/getTranslations-htem-Z8C.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +70 -5
- package/dist/index.js.map +1 -0
- package/dist/{mountDevtools-CtiMC5PM.js → mountDevtools-DgjYMAiI.js} +25 -6
- package/dist/mountDevtools-DgjYMAiI.js.map +1 -0
- package/dist/plugin/buildPlugin.d.ts +77 -0
- package/dist/plugin/devDiagnostics.d.ts +2 -0
- package/dist/plugin/devPlugin.d.ts +19 -0
- package/dist/plugin/version.d.ts +6 -0
- package/dist/plugin.js +363 -33
- package/dist/plugin.js.map +1 -1
- package/dist/react/GateBoundary.d.ts +45 -0
- package/dist/react/useGate.d.ts +20 -0
- package/dist/react.d.ts +3 -0
- package/dist/react.js +67 -15
- package/dist/react.js.map +1 -1
- package/dist/{compiler-CMOyCfBe.js → scope-registration-ACWKuj8f.js} +536 -13
- package/dist/scope-registration-ACWKuj8f.js.map +1 -0
- package/dist/{server-C0yDN0XT.js → server-D_J3294k.js} +3 -3
- package/dist/{server-C0yDN0XT.js.map → server-D_J3294k.js.map} +1 -1
- package/dist/server.js +3 -3
- package/dist/testing.js +73 -0
- package/dist/testing.js.map +1 -0
- package/dist/vanilla.js +4 -4
- package/dist/vue.d.ts +19 -0
- package/dist/vue.js +47 -6
- package/dist/vue.js.map +1 -1
- package/package.json +7 -2
- package/dist/compiler-CMOyCfBe.js.map +0 -1
- package/dist/data-Yv_f3OCA.js.map +0 -1
- package/dist/getTranslations-BdfteEhG.js.map +0 -1
- package/dist/mountDevtools-CtiMC5PM.js.map +0 -1
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
# vite-bundled-i18n
|
|
2
2
|
|
|
3
3
|
Make translations behave like code: split, scoped, and bundled per route.
|
|
4
4
|
|
|
@@ -22,24 +22,46 @@ Layout.tsx ──→ Dictionary rules ──→ __i18n/en/_dict/glob
|
|
|
22
22
|
Type generation ──→ .i18n/i18n-generated.ts (full autocomplete)
|
|
23
23
|
```
|
|
24
24
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
1. **Build-time analysis** — AST extractor walks your import graph, finds every `t()`, `useI18n()`, `i18nKey()` call, and maps keys to routes. No code execution needed.
|
|
28
|
-
2. **Bundle generation** — keys are grouped into scope bundles (per-page) and dictionary bundles (shared/global). Each bundle is a static JSON asset or compiled JS module.
|
|
29
|
-
3. **Thin runtime** — minimal `t()` function that loads the right bundle on demand. React, Vue, and vanilla adapters are ~50 lines each.
|
|
25
|
+
The Vite plugin parses your import graph, maps every `t()` / `useI18n()` / `i18nKey()` call to the route that reached it, and emits per-route JSON plus optional compiled `Map` modules. The runtime is a thin `t()` that loads the right bundle on demand. React, Vue, and vanilla adapters all share a ~50-line core.
|
|
30
26
|
|
|
31
27
|
## Features
|
|
32
28
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
- **
|
|
29
|
+
### What makes it different
|
|
30
|
+
|
|
31
|
+
- **Scope bundles** — each route loads only its own translations in one HTTP request
|
|
32
|
+
- **Page scope map** — framework-neutral `scope-map.json` + typed `PAGE_SCOPE_MAP` const, so any router can parallelize scope loads with component resolution ([router integration](#router-integration))
|
|
33
|
+
- **Cross-namespace packing** (opt-in) — inline a route's cross-namespace keys, tree-shaken, into its scope bundle. 1–3 foreign keys don't force a whole dictionary to load globally
|
|
34
|
+
- **Persistent extraction cache** — per-file AST results survive between runs. Warm dev starts in ~250 ms instead of 3–10 s; repeat builds skip the walk when nothing changed
|
|
36
35
|
- **Progressive autocomplete** — generated types let the IDE suggest one key segment at a time
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
- **
|
|
41
|
-
- **
|
|
42
|
-
- **
|
|
36
|
+
|
|
37
|
+
### Also included
|
|
38
|
+
|
|
39
|
+
- **Dictionary ownership** — named dictionaries claim keys by `include` / `exclude` / `priority`, pinned in memory
|
|
40
|
+
- **Placeholder validation** — `t('cart.total', { amount })` is type-checked against `{{amount}}` in the JSON
|
|
41
|
+
- **Compiled mode** — optional `Map`-based modules for O(1) lookups without JSON parsing
|
|
42
|
+
- **Multi-framework** — React, Vue, vanilla JS share a single core
|
|
43
|
+
- **SSR** — server rendering with automatic client hydration via `window.__I18N_RESOURCES__`
|
|
44
|
+
- **AST extraction** — `t()`, `useI18n()`, `i18nKey()`, `defineI18nData()`, configurable `keyFields`, `as const` objects, string enums, helper functions that receive `t` as a parameter
|
|
45
|
+
- **Dev toolbar** — scope-aware missing-key panel (filters by current route, resets on locale change and HMR), per-namespace bundle efficiency, live updates on navigation
|
|
46
|
+
|
|
47
|
+
## Performance
|
|
48
|
+
|
|
49
|
+
The library is a performance play end-to-end. Representative numbers for a 50-page admin panel with 3,000 translation keys:
|
|
50
|
+
|
|
51
|
+
| | Traditional i18n | vite-bundled-i18n |
|
|
52
|
+
|---|---|---|
|
|
53
|
+
| Keys per page load | 3,000 (all) | 25–40 (route-extracted) |
|
|
54
|
+
| Bundle size per scope | N/A (monolithic) | ~97% smaller than the source namespace |
|
|
55
|
+
| HTTP requests per route | many (or one huge) | 1 scope bundle + cached dictionaries |
|
|
56
|
+
| Cold dev start | — | ~200 ms |
|
|
57
|
+
| Warm dev start | — | ~250 ms (extraction cache keeps prior AST parses) |
|
|
58
|
+
| Repeat `vite build`, unchanged code | full walk | near-zero parse (cache-hit, stat-only) |
|
|
59
|
+
| HMR key edit → browser refetch | full re-walk | ~30 ms (surgical cache update) |
|
|
60
|
+
| Compiled-mode `t('key')` | JSON parse + path traversal | O(1) `Map.get` |
|
|
61
|
+
|
|
62
|
+
The extraction cache persists to `.i18n/cache/` and auto-invalidates on plugin upgrade, config change, or Node major version change. Disable with `cache: false` or `VITE_I18N_NO_CACHE=1`. See [API docs — Extraction cache](./docs/api.md#extraction-cache-cache).
|
|
63
|
+
|
|
64
|
+
Compiled mode replaces JSON parsing with pre-resolved flat `Map` modules. Faster than JSON at the browser level (no parse on first lookup), smaller gzipped (shared string pool), cacheable by the browser's module loader. Falls back to JSON automatically when compiled modules aren't available.
|
|
43
65
|
|
|
44
66
|
## Setup
|
|
45
67
|
|
|
@@ -143,6 +165,31 @@ function ProductsPage() {
|
|
|
143
165
|
|
|
144
166
|
**`useI18n(scope)`** triggers a single HTTP request to load the scope bundle. Dictionaries are always available. Previously visited scopes are instant (cached). Missing-key warnings are automatically suppressed while a scope is loading — no need to guard every `useMemo`.
|
|
145
167
|
|
|
168
|
+
**`useI18n()` without a scope** returns a translator bound to the current cache — whatever's already loaded (dictionaries + any scope the parent or sibling components registered). Use this in child components below a page that has already declared its scope, or in layout components that only read dictionary keys.
|
|
169
|
+
|
|
170
|
+
```tsx
|
|
171
|
+
// Pattern A — page registers its own scope
|
|
172
|
+
function ProductsPage() {
|
|
173
|
+
const { t } = useI18n('products.show') // loads products.show bundle
|
|
174
|
+
return <section><Header /><Details /></section>
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
// Pattern B — page composes children; each child declares its own scope
|
|
178
|
+
function AdminPage() {
|
|
179
|
+
return <><Sidebar /><MainContent /></> // no scope at the page level
|
|
180
|
+
}
|
|
181
|
+
function Sidebar() {
|
|
182
|
+
const { t } = useI18n('sidebar.admin') // child registers
|
|
183
|
+
return <nav>{t('sidebar.admin.heading')}</nav>
|
|
184
|
+
}
|
|
185
|
+
function MainContent() {
|
|
186
|
+
const { t } = useI18n() // reads whatever's loaded
|
|
187
|
+
return <main>{t('sidebar.admin.welcome')}</main>
|
|
188
|
+
}
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Both patterns feed the same `PAGE_SCOPE_MAP` — the walker aggregates scopes across the full route tree, so routers using the [integration pattern](#router-integration) preload correctly either way.
|
|
192
|
+
|
|
146
193
|
**`I18nBoundary`** handles scope loading without early returns:
|
|
147
194
|
|
|
148
195
|
```tsx
|
|
@@ -153,6 +200,56 @@ function ProductsPage() {
|
|
|
153
200
|
|
|
154
201
|
**Navigation lifecycle:** The provider persists across page navigations (Inertia, React Router, Next.js). Dictionaries load once. Each page scope loads on mount — only the page content waits, not the layout.
|
|
155
202
|
|
|
203
|
+
## Router Integration
|
|
204
|
+
|
|
205
|
+
`useI18n('products.show')` triggers the scope load on mount — but mount only happens *after* the router has resolved the matched component. On slow connections this serializes the scope fetch behind the component chunk. `PAGE_SCOPE_MAP` unblocks this: the scope list for every page is a build-time constant, fully typed, importable anywhere.
|
|
206
|
+
|
|
207
|
+
Combine it with your router's async page-resolve hook and `Promise.all` so both promises race in parallel:
|
|
208
|
+
|
|
209
|
+
```ts
|
|
210
|
+
import {
|
|
211
|
+
PAGE_SCOPE_MAP,
|
|
212
|
+
type I18nPageIdentifier,
|
|
213
|
+
} from 'vite-bundled-i18n/generated'
|
|
214
|
+
import { i18n } from './i18n'
|
|
215
|
+
|
|
216
|
+
// Sketch — adapt to your router's resolve API
|
|
217
|
+
async function resolvePage(
|
|
218
|
+
pageId: I18nPageIdentifier,
|
|
219
|
+
loadComponent: () => Promise<unknown>,
|
|
220
|
+
) {
|
|
221
|
+
const scopes = PAGE_SCOPE_MAP[pageId]
|
|
222
|
+
const locale = i18n.getLocale()
|
|
223
|
+
await Promise.all([
|
|
224
|
+
loadComponent(),
|
|
225
|
+
...scopes.map((scope) => i18n.loadScope(locale, scope)),
|
|
226
|
+
])
|
|
227
|
+
}
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
Calling `loadScope` is safe from concurrent paths. The runtime deduplicates by `(locale, scope)` — 100 parallel calls fire exactly one fetch, share the same promise, and resolve together. On fetch failure the in-flight entry clears, so a retry starts fresh. Side effects (cache writes, devbar state, dependent scope flags) run once per logical load, not once per caller.
|
|
231
|
+
|
|
232
|
+
**Page identifiers.** The default strips `src/pages/` and common `.tsx` / `.page.tsx` suffixes:
|
|
233
|
+
|
|
234
|
+
```
|
|
235
|
+
src/pages/giftcards/show.tsx → 'giftcards/show'
|
|
236
|
+
src/pages/products/show.page.tsx → 'products/show'
|
|
237
|
+
```
|
|
238
|
+
|
|
239
|
+
When your router exposes a different token at runtime, override:
|
|
240
|
+
|
|
241
|
+
```ts
|
|
242
|
+
i18nPlugin(config, {
|
|
243
|
+
pages: ['admin/**/pages/*.tsx'],
|
|
244
|
+
locales: ['en'],
|
|
245
|
+
defaultLocale: 'en',
|
|
246
|
+
pageIdentifier: (abs) =>
|
|
247
|
+
abs.replace(/^.*?\/admin\//, 'admin/').replace(/\.tsx$/, ''),
|
|
248
|
+
})
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
Whatever your function returns becomes the key in `scope-map.json` (served at `/__i18n/scope-map.json` in dev, emitted at build under `assetsDir`) and the `I18nPageIdentifier` union in generated types. Routers that want the data without types can fetch the JSON directly.
|
|
252
|
+
|
|
156
253
|
## Vue
|
|
157
254
|
|
|
158
255
|
```ts
|
|
@@ -258,6 +355,7 @@ The build generates reports that show exactly what was extracted, what's missing
|
|
|
258
355
|
- `unused.json` — keys in locale files that no route references (candidates for removal)
|
|
259
356
|
- `stats.json` — per-route and per-namespace extraction statistics
|
|
260
357
|
- `ownership.json` — which dictionary owns which key, with collision data
|
|
358
|
+
- `scope-map.json` — framework-neutral `page id → { scopes, dictionaries }` index ([router integration](#router-integration))
|
|
261
359
|
|
|
262
360
|
### Edge cases
|
|
263
361
|
|
|
@@ -268,6 +366,7 @@ Keys that the AST extractor **cannot see** (dynamic concatenation, computed keys
|
|
|
268
366
|
```
|
|
269
367
|
__i18n/{locale}/_dict/{name}.json — dictionary bundles (JSON)
|
|
270
368
|
__i18n/{locale}/{scope}.json — scope bundles (JSON)
|
|
369
|
+
__i18n/scope-map.json — page id → scopes index
|
|
271
370
|
__i18n/compiled/manifest.js — compiled module manifest
|
|
272
371
|
__i18n/compiled/{locale}/... — compiled Map modules (optional)
|
|
273
372
|
```
|
|
@@ -290,7 +389,9 @@ React and Vue adapters detect and consume the hydrated data automatically.
|
|
|
290
389
|
|
|
291
390
|
Translation bundles are served via Vite middleware — no files written to disk. Types regenerate on locale file changes. The dev toolbar updates live on navigation.
|
|
292
391
|
|
|
293
|
-
|
|
392
|
+
**Dev toolbar behavior (v0.4.0+).** Missing-key entries are tagged with the current scope and a monotonic epoch. Navigating between pages automatically filters the "Missing Translations" panel to show only misses from the current route. Changing locale bumps the epoch so prior entries clear. HMR updates reset key-usage state automatically — editing a file doesn't leave stale misses behind.
|
|
393
|
+
|
|
394
|
+
**Sidecar setups** (Laravel serving assets from public/):
|
|
294
395
|
|
|
295
396
|
```ts
|
|
296
397
|
i18nPlugin(i18nConfig, {
|
|
@@ -351,6 +452,8 @@ cache: {
|
|
|
351
452
|
| `vite-bundled-i18n/vanilla` | `getTranslations`, `initI18n` |
|
|
352
453
|
| `vite-bundled-i18n/server` | `initServerI18n` (SSR) |
|
|
353
454
|
| `vite-bundled-i18n/plugin` | Vite plugin (`i18nPlugin`) |
|
|
455
|
+
| `vite-bundled-i18n/generated` | Generated types + `PAGE_SCOPE_MAP` / `I18nPageIdentifier` |
|
|
456
|
+
| `vite-bundled-i18n/testing` | `createTestI18n`, `I18nTestProvider`, `createI18nTestPlugin` |
|
|
354
457
|
|
|
355
458
|
## Documentation
|
|
356
459
|
|
|
@@ -358,6 +461,12 @@ cache: {
|
|
|
358
461
|
- [API Reference](./docs/api.md)
|
|
359
462
|
- [Architecture](./docs/architecture.md)
|
|
360
463
|
|
|
464
|
+
## Releases
|
|
465
|
+
|
|
466
|
+
Current release: **v0.6.0** — framework-agnostic readiness gate (`i18n.gate`, `<GateBoundary>`, `useGate()`), runtime `createScopeMapClient()`, `t.dynamic()` escape hatch, `bundling.dynamicKeys` + `strictScopeRegistration`, `vite-bundled-i18n/testing` subpackage. Breaking: `loadScope` now auto-registers with the gate by default — opt out via `{ trackReadiness: false }`.
|
|
467
|
+
|
|
468
|
+
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.
|
|
469
|
+
|
|
361
470
|
## License
|
|
362
471
|
|
|
363
472
|
[MIT](./LICENSE)
|
package/dist/cli/commands.d.ts
CHANGED
|
@@ -26,6 +26,28 @@ export interface CliConfig {
|
|
|
26
26
|
* See `I18nSharedConfig.bundling.crossNamespacePacking`.
|
|
27
27
|
*/
|
|
28
28
|
crossNamespacePacking?: boolean;
|
|
29
|
+
/**
|
|
30
|
+
* Runtime-computed keys to treat as always-extracted. Matches
|
|
31
|
+
* `I18nSharedConfig.bundling.dynamicKeys`. CLI-side JSON config only,
|
|
32
|
+
* since function-based identifiers aren't serializable.
|
|
33
|
+
*/
|
|
34
|
+
dynamicKeys?: readonly string[];
|
|
35
|
+
/**
|
|
36
|
+
* Severity for the "page registers no scope" audit. Matches
|
|
37
|
+
* `I18nSharedConfig.bundling.strictScopeRegistration`.
|
|
38
|
+
*/
|
|
39
|
+
strictScopeRegistration?: 'off' | 'warn' | 'error';
|
|
40
|
+
/**
|
|
41
|
+
* Extraction cache control. `false` disables, an object configures the
|
|
42
|
+
* backing directory and persistence. Env vars (`VITE_I18N_NO_CACHE`,
|
|
43
|
+
* `VITE_I18N_CLEAR_CACHE`, `VITE_I18N_CACHE_DEBUG`) always take
|
|
44
|
+
* precedence. See `resolveCacheConfig`.
|
|
45
|
+
*/
|
|
46
|
+
cache?: boolean | {
|
|
47
|
+
enabled?: boolean;
|
|
48
|
+
dir?: string;
|
|
49
|
+
persist?: boolean;
|
|
50
|
+
};
|
|
29
51
|
}
|
|
30
52
|
/**
|
|
31
53
|
* Run the walker and print a summary table to stdout.
|
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as
|
|
2
|
+
import { _ as writeRuntimeConst, a as PLUGIN_VERSION, b as generateBundles, c as createExtractionCache, f as flattenLocaleKeys, g as runtimePathFromTypesPath, i as buildScopeMap, m as generateReports, n as compileAll, o as resolveCacheConfig, r as applyDynamicKeys, s as computeConfigHash, t as checkScopeRegistration, u as walkAll, v as writeTypes } from "../scope-registration-ACWKuj8f.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
|
@@ -14,21 +14,88 @@ function resolveConfig(config) {
|
|
|
14
14
|
extractionScope: config.extractionScope ?? "global"
|
|
15
15
|
};
|
|
16
16
|
}
|
|
17
|
-
function
|
|
17
|
+
function buildCliCache(config, rootDir) {
|
|
18
|
+
const cacheSettings = resolveCacheConfig(config.cache, { rootDir });
|
|
19
|
+
if (!cacheSettings.enabled) return void 0;
|
|
20
|
+
if (cacheSettings.clearBeforeStart) try {
|
|
21
|
+
fs.rmSync(cacheSettings.dir, {
|
|
22
|
+
recursive: true,
|
|
23
|
+
force: true
|
|
24
|
+
});
|
|
25
|
+
} catch {}
|
|
26
|
+
return createExtractionCache({
|
|
27
|
+
dir: cacheSettings.dir,
|
|
28
|
+
pluginVersion: PLUGIN_VERSION,
|
|
29
|
+
configHash: computeConfigHash({
|
|
30
|
+
pages: config.pages,
|
|
31
|
+
defaultLocale: config.defaultLocale,
|
|
32
|
+
extractionScope: config.extractionScope ?? "global",
|
|
33
|
+
hookSources: config.hookSources,
|
|
34
|
+
dictionaries: config.dictionaries,
|
|
35
|
+
crossNamespacePacking: config.crossNamespacePacking
|
|
36
|
+
}),
|
|
37
|
+
debug: cacheSettings.debug
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
function persistCache(config, cache, rootDir) {
|
|
41
|
+
if (!cache) return;
|
|
42
|
+
if (resolveCacheConfig(config.cache, { rootDir }).persist) cache.persistToDisk();
|
|
43
|
+
}
|
|
44
|
+
function runWalker(config, cache) {
|
|
18
45
|
const { rootDir, localesDir, extractionScope } = resolveConfig(config);
|
|
19
|
-
|
|
46
|
+
const analysis = walkAll({
|
|
20
47
|
pages: config.pages,
|
|
21
48
|
rootDir,
|
|
22
49
|
localesDir,
|
|
23
50
|
defaultLocale: config.defaultLocale,
|
|
24
51
|
extractionScope,
|
|
25
|
-
hookSources: config.hookSources
|
|
52
|
+
hookSources: config.hookSources,
|
|
53
|
+
cache
|
|
26
54
|
});
|
|
55
|
+
if (config.dynamicKeys && config.dynamicKeys.length > 0) {
|
|
56
|
+
const report = applyDynamicKeys(analysis, {
|
|
57
|
+
dynamicKeys: config.dynamicKeys,
|
|
58
|
+
dictionaries: config.dictionaries,
|
|
59
|
+
crossNamespacePacking: config.crossNamespacePacking
|
|
60
|
+
});
|
|
61
|
+
for (const orphan of report.orphans) console.warn(`[vite-bundled-i18n] dynamicKeys entry "${orphan}" matches no route and no dictionary — it won't ship anywhere.`);
|
|
62
|
+
}
|
|
63
|
+
const strictMode = config.strictScopeRegistration ?? "warn";
|
|
64
|
+
if (strictMode !== "off") {
|
|
65
|
+
const report = checkScopeRegistration(analysis, {
|
|
66
|
+
rootDir,
|
|
67
|
+
mode: strictMode
|
|
68
|
+
});
|
|
69
|
+
if (report.violations.length > 0) {
|
|
70
|
+
if (strictMode === "error") throw new Error("vite-bundled-i18n: scope registration failures (strictScopeRegistration: 'error'):\n\n" + report.messages.join("\n\n"));
|
|
71
|
+
for (const message of report.messages) console.warn(message);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return analysis;
|
|
27
75
|
}
|
|
28
76
|
function collectScopeNames(analysis) {
|
|
29
77
|
return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();
|
|
30
78
|
}
|
|
31
79
|
/**
|
|
80
|
+
* Emit both the typed `.ts` (for TSC/IDE) and runtime `.js` (for Vite
|
|
81
|
+
* resolve.alias) generated files. Called by every CLI command that
|
|
82
|
+
* previously only wrote the `.ts` file — keeps CLI output aligned with
|
|
83
|
+
* the Vite plugin's `emitGeneratedArtifacts` so there's no drift.
|
|
84
|
+
*/
|
|
85
|
+
function emitGeneratedPair(analysis, config, localesDir, rootDir, typesOutPath) {
|
|
86
|
+
const scopeNames = collectScopeNames(analysis);
|
|
87
|
+
const scopeMap = buildScopeMap(analysis, {
|
|
88
|
+
rootDir,
|
|
89
|
+
defaultLocale: config.defaultLocale,
|
|
90
|
+
dictionaries: config.dictionaries
|
|
91
|
+
});
|
|
92
|
+
const pageScopeMap = {};
|
|
93
|
+
for (const [id, entry] of Object.entries(scopeMap.pages)) pageScopeMap[id] = entry.scopes;
|
|
94
|
+
const hasPageMap = Object.keys(pageScopeMap).length > 0;
|
|
95
|
+
writeTypes(localesDir, config.defaultLocale, typesOutPath, scopeNames, hasPageMap ? pageScopeMap : void 0);
|
|
96
|
+
writeRuntimeConst(runtimePathFromTypesPath(typesOutPath), hasPageMap ? pageScopeMap : void 0);
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
32
99
|
* Pad a string to the given width.
|
|
33
100
|
*/
|
|
34
101
|
function pad(str, width) {
|
|
@@ -54,8 +121,10 @@ function printTable(headers, rows) {
|
|
|
54
121
|
* Returns the ProjectAnalysis for programmatic use.
|
|
55
122
|
*/
|
|
56
123
|
function analyze(config) {
|
|
57
|
-
const { localesDir } = resolveConfig(config);
|
|
58
|
-
const
|
|
124
|
+
const { rootDir, localesDir } = resolveConfig(config);
|
|
125
|
+
const cache = buildCliCache(config, rootDir);
|
|
126
|
+
const analysis = runWalker(config, cache);
|
|
127
|
+
persistCache(config, cache, rootDir);
|
|
59
128
|
const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);
|
|
60
129
|
const totalAvailable = Array.from(availableKeys.values()).reduce((sum, keys) => sum + keys.length, 0);
|
|
61
130
|
printTable([
|
|
@@ -80,15 +149,17 @@ function analyze(config) {
|
|
|
80
149
|
* Prints what was generated to stdout.
|
|
81
150
|
*/
|
|
82
151
|
function generate(config) {
|
|
83
|
-
const { outDir, typesOutPath, localesDir } = resolveConfig(config);
|
|
84
|
-
const
|
|
152
|
+
const { rootDir, outDir, typesOutPath, localesDir } = resolveConfig(config);
|
|
153
|
+
const cache = buildCliCache(config, rootDir);
|
|
154
|
+
const analysis = runWalker(config, cache);
|
|
155
|
+
persistCache(config, cache, rootDir);
|
|
85
156
|
const bundles = generateBundles(analysis, {
|
|
86
157
|
localesDir,
|
|
87
158
|
locales: config.locales,
|
|
88
159
|
outDir,
|
|
89
160
|
crossNamespacePacking: config.crossNamespacePacking
|
|
90
161
|
});
|
|
91
|
-
|
|
162
|
+
emitGeneratedPair(analysis, config, localesDir, rootDir, typesOutPath);
|
|
92
163
|
console.log(`Generated ${bundles.length} bundle(s):`);
|
|
93
164
|
for (const b of bundles) console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);
|
|
94
165
|
console.log(`Types written to ${typesOutPath}`);
|
|
@@ -98,8 +169,11 @@ function generate(config) {
|
|
|
98
169
|
* Prints summary to stdout.
|
|
99
170
|
*/
|
|
100
171
|
function report(config) {
|
|
101
|
-
const { outDir, localesDir } = resolveConfig(config);
|
|
102
|
-
|
|
172
|
+
const { rootDir, outDir, localesDir } = resolveConfig(config);
|
|
173
|
+
const cache = buildCliCache(config, rootDir);
|
|
174
|
+
const analysis = runWalker(config, cache);
|
|
175
|
+
persistCache(config, cache, rootDir);
|
|
176
|
+
generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);
|
|
103
177
|
console.log(`Reports written to ${outDir}:`);
|
|
104
178
|
console.log(" manifest.json");
|
|
105
179
|
console.log(" missing.json");
|
|
@@ -111,8 +185,10 @@ function report(config) {
|
|
|
111
185
|
* Prints a summary to stdout.
|
|
112
186
|
*/
|
|
113
187
|
function compile(config) {
|
|
114
|
-
const { outDir, localesDir } = resolveConfig(config);
|
|
115
|
-
const
|
|
188
|
+
const { rootDir, outDir, localesDir } = resolveConfig(config);
|
|
189
|
+
const cache = buildCliCache(config, rootDir);
|
|
190
|
+
const analysis = runWalker(config, cache);
|
|
191
|
+
persistCache(config, cache, rootDir);
|
|
116
192
|
const compiledOutDir = path.join(outDir, "compiled");
|
|
117
193
|
compileAll(analysis, {
|
|
118
194
|
localesDir,
|
|
@@ -129,8 +205,10 @@ function compile(config) {
|
|
|
129
205
|
* Run analyze + generate + compile + report all at once.
|
|
130
206
|
*/
|
|
131
207
|
function build(config) {
|
|
132
|
-
const { outDir, typesOutPath, localesDir } = resolveConfig(config);
|
|
133
|
-
const
|
|
208
|
+
const { rootDir, outDir, typesOutPath, localesDir } = resolveConfig(config);
|
|
209
|
+
const cache = buildCliCache(config, rootDir);
|
|
210
|
+
const analysis = runWalker(config, cache);
|
|
211
|
+
persistCache(config, cache, rootDir);
|
|
134
212
|
const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);
|
|
135
213
|
const totalAvailable = Array.from(availableKeys.values()).reduce((sum, keys) => sum + keys.length, 0);
|
|
136
214
|
printTable([
|
|
@@ -153,7 +231,7 @@ function build(config) {
|
|
|
153
231
|
outDir,
|
|
154
232
|
crossNamespacePacking: config.crossNamespacePacking
|
|
155
233
|
});
|
|
156
|
-
|
|
234
|
+
emitGeneratedPair(analysis, config, localesDir, rootDir, typesOutPath);
|
|
157
235
|
console.log(`\nGenerated ${bundles.length} bundle(s)`);
|
|
158
236
|
console.log(`Types written to ${typesOutPath}`);
|
|
159
237
|
const compiledOutDir = path.join(outDir, "compiled");
|
|
@@ -180,7 +258,7 @@ var COMMANDS = [
|
|
|
180
258
|
"build"
|
|
181
259
|
];
|
|
182
260
|
function printUsage() {
|
|
183
|
-
console.log("Usage: vite-bundled-i18n <command> [
|
|
261
|
+
console.log("Usage: vite-bundled-i18n <command> [options]");
|
|
184
262
|
console.log("");
|
|
185
263
|
console.log("Commands:");
|
|
186
264
|
console.log(" analyze — Walk imports and print a summary of key usage per route");
|
|
@@ -191,6 +269,8 @@ function printUsage() {
|
|
|
191
269
|
console.log("");
|
|
192
270
|
console.log("Options:");
|
|
193
271
|
console.log(" --config <path> Path to config file (default: i18n.config.json)");
|
|
272
|
+
console.log(" --no-cache Disable the extraction cache for this run");
|
|
273
|
+
console.log(" --clear-cache Clear the extraction cache before running");
|
|
194
274
|
}
|
|
195
275
|
function loadConfig(configPath) {
|
|
196
276
|
const resolved = path.resolve(configPath);
|
|
@@ -205,9 +285,13 @@ function parseArgs(argv) {
|
|
|
205
285
|
const args = argv.slice(2);
|
|
206
286
|
let command;
|
|
207
287
|
let configPath = "i18n.config.json";
|
|
288
|
+
let noCache = false;
|
|
289
|
+
let clearCache = false;
|
|
208
290
|
for (let i = 0; i < args.length; i++) {
|
|
209
291
|
const arg = args[i];
|
|
210
292
|
if (arg === "--config" && i + 1 < args.length) configPath = args[++i];
|
|
293
|
+
else if (arg === "--no-cache") noCache = true;
|
|
294
|
+
else if (arg === "--clear-cache") clearCache = true;
|
|
211
295
|
else if (arg === "--help" || arg === "-h") {
|
|
212
296
|
printUsage();
|
|
213
297
|
process.exit(0);
|
|
@@ -224,11 +308,15 @@ function parseArgs(argv) {
|
|
|
224
308
|
}
|
|
225
309
|
return {
|
|
226
310
|
command,
|
|
227
|
-
configPath
|
|
311
|
+
configPath,
|
|
312
|
+
noCache,
|
|
313
|
+
clearCache
|
|
228
314
|
};
|
|
229
315
|
}
|
|
230
|
-
var { command, configPath } = parseArgs(process.argv);
|
|
316
|
+
var { command, configPath, noCache, clearCache } = parseArgs(process.argv);
|
|
231
317
|
var config = loadConfig(configPath);
|
|
318
|
+
if (noCache) config.cache = false;
|
|
319
|
+
if (clearCache) process.env.VITE_I18N_CLEAR_CACHE = "1";
|
|
232
320
|
({
|
|
233
321
|
analyze,
|
|
234
322
|
generate,
|
package/dist/cli/index.js.map
CHANGED
|
@@ -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 /** Additional module specifiers that export `useI18n`. */\n hookSources?: string[];\n /**\n * Inline cross-namespace keys (tree-shaken) into each scope bundle.\n * See `I18nSharedConfig.bundling.crossNamespacePacking`.\n */\n crossNamespacePacking?: boolean;\n}\n\nfunction resolveConfig(config: CliConfig) {\n const rootDir = config.rootDir ?? process.cwd();\n const outDir = config.outDir ?? path.join(rootDir, '.i18n');\n const typesOutPath =\n config.typesOutPath ?? path.join(outDir, 'i18n-generated.ts');\n const localesDir = path.isAbsolute(config.localesDir)\n ? config.localesDir\n : path.join(rootDir, config.localesDir);\n const extractionScope = config.extractionScope ?? 'global';\n\n return { rootDir, outDir, typesOutPath, localesDir, extractionScope } as const;\n}\n\nfunction runWalker(config: CliConfig): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n hookSources: config.hookSources,\n });\n}\n\nfunction collectScopeNames(analysis: ProjectAnalysis): string[] {\n return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n}\n\n/**\n * Pad a string to the given width.\n */\nfunction pad(str: string, width: number): string {\n return str + ' '.repeat(Math.max(0, width - str.length));\n}\n\n/**\n * Print a simple ASCII table to stdout.\n */\nfunction printTable(\n headers: string[],\n rows: string[][],\n): void {\n const colWidths = headers.map((h, i) =>\n Math.max(h.length, ...rows.map((r) => (r[i] ?? '').length)),\n );\n\n const sep =\n '\\u250c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u252c') +\n '\\u2510';\n const mid =\n '\\u251c' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u253c') +\n '\\u2524';\n const bot =\n '\\u2514' +\n colWidths.map((w) => '\\u2500'.repeat(w + 2)).join('\\u2534') +\n '\\u2518';\n\n const formatRow = (cells: string[]) =>\n '\\u2502' +\n cells.map((c, i) => ' ' + pad(c, colWidths[i]) + ' ').join('\\u2502') +\n '\\u2502';\n\n console.log(sep);\n console.log(formatRow(headers));\n console.log(mid);\n for (const row of rows) {\n console.log(formatRow(row));\n }\n console.log(bot);\n}\n\n/**\n * Run the walker and print a summary table to stdout.\n * Returns the ProjectAnalysis for programmatic use.\n */\nexport function analyze(config: CliConfig): ProjectAnalysis {\n const { localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const availableKeys = flattenLocaleKeys(localesDir, config.defaultLocale);\n const totalAvailable = Array.from(availableKeys.values()).reduce(\n (sum, keys) => sum + keys.length,\n 0,\n );\n\n const rows = analysis.routes.map((route) => {\n const usedCount = route.keys.filter((k) => !k.dynamic).length;\n return [\n route.routeId,\n String(usedCount),\n String(totalAvailable),\n String(totalAvailable - usedCount),\n ];\n });\n\n printTable(['Route', 'Used Keys', 'Available', 'Pruned'], rows);\n\n console.log(\n `\\n${analysis.routes.length} route(s), ${analysis.allKeys.length} unique key(s), ${analysis.availableNamespaces.length} namespace(s)`,\n );\n\n return analysis;\n}\n\n/**\n * Run the walker, then generate bundles and types.\n * Prints what was generated to stdout.\n */\nexport function generate(config: CliConfig): void {\n const { outDir, typesOutPath, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`Generated ${bundles.length} bundle(s):`);\n for (const b of bundles) {\n console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);\n }\n console.log(`Types written to ${typesOutPath}`);\n}\n\n/**\n * Run the walker, then generate diagnostic reports.\n * Prints summary to stdout.\n */\nexport function report(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n\n generateReports(analysis, localesDir, config.defaultLocale, outDir, config.dictionaries);\n\n console.log(`Reports written to ${outDir}:`);\n console.log(' manifest.json');\n console.log(' missing.json');\n console.log(' unused.json');\n console.log(' stats.json');\n}\n\n/**\n * Run the walker, then compile pre-resolved flat Map modules.\n * Prints a summary to stdout.\n */\nexport function compile(config: CliConfig): void {\n const { outDir, localesDir } = resolveConfig(config);\n const analysis = runWalker(config);\n const compiledOutDir = path.join(outDir, 'compiled');\n\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\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 crossNamespacePacking: config.crossNamespacePacking,\n });\n\n writeTypes(localesDir, config.defaultLocale, typesOutPath, collectScopeNames(analysis));\n\n console.log(`\\nGenerated ${bundles.length} bundle(s)`);\n console.log(`Types written to ${typesOutPath}`);\n\n // Compile\n const compiledOutDir = path.join(outDir, 'compiled');\n compileAll(analysis, {\n localesDir,\n locales: config.locales,\n defaultLocale: config.defaultLocale,\n outDir: compiledOutDir,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\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)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W,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 fs from 'node:fs';\nimport path from 'node:path';\nimport { walkAll } from '../extractor/walker';\nimport { generateBundles } from '../extractor/bundle-generator';\nimport { writeTypes, writeRuntimeConst, runtimePathFromTypesPath } 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';\nimport {\n createExtractionCache,\n computeConfigHash,\n type ExtractionCache,\n} from '../extractor/extraction-cache';\nimport { resolveCacheConfig } from '../extractor/cache-config';\nimport { PLUGIN_VERSION } from '../plugin/version';\nimport { buildScopeMap } from '../extractor/scope-map';\nimport { applyDynamicKeys } from '../extractor/dynamic-keys';\nimport { checkScopeRegistration } from '../extractor/scope-registration';\n\nexport interface CliConfig {\n /** Glob patterns for page entry points. */\n pages: string[];\n /** Locales directory (relative to rootDir). */\n localesDir: string;\n /** All supported locale codes. */\n locales: string[];\n /** Default locale. */\n defaultLocale: string;\n /** Root directory. Defaults to process.cwd(). */\n rootDir?: string;\n /** Output directory for generated bundles. Defaults to '.i18n'. */\n outDir?: string;\n /** Output path for generated types. Defaults to '.i18n/i18n.d.ts'. */\n typesOutPath?: string;\n /** Extraction scope. Defaults to 'global'. */\n extractionScope?: 'global' | 'scoped';\n /** Optional dictionary configurations for compiled mode. */\n dictionaries?: Record<string, DictionaryConfig>;\n /** Additional module specifiers that export `useI18n`. */\n hookSources?: string[];\n /**\n * Inline cross-namespace keys (tree-shaken) into each scope bundle.\n * See `I18nSharedConfig.bundling.crossNamespacePacking`.\n */\n crossNamespacePacking?: boolean;\n /**\n * Runtime-computed keys to treat as always-extracted. Matches\n * `I18nSharedConfig.bundling.dynamicKeys`. CLI-side JSON config only,\n * since function-based identifiers aren't serializable.\n */\n dynamicKeys?: readonly string[];\n /**\n * Severity for the \"page registers no scope\" audit. Matches\n * `I18nSharedConfig.bundling.strictScopeRegistration`.\n */\n strictScopeRegistration?: 'off' | 'warn' | 'error';\n /**\n * Extraction cache control. `false` disables, an object configures the\n * backing directory and persistence. Env vars (`VITE_I18N_NO_CACHE`,\n * `VITE_I18N_CLEAR_CACHE`, `VITE_I18N_CACHE_DEBUG`) always take\n * precedence. See `resolveCacheConfig`.\n */\n cache?: boolean | {\n enabled?: boolean;\n dir?: string;\n persist?: boolean;\n };\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 buildCliCache(config: CliConfig, rootDir: string): ExtractionCache | undefined {\n const cacheSettings = resolveCacheConfig(config.cache, { rootDir });\n if (!cacheSettings.enabled) return undefined;\n\n if (cacheSettings.clearBeforeStart) {\n try {\n fs.rmSync(cacheSettings.dir, { recursive: true, force: true });\n } catch {\n // Non-fatal — fall through to a fresh cache.\n }\n }\n\n return createExtractionCache({\n dir: cacheSettings.dir,\n pluginVersion: PLUGIN_VERSION,\n configHash: computeConfigHash({\n pages: config.pages,\n defaultLocale: config.defaultLocale,\n extractionScope: config.extractionScope ?? 'global',\n hookSources: config.hookSources,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\n }),\n debug: cacheSettings.debug,\n });\n}\n\nfunction persistCache(config: CliConfig, cache: ExtractionCache | undefined, rootDir: string): void {\n if (!cache) return;\n const cacheSettings = resolveCacheConfig(config.cache, { rootDir });\n if (cacheSettings.persist) {\n cache.persistToDisk();\n }\n}\n\nfunction runWalker(config: CliConfig, cache?: ExtractionCache): ProjectAnalysis {\n const { rootDir, localesDir, extractionScope } = resolveConfig(config);\n\n const analysis = walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n hookSources: config.hookSources,\n cache,\n });\n\n // Mirror the build plugin: apply declared dynamic keys and audit scope\n // registration so CLI-generated artifacts match `vite build` exactly.\n // Shared primitive, same semantics, no drift.\n if (config.dynamicKeys && config.dynamicKeys.length > 0) {\n const report = applyDynamicKeys(analysis, {\n dynamicKeys: config.dynamicKeys,\n dictionaries: config.dictionaries,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n for (const orphan of report.orphans) {\n console.warn(\n `[vite-bundled-i18n] dynamicKeys entry \"${orphan}\" matches no route ` +\n `and no dictionary — it won't ship anywhere.`,\n );\n }\n }\n\n const strictMode = config.strictScopeRegistration ?? 'warn';\n if (strictMode !== 'off') {\n const report = checkScopeRegistration(analysis, { rootDir, mode: strictMode });\n if (report.violations.length > 0) {\n if (strictMode === 'error') {\n throw new Error(\n 'vite-bundled-i18n: scope registration failures (strictScopeRegistration: \\'error\\'):\\n\\n' +\n report.messages.join('\\n\\n'),\n );\n }\n for (const message of report.messages) console.warn(message);\n }\n }\n\n return analysis;\n}\n\nfunction collectScopeNames(analysis: ProjectAnalysis): string[] {\n return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();\n}\n\n/**\n * Emit both the typed `.ts` (for TSC/IDE) and runtime `.js` (for Vite\n * resolve.alias) generated files. Called by every CLI command that\n * previously only wrote the `.ts` file — keeps CLI output aligned with\n * the Vite plugin's `emitGeneratedArtifacts` so there's no drift.\n */\nfunction emitGeneratedPair(\n analysis: ProjectAnalysis,\n config: CliConfig,\n localesDir: string,\n rootDir: string,\n typesOutPath: string,\n): void {\n const scopeNames = collectScopeNames(analysis);\n const scopeMap = buildScopeMap(analysis, {\n rootDir,\n defaultLocale: config.defaultLocale,\n dictionaries: config.dictionaries,\n });\n const pageScopeMap: Record<string, readonly string[]> = {};\n for (const [id, entry] of Object.entries(scopeMap.pages)) {\n pageScopeMap[id] = entry.scopes;\n }\n const hasPageMap = Object.keys(pageScopeMap).length > 0;\n writeTypes(\n localesDir,\n config.defaultLocale,\n typesOutPath,\n scopeNames,\n hasPageMap ? pageScopeMap : undefined,\n );\n writeRuntimeConst(\n runtimePathFromTypesPath(typesOutPath),\n hasPageMap ? pageScopeMap : undefined,\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 { rootDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, typesOutPath, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\n\n const bundles = generateBundles(analysis, {\n localesDir,\n locales: config.locales,\n outDir,\n crossNamespacePacking: config.crossNamespacePacking,\n });\n\n emitGeneratedPair(analysis, config, localesDir, rootDir, 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 { rootDir, outDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 { rootDir, outDir, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 crossNamespacePacking: config.crossNamespacePacking,\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 { rootDir, outDir, typesOutPath, localesDir } = resolveConfig(config);\n const cache = buildCliCache(config, rootDir);\n const analysis = runWalker(config, cache);\n persistCache(config, cache, rootDir);\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 crossNamespacePacking: config.crossNamespacePacking,\n });\n\n emitGeneratedPair(analysis, config, localesDir, rootDir, 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 crossNamespacePacking: config.crossNamespacePacking,\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> [options]');\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 console.log(' --no-cache Disable the extraction cache for this run');\n console.log(' --clear-cache Clear the extraction cache before running');\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\ninterface ParsedArgs {\n command: Command;\n configPath: string;\n noCache: boolean;\n clearCache: boolean;\n}\n\nfunction parseArgs(argv: string[]): ParsedArgs {\n const args = argv.slice(2);\n let command: Command | undefined;\n let configPath = 'i18n.config.json';\n let noCache = false;\n let clearCache = false;\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 === '--no-cache') {\n noCache = true;\n } else if (arg === '--clear-cache') {\n clearCache = true;\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, noCache, clearCache };\n}\n\nconst { command, configPath, noCache, clearCache } = parseArgs(process.argv);\nconst config = loadConfig(configPath);\n\n// CLI flags merge into the config's `cache` field so downstream resolution\n// sees them. Env vars still take the final word via resolveCacheConfig.\nif (noCache) {\n config.cache = false;\n}\nif (clearCache) {\n // Resolve-time handling: a CLI-driven clear is honored even when config\n // doesn't opt into the cache object form. We signal via an env var so\n // the central resolver is the single source of truth.\n process.env.VITE_I18N_CLEAR_CACHE = '1';\n}\n\nconst commands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AAK,IAAI,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;EACpC,MAAM,MAAM,KAAK;AACjB,MAAI,QAAQ,cAAc,IAAI,IAAI,KAAK,OACrC,cAAa,KAAK,EAAE;WACX,QAAQ,aACjB,WAAU;WACD,QAAQ,gBACjB,cAAa;WACJ,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;EAAS;EAAY;;AAG/D,IAAM,EAAE,SAAS,YAAY,SAAS,eAAe,UAAU,QAAQ,KAAK;AAC5E,IAAM,SAAS,WAAW,WAAW;AAIrC,IAAI,QACF,QAAO,QAAQ;AAEjB,IAAI,WAIF,SAAQ,IAAI,wBAAwB;CAGsB;CAC1D;CACA;CACA;CACA;CACA;CACD,EAEQ,SAAS,OAAO"}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createContext } from "react";
|
|
2
|
+
//#region src/react/context.ts
|
|
3
|
+
/**
|
|
4
|
+
* React context for the i18n instance.
|
|
5
|
+
*
|
|
6
|
+
* Provided by `I18nProvider`, consumed by `useI18n`.
|
|
7
|
+
* The default value is `null` — using `useI18n` outside of a provider
|
|
8
|
+
* will throw a descriptive error.
|
|
9
|
+
*/
|
|
10
|
+
var I18nContext = createContext(null);
|
|
11
|
+
//#endregion
|
|
12
|
+
export { I18nContext as t };
|
|
13
|
+
|
|
14
|
+
//# sourceMappingURL=context-B66VMNFr.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-B66VMNFr.js","names":[],"sources":["../src/react/context.ts"],"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 dictsReady: boolean;\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"],"mappings":";;;;;;;;;AAsBA,IAAa,cAAc,cAAuC,KAAK"}
|
package/dist/core/config.d.ts
CHANGED
|
@@ -56,6 +56,40 @@ export interface I18nSharedConfig {
|
|
|
56
56
|
* @default false
|
|
57
57
|
*/
|
|
58
58
|
crossNamespacePacking?: boolean;
|
|
59
|
+
/**
|
|
60
|
+
* After extraction, verify that every file matching the `pages` glob
|
|
61
|
+
* declares at least one `useI18n('<literal>')` scope. Files without
|
|
62
|
+
* a registered scope don't contribute to any scope bundle — their
|
|
63
|
+
* translation keys only work if covered by a dictionary, which is
|
|
64
|
+
* almost always a mistake.
|
|
65
|
+
*
|
|
66
|
+
* - `'off'` — no check
|
|
67
|
+
* - `'warn'` (default) — log a warning per offender via Vite's logger
|
|
68
|
+
* - `'error'` — throw during the build; fails CI
|
|
69
|
+
*/
|
|
70
|
+
strictScopeRegistration?: 'off' | 'warn' | 'error';
|
|
71
|
+
/**
|
|
72
|
+
* Fully qualified keys the extractor can't see from static `t()` calls —
|
|
73
|
+
* e.g. keys built from variables (`t.dynamic(\`status.\${state}\`)`) or
|
|
74
|
+
* keys resolved at runtime via a map.
|
|
75
|
+
*
|
|
76
|
+
* Each listed key is added to every route whose scope's primary
|
|
77
|
+
* namespace (or packed cross-ns extras namespace) matches the key's
|
|
78
|
+
* namespace. Dictionary-owned keys are skipped — dictionaries already
|
|
79
|
+
* guarantee global availability.
|
|
80
|
+
*
|
|
81
|
+
* Keys whose namespace matches no route and isn't dictionary-owned
|
|
82
|
+
* emit a build warning. A "dangling" dynamic key silently bloats
|
|
83
|
+
* nothing; flagging it forces the user to correct the config.
|
|
84
|
+
*
|
|
85
|
+
* @example
|
|
86
|
+
* ```ts
|
|
87
|
+
* bundling: {
|
|
88
|
+
* dynamicKeys: ['status.active', 'status.pending', 'status.failed'],
|
|
89
|
+
* }
|
|
90
|
+
* ```
|
|
91
|
+
*/
|
|
92
|
+
dynamicKeys?: readonly string[];
|
|
59
93
|
};
|
|
60
94
|
}
|
|
61
95
|
/**
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runtime shim for the `vite-bundled-i18n/generated` package export.
|
|
3
|
+
*
|
|
4
|
+
* This is a package-shipped placeholder with empty exports. It guarantees
|
|
5
|
+
* that `import { PAGE_SCOPE_MAP } from 'vite-bundled-i18n/generated'` always
|
|
6
|
+
* resolves at module-resolution time, even before the i18nPlugin has run
|
|
7
|
+
* for the first time.
|
|
8
|
+
*
|
|
9
|
+
* Real values come from `.i18n/i18n-generated.js` in the consumer project,
|
|
10
|
+
* written by the plugin's `buildStart` hook. The plugin also programmatically
|
|
11
|
+
* registers a Vite `resolve.alias` so that both dev and build resolve
|
|
12
|
+
* `vite-bundled-i18n/generated` directly to that file, bypassing this shim.
|
|
13
|
+
*
|
|
14
|
+
* Non-Vite consumers (raw Node scripts, tests that don't go through Vite)
|
|
15
|
+
* fall through to these empty defaults.
|
|
16
|
+
*/
|
|
17
|
+
/** @type {Readonly<Record<string, readonly string[]>>} */
|
|
18
|
+
export declare const PAGE_SCOPE_MAP: Readonly<{}>;
|