vite-bundled-i18n 0.5.0 → 0.6.1
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 +140 -5
- package/dist/cli/commands.d.ts +11 -0
- package/dist/cli/index.js +43 -4
- 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 +56 -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/dynamic-keys.d.ts +41 -0
- package/dist/extractor/scope-registration.d.ts +50 -0
- package/dist/extractor/type-generator.d.ts +29 -2
- package/dist/extractor/walker-types.d.ts +6 -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 +59 -0
- package/dist/plugin.js +246 -118
- 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-DFE3gpoU.js → scope-registration-C_nZD1Sa.js} +295 -4
- package/dist/scope-registration-C_nZD1Sa.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-DFE3gpoU.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
|
@@ -30,8 +30,13 @@ The Vite plugin parses your import graph, maps every `t()` / `useI18n()` / `i18n
|
|
|
30
30
|
|
|
31
31
|
- **Scope bundles** — each route loads only its own translations in one HTTP request
|
|
32
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
|
+
- **Readiness gate** — framework-agnostic `i18n.gate` tracks outstanding `loadScope()` calls; React `<GateBoundary>` / `useGate()` and Vue `useGate()` consume it directly. One primitive, zero consumer counters
|
|
34
|
+
- **`createScopeMapClient()`** — typed runtime client for the emitted scope-map, with in-flight dedup and generation-safe invalidation. Works in any router context
|
|
33
35
|
- **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
36
|
- **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
|
|
37
|
+
- **Lean dev bundles** — dev responses are tree-shaken by default (matches prod shape). ~10–20× smaller on large apps; opt-out via `bundling.dev.leanBundles: false`
|
|
38
|
+
- **`t.dynamic()` + `bundling.dynamicKeys`** — loose-typed escape hatch for runtime-computed keys, paired with a config list so declared dynamic keys actually ship
|
|
39
|
+
- **`vite-bundled-i18n/testing`** — `createTestI18n`, `I18nTestProvider`, `createI18nTestPlugin` — synchronous, network-free, ready-by-default for unit tests
|
|
35
40
|
- **Progressive autocomplete** — generated types let the IDE suggest one key segment at a time
|
|
36
41
|
|
|
37
42
|
### Also included
|
|
@@ -42,6 +47,7 @@ The Vite plugin parses your import graph, maps every `t()` / `useI18n()` / `i18n
|
|
|
42
47
|
- **Multi-framework** — React, Vue, vanilla JS share a single core
|
|
43
48
|
- **SSR** — server rendering with automatic client hydration via `window.__I18N_RESOURCES__`
|
|
44
49
|
- **AST extraction** — `t()`, `useI18n()`, `i18nKey()`, `defineI18nData()`, configurable `keyFields`, `as const` objects, string enums, helper functions that receive `t` as a parameter
|
|
50
|
+
- **Scope registration audit** — `bundling.strictScopeRegistration: 'off' | 'warn' | 'error'` catches routes that extract zero keys at build time
|
|
45
51
|
- **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
52
|
|
|
47
53
|
## Performance
|
|
@@ -51,7 +57,8 @@ The library is a performance play end-to-end. Representative numbers for a 50-pa
|
|
|
51
57
|
| | Traditional i18n | vite-bundled-i18n |
|
|
52
58
|
|---|---|---|
|
|
53
59
|
| Keys per page load | 3,000 (all) | 25–40 (route-extracted) |
|
|
54
|
-
|
|
|
60
|
+
| Scope bundle size (prod) | N/A (monolithic) | ~97% smaller than the source namespace |
|
|
61
|
+
| Scope bundle size (dev) | — | same as prod by default (lean bundles) |
|
|
55
62
|
| HTTP requests per route | many (or one huge) | 1 scope bundle + cached dictionaries |
|
|
56
63
|
| Cold dev start | — | ~200 ms |
|
|
57
64
|
| Warm dev start | — | ~250 ms (extraction cache keeps prior AST parses) |
|
|
@@ -63,6 +70,8 @@ The extraction cache persists to `.i18n/cache/` and auto-invalidates on plugin u
|
|
|
63
70
|
|
|
64
71
|
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.
|
|
65
72
|
|
|
73
|
+
Lean dev bundles tree-shake each scope response to the keys the route actually extracted — same shape as the production build. On a 50-page admin, dev scope responses drop from ~140 kB to ~8 kB. Opt out via `bundling.dev.leanBundles: false` if you want the v0.6.0 full-namespace behavior.
|
|
74
|
+
|
|
66
75
|
## Setup
|
|
67
76
|
|
|
68
77
|
Three files wire everything together:
|
|
@@ -165,6 +174,31 @@ function ProductsPage() {
|
|
|
165
174
|
|
|
166
175
|
**`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`.
|
|
167
176
|
|
|
177
|
+
**`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.
|
|
178
|
+
|
|
179
|
+
```tsx
|
|
180
|
+
// Pattern A — page registers its own scope
|
|
181
|
+
function ProductsPage() {
|
|
182
|
+
const { t } = useI18n('products.show') // loads products.show bundle
|
|
183
|
+
return <section><Header /><Details /></section>
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Pattern B — page composes children; each child declares its own scope
|
|
187
|
+
function AdminPage() {
|
|
188
|
+
return <><Sidebar /><MainContent /></> // no scope at the page level
|
|
189
|
+
}
|
|
190
|
+
function Sidebar() {
|
|
191
|
+
const { t } = useI18n('sidebar.admin') // child registers
|
|
192
|
+
return <nav>{t('sidebar.admin.heading')}</nav>
|
|
193
|
+
}
|
|
194
|
+
function MainContent() {
|
|
195
|
+
const { t } = useI18n() // reads whatever's loaded
|
|
196
|
+
return <main>{t('sidebar.admin.welcome')}</main>
|
|
197
|
+
}
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
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.
|
|
201
|
+
|
|
168
202
|
**`I18nBoundary`** handles scope loading without early returns:
|
|
169
203
|
|
|
170
204
|
```tsx
|
|
@@ -225,6 +259,53 @@ i18nPlugin(config, {
|
|
|
225
259
|
|
|
226
260
|
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.
|
|
227
261
|
|
|
262
|
+
For pure runtime access without tying into the plugin's type generation, `createScopeMapClient()` is the framework-agnostic fetcher:
|
|
263
|
+
|
|
264
|
+
```ts
|
|
265
|
+
import { createScopeMapClient } from 'vite-bundled-i18n'
|
|
266
|
+
|
|
267
|
+
const scopeMap = createScopeMapClient()
|
|
268
|
+
await scopeMap.load()
|
|
269
|
+
scopeMap.getSync('products/show') // ['products.show']
|
|
270
|
+
```
|
|
271
|
+
|
|
272
|
+
Dedupes concurrent `load()` calls, invalidation during an in-flight fetch is generation-safe, and the default URL honors the plugin-injected base path so Laravel / subdirectory deploys work without wiring.
|
|
273
|
+
|
|
274
|
+
## Readiness gate
|
|
275
|
+
|
|
276
|
+
`i18n.gate` is a framework-agnostic primitive that tracks outstanding `loadScope()` calls. Every scope load auto-registers; when all settle, the gate flips back to ready. React and Vue adapters read it directly — no consumer counter needed.
|
|
277
|
+
|
|
278
|
+
```tsx
|
|
279
|
+
import { GateBoundary, useGate } from 'vite-bundled-i18n/react'
|
|
280
|
+
|
|
281
|
+
// Children always mounted; fallback overlays while loading.
|
|
282
|
+
<GateBoundary fallback={<LoadingBar />}>
|
|
283
|
+
<App />
|
|
284
|
+
</GateBoundary>
|
|
285
|
+
|
|
286
|
+
// Or read the state manually.
|
|
287
|
+
function Indicator() {
|
|
288
|
+
const { ready, pendingCount } = useGate()
|
|
289
|
+
if (ready) return null
|
|
290
|
+
return <Spinner label={`Loading ${pendingCount} scope(s)…`} />
|
|
291
|
+
}
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Vue exposes the same shape:
|
|
295
|
+
|
|
296
|
+
```ts
|
|
297
|
+
import { useGate } from 'vite-bundled-i18n/vue'
|
|
298
|
+
const { ready, pendingCount } = useGate()
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
**Breaking in v0.6.0:** `loadScope()` now auto-tracks the gate by default. Apps that kept their own readiness counters should remove them. Per-call opt-out:
|
|
302
|
+
|
|
303
|
+
```ts
|
|
304
|
+
await i18n.loadScope(locale, scope, { trackReadiness: false })
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
The primitive is designed to be authoritative — no feature-flag softening. See [API docs — Readiness gate](./docs/api.md#readiness-gate).
|
|
308
|
+
|
|
228
309
|
## Vue
|
|
229
310
|
|
|
230
311
|
```ts
|
|
@@ -267,6 +348,23 @@ translations.tryGet('shared.ok') // undefined on miss (no fal
|
|
|
267
348
|
translations.require('shared.ok') // throws on miss
|
|
268
349
|
translations.namespace('global').get('nav.home') // namespace-scoped access
|
|
269
350
|
translations.forLocale('bg').get('shared.ok') // cross-locale lookup
|
|
351
|
+
|
|
352
|
+
t.dynamic(`status.${state}`) // escape hatch — loose-typed
|
|
353
|
+
t.dynamic(`status.${state}`, 'Unknown') // same overloads as t()
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
`t.dynamic(key)` accepts any string, bypassing the typed `TranslationKey` union. Identical runtime to `t()` — only the type contract differs. Use for keys assembled from variables. Pair with `bundling.dynamicKeys` so declared runtime keys actually ship:
|
|
357
|
+
|
|
358
|
+
```ts
|
|
359
|
+
defineI18nConfig({
|
|
360
|
+
localesDir: 'locales',
|
|
361
|
+
bundling: {
|
|
362
|
+
// Each key is injected into every route whose scope primary namespace
|
|
363
|
+
// matches. Dictionary-owned keys are skipped; orphans (no matching
|
|
364
|
+
// route, no dictionary) emit a build warning.
|
|
365
|
+
dynamicKeys: ['status.active', 'status.pending', 'status.failed'],
|
|
366
|
+
},
|
|
367
|
+
})
|
|
270
368
|
```
|
|
271
369
|
|
|
272
370
|
## Dictionaries
|
|
@@ -417,17 +515,54 @@ cache: {
|
|
|
417
515
|
}
|
|
418
516
|
```
|
|
419
517
|
|
|
518
|
+
## Testing
|
|
519
|
+
|
|
520
|
+
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:
|
|
521
|
+
|
|
522
|
+
```ts
|
|
523
|
+
import { createTestI18n, I18nTestProvider } from 'vite-bundled-i18n/testing'
|
|
524
|
+
import { render, screen } from '@testing-library/react'
|
|
525
|
+
|
|
526
|
+
const i18n = createTestI18n({
|
|
527
|
+
translations: {
|
|
528
|
+
shared: { ok: 'OK' },
|
|
529
|
+
products: { show: { title: 'Details' } },
|
|
530
|
+
},
|
|
531
|
+
})
|
|
532
|
+
|
|
533
|
+
render(
|
|
534
|
+
<I18nTestProvider instance={i18n}>
|
|
535
|
+
<MyComponent />
|
|
536
|
+
</I18nTestProvider>,
|
|
537
|
+
)
|
|
538
|
+
```
|
|
539
|
+
|
|
540
|
+
Options:
|
|
541
|
+
|
|
542
|
+
- `locale` — default `'en'`
|
|
543
|
+
- `defaultLocale` — default: same as `locale`
|
|
544
|
+
- `supportedLocales` — default: `[locale]`
|
|
545
|
+
- `passthroughMissing` — default `true`. Set `false` to have missing keys throw, turning "I forgot to seed" into a hard test failure instead of a silent key-as-value.
|
|
546
|
+
|
|
547
|
+
Vue equivalent:
|
|
548
|
+
|
|
549
|
+
```ts
|
|
550
|
+
import { createI18nTestPlugin } from 'vite-bundled-i18n/testing'
|
|
551
|
+
app.use(createI18nTestPlugin(i18n))
|
|
552
|
+
```
|
|
553
|
+
|
|
420
554
|
## Package Entries
|
|
421
555
|
|
|
422
556
|
| Entry | Purpose |
|
|
423
557
|
|-------|---------|
|
|
424
|
-
| `vite-bundled-i18n` | Core runtime, config helpers,
|
|
425
|
-
| `vite-bundled-i18n/react` | `I18nProvider`, `useI18n`, `I18nBoundary`, `DevToolbar` |
|
|
426
|
-
| `vite-bundled-i18n/vue` | `createI18nPlugin`, `useI18n` |
|
|
558
|
+
| `vite-bundled-i18n` | Core runtime, config helpers, `createReadinessGate`, `createScopeMapClient` |
|
|
559
|
+
| `vite-bundled-i18n/react` | `I18nProvider`, `useI18n`, `I18nBoundary`, `GateBoundary`, `useGate`, `DevToolbar` |
|
|
560
|
+
| `vite-bundled-i18n/vue` | `createI18nPlugin`, `useI18n`, `useGate` |
|
|
427
561
|
| `vite-bundled-i18n/vanilla` | `getTranslations`, `initI18n` |
|
|
428
562
|
| `vite-bundled-i18n/server` | `initServerI18n` (SSR) |
|
|
429
563
|
| `vite-bundled-i18n/plugin` | Vite plugin (`i18nPlugin`) |
|
|
430
564
|
| `vite-bundled-i18n/generated` | Generated types + `PAGE_SCOPE_MAP` / `I18nPageIdentifier` |
|
|
565
|
+
| `vite-bundled-i18n/testing` | `createTestI18n`, `I18nTestProvider`, `createI18nTestPlugin` |
|
|
431
566
|
|
|
432
567
|
## Documentation
|
|
433
568
|
|
|
@@ -437,7 +572,7 @@ cache: {
|
|
|
437
572
|
|
|
438
573
|
## Releases
|
|
439
574
|
|
|
440
|
-
Current release: **v0.
|
|
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 }`.
|
|
441
576
|
|
|
442
577
|
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.
|
|
443
578
|
|
package/dist/cli/commands.d.ts
CHANGED
|
@@ -26,6 +26,17 @@ 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';
|
|
29
40
|
/**
|
|
30
41
|
* Extraction cache control. `false` disables, an object configures the
|
|
31
42
|
* backing directory and persistence. Env vars (`VITE_I18N_NO_CACHE`,
|
package/dist/cli/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import { a as createExtractionCache,
|
|
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-C_nZD1Sa.js";
|
|
3
3
|
import fs from "node:fs";
|
|
4
4
|
import path from "node:path";
|
|
5
5
|
//#region src/cli/commands.ts
|
|
@@ -43,7 +43,7 @@ function persistCache(config, cache, rootDir) {
|
|
|
43
43
|
}
|
|
44
44
|
function runWalker(config, cache) {
|
|
45
45
|
const { rootDir, localesDir, extractionScope } = resolveConfig(config);
|
|
46
|
-
|
|
46
|
+
const analysis = walkAll({
|
|
47
47
|
pages: config.pages,
|
|
48
48
|
rootDir,
|
|
49
49
|
localesDir,
|
|
@@ -52,11 +52,50 @@ function runWalker(config, cache) {
|
|
|
52
52
|
hookSources: config.hookSources,
|
|
53
53
|
cache
|
|
54
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;
|
|
55
75
|
}
|
|
56
76
|
function collectScopeNames(analysis) {
|
|
57
77
|
return [...new Set(analysis.routes.flatMap((route) => route.scopes))].sort();
|
|
58
78
|
}
|
|
59
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
|
+
/**
|
|
60
99
|
* Pad a string to the given width.
|
|
61
100
|
*/
|
|
62
101
|
function pad(str, width) {
|
|
@@ -120,7 +159,7 @@ function generate(config) {
|
|
|
120
159
|
outDir,
|
|
121
160
|
crossNamespacePacking: config.crossNamespacePacking
|
|
122
161
|
});
|
|
123
|
-
|
|
162
|
+
emitGeneratedPair(analysis, config, localesDir, rootDir, typesOutPath);
|
|
124
163
|
console.log(`Generated ${bundles.length} bundle(s):`);
|
|
125
164
|
for (const b of bundles) console.log(` ${b.locale}/${b.name} — ${b.keyCount} keys (${b.prunedCount} pruned)`);
|
|
126
165
|
console.log(`Types written to ${typesOutPath}`);
|
|
@@ -192,7 +231,7 @@ function build(config) {
|
|
|
192
231
|
outDir,
|
|
193
232
|
crossNamespacePacking: config.crossNamespacePacking
|
|
194
233
|
});
|
|
195
|
-
|
|
234
|
+
emitGeneratedPair(analysis, config, localesDir, rootDir, typesOutPath);
|
|
196
235
|
console.log(`\nGenerated ${bundles.length} bundle(s)`);
|
|
197
236
|
console.log(`Types written to ${typesOutPath}`);
|
|
198
237
|
const compiledOutDir = path.join(outDir, "compiled");
|
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 fs from 'node:fs';\nimport 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';\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';\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 * 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 return walkAll({\n pages: config.pages,\n rootDir,\n localesDir,\n defaultLocale: config.defaultLocale,\n extractionScope,\n hookSources: config.hookSources,\n cache,\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 { 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 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 { 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 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> [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: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};\n\ncommands[command](config);\n"],"mappings":";;;;;AAyDA,SAAS,cAAc,QAAmB;CACxC,MAAM,UAAU,OAAO,WAAW,QAAQ,KAAK;CAC/C,MAAM,SAAS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AAO,KAAK,MAAM,EAAE;CAC1B,IAAI;CACJ,IAAI,aAAa;CACjB,IAAI,UAAU;CACd,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,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"}
|
|
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: Record<Command, (cfg: CliConfig) => void> = {\n analyze,\n generate,\n compile,\n report,\n build,\n};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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,62 @@ 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[];
|
|
93
|
+
/** Dev-server bundle shape. Build output is always tree-shaken. */
|
|
94
|
+
dev?: {
|
|
95
|
+
/**
|
|
96
|
+
* Tree-shake dev bundles using the walker's extraction data.
|
|
97
|
+
*
|
|
98
|
+
* When `true` (default), each dev scope-bundle response contains only
|
|
99
|
+
* the keys the route's AST extraction found — same shape as the
|
|
100
|
+
* production build. Matches prod semantics and keeps per-scope payloads
|
|
101
|
+
* small on large apps (typically 10× to 20× smaller than the full
|
|
102
|
+
* namespace).
|
|
103
|
+
*
|
|
104
|
+
* When `false`, falls back to the v0.6.0 behavior of shipping the
|
|
105
|
+
* whole namespace (plus any full cross-ns extras). Kept for escape
|
|
106
|
+
* hatch — properly-structured apps should leave the default on.
|
|
107
|
+
*
|
|
108
|
+
* Falls back to full namespaces automatically when `options.pages`
|
|
109
|
+
* isn't configured (no analysis available).
|
|
110
|
+
*
|
|
111
|
+
* @default true
|
|
112
|
+
*/
|
|
113
|
+
leanBundles?: boolean;
|
|
114
|
+
};
|
|
59
115
|
};
|
|
60
116
|
}
|
|
61
117
|
/**
|
|
@@ -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<{}>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/core/i18n-generated-shim.ts
|
|
2
|
+
/**
|
|
3
|
+
* Runtime shim for the `vite-bundled-i18n/generated` package export.
|
|
4
|
+
*
|
|
5
|
+
* This is a package-shipped placeholder with empty exports. It guarantees
|
|
6
|
+
* that `import { PAGE_SCOPE_MAP } from 'vite-bundled-i18n/generated'` always
|
|
7
|
+
* resolves at module-resolution time, even before the i18nPlugin has run
|
|
8
|
+
* for the first time.
|
|
9
|
+
*
|
|
10
|
+
* Real values come from `.i18n/i18n-generated.js` in the consumer project,
|
|
11
|
+
* written by the plugin's `buildStart` hook. The plugin also programmatically
|
|
12
|
+
* registers a Vite `resolve.alias` so that both dev and build resolve
|
|
13
|
+
* `vite-bundled-i18n/generated` directly to that file, bypassing this shim.
|
|
14
|
+
*
|
|
15
|
+
* Non-Vite consumers (raw Node scripts, tests that don't go through Vite)
|
|
16
|
+
* fall through to these empty defaults.
|
|
17
|
+
*/
|
|
18
|
+
/** @type {Readonly<Record<string, readonly string[]>>} */
|
|
19
|
+
var PAGE_SCOPE_MAP = Object.freeze({});
|
|
20
|
+
//#endregion
|
|
21
|
+
export { PAGE_SCOPE_MAP };
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=i18n-generated-shim.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"i18n-generated-shim.js","names":[],"sources":["../../src/core/i18n-generated-shim.ts"],"sourcesContent":["/**\n * Runtime shim for the `vite-bundled-i18n/generated` package export.\n *\n * This is a package-shipped placeholder with empty exports. It guarantees\n * that `import { PAGE_SCOPE_MAP } from 'vite-bundled-i18n/generated'` always\n * resolves at module-resolution time, even before the i18nPlugin has run\n * for the first time.\n *\n * Real values come from `.i18n/i18n-generated.js` in the consumer project,\n * written by the plugin's `buildStart` hook. The plugin also programmatically\n * registers a Vite `resolve.alias` so that both dev and build resolve\n * `vite-bundled-i18n/generated` directly to that file, bypassing this shim.\n *\n * Non-Vite consumers (raw Node scripts, tests that don't go through Vite)\n * fall through to these empty defaults.\n */\n\n/** @type {Readonly<Record<string, readonly string[]>>} */\nexport const PAGE_SCOPE_MAP = Object.freeze({});\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,IAAa,iBAAiB,OAAO,OAAO,EAAE,CAAC"}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Framework-agnostic runtime client for the `scope-map.json` artifact
|
|
3
|
+
* emitted by the Vite plugin / dev middleware.
|
|
4
|
+
*
|
|
5
|
+
* Consumers use this alongside their router's async resolve hook to
|
|
6
|
+
* parallelize scope loading with component resolution:
|
|
7
|
+
*
|
|
8
|
+
* ```ts
|
|
9
|
+
* import { createScopeMapClient } from 'vite-bundled-i18n';
|
|
10
|
+
* import { i18n } from './i18n';
|
|
11
|
+
*
|
|
12
|
+
* const scopeMap = createScopeMapClient();
|
|
13
|
+
*
|
|
14
|
+
* router.beforeResolve(async (to, from, next) => {
|
|
15
|
+
* const [scopes] = await Promise.all([
|
|
16
|
+
* scopeMap.get(to.name as string),
|
|
17
|
+
* to.meta.loadComponent?.(),
|
|
18
|
+
* ]);
|
|
19
|
+
* await Promise.all(scopes.map((s) => i18n.loadScope(i18n.getLocale(), s)));
|
|
20
|
+
* next();
|
|
21
|
+
* });
|
|
22
|
+
* ```
|
|
23
|
+
*
|
|
24
|
+
* The client keeps an in-memory cache. `load()` is idempotent — concurrent
|
|
25
|
+
* calls share a single fetch. `invalidate()` clears the cache so the next
|
|
26
|
+
* access re-fetches.
|
|
27
|
+
*/
|
|
28
|
+
export interface ScopeMapPageEntryRuntime {
|
|
29
|
+
readonly scopes: readonly string[];
|
|
30
|
+
readonly dictionaries: readonly string[];
|
|
31
|
+
}
|
|
32
|
+
export interface ScopeMapFileRuntime {
|
|
33
|
+
readonly version: number;
|
|
34
|
+
readonly defaultLocale: string;
|
|
35
|
+
readonly pages: Readonly<Record<string, ScopeMapPageEntryRuntime>>;
|
|
36
|
+
}
|
|
37
|
+
export interface CreateScopeMapClientOptions {
|
|
38
|
+
/** Static URL override. Defaults to `/__i18n/scope-map.json`. */
|
|
39
|
+
url?: string;
|
|
40
|
+
/**
|
|
41
|
+
* Dynamic URL resolver. Called on every `load()` — use this when the URL
|
|
42
|
+
* depends on runtime state (e.g. an authenticated tenant id, a deploy
|
|
43
|
+
* channel). Overrides `url` when provided.
|
|
44
|
+
*/
|
|
45
|
+
resolveUrl?: () => string;
|
|
46
|
+
/**
|
|
47
|
+
* Custom `fetch` implementation. Defaults to `globalThis.fetch`. Tests
|
|
48
|
+
* inject a mock; SSR layers inject a server-side fetch.
|
|
49
|
+
*/
|
|
50
|
+
fetchImpl?: typeof fetch;
|
|
51
|
+
}
|
|
52
|
+
export interface ScopeMapClient {
|
|
53
|
+
/**
|
|
54
|
+
* Return the scope list for `pageId`. Triggers a load if the map isn't
|
|
55
|
+
* cached yet; subsequent calls resolve from memory. Unknown page ids
|
|
56
|
+
* resolve to an empty array — the caller decides whether that's an error.
|
|
57
|
+
*/
|
|
58
|
+
get(pageId: string): Promise<readonly string[]>;
|
|
59
|
+
/**
|
|
60
|
+
* Synchronous lookup. Returns the scope list if the map is already loaded,
|
|
61
|
+
* otherwise `null`. Use this when you can tolerate a miss (e.g. in a
|
|
62
|
+
* render path that also calls `load()` elsewhere).
|
|
63
|
+
*/
|
|
64
|
+
getSync(pageId: string): readonly string[] | null;
|
|
65
|
+
/**
|
|
66
|
+
* Fetch the scope-map once (concurrent callers share the in-flight
|
|
67
|
+
* promise). A second call after a successful load is a no-op.
|
|
68
|
+
*/
|
|
69
|
+
load(): Promise<void>;
|
|
70
|
+
/** Clear the in-memory cache so the next access re-fetches. */
|
|
71
|
+
invalidate(): void;
|
|
72
|
+
/** `true` once `load()` has completed successfully. */
|
|
73
|
+
isLoaded(): boolean;
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Create a new {@link ScopeMapClient}. Safe to instantiate multiple times;
|
|
77
|
+
* each instance keeps its own cache.
|
|
78
|
+
*/
|
|
79
|
+
export declare function createScopeMapClient(options?: CreateScopeMapClientOptions): ScopeMapClient;
|