@hakistack/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
@@ -17,8 +17,9 @@ npm i @hakistack/i18n @jsverse/transloco
17
17
  ```
18
18
 
19
19
  `@jsverse/transloco` is a peer dependency (you control its version). The CLI
20
- depends on `jiti` (installed automatically) and, for the `watch` command only,
21
- on `chokidar` (an optional dependency).
20
+ depends on `jiti` (installed automatically), parses `*.i18n.ts` with your
21
+ project's `typescript` (an optional peer — every Angular project already has
22
+ it) and, for the `watch` command only, uses `chokidar` (an optional dependency).
22
23
 
23
24
  ## 1. Author translations (`*.i18n.ts`)
24
25
 
@@ -44,17 +45,11 @@ export const HOME = defineTranslations('home', {
44
45
  - `{ scoped: true }` emits a per-scope JSON file (forward-compat for
45
46
  `provideTranslocoScope` lazy loading); eager modules merge into the root JSON.
46
47
 
47
- Declare your locale set once so `t()` autocompletes the right locales:
48
-
49
- ```ts
50
- // src/app/i18n-locales.d.ts
51
- import '@hakistack/i18n/engine';
52
- declare module '@hakistack/i18n/engine' {
53
- interface I18nLocales {
54
- es: string;
55
- }
56
- }
57
- ```
48
+ Locales are declared once, in `i18n.config` (`locales`). `scan` turns them into
49
+ an `I18nLocales` augmentation (`i18n-locales.generated.d.ts`), so `t()`
50
+ autocompletes exactly those locales and `languages[].id` in `provideI18n`
51
+ suggests them. A hand-written `I18nLocales` augmentation from an older setup
52
+ can stay (identical declarations merge) or be deleted.
58
53
 
59
54
  ## 2. Configure the codegen (`i18n.config.json`)
60
55
 
@@ -74,31 +69,67 @@ generated directive.)
74
69
  ## 3. Run the codegen
75
70
 
76
71
  ```bash
77
- npx hakistack-i18n scan # emit barrel + TK literal + typed directive
78
- npx hakistack-i18n generate # write JSON translation files
79
- npx hakistack-i18n validate # gate on missing / placeholder-mismatched strings
80
- npx hakistack-i18n watch # re-run scan on *.i18n.ts changes (during ng serve)
81
- npx hakistack-i18n find-unused # report defined keys with no references
72
+ npx hakistack-i18n check # scan + validate + generate — the everyday command (prebuild, CI)
73
+ npx hakistack-i18n watch # the same on every *.i18n.ts change (run next to ng serve)
74
+ npx hakistack-i18n find-unused # report keys with no reference (--strict fails on them)
82
75
  ```
83
76
 
77
+ The steps are also available alone: `scan` (barrel, `TK`, directive, locale
78
+ types), `validate` (missing / empty / placeholder-mismatched translations) and
79
+ `generate` (JSON + per-language modules). `check` stops at the first step that
80
+ fails and exits with code 1; `watch` prints errors and keeps running.
81
+
82
+ `scan` parses the files (TypeScript AST, nothing is executed). It finds
83
+ `export const X = defineTranslations('scope', …)`, local constants exported
84
+ with `export { X }` / `export { X as Y }`, and aliased or namespace imports of
85
+ `defineTranslations`; commented-out code never counts. The scope must be a
86
+ string literal. Problems are reported as `file:line`, and on an error (duplicate
87
+ export names, a key defined twice, a key that is both a translation and a
88
+ group) nothing is written and the command exits with code 1. `validate` and
89
+ `generate` re-check the executed registry, which also catches conflicts hidden
90
+ behind spreads or references.
91
+
92
+ Outputs are written atomically and only when their content changed, so dev
93
+ servers don't rebuild for nothing. Files a previous run wrote that are no
94
+ longer produced — a removed locale or scoped module, a renamed directive — are
95
+ deleted; the CLI only ever deletes files it wrote itself (tracked in
96
+ `node_modules/.cache/hakistack-i18n/`).
97
+
84
98
  Typical `package.json` wiring:
85
99
 
86
100
  ```jsonc
87
101
  {
88
102
  "scripts": {
89
- "i18n:scan": "hakistack-i18n scan",
90
- "i18n:generate": "hakistack-i18n generate",
91
- "i18n:validate": "hakistack-i18n validate",
92
- "prestart": "npm run i18n:scan",
93
- "prebuild": "npm run i18n:scan && npm run i18n:generate && npm run i18n:validate"
103
+ "i18n:check": "hakistack-i18n check",
104
+ "i18n:watch": "hakistack-i18n watch",
105
+ "prestart": "npm run i18n:check",
106
+ "prebuild": "npm run i18n:check"
94
107
  }
95
108
  }
