@hakistack/i18n 0.0.0-stage → 0.1.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,339 @@
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 source locale. `t()` stores its first argument here, every other locale
17
+ * is optional, and build-time + runtime fallbacks end here. This is fixed by
18
+ * the engine's types (`TranslationValue.en`), so it is not configurable.
19
+ */
20
+ const SOURCE_LANG = 'en';
21
+ /**
22
+ * Runtime brand stamped (non-enumerably) on every `TranslationValue` produced
23
+ * by `t()` or by bare-string normalization.
24
+ *
25
+ * Without a brand, a *group* whose child happens to be named `en` — e.g.
26
+ * `languages: { en: 'English', es: 'Español' }` in a language picker — is
27
+ * indistinguishable from a leaf. `Symbol.for` (global registry) is used so the
28
+ * codegen CLI (which bundles its own copy of the engine) recognizes values
29
+ * created by the consumer's installed copy.
30
+ */
31
+ const TRANSLATION_BRAND = Symbol.for('@hakistack/i18n:translation-value');
32
+ /**
33
+ * Define a single translation value.
34
+ *
35
+ * @param en - English (source) translation — required.
36
+ * @param translations - Other-locale translations — optional, autocompletes the
37
+ * consumer's declared locales.
38
+ * @param options.comment - Translator-facing context. Emitted as a sibling
39
+ * `<key>.comment` entry in the JSON for translator review; stripped at runtime
40
+ * by the comment interceptor so it never renders.
41
+ *
42
+ * @example
43
+ * t('Hello', { es: 'Hola' })
44
+ * t('Save') // English only — other locales fall back to English
45
+ * t('Welcome', { es: '¡Bienvenido!' }, { comment: 'Greeting on home dashboard' })
46
+ */
47
+ function t(en, translations, options) {
48
+ const value = brand({ en, ...translations });
49
+ if (options?.comment) {
50
+ value.__comment = options.comment;
51
+ }
52
+ return value;
53
+ }
54
+ /** Stamp the non-enumerable brand on a plain `{ en, … }` record. */
55
+ function brand(value) {
56
+ Object.defineProperty(value, TRANSLATION_BRAND, { value: true, enumerable: false, writable: false, configurable: false });
57
+ return value;
58
+ }
59
+ /**
60
+ * Define a translation module with auto-generated keys.
61
+ *
62
+ * @param scope - The scope/prefix for these translations.
63
+ * @param translations - The translation definitions (full `t()` form or
64
+ * bare-string shorthand, nested freely).
65
+ * @param options.scoped - Emit to a per-scope JSON file (see {@link TranslationModule.scoped}).
66
+ *
67
+ * @example
68
+ * export const COMMON = defineTranslations('common', {
69
+ * buttons: {
70
+ * save: t('Save', { es: 'Guardar' }),
71
+ * cancel: t('Cancel', { es: 'Cancelar' }),
72
+ * reset: 'Reset', // shorthand
73
+ * },
74
+ * });
75
+ * // COMMON.keys.buttons.save === 'common.buttons.save'
76
+ */
77
+ function defineTranslations(scope, translations, options) {
78
+ const normalized = normalizeTree(translations);
79
+ const keys = buildKeys(normalized, scope);
80
+ return {
81
+ scope,
82
+ translations: normalized,
83
+ keys,
84
+ scoped: options?.scoped ?? false,
85
+ };
86
+ }
87
+ // =============================================================================
88
+ // Internal Utilities
89
+ // =============================================================================
90
+ /**
91
+ * Normalize an authored tree by replacing every bare-string leaf with
92
+ * `{ en: value }`. The output contains only `TranslationValue` leaves and
93
+ * nested records — the canonical shape consumed by the generator/validator.
94
+ */
95
+ function normalizeTree(node) {
96
+ if (typeof node === 'string') {
97
+ return brand({ en: node });
98
+ }
99
+ if (isTranslationValue(node)) {
100
+ return node;
101
+ }
102
+ const result = {};
103
+ for (const [key, value] of Object.entries(node)) {
104
+ result[key] = normalizeTree(value);
105
+ }
106
+ return result;
107
+ }
108
+ /** Recursively builds the dot-path keys object from a normalized tree. */
109
+ function buildKeys(obj, prefix) {
110
+ const result = {};
111
+ for (const [key, value] of Object.entries(obj)) {
112
+ const fullKey = prefix ? `${prefix}.${key}` : key;
113
+ if (isTranslationValue(value)) {
114
+ result[key] = fullKey;
115
+ }
116
+ else if (typeof value === 'object' && value !== null) {
117
+ result[key] = buildKeys(value, fullKey);
118
+ }
119
+ }
120
+ return result;
121
+ }
122
+ /** Type guard: is this value a branded `TranslationValue` (created by `t()` or normalization)? */
123
+ function isTranslationValue(value) {
124
+ return value !== null && typeof value === 'object' && value[TRANSLATION_BRAND] === true;
125
+ }
126
+ // =============================================================================
127
+ // Auto-derive a merged keys tree from module scopes (value-level)
128
+ // =============================================================================
129
+ /**
130
+ * Build a merged keys tree from a list of translation modules by placing each
131
+ * module's `keys` object at its scope path and deep-merging.
132
+ *
133
+ * This is the **runtime** value used by the directive (via the `I18N_KEYS`
134
+ * token) — it produces the exact nested shape the scanner emits as the typed
135
+ * `TK` literal. The scanner emits a concrete literal for *compile-time*
136
+ * autocomplete; this function produces the identical structure at runtime, so
137
+ * the two never diverge.
138
+ *
139
+ * Modules sharing a scope are merged (the scanner emits the same spread for the
140
+ * `TK` literal). Throws on scalar/scope conflicts.
141
+ */
142
+ function buildKeysTree(modules) {
143
+ const tree = {};
144
+ // Sort by scope depth so parent scopes are placed before children — guarantees
145
+ // a deeper scope descends through an already-copied parent slot.
146
+ const sorted = [...modules].sort((a, b) => a.scope.split('.').length - b.scope.split('.').length);
147
+ for (const mod of sorted) {
148
+ placeAtScope(tree, mod.scope, mod.keys);
149
+ }
150
+ return tree;
151
+ }
152
+ function placeAtScope(tree, scope, keys) {
153
+ const path = scope.split('.');
154
+ let current = tree;
155
+ for (let i = 0; i < path.length - 1; i++) {
156
+ const part = path[i];
157
+ const slot = current[part];
158
+ if (slot === undefined) {
159
+ current[part] = {};
160
+ }
161
+ else if (typeof slot !== 'object' || slot === null) {
162
+ throw new Error(`i18n: scope conflict at '${path.slice(0, i + 1).join('.')}': scalar where nested scope expected`);
163
+ }
164
+ current = current[part];
165
+ }
166
+ const leaf = path[path.length - 1];
167
+ const existing = current[leaf];
168
+ if (existing === undefined) {
169
+ current[leaf] = { ...keys };
170
+ }
171
+ else if (typeof existing === 'object' && existing !== null) {
172
+ current[leaf] = { ...keys, ...existing };
173
+ }
174
+ else {
175
+ throw new Error(`i18n: scope conflict at '${scope}': scalar where nested scope expected`);
176
+ }
177
+ }
178
+
179
+ /**
180
+ * Build a per-language translation tree from the in-memory module registry.
181
+ *
182
+ * Shared by:
183
+ * - the generator CLI — writes the tree as JSON to `<outputDir>/<lang>.json`
184
+ * for translator-facing tooling (build artifacts, not a runtime dependency).
185
+ * - the runtime `TranslocoRegistryLoader` — returns the tree synchronously to
186
+ * Transloco, eliminating the HTTP fetch.
187
+ *
188
+ * Producing the tree from the registry guarantees the runtime sees the exact
189
+ * shape the generator emits — there's no "JSON drifted from TS" failure mode.
190
+ *
191
+ * Locale handling is parameterized: every function takes the `defaultLang`
192
+ * (source/fallback locale) explicitly rather than reading a hardcoded constant,
193
+ * so the engine is reusable across consumers with different locale sets.
194
+ */
195
+ /**
196
+ * Resolve a single `TranslationValue` for a given language.
197
+ * Falls back to `defaultLang` for any locale that didn't supply a translation —
198
+ * mirrors `useFallbackTranslation: true` in the runtime Transloco config.
199
+ */
200
+ function getTranslation(value, lang, defaultLang) {
201
+ const byLang = value;
202
+ if (lang === defaultLang) {
203
+ return byLang[defaultLang] ?? value.en;
204
+ }
205
+ return byLang[lang] ?? byLang[defaultLang] ?? value.en;
206
+ }
207
+ /**
208
+ * Walk a normalized translation subtree (all leaves are `TranslationValue`s) and
209
+ * emit a string-only tree for the given language.
210
+ *
211
+ * If a leaf carries a `__comment` (set via `t(en, others, { comment })`), a
212
+ * sibling entry `<key>.comment` is added at the same level. Translators see it;
213
+ * the runtime interceptor strips it before it reaches the store.
214
+ */
215
+ function extractLanguage(translations, lang, defaultLang) {
216
+ const result = {};
217
+ for (const [key, value] of Object.entries(translations)) {
218
+ if (isTranslationValue(value)) {
219
+ result[key] = getTranslation(value, lang, defaultLang);
220
+ if (value.__comment) {
221
+ result[`${key}.comment`] = value.__comment;
222
+ }
223
+ }
224
+ else if (typeof value === 'object' && value !== null) {
225
+ result[key] = extractLanguage(value, lang, defaultLang);
226
+ }
227
+ }
228
+ return result;
229
+ }
230
+ /**
231
+ * Place a subtree at a dot-delimited scope path in the target tree, creating
232
+ * intermediate objects as needed. If the path already holds an object, the new
233
+ * subtree's leaves are merged into it.
234
+ */
235
+ function setAtScope(target, scope, subtree) {
236
+ const parts = scope.split('.');
237
+ let current = target;
238
+ for (let i = 0; i < parts.length - 1; i++) {
239
+ const part = parts[i];
240
+ const slot = current[part];
241
+ if (slot === undefined || typeof slot === 'string') {
242
+ current[part] = {};
243
+ }
244
+ current = current[part];
245
+ }
246
+ const leaf = parts[parts.length - 1];
247
+ const existing = current[leaf];
248
+ if (existing && typeof existing === 'object') {
249
+ Object.assign(existing, subtree);
250
+ }
251
+ else {
252
+ current[leaf] = subtree;
253
+ }
254
+ }
255
+ /**
256
+ * Build the complete translation tree for a single language from the registry.
257
+ * The returned tree matches the JSON file layout exactly — same keys, nesting,
258
+ * and fallbacks — so a consumer cannot tell whether the data came from the
259
+ * registry or from disk.
260
+ */
261
+ function buildLanguageTree(registry, lang, defaultLang) {
262
+ const tree = {};
263
+ for (const mod of registry) {
264
+ const subtree = extractLanguage(mod.translations, lang, defaultLang);
265
+ setAtScope(tree, mod.scope, subtree);
266
+ }
267
+ return tree;
268
+ }
269
+ /**
270
+ * Build the eager (root) tree — only modules declared without `{ scoped: true }`.
271
+ * Used by the generator when route-level scope providers are adopted.
272
+ */
273
+ function buildEagerTree(registry, lang, defaultLang) {
274
+ const tree = {};
275
+ for (const mod of registry) {
276
+ if (mod.scoped)
277
+ continue;
278
+ const subtree = extractLanguage(mod.translations, lang, defaultLang);
279
+ setAtScope(tree, mod.scope, subtree);
280
+ }
281
+ return tree;
282
+ }
283
+ /**
284
+ * Build the per-scope tree for a single scoped module — returned unwrapped
285
+ * (no scope key around it), matching the layout `provideTranslocoScope` expects
286
+ * to load from `<scope-with-slashes>/<lang>.json`.
287
+ *
288
+ * `scope` may be given in dotted (`administration.users`) or slash form
289
+ * (`administration/users` — what Transloco hands a loader); both match.
290
+ *
291
+ * Returns `null` if no module with the given scope exists, or if it's eager.
292
+ */
293
+ function buildScopedTree(registry, lang, defaultLang, scope) {
294
+ const wanted = normalizeScope(scope);
295
+ for (const mod of registry) {
296
+ if (mod.scoped && normalizeScope(mod.scope) === wanted) {
297
+ return extractLanguage(mod.translations, lang, defaultLang);
298
+ }
299
+ }
300
+ return null;
301
+ }
302
+ /**
303
+ * Convert a dot-separated scope to its filesystem path.
304
+ * 'administration.users' → 'administration/users'
305
+ */
306
+ function scopeToFilesystemPath(scope) {
307
+ return scope.replace(/\./g, '/');
308
+ }
309
+ /**
310
+ * Canonical dotted form of a scope, accepting either separator.
311
+ * 'administration/users' → 'administration.users'
312
+ */
313
+ function normalizeScope(scope) {
314
+ return scope.replace(/\//g, '.');
315
+ }
316
+
317
+ /*
318
+ * @hakistack/i18n/engine
319
+ *
320
+ * The Angular-free authoring + tree-building engine. This entry point has NO
321
+ * Angular dependency, so it loads in a plain Node context — which is what lets
322
+ * the codegen CLI execute your `*.i18n.ts` modules via a TS loader.
323
+ *
324
+ * Author your translation modules against THIS entry point:
325
+ *
326
+ * ```ts
327
+ * import { defineTranslations, t } from '@hakistack/i18n/engine';
328
+ * ```
329
+ *
330
+ * Runtime APIs (`provideI18n`, `translateSignal`, the directive base) live on
331
+ * the main `@hakistack/i18n` entry point.
332
+ */
333
+
334
+ /**
335
+ * Generated bundle index. Do not edit.
336
+ */
337
+
338
+ export { SOURCE_LANG, TRANSLATION_BRAND, buildEagerTree, buildKeysTree, buildLanguageTree, buildScopedTree, defineTranslations, extractLanguage, getTranslation, isTranslationValue, normalizeScope, scopeToFilesystemPath, setAtScope, t };
339
+ //# sourceMappingURL=hakistack-i18n-engine.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hakistack-i18n-engine.mjs","sources":["../../../../projects/hakistack/i18n/engine/define-translations.ts","../../../../projects/hakistack/i18n/engine/build-tree.ts","../../../../projects/hakistack/i18n/engine/public-api.ts","../../../../projects/hakistack/i18n/engine/hakistack-i18n-engine.ts"],"sourcesContent":["/**\n * Type-safe translation definitions — the authoring heart of `@hakistack/i18n`.\n *\n * Consumers author translations in `.ts` files (`*.i18n.ts`) using\n * `defineTranslations()` + `t()`. English is the required source locale; every\n * other locale is optional. The companion `keys` object gives type-safe\n * dot-path access at the value level, and the scanner derives a merged `TK`\n * literal from these modules.\n *\n * Unlike the original app-local engine, locales here are **not hardcoded**.\n * Consumers declare their locale union by augmenting the {@link I18nLocales}\n * interface (the scanner / schematic can emit this augmentation), so `t()` gets\n * autocomplete on exactly the locales the project supports.\n */\n\n// =============================================================================\n// Locale configuration (consumer-augmented)\n// =============================================================================\n\n/**\n * The set of locales a project supports, as a type.\n *\n * `en` is the always-present source locale (English is the source of truth).\n * Consumers add their other locales by declaration-merging this interface:\n *\n * ```ts\n * declare module '@hakistack/i18n/engine' {\n * interface I18nLocales {\n * es: string;\n * fr: string;\n * }\n * }\n * ```\n *\n * After augmentation, `t('Hello', { es: '…', fr: '…' })` autocompletes `es`/`fr`\n * and `Language` resolves to `'en' | 'es' | 'fr'`.\n */\nexport interface I18nLocales {\n /** Source locale — always required on every translation value. */\n en: string;\n}\n\n/** Union of every declared locale id (e.g. `'en' | 'es'`). */\nexport type LocaleId = keyof I18nLocales & string;\n\n/**\n * The source locale. `t()` stores its first argument here, every other locale\n * is optional, and build-time + runtime fallbacks end here. This is fixed by\n * the engine's types (`TranslationValue.en`), so it is not configurable.\n */\nexport const SOURCE_LANG = 'en';\nexport type SourceLang = typeof SOURCE_LANG;\n\n/**\n * Runtime brand stamped (non-enumerably) on every `TranslationValue` produced\n * by `t()` or by bare-string normalization.\n *\n * Without a brand, a *group* whose child happens to be named `en` — e.g.\n * `languages: { en: 'English', es: 'Español' }` in a language picker — is\n * indistinguishable from a leaf. `Symbol.for` (global registry) is used so the\n * codegen CLI (which bundles its own copy of the engine) recognizes values\n * created by the consumer's installed copy.\n */\nexport const TRANSLATION_BRAND: unique symbol = Symbol.for('@hakistack/i18n:translation-value');\n\n/** Alias kept for ergonomics — the active/target language id. */\nexport type Language = LocaleId;\n\n// =============================================================================\n// Type Definitions\n// =============================================================================\n\n/**\n * A single translation value across all declared locales.\n *\n * English (`en`) is required; every other declared locale is optional and falls\n * back to English at build time and runtime. The optional `__comment` field\n * stores translator-facing context — it is emitted as a sibling `<key>.comment`\n * entry in the JSON and stripped by the runtime interceptor so it never renders.\n */\nexport type TranslationValue = OtherLocales & {\n en: string;\n /** Internal — translator-context comment, attached via `t(en, others, { comment })`. */\n __comment?: string;\n /** Internal — runtime brand; only `t()` / normalization create branded values. */\n readonly [TRANSLATION_BRAND]: true;\n};\n\n/** Optional non-source locale fields, derived from the augmented locale set. */\nexport type OtherLocales = {\n [K in Exclude<LocaleId, 'en'>]?: string;\n};\n\n/**\n * Define a single translation value.\n *\n * @param en - English (source) translation — required.\n * @param translations - Other-locale translations — optional, autocompletes the\n * consumer's declared locales.\n * @param options.comment - Translator-facing context. Emitted as a sibling\n * `<key>.comment` entry in the JSON for translator review; stripped at runtime\n * by the comment interceptor so it never renders.\n *\n * @example\n * t('Hello', { es: 'Hola' })\n * t('Save') // English only — other locales fall back to English\n * t('Welcome', { es: '¡Bienvenido!' }, { comment: 'Greeting on home dashboard' })\n */\nexport function t(en: string, translations?: OtherLocales, options?: { comment?: string }): TranslationValue {\n const value = brand({ en, ...translations });\n if (options?.comment) {\n value.__comment = options.comment;\n }\n return value;\n}\n\n/** Stamp the non-enumerable brand on a plain `{ en, … }` record. */\nfunction brand(value: OtherLocales & { en: string; __comment?: string }): TranslationValue {\n Object.defineProperty(value, TRANSLATION_BRAND, { value: true, enumerable: false, writable: false, configurable: false });\n return value as TranslationValue;\n}\n\n/**\n * Authored translation node — what callers write inside `defineTranslations()`.\n * Accepts:\n * - `TranslationValue` (full form, from `t()`)\n * - `string` (shorthand for English-only — equivalent to `t(value)`)\n * - nested object of either\n *\n * Only `t()` produces a leaf. A hand-written `{ en: '…', es: '…' }` object is a\n * *group* with children named `en`/`es` — which is what a language picker wants.\n *\n * Strings are normalized to `TranslationValue` at module construction so the\n * rest of the pipeline (generator, validator, keys builder) only ever sees the\n * canonical `{ en, … }` shape.\n *\n * Note: any leaf string containing `{{…}}` placeholders MUST use `t()` — the\n * validator rejects bare placeholder strings because parity across locales\n * cannot be expressed with the shorthand.\n */\nexport type AuthoredTranslationNode = TranslationValue | string | { [key: string]: AuthoredTranslationNode };\n\n/** Canonical (post-normalization) translation node — internal use only. */\ntype TranslationNode = TranslationValue | { [key: string]: TranslationNode };\n\n/**\n * Recursively builds dot-notation key strings from the authored object shape.\n * Treats both `TranslationValue` and `string` as leaves (string is shorthand).\n */\ntype BuildKeyObject<T, Prefix extends string = ''> = {\n readonly [K in keyof T]: K extends string\n ? T[K] extends TranslationValue | string\n ? Prefix extends ''\n ? K\n : `${Prefix}.${K}`\n : T[K] extends Record<string, unknown>\n ? BuildKeyObject<T[K], Prefix extends '' ? K : `${Prefix}.${K}`>\n : never\n : never;\n};\n\n/**\n * Translation module returned by {@link defineTranslations}.\n *\n * `translations` stores the normalized form (every bare string promoted to\n * `{ en: value }`); `keys` is the type-derived companion of dot-paths.\n */\nexport interface TranslationModule<T extends Record<string, AuthoredTranslationNode> = Record<string, AuthoredTranslationNode>> {\n /** Scope/prefix for these translations (e.g. `'common'`, `'administration.users'`). */\n scope: string;\n /** Normalized translation definitions (strings promoted to `{ en: value }`). */\n translations: T;\n /** Auto-generated keys object for type-safe usage. */\n keys: BuildKeyObject<T>;\n /**\n * If `true`, the generator emits this module's data to a subdirectory matching\n * its scope path (`administration.users` → `administration/users/<lang>.json`)\n * rather than merging into the root `<lang>.json`. Future-proofs\n * `provideTranslocoScope`-based lazy loading. Default: `false` (eager).\n */\n scoped: boolean;\n}\n\n/**\n * Define a translation module with auto-generated keys.\n *\n * @param scope - The scope/prefix for these translations.\n * @param translations - The translation definitions (full `t()` form or\n * bare-string shorthand, nested freely).\n * @param options.scoped - Emit to a per-scope JSON file (see {@link TranslationModule.scoped}).\n *\n * @example\n * export const COMMON = defineTranslations('common', {\n * buttons: {\n * save: t('Save', { es: 'Guardar' }),\n * cancel: t('Cancel', { es: 'Cancelar' }),\n * reset: 'Reset', // shorthand\n * },\n * });\n * // COMMON.keys.buttons.save === 'common.buttons.save'\n */\nexport function defineTranslations<T extends Record<string, AuthoredTranslationNode>>(\n scope: string,\n translations: T,\n options?: { scoped?: boolean },\n): TranslationModule<T> {\n const normalized = normalizeTree(translations) as Record<string, TranslationNode>;\n const keys = buildKeys(normalized, scope) as BuildKeyObject<T>;\n return {\n scope,\n translations: normalized as unknown as T,\n keys,\n scoped: options?.scoped ?? false,\n };\n}\n\n// =============================================================================\n// Internal Utilities\n// =============================================================================\n\n/**\n * Normalize an authored tree by replacing every bare-string leaf with\n * `{ en: value }`. The output contains only `TranslationValue` leaves and\n * nested records — the canonical shape consumed by the generator/validator.\n */\nfunction normalizeTree(node: AuthoredTranslationNode): TranslationNode {\n if (typeof node === 'string') {\n return brand({ en: node });\n }\n if (isTranslationValue(node)) {\n return node;\n }\n const result: Record<string, TranslationNode> = {};\n for (const [key, value] of Object.entries(node)) {\n result[key] = normalizeTree(value as AuthoredTranslationNode);\n }\n return result;\n}\n\n/** Recursively builds the dot-path keys object from a normalized tree. */\nfunction buildKeys(obj: Record<string, unknown>, prefix: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(obj)) {\n const fullKey = prefix ? `${prefix}.${key}` : key;\n if (isTranslationValue(value)) {\n result[key] = fullKey;\n } else if (typeof value === 'object' && value !== null) {\n result[key] = buildKeys(value as Record<string, unknown>, fullKey);\n }\n }\n return result;\n}\n\n/** Type guard: is this value a branded `TranslationValue` (created by `t()` or normalization)? */\nexport function isTranslationValue(value: unknown): value is TranslationValue {\n return value !== null && typeof value === 'object' && (value as Record<symbol, unknown>)[TRANSLATION_BRAND] === true;\n}\n\n// =============================================================================\n// Auto-derive a merged keys tree from module scopes (value-level)\n// =============================================================================\n\n/**\n * Build a merged keys tree from a list of translation modules by placing each\n * module's `keys` object at its scope path and deep-merging.\n *\n * This is the **runtime** value used by the directive (via the `I18N_KEYS`\n * token) — it produces the exact nested shape the scanner emits as the typed\n * `TK` literal. The scanner emits a concrete literal for *compile-time*\n * autocomplete; this function produces the identical structure at runtime, so\n * the two never diverge.\n *\n * Modules sharing a scope are merged (the scanner emits the same spread for the\n * `TK` literal). Throws on scalar/scope conflicts.\n */\nexport function buildKeysTree(modules: readonly TranslationModule[]): Record<string, unknown> {\n const tree: Record<string, unknown> = {};\n\n // Sort by scope depth so parent scopes are placed before children — guarantees\n // a deeper scope descends through an already-copied parent slot.\n const sorted = [...modules].sort((a, b) => a.scope.split('.').length - b.scope.split('.').length);\n\n for (const mod of sorted) {\n placeAtScope(tree, mod.scope, mod.keys);\n }\n return tree;\n}\n\nfunction placeAtScope(tree: Record<string, unknown>, scope: string, keys: unknown): void {\n const path = scope.split('.');\n let current = tree;\n\n for (let i = 0; i < path.length - 1; i++) {\n const part = path[i];\n const slot = current[part];\n if (slot === undefined) {\n current[part] = {};\n } else if (typeof slot !== 'object' || slot === null) {\n throw new Error(`i18n: scope conflict at '${path.slice(0, i + 1).join('.')}': scalar where nested scope expected`);\n }\n current = current[part] as Record<string, unknown>;\n }\n\n const leaf = path[path.length - 1];\n const existing = current[leaf];\n\n if (existing === undefined) {\n current[leaf] = { ...(keys as object) };\n } else if (typeof existing === 'object' && existing !== null) {\n current[leaf] = { ...(keys as object), ...(existing as object) };\n } else {\n throw new Error(`i18n: scope conflict at '${scope}': scalar where nested scope expected`);\n }\n}\n","/**\n * Build a per-language translation tree from the in-memory module registry.\n *\n * Shared by:\n * - the generator CLI — writes the tree as JSON to `<outputDir>/<lang>.json`\n * for translator-facing tooling (build artifacts, not a runtime dependency).\n * - the runtime `TranslocoRegistryLoader` — returns the tree synchronously to\n * Transloco, eliminating the HTTP fetch.\n *\n * Producing the tree from the registry guarantees the runtime sees the exact\n * shape the generator emits — there's no \"JSON drifted from TS\" failure mode.\n *\n * Locale handling is parameterized: every function takes the `defaultLang`\n * (source/fallback locale) explicitly rather than reading a hardcoded constant,\n * so the engine is reusable across consumers with different locale sets.\n */\n\nimport { AuthoredTranslationNode, isTranslationValue, TranslationModule, TranslationValue } from './define-translations';\n\n/** A nested string-tree as Transloco / the JSON files consume it. */\nexport interface LanguageTree {\n [key: string]: string | LanguageTree;\n}\n\n/**\n * Resolve a single `TranslationValue` for a given language.\n * Falls back to `defaultLang` for any locale that didn't supply a translation —\n * mirrors `useFallbackTranslation: true` in the runtime Transloco config.\n */\nexport function getTranslation(value: TranslationValue, lang: string, defaultLang: string): string {\n const byLang = value as Record<string, string | undefined>;\n if (lang === defaultLang) {\n return byLang[defaultLang] ?? value.en;\n }\n return byLang[lang] ?? byLang[defaultLang] ?? value.en;\n}\n\n/**\n * Walk a normalized translation subtree (all leaves are `TranslationValue`s) and\n * emit a string-only tree for the given language.\n *\n * If a leaf carries a `__comment` (set via `t(en, others, { comment })`), a\n * sibling entry `<key>.comment` is added at the same level. Translators see it;\n * the runtime interceptor strips it before it reaches the store.\n */\nexport function extractLanguage(translations: Record<string, unknown>, lang: string, defaultLang: string): LanguageTree {\n const result: LanguageTree = {};\n for (const [key, value] of Object.entries(translations)) {\n if (isTranslationValue(value)) {\n result[key] = getTranslation(value, lang, defaultLang);\n if (value.__comment) {\n result[`${key}.comment`] = value.__comment;\n }\n } else if (typeof value === 'object' && value !== null) {\n result[key] = extractLanguage(value as Record<string, unknown>, lang, defaultLang);\n }\n }\n return result;\n}\n\n/**\n * Place a subtree at a dot-delimited scope path in the target tree, creating\n * intermediate objects as needed. If the path already holds an object, the new\n * subtree's leaves are merged into it.\n */\nexport function setAtScope(target: LanguageTree, scope: string, subtree: LanguageTree): void {\n const parts = scope.split('.');\n let current: LanguageTree = target;\n\n for (let i = 0; i < parts.length - 1; i++) {\n const part = parts[i];\n const slot = current[part];\n if (slot === undefined || typeof slot === 'string') {\n current[part] = {};\n }\n current = current[part] as LanguageTree;\n }\n\n const leaf = parts[parts.length - 1];\n const existing = current[leaf];\n if (existing && typeof existing === 'object') {\n Object.assign(existing, subtree);\n } else {\n current[leaf] = subtree;\n }\n}\n\n/**\n * Build the complete translation tree for a single language from the registry.\n * The returned tree matches the JSON file layout exactly — same keys, nesting,\n * and fallbacks — so a consumer cannot tell whether the data came from the\n * registry or from disk.\n */\nexport function buildLanguageTree(\n registry: readonly TranslationModule<Record<string, AuthoredTranslationNode>>[],\n lang: string,\n defaultLang: string,\n): LanguageTree {\n const tree: LanguageTree = {};\n for (const mod of registry) {\n const subtree = extractLanguage(mod.translations, lang, defaultLang);\n setAtScope(tree, mod.scope, subtree);\n }\n return tree;\n}\n\n/**\n * Build the eager (root) tree — only modules declared without `{ scoped: true }`.\n * Used by the generator when route-level scope providers are adopted.\n */\nexport function buildEagerTree(\n registry: readonly TranslationModule<Record<string, AuthoredTranslationNode>>[],\n lang: string,\n defaultLang: string,\n): LanguageTree {\n const tree: LanguageTree = {};\n for (const mod of registry) {\n if (mod.scoped) continue;\n const subtree = extractLanguage(mod.translations, lang, defaultLang);\n setAtScope(tree, mod.scope, subtree);\n }\n return tree;\n}\n\n/**\n * Build the per-scope tree for a single scoped module — returned unwrapped\n * (no scope key around it), matching the layout `provideTranslocoScope` expects\n * to load from `<scope-with-slashes>/<lang>.json`.\n *\n * `scope` may be given in dotted (`administration.users`) or slash form\n * (`administration/users` — what Transloco hands a loader); both match.\n *\n * Returns `null` if no module with the given scope exists, or if it's eager.\n */\nexport function buildScopedTree(\n registry: readonly TranslationModule<Record<string, AuthoredTranslationNode>>[],\n lang: string,\n defaultLang: string,\n scope: string,\n): LanguageTree | null {\n const wanted = normalizeScope(scope);\n for (const mod of registry) {\n if (mod.scoped && normalizeScope(mod.scope) === wanted) {\n return extractLanguage(mod.translations, lang, defaultLang);\n }\n }\n return null;\n}\n\n/**\n * Convert a dot-separated scope to its filesystem path.\n * 'administration.users' → 'administration/users'\n */\nexport function scopeToFilesystemPath(scope: string): string {\n return scope.replace(/\\./g, '/');\n}\n\n/**\n * Canonical dotted form of a scope, accepting either separator.\n * 'administration/users' → 'administration.users'\n */\nexport function normalizeScope(scope: string): string {\n return scope.replace(/\\//g, '.');\n}\n","/*\n * @hakistack/i18n/engine\n *\n * The Angular-free authoring + tree-building engine. This entry point has NO\n * Angular dependency, so it loads in a plain Node context — which is what lets\n * the codegen CLI execute your `*.i18n.ts` modules via a TS loader.\n *\n * Author your translation modules against THIS entry point:\n *\n * ```ts\n * import { defineTranslations, t } from '@hakistack/i18n/engine';\n * ```\n *\n * Runtime APIs (`provideI18n`, `translateSignal`, the directive base) live on\n * the main `@hakistack/i18n` entry point.\n */\n\nexport { buildKeysTree, defineTranslations, isTranslationValue, SOURCE_LANG, t, TRANSLATION_BRAND } from './define-translations';\nexport type {\n AuthoredTranslationNode,\n I18nLocales,\n Language,\n LocaleId,\n OtherLocales,\n SourceLang,\n TranslationModule,\n TranslationValue,\n} from './define-translations';\n\nexport {\n buildEagerTree,\n buildLanguageTree,\n buildScopedTree,\n extractLanguage,\n getTranslation,\n normalizeScope,\n scopeToFilesystemPath,\n setAtScope,\n} from './build-tree';\nexport type { LanguageTree } from './build-tree';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;AAaG;AAgCH;;;;AAIG;AACI,MAAM,WAAW,GAAG;AAG3B;;;;;;;;;AASG;AACI,MAAM,iBAAiB,GAAkB,MAAM,CAAC,GAAG,CAAC,mCAAmC;AA8B9F;;;;;;;;;;;;;;AAcG;SACa,CAAC,CAAC,EAAU,EAAE,YAA2B,EAAE,OAA8B,EAAA;IACvF,MAAM,KAAK,GAAG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