vite-bundled-i18n 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,55 +1,29 @@
1
1
  # vite-bundled-i18n
2
2
 
3
- Route-aware i18n for Vite apps.
4
-
5
- It gives you:
6
-
7
- - one translator API across React and non-React code
8
- - named dictionaries with ownership and priority
9
- - scope bundles for pages like `products.index`
10
- - generated key and placeholder types
11
- - production `__i18n/...` assets emitted by Vite
12
- - optional compiled-map runtime loading in production
13
-
14
- ## Install
15
-
16
- Requirements:
17
-
18
- - Node `>=20`
19
- - a Vite app for plugin/build integration
20
- - `react` and `react-dom` only if you use the React adapter
21
-
22
- ```bash
23
- npm install vite-bundled-i18n
24
- ```
25
-
26
- If you use React:
3
+ Route-aware internationalization for Vite. Each page loads only the translations it uses. Keys are fully typed. Production builds emit static, scope-matched bundles.
27
4
 
28
5
  ```bash
29
- npm install react react-dom
6
+ npm i vite-bundled-i18n
30
7
  ```
31
8
 
32
- If you use Vue:
9
+ Requires Node `>=20` and Vite. React, Vue, and vanilla adapters are included — framework peer dependencies are optional.
33
10
 
34
- ```bash
35
- npm install vue
36
- ```
11
+ ## Features
37
12
 
38
- For local package validation:
13
+ - **Scope bundles** — translations grouped by route (`products.index`) and loaded on demand
14
+ - **Dictionary ownership** — named dictionaries claim keys by pattern with explicit priority
15
+ - **Type generation** — TypeScript types for every key and placeholder, generated from source
16
+ - **Compiled production output** — Vite plugin emits `__i18n/` assets as static JSON or compiled modules
17
+ - **Multi-framework** — React, Vue, and vanilla JS share a single core
18
+ - **SSR** — server-side rendering with automatic client hydration
19
+ - **AST extraction** — finds translation keys in source without execution
39
20
 
40
- ```bash
41
- # in this repo
42
- npm run build
43
- npm pack
44
-
45
- # in your app
46
- npm install /absolute/path/to/vite-bundled-i18n-0.1.0.tgz
47
- ```
21
+ ## Setup
48
22
 
49
- ## Quick Start
23
+ Three files wire everything together: a config that declares your locale directory and dictionaries (bundles that group related keys under a name, like `global` for shared UI strings), a runtime instance that holds locale state, and a Vite plugin that handles extraction, type generation, and bundle emission.
50
24
 
51
25
  ```ts
52
- // src/i18n.config.ts
26
+ // src/i18n.config.ts — declares dictionaries and where locale JSON files live
53
27
  import { defineI18nConfig } from 'vite-bundled-i18n'
54
28
 
55
29
  export const i18nConfig = defineI18nConfig({
@@ -65,7 +39,7 @@ export const i18nConfig = defineI18nConfig({
65
39
  ```
66
40
 
67
41
  ```ts
68
- // src/i18n.ts
42
+ // src/i18n.ts — runtime instance used by adapters and server code
69
43
  import { createI18n } from 'vite-bundled-i18n'
70
44
  import { i18nConfig } from './i18n.config'
71
45
 
@@ -79,7 +53,7 @@ export const i18n = createI18n({
79
53
  ```
80
54
 
81
55
  ```ts
82
- // vite.config.ts
56
+ // vite.config.ts — plugin scans pages, extracts keys, emits bundles and types
83
57
  import { defineConfig } from 'vite'
84
58
  import react from '@vitejs/plugin-react'
85
59
  import { i18nPlugin } from 'vite-bundled-i18n/plugin'
@@ -99,6 +73,8 @@ export default defineConfig({
99
73
  })
100
74
  ```
101
75
 