96
109
  ```
97
110
 
98
- The scan emits three files into `definitionsDir` (never hand-edited):
99
- `index.generated.ts` (the `ALL_TRANSLATIONS` registry), `keys.generated.ts`
100
- (the flat camelCase `TK` literal — `TK.home.welcome === 'home.welcome'`), and
101
- `appTranslate.directive.ts` (the typed template directive).
111
+ Generated into `definitionsDir` (never hand-edited):
112
+
113
+ | File | From | Contents |
114
+ |------|------|----------|
115
+ | `keys.generated.ts` | `scan` | `TK` — `TK.home.welcome === 'home.welcome'`, typed as that literal |
116
+ | `index.generated.ts` | `scan` | `ALL_TRANSLATIONS`, the registry of every module |
117
+ | `appTranslate.directive.ts` | `scan` | the typed template directive |
118
+ | `i18n-locales.generated.d.ts` | `scan` | the `I18nLocales` augmentation from `locales` |
119
+ | `translations.generated.ts` + `translations/` | `generate` | `TRANSLATIONS`: one lazily imported module per language (and per scoped scope) |
120
+
121
+ `TK` holds the key strings themselves for every module `scan` can read
122
+ statically, so importing `TK` does not import any `*.i18n.ts` module. A module
123
+ built with spreads or references is referenced as `NAME.keys` instead (and is
124
+ bundled with `TK`).
125
+
126
+ Several modules may share a scope, and a module may nest under another one's
127
+ scope (`admin` + `admin.users`): their keys are deep-merged (`mergeKeys` in the
128
+ generated `TK`, the same merge the runtime and the JSON use). A key defined
129
+ twice, or a key that is both a translation and a group, is an error:
130
+ `validate` and `generate` list each conflict with its scopes and exit with code
131
+ 1, and the runtime throws instead of letting one module silently win. Export
132
+ names must be unique across `*.i18n.ts` files (`scan` refuses duplicates).
102
133
 
103
134
  ## 4. Wire it up (one call)
104
135
 
@@ -123,8 +154,40 @@ export const appConfig: ApplicationConfig = {
123
154
  };
124
155
  ```
125
156
 
126
- No HTTP fetch by default — the registry loader serves translations from memory
127
- (SSR-safe, offline-friendly). Pass `loader: 'http'` to fetch `*.json` instead.
157
+ The registry loader serves every language from memory (no HTTP, SSR-safe,
158
+ offline-friendly) — simplest for small apps, but every language is in the
159
+ initial bundle. For larger apps load one language at a time:
160
+
161
+ ```ts
162
+ import { TK } from './i18n/definitions/keys.generated';
163
+ import { TRANSLATIONS } from './i18n/definitions/translations.generated';
164
+
165
+ provideI18n({
166
+ keys: TK, // instead of registry: no *.i18n.ts module is imported
167
+ translations: TRANSLATIONS, // one chunk per language, imported when first needed
168
+ languages: [...],
169
+ })
170
+ ```
171
+
172
+ The lazy loader is SSR-safe (server rendering waits for the import) and needs
173
+ no HTTP setup. Only the active language is downloaded: every generated tree
174
+ already resolves untranslated keys to the fallback language, so the fallback
175
+ language itself is never loaded alongside. `loader: 'http'` with `keys: TK` fetches the generated
176
+ `<assetsPath>/<lang>.json` instead, so translations can change without a
177
+ rebuild.
178
+
179
+ Measured on a production build with 2,000+ keys in 4 languages: the initial
180
+ JS goes from 604.0 kB / 126.8 kB gzip (registry) to 184.9 kB / 56.9 kB gzip
181
+ (lazy), plus a ~18.7 kB gzip chunk for the active language only.
182
+
183
+ `persistLanguage` only controls localStorage persistence: the generated
184
+ directive and `translateSignal` load the active language themselves.
185
+ `LanguageService.language()` and `<html lang>` follow Transloco's active
186
+ language however it is changed; `setLanguage()` ignores languages that are not
187
+ in `languages`.
188
+
189
+ In dev mode a missing key renders as `[scope.key]` and logs one console warning
190
+ per key (`missingKeyInDev: 'empty'` renders `''`); production renders `''`.
128
191
 
129
192
  ## 5. Use translations
130
193
 
@@ -144,9 +207,97 @@ protected readonly welcome = translateSignal(TK.home.welcome);
144
207
  <div *appTranslate="let t; prefix: 'admin'">{{ t.users.title() }}</div>
