@hakistack/i18n 0.0.0-stage → 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.
@@ -0,0 +1,324 @@
1
+ /**
2
+ * Type-safe translation definitions — the authoring heart of `@hakistack/i18n`.
3
+ *
4
+ * Consumers author translations in `.ts` files (`*.i18n.ts`) using
5
+ * `defineTranslations()` + `t()`. English is the required source locale; every
6
+ * other locale is optional. The companion `keys` object gives type-safe
7
+ * dot-path access at the value level, and the scanner derives a merged `TK`
8
+ * literal from these modules.
9
+ *
10
+ * Unlike the original app-local engine, locales here are **not hardcoded**.
11
+ * Consumers declare their locale union by augmenting the {@link I18nLocales}
12
+ * interface (the scanner / schematic can emit this augmentation), so `t()` gets
13
+ * autocomplete on exactly the locales the project supports.
14
+ */
15
+ /**
16
+ * The set of locales a project supports, as a type.
17
+ *
18
+ * `en` is the always-present source locale (English is the source of truth).
19
+ * Consumers add their other locales by declaration-merging this interface:
20
+ *
21
+ * ```ts
22
+ * declare module '@hakistack/i18n/engine' {
23
+ * interface I18nLocales {
24
+ * es: string;
25
+ * fr: string;
26
+ * }
27
+ * }
28
+ * ```
29
+ *
30
+ * After augmentation, `t('Hello', { es: '…', fr: '…' })` autocompletes `es`/`fr`
31
+ * and `Language` resolves to `'en' | 'es' | 'fr'`.
32
+ */
33
+ interface I18nLocales {
34
+ /** Source locale — always required on every translation value. */
35
+ en: string;
36
+ }
37
+ /** Union of every declared locale id (e.g. `'en' | 'es'`). */
38
+ type LocaleId = keyof I18nLocales & string;
39
+ /**
40
+ * The source locale. `t()` stores its first argument here, every other locale
41
+ * is optional, and build-time + runtime fallbacks end here. This is fixed by
42
+ * the engine's types (`TranslationValue.en`), so it is not configurable.
43
+ */
44
+ declare const SOURCE_LANG = "en";
45
+ type SourceLang = typeof SOURCE_LANG;
46
+ /**
47
+ * Runtime brand stamped (non-enumerably) on every `TranslationValue` produced
48
+ * by `t()` or by bare-string normalization.
49
+ *
50
+ * Without a brand, a *group* whose child happens to be named `en` — e.g.
51
+ * `languages: { en: 'English', es: 'Español' }` in a language picker — is
52
+ * indistinguishable from a leaf. `Symbol.for` (global registry) is used so the
53
+ * codegen CLI (which bundles its own copy of the engine) recognizes values
54
+ * created by the consumer's installed copy.
55
+ */
56
+ declare const TRANSLATION_BRAND: unique symbol;
57
+ /** Alias kept for ergonomics — the active/target language id. */
58
+ type Language = LocaleId;
59
+ /**
60
+ * A single translation value across all declared locales.
61
+ *
62
+ * English (`en`) is required; every other declared locale is optional and falls
63
+ * back to English at build time and runtime. The optional `__comment` field
64
+ * stores translator-facing context — it is emitted as a sibling `<key>.comment`
65
+ * entry in the JSON and stripped by the runtime interceptor so it never renders.
66
+ */
67
+ type TranslationValue = OtherLocales & {
68
+ en: string;
69
+ /** Internal — translator-context comment, attached via `t(en, others, { comment })`. */
70
+ __comment?: string;
71
+ /** Internal — runtime brand; only `t()` / normalization create branded values. */
72
+ readonly [TRANSLATION_BRAND]: true;
73
+ };
74
+ /** Optional non-source locale fields, derived from the augmented locale set. */
75
+ type OtherLocales = {
76
+ [K in Exclude<LocaleId, 'en'>]?: string;
77
+ };
78
+ /**
79
+ * Define a single translation value.
80
+ *
81
+ * @param en - English (source) translation — required.
82
+ * @param translations - Other-locale translations — optional, autocompletes the
83
+ * consumer's declared locales.
84
+ * @param options.comment - Translator-facing context. Emitted as a sibling
85
+ * `<key>.comment` entry in the JSON for translator review; stripped at runtime
86
+ * by the comment interceptor so it never renders.
87
+ *
88
+ * @example
89
+ * t('Hello', { es: 'Hola' })
90
+ * t('Save') // English only — other locales fall back to English
91
+ * t('Welcome', { es: '¡Bienvenido!' }, { comment: 'Greeting on home dashboard' })
92
+ */
93
+ declare function t(en: string, translations?: OtherLocales, options?: {
94
+ comment?: string;
95
+ }): TranslationValue;
96
+ /**
97
+ * Authored translation node — what callers write inside `defineTranslations()`.
98
+ * Accepts:
99
+ * - `TranslationValue` (full form, from `t()`)
100
+ * - `string` (shorthand for English-only — equivalent to `t(value)`)
101
+ * - nested object of either
102
+ *
103
+ * Only `t()` produces a leaf. A hand-written `{ en: '…', es: '…' }` object is a
104
+ * *group* with children named `en`/`es` — which is what a language picker wants.
105
+ *
106
+ * Strings are normalized to `TranslationValue` at module construction so the
107
+ * rest of the pipeline (generator, validator, keys builder) only ever sees the
108
+ * canonical `{ en, … }` shape.
109
+ *
110
+ * Note: any leaf string containing `{{…}}` placeholders MUST use `t()` — the
111
+ * validator rejects bare placeholder strings because parity across locales
112
+ * cannot be expressed with the shorthand.
113
+ */
114
+ type AuthoredTranslationNode = TranslationValue | string | {
115
+ [key: string]: AuthoredTranslationNode;
116
+ };
117
+ /**
118
+ * Recursively builds dot-notation key strings from the authored object shape.
119
+ * Treats both `TranslationValue` and `string` as leaves (string is shorthand).
120
+ */
121
+ type BuildKeyObject<T, Prefix extends string = ''> = {
122
+ readonly [K in keyof T]: K extends string ? T[K] extends TranslationValue | string ? Join<Prefix, K> : T[K] extends Record<string, unknown> ? BuildKeyObject<T[K], Join<Prefix, K>> : never : never;
123
+ };
124
+ type Join<Prefix extends string, K extends string> = Prefix extends '' ? K : `${Prefix}.${K}`;
125
+ /**
126
+ * Translation module returned by {@link defineTranslations}.
127
+ *
128
+ * `translations` stores the normalized form (every bare string promoted to
129
+ * `{ en: value }`); `keys` is the type-derived companion of dot-paths.
130
+ */
131
+ interface TranslationModule<T extends Record<string, AuthoredTranslationNode> = Record<string, AuthoredTranslationNode>, S extends string = string> {
132
+ /** Scope/prefix for these translations (e.g. `'common'`, `'administration.users'`). */
133
+ scope: S;
134
+ /** Normalized translation definitions (strings promoted to `{ en: value }`). */
135
+ translations: T;
136
+ /** Auto-generated keys object for type-safe usage (full keys, scope included: `'common.buttons.save'`). */
137
+ keys: BuildKeyObject<T, S>;
138
+ /**
139
+ * If `true`, the generator emits this module's data to a subdirectory matching
140
+ * its scope path (`administration.users` → `administration/users/<lang>.json`)
141
+ * rather than merging into the root `<lang>.json`. Future-proofs
142
+ * `provideTranslocoScope`-based lazy loading. Default: `false` (eager).
143
+ */
144
+ scoped: boolean;
145
+ }
146
+ /**
147
+ * Define a translation module with auto-generated keys.
148
+ *
149
+ * @param scope - The scope/prefix for these translations.
150
+ * @param translations - The translation definitions (full `t()` form or
151
+ * bare-string shorthand, nested freely).
152
+ * @param options.scoped - Emit to a per-scope JSON file (see {@link TranslationModule.scoped}).
153
+ *
154
+ * @example
155
+ * export const COMMON = defineTranslations('common', {
156
+ * buttons: {
157
+ * save: t('Save', { es: 'Guardar' }),
158
+ * cancel: t('Cancel', { es: 'Cancelar' }),
159
+ * reset: 'Reset', // shorthand
160
+ * },
161
+ * });
162
+ * // COMMON.keys.buttons.save === 'common.buttons.save'
163
+ */
164
+ declare function defineTranslations<T extends Record<string, AuthoredTranslationNode>, const S extends string = string>(scope: S, translations: T, options?: {
165
+ scoped?: boolean;
166
+ }): TranslationModule<T, S>;
167
+ /** Type guard: is this value a branded `TranslationValue` (created by `t()` or normalization)? */
168
+ declare function isTranslationValue(value: unknown): value is TranslationValue;
169
+ /**
170
+ * Build a merged keys tree from a list of translation modules by placing each
171
+ * module's `keys` object at its scope path and deep-merging.
172
+ *
173
+ * This is the **runtime** value used by the directive (via the `I18N_KEYS`
174
+ * token). It uses the same deep merge as the scanner-emitted `TK` literal
175
+ * (`mergeKeys`) and the language trees, so all three agree on which keys exist.
176
+ * Throws when a key is defined twice or is both a translation and a group.
177
+ */
178
+ declare function buildKeysTree(modules: readonly TranslationModule[]): Record<string, unknown>;
179
+ /** A key defined by more than one module, or used both as a translation and as a group. */
180
+ interface KeyConflict {
181
+ /** Full dotted key, e.g. `'common.buttons.save'`. */
182
+ key: string;
183
+ kind: 'duplicate' | 'translation-and-group';
184
+ /** Scopes of the modules involved (one entry per contributing module). */
185
+ scopes: string[];
186
+ }
187
+ /**
188
+ * Find every key collision across the registry, including the ones a deep
189
+ * merge cannot see: a dotted key name (`'a.b'`) colliding with a nested group
190
+ * (`a: { b }`) produces the same Transloco key.
191
+ */
192
+ declare function findKeyConflicts(modules: readonly TranslationModule[]): KeyConflict[];
193
+
194
+ /**
195
+ * Build a per-language translation tree from the in-memory module registry.
196
+ *
197
+ * Shared by:
198
+ * - the generator CLI — writes the tree as JSON to `<outputDir>/<lang>.json`
199
+ * for translator-facing tooling (build artifacts, not a runtime dependency).
200
+ * - the runtime `TranslocoRegistryLoader` — returns the tree synchronously to
201
+ * Transloco, eliminating the HTTP fetch.
202
+ *
203
+ * Producing the tree from the registry guarantees the runtime sees the exact
204
+ * shape the generator emits — there's no "JSON drifted from TS" failure mode.
205
+ *
206
+ * Locale handling is parameterized: every function takes the `defaultLang`
207
+ * (source/fallback locale) explicitly rather than reading a hardcoded constant,
208
+ * so the engine is reusable across consumers with different locale sets.
209
+ */
210
+
211
+ /** A nested string-tree as Transloco / the JSON files consume it. */
212
+ interface LanguageTree {
213
+ [key: string]: string | LanguageTree;
214
+ }
215
+ /** Options for building string trees from the registry. */
216
+ interface LanguageTreeOptions {
217
+ /**
218
+ * Emit translator comments as `<key>.comment` siblings. Default `true` (the
219
+ * translator-facing JSON). The runtime registry loader passes `false` so
220
+ * comments never reach Transloco's store.
221
+ */
222
+ comments?: boolean;
223
+ }
224
+ /**
225
+ * Resolve a single `TranslationValue` for a given language.
226
+ * Falls back to `defaultLang` for any locale that didn't supply a translation —
227
+ * mirrors `useFallbackTranslation: true` in the runtime Transloco config.
228
+ */
229
+ declare function getTranslation(value: TranslationValue, lang: string, defaultLang: string): string;
230
+ /**
231
+ * Walk a normalized translation subtree (all leaves are `TranslationValue`s) and
232
+ * emit a string-only tree for the given language.
233
+ *
234
+ * If a leaf carries a `__comment` (set via `t(en, others, { comment })`) and
235
+ * `options.comments` is not `false`, a sibling entry `<key>.comment` is added at
236
+ * the same level for translators.
237
+ */
238
+ declare function extractLanguage(translations: Record<string, unknown>, lang: string, defaultLang: string, options?: LanguageTreeOptions): LanguageTree;
239
+ /**
240
+ * Deep-merge a subtree into the target at a dot-delimited scope path, creating
241
+ * intermediate objects as needed. Throws when a key would be defined twice or
242
+ * when a translation and a group collide (see `mergeInto`).
243
+ */
244
+ declare function setAtScope(target: LanguageTree, scope: string, subtree: LanguageTree): void;
245
+ type Registry = readonly TranslationModule<Record<string, AuthoredTranslationNode>>[];
246
+ /**
247
+ * Build the complete translation tree for a single language from the registry.
248
+ * The returned tree matches the JSON file layout exactly — same keys, nesting,
249
+ * and fallbacks — so a consumer cannot tell whether the data came from the
250
+ * registry or from disk.
251
+ */
252
+ declare function buildLanguageTree(registry: Registry, lang: string, defaultLang: string, options?: LanguageTreeOptions): LanguageTree;
253
+ /**
254
+ * Build the eager (root) tree — only modules declared without `{ scoped: true }`.
255
+ * Used by the generator when route-level scope providers are adopted.
256
+ */
257
+ declare function buildEagerTree(registry: Registry, lang: string, defaultLang: string, options?: LanguageTreeOptions): LanguageTree;
258
+ /**
259
+ * Build the per-scope tree for a scope — returned unwrapped (no scope key
260
+ * around it), matching the layout `provideTranslocoScope` expects to load from
261
+ * `<scope-with-slashes>/<lang>.json`. Every scoped module declaring that scope
262
+ * is merged in.
263
+ *
264
+ * `scope` may be given in dotted (`administration.users`) or slash form
265
+ * (`administration/users` — what Transloco hands a loader); both match.
266
+ *
267
+ * Returns `null` if no scoped module declares the scope.
268
+ */
269
+ declare function buildScopedTree(registry: Registry, lang: string, defaultLang: string, scope: string, options?: LanguageTreeOptions): LanguageTree | null;
270
+ /**
271
+ * Convert a dot-separated scope to its filesystem path.
272
+ * 'administration.users' → 'administration/users'
273
+ */
274
+ declare function scopeToFilesystemPath(scope: string): string;
275
+ /**
276
+ * Canonical dotted form of a scope, accepting either separator.
277
+ * 'administration/users' → 'administration.users'
278
+ */
279
+ declare function normalizeScope(scope: string): string;
280
+
281
+ type Intersect<T extends readonly unknown[]> = T extends readonly [infer Head, ...infer Rest] ? Head & Intersect<Rest> : unknown;
282
+ /**
283
+ * Deep-merge several keys objects into one. Emitted by `hakistack-i18n scan`
284
+ * wherever several modules contribute to the same `TK` branch (modules sharing
285
+ * a scope, or a module plus deeper scopes nested under it). The intersection
286
+ * type exposes every contributed key, matching the runtime value exactly.
287
+ *
288
+ * @example
289
+ * mergeKeys(COMMON_A.keys, COMMON_B.keys, { users: ADMIN_USERS.keys })
290
+ */
291
+ declare function mergeKeys<const T extends readonly object[]>(...parts: T): Intersect<T>;
292
+
293
+ /**
294
+ * Type-level key metadata: which interpolation params a translation key needs.
295
+ *
296
+ * A key with `{{…}}` placeholders in its source text is typed as a *branded*
297
+ * string — `I18nKey<'home.welcome', 'username'>` — whose runtime value is still
298
+ * the plain key string Transloco expects. The brand is a phantom property that
299
+ * exists only in the type system; nothing is added at runtime.
300
+ *
301
+ * Placeholder names are read from the source (`en`) text — the one every other
302
+ * locale must match (the validator enforces placeholder parity) — by
303
+ * `hakistack-i18n scan`, which emits them on the generated `TK`. They are not
304
+ * inferred by `t()` in the type system: parsing `{{…}}` with template-literal
305
+ * types made type-checking 4–6× slower on a 5,000-key project, while reading
306
+ * them once at codegen time costs nothing to the compiler.
307
+ */
308
+ /** Phantom marker carrying a key's placeholder names (type-only, never present at runtime). */
309
+ declare const I18N_PARAMS: unique symbol;
310
+ /** A translation key whose text interpolates the params `P`. Plain `K` at runtime. */
311
+ type I18nKey<K extends string = string, P extends string = string> = K & {
312
+ readonly [I18N_PARAMS]: P;
313
+ };
314
+ /** Placeholder names a key needs (`never` for a plain string key, or when unknown). */
315
+ type KeyParams<K> = K extends {
316
+ readonly [I18N_PARAMS]: infer P extends string;
317
+ } ? P : never;
318
+ /** The params object a key requires: one entry per placeholder. */
319
+ type ParamsOf<K> = {
320
+ [N in KeyParams<K>]: unknown;
321
+ };
322
+
323
+ export { SOURCE_LANG, TRANSLATION_BRAND, buildEagerTree, buildKeysTree, buildLanguageTree, buildScopedTree, defineTranslations, extractLanguage, findKeyConflicts, getTranslation, isTranslationValue, mergeKeys, normalizeScope, scopeToFilesystemPath, setAtScope, t };
324
+ export type { AuthoredTranslationNode, I18nKey, I18nLocales, KeyConflict, KeyParams, Language, LanguageTree, LanguageTreeOptions, LocaleId, OtherLocales, ParamsOf, SourceLang, TranslationModule, TranslationValue };