76
+ ### React
77
+
102
78
  ```tsx
103
79
  // src/main.tsx
104
80
  import { createRoot } from 'react-dom/client'
@@ -117,20 +93,22 @@ createRoot(document.getElementById('root')!).render(
117
93
  import { useI18n } from 'vite-bundled-i18n/react'
118
94
 
119
95
  export function ProductsPage() {
96
+ // t and translations.get are interchangeable — t is a shorthand alias.
97
+ // Both accept a key, optional placeholders, and an optional fallback string.
120
98
  const { t, translations, ready } = useI18n('products.index')
121
99
 
122
100
  if (!ready) return <div>{t('shared.loading', 'Loading...')}</div>
123
101
 
124
102
  return (
125
103
  <section>
126
- <h1>{translations.get('products.index.heading', 'All Products')}</h1>
104
+ <h1>{t('products.index.heading', 'All Products')}</h1>
127
105
  <p>{t('products.index.subheading', { count: 24 }, 'Browse {{count}} items')}</p>
128
106
  </section>
129
107
  )
130
108
  }
131
109
  ```
132
110
 
133
- ### Vue Quick Start
111
+ ### Vue
134
112
 
135
113
  ```ts
136
114
  import { createApp } from 'vue'
@@ -142,9 +120,9 @@ app.use(createI18nPlugin(i18n))
142
120
  app.mount('#app')
143
121
  ```
144
122
 
145
- ## Public API Shape
123
+ ## API
146
124
 
147
- The main API is the translator object:
125
+ The translator object returned by `useI18n` (React), `useI18n` (Vue), or `getTranslations` (vanilla):
148
126
 
149
127
  ```ts
150
128
  const translations = await getTranslations(i18n, 'products.index')
@@ -156,48 +134,20 @@ translations.has('actions.save')
156
134
  translations.namespace('global').get('nav.home')
157
135
  ```
158
136
 
159
- React returns the same shape plus top-level aliases:
160
-
161
- ```ts
162
- const { t, get, has, tryGet, require, translations, ready, locale } = useI18n()
163
- ```
164
-
165
- Package entries:
166
-
167
- - `vite-bundled-i18n`
168
- - `vite-bundled-i18n/react`
169
- - `vite-bundled-i18n/vanilla`
170
- - `vite-bundled-i18n/vue`
171
- - `vite-bundled-i18n/server`
172
- - `vite-bundled-i18n/plugin`
173
-
174
- ## Data Files
175
-
176
- For data/config code, keep keys in data and resolve later:
177
-
178
- ```ts
179
- import { defineI18nData, i18nKey } from 'vite-bundled-i18n'
180
-
181
- export const nav = defineI18nData([
182
- { href: '/', labelKey: i18nKey('global.nav.home') },
183
- { href: '/cart', labelKey: i18nKey('global.nav.cart') },
184
- ])
185
- ```
186
-
187
- The extractor understands these helpers.
188
-
189
- Avoid module-top-level eager translation:
137
+ ### Package Entries
190
138
 
191
- ```ts
192
- // Avoid
193
- export const nav = [{ label: t('global.nav.home') }]
194
- ```
195
-
196
- Store keys in data and resolve them later.
139
+ | Entry | Purpose |
140
+ |-------|---------|
141
+ | `vite-bundled-i18n` | Core runtime and configuration |
142
+ | `vite-bundled-i18n/react` | React adapter (`I18nProvider`, `useI18n`) |
143
+ | `vite-bundled-i18n/vue` | Vue adapter (`createI18nPlugin`, `useI18n`) |
144
+ | `vite-bundled-i18n/vanilla` | Framework-agnostic `getTranslations` |
145
+ | `vite-bundled-i18n/server` | SSR utilities (`initServerI18n`) |
146
+ | `vite-bundled-i18n/plugin` | Vite build plugin |
197
147
 
198
148
  ## Dictionaries
199
149
 
200
- Dictionaries are key-ownership rules, not component-file ownership rules:
150
+ Dictionaries define key ownership — which translation keys belong to which bundle:
201
151
 