145
208
  ```
146
209
 
210
+ ### Typed interpolation params
211
+
212
+ For every `t('…')` whose source text has `{{…}}` placeholders, `scan` types the
213
+ key with its params (`I18nKey<'home.greeting', 'username'>` — still the plain
214
+ string `'home.greeting'` at runtime). The compiler then checks them, in
215
+ components and in strict templates:
216
+
217
+ ```ts
218
+ // home.i18n.ts: greeting: t('Welcome back, {{ username }}!', { es: '¡Hola de nuevo, {{username}}!' })
219
+ translateSignal(TK.home.greeting, { username }); // ✓
220
+ translateSignal(TK.home.greeting, computed(() => ({ username: name() }))); // ✓ reactive params
221
+ translateSignal(TK.home.greeting); // ✗ params required
222
+ translateSignal(TK.home.greeting, { user: 'x' }); // ✗ unknown param
223
+ ```
224
+
225
+ ```html
226
+ {{ t.home.greeting({ username: user.name }) }} <!-- ✗ without the param under strictTemplates -->
227
+ ```
228
+
229
+ `translateSignal` is Transloco's own (same arguments and behavior) with this
230
+ check added; plain string keys stay untyped. Params come from the source
231
+ (`en`) text — `validate` keeps every locale in parity — and a nested
232
+ `{{ user.name }}` requires `user`. They are read once by the codegen rather than
233
+ parsed by the type system: on a 5,000-key project, template-literal parsing made
234
+ type-checking 4–6× slower, while the generated `TK` adds ~0.3 s.
235
+
236
+ ## 6. Language, locale and direction
237
+
238
+ A language option can carry its formatting locale and text direction:
239
+
240
+ ```ts
241
+ languages: [
242
+ { id: 'en', label: 'English' },
243
+ { id: 'es', label: 'Español', locale: 'es-PR' }, // Spanish texts, Puerto Rico formats
244
+ { id: 'ar', label: 'العربية' }, // dir: 'rtl' derived from the locale
245
+ ],
246
+ ```
247
+
248
+ `LanguageService` exposes `language()` (translations), `locale()` (BCP 47, for
249
+ `Intl.*` or locale pipes) and `dir()`, and keeps `<html lang>` (the locale) and
250
+ `<html dir>` in sync — also during SSR:
251
+
252
+ ```ts
253
+ private readonly lang = inject(LanguageService);
254
+ readonly price = computed(() => new Intl.NumberFormat(this.lang.locale(), { style: 'currency', currency: 'USD' }).format(19.9));
255
+ ```
256
+
257
+ For pipes, `@jsverse/transloco-locale` works alongside: map languages to
258
+ locales with `langToLocaleMapping: { es: 'es-PR' }`. Pluralization and ICU
259
+ messages are Transloco's (`@jsverse/transloco-messageformat`); nothing here
260
+ replaces them.
261
+
262
+ ## 7. SSR
263
+
264
+ `persistLanguage: 'cookie'` remembers the user's choice in a
265
+ `hakistack_i18n_lang` cookie that the server reads from the request, so the
266
+ server renders the user's language and hydration shows no switch.
267
+ `detectLanguage: true` picks the best match for `Accept-Language` (server) or
268
+ `navigator.languages` (browser) when nothing is remembered; a detected language
269
+ is not stored. Every piece of state lives in the application's injector, so
270
+ concurrent requests never share a language. The `'lazy'` loader is an Angular
271
+ pending task: the server waits for the active language before serializing.
272
+
273
+ Verified with a real `renderApplication` (Angular 21.2): three concurrent
274
+ requests — cookie `es`, `Accept-Language: ar-EG`, no preference — render
275
+ `<html lang="es-PR" dir="ltr">`, `<html lang="ar" dir="rtl">` and
276
+ `<html lang="en" dir="ltr">` with their own texts, with both the registry and
277
+ the lazy loader.
278
+
147
279
  ## Entry points
148
280
 
149
281
  | Import | Contains |
150
282
  |--------|----------|
151
- | `@hakistack/i18n` | Runtime: `provideI18n`, `LanguageService`, `translateSignal`, `TranslateDirectiveBase`, loaders/hooks. (Re-exports the engine too.) |
283
+ | `@hakistack/i18n` | Runtime: `provideI18n`, `LanguageService`, `translateSignal`, `TranslateDirectiveBase`, loaders/hooks, `I18nTranslationLoaders`. (Re-exports the engine too.) |
152
284
  | `@hakistack/i18n/engine` | Angular-free authoring/tree engine: `defineTranslations`, `t`, build-tree helpers. Loads in Node — this is what the codegen executes. |
285
+
286
+ ## Finding unused keys
287
+
288
+ `hakistack-i18n find-unused` classifies every key:
289
+
290
+ - **used** — `TK.home.welcome` (also through `import { TK as K }` or
291
+ `const home = TK.home; home.welcome`), the exact key as a string
292
+ (`translate('home.welcome')`), or `t.home.welcome()` in a template under
293
+ `*appTranslate="let t"` (with its `prefix:` applied);
294
+ - **possibly used** — only dynamic references that may reach it: a TK group
295
+ used as a value or indexed (`TK.home[name]`), a key prefix in a string
296
+ (`'home.' + name`, `` `home.${name}` ``), a group name passed to a
297
+ `translate*` call (`translateObject('home')`). Never reported as unused;
298
+ - **test-only** — referenced only from `*.spec.ts`;
299
+ - **claimed** — matched by a `/* i18n-used: home.dynamic.* */` comment;
300
+ - **unused** — everything else. `--strict` exits with code 1 when there are any.
301
+
302
+ Comments never count as references.
303
+