202
152
  ```ts
203
153
  dictionaries: {
@@ -213,39 +163,53 @@ dictionaries: {
213
163
  }
214
164
  ```
215
165
 
216
- Notes:
166
+ - `include` accepts exact keys, namespace wildcards, and prefix patterns
167
+ - Higher priority dictionaries claim keys first; lower priority dictionaries exclude already-owned keys
168
+ - Pinned dictionaries remain in memory and are never evicted
169
+
170
+ ## Data Files
171
+
172
+ For configuration or navigation data that references translation keys, use the extraction helpers:
173
+
174
+ ```ts
175
+ import { defineI18nData, i18nKey } from 'vite-bundled-i18n'
176
+
177
+ export const nav = defineI18nData([
178
+ { href: '/', labelKey: i18nKey('global.nav.home') },
179
+ { href: '/cart', labelKey: i18nKey('global.nav.cart') },
180
+ ])
181
+ ```
217
182
 
218
- - `include` supports exact keys, namespace wildcards, and prefix patterns
219
- - higher priority dictionaries claim keys first
220
- - lower priority dictionaries exclude already-owned keys
221
- - legacy `keys: ['shared']` is still supported
183
+ The AST extractor recognizes these helpers and includes referenced keys in scope analysis.
222
184
 
223
- ## Server / SSR
185
+ ## Server-Side Rendering
224
186
 
225
187
  ```ts
226
188
  import { initServerI18n } from 'vite-bundled-i18n/server'
227
189
 
228
190
  const { translations, scriptTag } = await initServerI18n(config, 'products.show')
229
191
  const html = renderToString(<App translations={translations} />)
230
- // Inject scriptTag into HTML
192
+ // Inject scriptTag into the HTML response
231
193
  ```
232
194
 
233
- On the client, both `I18nProvider` (React) and `createI18nPlugin` (Vue) automatically detect and consume `window.__I18N_RESOURCES__` — no manual wiring needed.
195
+ The React `I18nProvider` and Vue `createI18nPlugin` automatically detect and consume the injected `window.__I18N_RESOURCES__` on the client.
234
196
 
235
197
  ## Production Output
236
198
 
237
199
  During `vite build`, the plugin emits:
238
200
 
239
- - `__i18n/{locale}/_dict/{name}.json`
240
- - `__i18n/{locale}/{scope}.json`
241
- - `__i18n/compiled/manifest.js`
242
- - `__i18n/compiled/{locale}/...` compiled map modules
201
+ ```
202
+ __i18n/{locale}/_dict/{name}.json
203
+ __i18n/{locale}/{scope}.json
204
+ __i18n/compiled/manifest.js
205
+ __i18n/compiled/{locale}/...
206
+ ```
243
207
 
244
- The runtime can use emitted JSON bundles or the compiled manifest path automatically in production.
208
+ The runtime resolves these assets automatically in production — no additional configuration required.
245
209
 
246
210
  ## Fetch Options
247
211
 
248
- Configure `requestInit` on `createI18n()` to set headers, credentials, or cache mode:
212
+ Configure request behavior for translation loading:
249
213
 
250
214
  ```ts
251
215
  createI18n({
@@ -254,18 +218,11 @@ createI18n({
254
218
  })
255
219
  ```
256
220
 
257
- Supports static objects, sync functions, and async functions for dynamic auth tokens.
221
+ Accepts a static `RequestInit` object, a sync function, or an async function for dynamic auth tokens.
258
222
 
259
223
  ## Cache
260
224
 
261
- The runtime stores translations in memory by namespace.
262
-
263
- - dictionaries can be pinned
264
- - repeated scope and dictionary loads are deduplicated
265
- - non-pinned namespaces can be evicted with LRU policy
266
- - fallback locale lookup still applies
267
-
268
- Example:
225
+ In-memory translation cache with configurable eviction:
269
226
 
270
227
  ```ts
271
228
  cache: {
@@ -278,45 +235,13 @@ cache: {
278
235
  }
279
236
  ```
280
237
 
281
- ## Release Flow
282
-
283
- Recommended local release sequence:
284
-
285
- ```bash
286
- npm run lint
287
- npm test
288
- npm run build
289
- npm pack
290
- ```
291
-
292
- Publish:
293
-
294
- ```bash
295
- npm publish
296
- ```
297
-
298
- ## Docs
238
+ ## Documentation
299
239
 
300
240
  - [Getting Started](./docs/getting-started.md)
301
241
  - [API Reference](./docs/api.md)
302
242
  - [Architecture](./docs/architecture.md)
303
243
  - [Examples](./docs/examples.md)
304
244
 
305
- ## Repo Demo
306
-
307
- The root Vite app in `src/` is also the reference demo for this package.
308
-
309
- Run:
310
-
311
- ```bash
312
- npm install
313
- npm run dev
314
- ```
315
-
316
- Build:
317
-
318
- ```bash
319
- npm run build
320
- ```
245
+ ## License
321
246
 
322
- That emits the demo app to `demo-dist/` and the generated translation assets to `demo-dist/__i18n/`.
247
+ [MIT](./LICENSE)
package/dist/cli/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-DqlV3VrX.js";
2
+ import { a as writeTypes, i as generateReports, n as compileAll, r as flattenLocaleKeys, s as generateBundles, t as walkAll } from "../walker-Bf9fpAPX.js";
3
3
  import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  //#region src/cli/commands.ts
@@ -1,5 +1,5 @@
1
1
  import type { NestedTranslations } from './types';
2
2
  export declare function buildLoadPath(localesDir: string, locale: string, namespace: string): string;
3
- export declare function buildBundlePath(locale: string, bundleName: string): string;
3
+ export declare function buildBundlePath(base: string, locale: string, bundleName: string): string;
4
4
  export declare function fetchNamespace(localesDir: string, locale: string, namespace: string, requestInit?: RequestInit): Promise<NestedTranslations>;
5
- export declare function fetchBundle(locale: string, bundleName: string, requestInit?: RequestInit): Promise<Record<string, NestedTranslations>>;
5
+ export declare function fetchBundle(base: string, locale: string, bundleName: string, requestInit?: RequestInit): Promise<Record<string, NestedTranslations>>;
@@ -47,6 +47,24 @@ export interface I18nKeyMap {
47
47
  */
48
48
  export interface I18nParamsMap {
49
49
  }
50
+ /**
51
+ * Augmentable interface for nested key structure.
52
+ * Enables progressive autocomplete: typing `t('feedback.` suggests
53
+ * `pages`, `actions`, etc. as next segments.
54
+ */
55
+ export interface I18nNestedKeys {
56
+ }
57
+ /**
58
+ * Augmentable interface for valid scope identifiers.
59
+ * When populated by the type generator, constrains `useI18n(scope)` to valid scopes.
60
+ */
61
+ export interface I18nScopeMap {
62
+ }
63
+ /**
64
+ * Resolves to the union of registered scope identifiers when `I18nScopeMap`
65
+ * has entries, or falls back to `string` when it's empty.
66
+ */
67
+ export type ValidScope = keyof I18nScopeMap extends never ? string : keyof I18nScopeMap & string;
50
68
  /**
51
69
  * Resolves to the union of registered translation keys when `I18nKeyMap`
52
70
  * has entries, or falls back to `string` when it's empty (no generated types).
@@ -179,6 +197,12 @@ export interface DictionaryConfig {
179
197
  * - `admin*` (namespace prefix)
180
198
  */
181
199
  include?: string[];
200
+ /**
201
+ * Key patterns to exclude from this dictionary, applied after `include`.
202
+ * Same pattern syntax as `include`. Use to carve out sub-namespaces
203
+ * that shouldn't be preloaded (e.g., large validation keys).
204
+ */
205
+ exclude?: string[];
182
206
  /** Higher priority dictionaries claim matching keys first. */
183
207
  priority?: number;
184
208
  /** Whether this dictionary should be pinned in the runtime cache. */
@@ -265,6 +289,12 @@ export interface I18nConfig {
265
289
  * - Function: called before each request, may be async (e.g., for refreshing auth tokens)
266
290
  */
267
291
  requestInit?: RequestInit | (() => RequestInit | Promise<RequestInit>);
292
+ /**
293
+ * Overrides the build-injected base path for translation bundle fetches.
294
+ * Useful for CDN or reverse proxy deployments where the runtime fetch URL
295
+ * differs from the Vite build `base`.
296
+ */
297
+ publicBase?: string;
268
298
  }
269
299
  /**
270
300
  * The i18n instance returned by `createI18n()`.
@@ -185,8 +185,8 @@ function interpolate$1(text, params) {
185
185
  function buildLoadPath(localesDir, locale, namespace) {
186
186
  return `${localesDir.endsWith("/") ? localesDir.slice(0, -1) : localesDir}/${locale}/${namespace}.json`;
187
187
  }
188
- function buildBundlePath(locale, bundleName) {
189
- return `/__i18n/${locale}/${bundleName}.json`;
188
+ function buildBundlePath(base, locale, bundleName) {
189
+ return (base.endsWith("/") ? base : base + "/") + locale + "/" + bundleName + ".json";
190
190
  }
191
191
  async function fetchNamespace(localesDir, locale, namespace, requestInit) {
192
192
  const url = buildLoadPath(localesDir, locale, namespace);
@@ -194,8 +194,8 @@ async function fetchNamespace(localesDir, locale, namespace, requestInit) {
194
194
  if (!response.ok) throw new Error(`Failed to load translations: ${url} (${response.status} ${response.statusText})`);
195
195
  return response.json();
196
196
  }
197
- async function fetchBundle(locale, bundleName, requestInit) {
198
- const url = buildBundlePath(locale, bundleName);
197
+ async function fetchBundle(base, locale, bundleName, requestInit) {
198
+ const url = buildBundlePath(base, locale, bundleName);
199
199
  const response = requestInit ? await fetch(url, requestInit) : await fetch(url);
200
200
  if (!response.ok) throw new Error(`Failed to load translation bundle: ${url} (${response.status} ${response.statusText})`);
201
201
  return response.json();
@@ -341,6 +341,16 @@ function resolveRuntimeCache(config) {
341
341
  pinDictionaries: runtime.pinDictionaries ?? true
342
342
  };
343
343
  }
344
+ function getInjectedI18nBase() {
345
+ return typeof __VITE_I18N_BASE__ !== "undefined" ? __VITE_I18N_BASE__ : void 0;
346
+ }
347
+ /**
348
+ * Resolves the base path for bundle fetches.
349
+ * Resolution order: config.publicBase > __VITE_I18N_BASE__ > '/__i18n'
350
+ */
351
+ function resolveI18nBase(config) {
352
+ return config.publicBase ?? getInjectedI18nBase() ?? "/__i18n";
353
+ }
344
354
  function getInjectedCompiledManifestUrl() {
345
355
  return typeof __VITE_I18N_COMPILED_MANIFEST__ !== "undefined" ? __VITE_I18N_COMPILED_MANIFEST__ : void 0;
346
356
  }
@@ -390,6 +400,7 @@ function createI18n(config) {
390
400
  if (!config.supportedLocales.includes(config.defaultLocale)) throw new Error(`vite-bundled-i18n: defaultLocale "${config.defaultLocale}" must be included in supportedLocales`);
391
401
  const store = createStore();
392
402
  const frozenConfig = Object.freeze({ ...config });
403
+ const i18nBase = resolveI18nBase(config);
393
404
  const runtimeCache = resolveRuntimeCache(config);
394
405
  const compiledManifestUrl = config.compiled?.manifestUrl ?? getInjectedCompiledManifestUrl();
395
406
  const useCompiledRuntime = shouldUseCompiledRuntime(config, compiledManifestUrl);
@@ -404,6 +415,14 @@ function createI18n(config) {
404
415
  const keyUsage = [];
405
416
  /** The current scope set by useI18n, used for key tracking. */
406
417
  let activeScope;
418
+ /** Tracks whether a consolidated fetch error has been emitted. */
419
+ let fetchErrorEmitted = false;
420
+ function handleFetchError() {
421
+ if (!fetchErrorEmitted) {
422
+ fetchErrorEmitted = true;
423
+ console.error("vite-bundled-i18n: Cannot load translations. Ensure __i18n assets are accessible at the configured base path. Are you running the Vite dev server, or have you built with the i18n plugin?");
424
+ }
425
+ }
407
426
  let compiledManifestPromise = null;
408
427
  const compiledLocaleMaps = /* @__PURE__ */ new Map();
409
428
  function getCompiledLocaleMap(locale) {
@@ -570,15 +589,15 @@ function createI18n(config) {
570
589
  }
571
590
  }
572
591
  const reqInit = await resolveRequestInit(config.requestInit);
573
- const bundle = await fetchBundle(locale, `_dict/${name}`, reqInit);
592
+ const bundle = await fetchBundle(i18nBase, locale, `_dict/${name}`, reqInit);
574
593
  for (const [namespace, data] of Object.entries(bundle)) store.addResources(locale, namespace, data, {
575
594
  source: "dictionary",
576
595
  pinned: runtimeCache.pinDictionaries
577
596
  });
578
597
  loadedDicts.add(dictKey);
579
598
  evictUnused();
580
- } catch (error) {
581
- console.warn(`vite-bundled-i18n: Failed to load dictionary "${name}" for locale "${locale}".`, error);
599
+ } catch {
600
+ handleFetchError();
582
601
  }
583
602
  }
584
603
  /**
@@ -604,7 +623,7 @@ function createI18n(config) {
604
623
  return;
605
624
  }
606
625
  }
607
- const bundle = await fetchBundle(locale, scope, await resolveRequestInit(config.requestInit));
626
+ const bundle = await fetchBundle(i18nBase, locale, scope, await resolveRequestInit(config.requestInit));
608
627
  for (const [namespace, data] of Object.entries(bundle)) store.addResources(locale, namespace, data, {
609
628
  source: "scope",
610
629
  pinned: false
@@ -612,7 +631,11 @@ function createI18n(config) {
612
631
  loadedScopes.add(scopeKey);
613
632
  evictUnused();
614
633
  } catch (error) {
615
- console.warn(`vite-bundled-i18n: Failed to load scope "${scope}" for locale "${locale}".`, error);
634
+ if (error instanceof Error && error.message.includes("404")) {
635
+ loadedScopes.add(scopeKey);
636
+ return;
637
+ }
638
+ handleFetchError();
616
639
  }
617
640
  }
618
641
  /**
@@ -627,8 +650,8 @@ function createI18n(config) {
627
650
  pinned: false
628
651
  });
629
652
  evictUnused();
630
- } catch (error) {
631
- console.warn(`vite-bundled-i18n: Failed to load namespace "${ns}" for locale "${locale}".`, error);
653
+ } catch {
654
+ handleFetchError();
632
655
  }
633
656
  }
634
657
  function addResources(locale, namespace, data) {
@@ -891,4 +914,4 @@ function i18nKey(key) {
891
914
  //#endregion
892
915
  export { clearTranslations as a, mergeTranslations as c, createI18n as i, setTranslations as l, i18nKey as n, compiledHasKey as o, defineI18nConfig as r, compiledTranslate as s, defineI18nData as t };
893
916
 
894
- //# sourceMappingURL=data-Trz4mxne.js.map
917
+ //# sourceMappingURL=data-DctljUuI.js.map