mn-angular-lib 1.0.177 → 1.0.179

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.
Files changed (66) hide show
  1. package/fesm2022/mn-angular-lib-alert.mjs +535 -0
  2. package/fesm2022/mn-angular-lib-alert.mjs.map +1 -0
  3. package/fesm2022/mn-angular-lib-bottom-sheet.mjs +356 -0
  4. package/fesm2022/mn-angular-lib-bottom-sheet.mjs.map +1 -0
  5. package/fesm2022/mn-angular-lib-button.mjs +382 -0
  6. package/fesm2022/mn-angular-lib-button.mjs.map +1 -0
  7. package/fesm2022/mn-angular-lib-calendar-core.mjs +377 -0
  8. package/fesm2022/mn-angular-lib-calendar-core.mjs.map +1 -0
  9. package/fesm2022/mn-angular-lib-calendar.mjs +1513 -0
  10. package/fesm2022/mn-angular-lib-calendar.mjs.map +1 -0
  11. package/fesm2022/mn-angular-lib-collection.mjs +2277 -0
  12. package/fesm2022/mn-angular-lib-collection.mjs.map +1 -0
  13. package/fesm2022/mn-angular-lib-core.mjs +1232 -0
  14. package/fesm2022/mn-angular-lib-core.mjs.map +1 -0
  15. package/fesm2022/mn-angular-lib-display.mjs +728 -0
  16. package/fesm2022/mn-angular-lib-display.mjs.map +1 -0
  17. package/fesm2022/mn-angular-lib-forms.mjs +4260 -0
  18. package/fesm2022/mn-angular-lib-forms.mjs.map +1 -0
  19. package/fesm2022/mn-angular-lib-keyboard.mjs +195 -0
  20. package/fesm2022/mn-angular-lib-keyboard.mjs.map +1 -0
  21. package/fesm2022/mn-angular-lib-modal-core.mjs +945 -0
  22. package/fesm2022/mn-angular-lib-modal-core.mjs.map +1 -0
  23. package/fesm2022/mn-angular-lib-modal-ui.mjs +2016 -0
  24. package/fesm2022/mn-angular-lib-modal-ui.mjs.map +1 -0
  25. package/fesm2022/mn-angular-lib-modal.mjs +126 -0
  26. package/fesm2022/mn-angular-lib-modal.mjs.map +1 -0
  27. package/fesm2022/mn-angular-lib-rich-text-editor.mjs +275 -0
  28. package/fesm2022/mn-angular-lib-rich-text-editor.mjs.map +1 -0
  29. package/fesm2022/mn-angular-lib-segmented.mjs +246 -0
  30. package/fesm2022/mn-angular-lib-segmented.mjs.map +1 -0
  31. package/fesm2022/mn-angular-lib-tab.mjs +573 -0
  32. package/fesm2022/mn-angular-lib-tab.mjs.map +1 -0
  33. package/fesm2022/mn-angular-lib.mjs +21 -15509
  34. package/fesm2022/mn-angular-lib.mjs.map +1 -1
  35. package/package.json +66 -1
  36. package/src/lib/styles/index.css +2 -2
  37. package/types/mn-angular-lib-alert.d.ts +258 -0
  38. package/types/mn-angular-lib-bottom-sheet.d.ts +173 -0
  39. package/types/mn-angular-lib-button.d.ts +318 -0
  40. package/types/mn-angular-lib-calendar-core.d.ts +378 -0
  41. package/types/mn-angular-lib-calendar.d.ts +636 -0
  42. package/types/mn-angular-lib-collection.d.ts +1550 -0
  43. package/types/mn-angular-lib-core.d.ts +756 -0
  44. package/types/mn-angular-lib-display.d.ts +1075 -0
  45. package/types/mn-angular-lib-forms.d.ts +3235 -0
  46. package/types/mn-angular-lib-keyboard.d.ts +128 -0
  47. package/types/mn-angular-lib-modal-core.d.ts +1130 -0
  48. package/types/mn-angular-lib-modal-ui.d.ts +492 -0
  49. package/types/mn-angular-lib-modal.d.ts +27 -0
  50. package/types/mn-angular-lib-rich-text-editor.d.ts +157 -0
  51. package/types/mn-angular-lib-segmented.d.ts +395 -0
  52. package/types/mn-angular-lib-tab.d.ts +313 -0
  53. package/types/mn-angular-lib.d.ts +16 -10816
  54. /package/{src/lib/features → alert/src}/mn-alert/mn-alert-outlet/mn-alert-outlet.css +0 -0
  55. /package/{src/lib/features → bottom-sheet/src}/mn-bottom-sheet/mn-bottom-sheet.component.css +0 -0
  56. /package/{src/lib/features → button/src}/mn-skeleton/mn-skeleton.css +0 -0
  57. /package/{src/lib/features → collection/src}/mn-list/mn-list.component.css +0 -0
  58. /package/{src/lib/features → forms/src}/mn-checkbox/mn-checkbox.css +0 -0
  59. /package/{src/lib/features → forms/src}/mn-dropdown/mn-dropdown.css +0 -0
  60. /package/{src/lib/features → forms/src}/mn-multi-select/mn-multi-select.css +0 -0
  61. /package/{src/lib/features → keyboard/src}/mn-keyboard/mn-keyboard.component.css +0 -0
  62. /package/{src/lib/features → modal-ui/src}/mn-modal/components/mn-confirmation-body/mn-confirmation-body.component.css +0 -0
  63. /package/{src/lib/features → modal-ui/src}/mn-modal/components/mn-form-body/mn-form-body.component.css +0 -0
  64. /package/{src/lib/features → modal-ui/src}/mn-modal/components/mn-modal-shell/mn-modal-shell.component.css +0 -0
  65. /package/{src/lib/features → modal-ui/src}/mn-modal/components/mn-wizard-body/mn-wizard-body.component.css +0 -0
  66. /package/{src/lib/features → rich-text-editor/src}/mn-rich-text-editor/mn-rich-text-editor.component.css +0 -0
@@ -0,0 +1,1232 @@
1
+ import * as i0 from '@angular/core';
2
+ import { inject, ApplicationRef, Injectable, APP_INITIALIZER, Pipe, signal, InjectionToken, DestroyRef, Optional, SkipSelf, Attribute, Input, Directive } from '@angular/core';
3
+ import { HttpClient, HttpErrorResponse, HttpStatusCode, HttpParams } from '@angular/common/http';
4
+ import { BehaviorSubject, firstValueFrom, map, catchError, of } from 'rxjs';
5
+
6
+ /**
7
+ * Types for mn-lib configuration.
8
+ */
9
+
10
+ /**
11
+ * Type guard: checks whether a value is a translatable marker object.
12
+ */
13
+ function isTranslatable(value) {
14
+ return (typeof value === 'object' &&
15
+ value !== null &&
16
+ typeof value['$translate'] === 'string');
17
+ }
18
+
19
+ /**
20
+ * Key suffix per CLDR plural category.
21
+ *
22
+ * Only `one` earns a suffix: every locale shipped so far (`en`, `nl`) has exactly the two
23
+ * categories `one` and `other`, and `other` keeps the bare key. A locale with `few`/`many`
24
+ * (Polish, Russian, Arabic) resolves those to the plural until an entry is added here —
25
+ * adding one is the whole change, since the lookup is category-driven already.
26
+ */
27
+ const PLURAL_SUFFIX = {
28
+ one: 'One',
29
+ };
30
+ /** Params key whose presence turns a translation into a plural-aware lookup. */
31
+ const COUNT_PARAM = 'count';
32
+ class MnLanguageService {
33
+ http = inject(HttpClient);
34
+ appRef = inject(ApplicationRef);
35
+ _translations = {};
36
+ _locale$ = new BehaviorSubject('en');
37
+ _urlPattern = null;
38
+ _debug = false;
39
+ /**
40
+ * `Intl.PluralRules` per locale. Cached because {@link translate} runs on every change
41
+ * detection through the impure `mnTranslate` pipe, and constructing one is not cheap.
42
+ */
43
+ _pluralRules = new Map();
44
+ /** Observable of the current active locale. */
45
+ locale$ = this._locale$.asObservable();
46
+ /** Current active locale. */
47
+ get locale() {
48
+ return this._locale$.value;
49
+ }
50
+ /**
51
+ * Enable or disable debug logging.
52
+ */
53
+ setDebug(enabled) {
54
+ this._debug = enabled;
55
+ if (enabled) {
56
+ console.log(`[MnLanguage] Debug mode enabled`);
57
+ }
58
+ }
59
+ /**
60
+ * Configure the URL pattern used to fetch translation files.
61
+ * Use `{locale}` as placeholder, e.g. `"assets/i18n/{locale}.json"`.
62
+ */
63
+ configure(urlPattern) {
64
+ if (this._debug) {
65
+ console.log(`[MnLanguage] Configured urlPattern: ${urlPattern}`);
66
+ }
67
+ this._urlPattern = urlPattern;
68
+ }
69
+ /**
70
+ * Load translations for a locale from the configured URL pattern.
71
+ * If translations are already loaded for this locale, this is a no-op.
72
+ */
73
+ async loadLocale(locale) {
74
+ if (this._translations[locale])
75
+ return;
76
+ if (!this._urlPattern) {
77
+ console.warn(`[MnLanguage] No URL pattern configured. Call configure() or use provideMnLanguage().`);
78
+ return;
79
+ }
80
+ const url = this._urlPattern.replace('{locale}', locale);
81
+ if (this._debug) {
82
+ console.log(`[MnLanguage] Loading locale "${locale}" from ${url}`);
83
+ }
84
+ try {
85
+ const map = await firstValueFrom(this.http.get(url));
86
+ this._translations[locale] = map ?? {};
87
+ if (this._debug) {
88
+ console.log(`[MnLanguage] Loaded locale "${locale}"`, this._translations[locale]);
89
+ }
90
+ }
91
+ catch (err) {
92
+ console.warn(`[MnLanguage] Failed to load translations from ${url}`, err);
93
+ this._translations[locale] = {};
94
+ }
95
+ }
96
+ /**
97
+ * Switch the active locale. Loads translations if not yet loaded.
98
+ */
99
+ async setLocale(locale) {
100
+ if (this._debug) {
101
+ console.log(`[MnLanguage] Setting locale to "${locale}"`);
102
+ }
103
+ await this.loadLocale(locale);
104
+ this._locale$.next(locale);
105
+ this.appRef.tick();
106
+ }
107
+ /**
108
+ * Register translations for a locale directly from code (no HTTP needed).
109
+ */
110
+ registerTranslations(locale, translations) {
111
+ this._translations[locale] = {
112
+ ...(this._translations[locale] ?? {}),
113
+ ...translations,
114
+ };
115
+ }
116
+ /**
117
+ * Translate a key using the current locale, with optional parameter interpolation.
118
+ * Falls back to the key itself if no translation is found.
119
+ *
120
+ * Interpolation replaces `{{paramName}}` with the provided value.
121
+ *
122
+ * A `count` param additionally selects the wording that agrees with it: the key is
123
+ * resolved against its CLDR plural category first (`key` + `One`/`Two`/`Few`/`Many`/
124
+ * `Zero`), falling back to `key` when that sibling is undefined. Nothing has to opt in —
125
+ * a key with no sibling behaves exactly as before.
126
+ *
127
+ * ```ts
128
+ * // 'shift.asked' → '{{count}} members are notified'
129
+ * // 'shift.askedOne' → '{{count}} member is notified'
130
+ * lang.translate('shift.asked', { count: 3 }); // 3 members are notified
131
+ * lang.translate('shift.asked', { count: 1 }); // 1 member is notified
132
+ * ```
133
+ */
134
+ translate(key, params) {
135
+ const map = this._translations[this.locale] ?? {};
136
+ let value = this.getValueFromMap(map, this.resolvePluralKey(map, key, params));
137
+ if (value === undefined) {
138
+ if (this._debug) {
139
+ console.warn(`[MnLanguage] Missing translation for key: "${key}" in locale: "${this.locale}"`);
140
+ }
141
+ return key;
142
+ }
143
+ if (params) {
144
+ for (const [paramKey, paramValue] of Object.entries(params)) {
145
+ value = value.replace(new RegExp(`\\{\\{${paramKey}\\}\\}`, 'g'), String(paramValue));
146
+ }
147
+ }
148
+ return value;
149
+ }
150
+ /**
151
+ * Picks the wording that agrees with a `count` param.
152
+ *
153
+ * A key carrying a count resolves against its CLDR plural category first, so
154
+ * `askedMessage` + `askedMessageOne` render "3 leden krijgen bericht" and "1 lid krijgt
155
+ * bericht" off the same call. Both languages change the verb as well as the noun, which
156
+ * is why each form is a whole sentence under its own key rather than a swapped noun.
157
+ *
158
+ * Falls back to `key` whenever the sibling is undefined, so a key that never needed a
159
+ * plural — or an app that has not written one yet — behaves exactly as it did before.
160
+ * @param map The active locale's translations.
161
+ * @param key The dot-notated translation key.
162
+ * @param params The interpolation values, inspected for `count`.
163
+ * @returns The key to look up: the plural sibling, or `key` itself.
164
+ */
165
+ resolvePluralKey(map, key, params) {
166
+ const raw = params?.[COUNT_PARAM];
167
+ if (raw === undefined)
168
+ return key;
169
+ // A count off a JSON payload arrives as a string often enough that comparing it
170
+ // strictly would silently pick the plural for a count of one.
171
+ const count = Number(raw);
172
+ if (!Number.isFinite(count))
173
+ return key;
174
+ const suffix = PLURAL_SUFFIX[this.pluralCategory(count)];
175
+ if (suffix === undefined)
176
+ return key;
177
+ const variant = key + suffix;
178
+ return this.getValueFromMap(map, variant) !== undefined ? variant : key;
179
+ }
180
+ /**
181
+ * The CLDR plural category of a count in the active locale.
182
+ * @param count The count being quoted.
183
+ * @returns The category, falling back to English rules for an unusable locale.
184
+ */
185
+ pluralCategory(count) {
186
+ if (!this._pluralRules.has(this.locale)) {
187
+ try {
188
+ this._pluralRules.set(this.locale, new Intl.PluralRules(this.locale));
189
+ }
190
+ catch {
191
+ // An unknown or malformed locale tag: fall back rather than break every string.
192
+ this._pluralRules.set(this.locale, null);
193
+ }
194
+ }
195
+ const rules = this._pluralRules.get(this.locale);
196
+ if (!rules)
197
+ return count === 1 ? 'one' : 'other';
198
+ return rules.select(count);
199
+ }
200
+ /**
201
+ * Helper to retrieve a value from a potentially nested translation map using a dot-notated key.
202
+ */
203
+ getValueFromMap(map, key) {
204
+ // A flattened bundle holds the dotted key verbatim; a nested one is walked below.
205
+ const direct = map[key];
206
+ if (typeof direct === 'string')
207
+ return direct;
208
+ const parts = key.split('.');
209
+ let current = map;
210
+ for (const part of parts) {
211
+ if (current === null || typeof current !== 'object')
212
+ return undefined;
213
+ current = current[part];
214
+ }
215
+ return typeof current === 'string' ? current : undefined;
216
+ }
217
+ /**
218
+ * Translate a key **only if it is defined**, returning `undefined` otherwise.
219
+ *
220
+ * {@link translate} deliberately returns the key itself when it is missing, which
221
+ * makes it unusable for a library's own default labels: a consumer that never
222
+ * defined `mnCollection.rowsPerPage` would see that raw string in their UI. This
223
+ * lets a caller try a conventional key and fall back to a readable English default
224
+ * when the app has not translated it, so components ship translatable strings
225
+ * without forcing every consumer to define them.
226
+ *
227
+ * @param key The dot-notated translation key.
228
+ * @param params Optional `{{name}}` interpolation values.
229
+ * @returns The translation, or `undefined` when the key is not defined.
230
+ */
231
+ translateIfPresent(key, params) {
232
+ const map = this._translations[this.locale] ?? {};
233
+ if (this.getValueFromMap(map, key) === undefined)
234
+ return undefined;
235
+ return this.translate(key, params);
236
+ }
237
+ /**
238
+ * Shorthand alias for `translate`.
239
+ */
240
+ t(key, params) {
241
+ return this.translate(key, params);
242
+ }
243
+ /**
244
+ * Resolve the effective default locale from a domain-to-locale map.
245
+ * Matches `window.location.hostname` against the map keys.
246
+ * Returns the mapped locale, or the provided fallback if no match is found.
247
+ */
248
+ resolveLocaleForDomain(domainLocaleMap, fallback) {
249
+ if (!domainLocaleMap || typeof window === 'undefined')
250
+ return fallback;
251
+ const hostname = window.location.hostname;
252
+ return domainLocaleMap[hostname] ?? fallback;
253
+ }
254
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnLanguageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
255
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnLanguageService, providedIn: 'root' });
256
+ }
257
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnLanguageService, decorators: [{
258
+ type: Injectable,
259
+ args: [{ providedIn: 'root' }]
260
+ }] });
261
+
262
+ /**
263
+ * Provides an APP_INITIALIZER that configures the MnLanguageService and
264
+ * preloads the requested locales during application bootstrap.
265
+ *
266
+ * Usage in app.config.ts:
267
+ * ...provideMnLanguage({
268
+ * urlPattern: 'assets/i18n/{locale}.json',
269
+ * defaultLocale: 'en',
270
+ * preload: ['en', 'nl'],
271
+ * })
272
+ */
273
+ function provideMnLanguage(config) {
274
+ return [
275
+ {
276
+ provide: APP_INITIALIZER,
277
+ multi: true,
278
+ useFactory: (svc) => async () => {
279
+ if (config.debug) {
280
+ svc.setDebug(true);
281
+ }
282
+ svc.configure(config.urlPattern);
283
+ const effectiveLocale = svc.resolveLocaleForDomain(config.domainLocaleMap, config.defaultLocale);
284
+ const localesToLoad = config.preload ?? [effectiveLocale];
285
+ await Promise.all(localesToLoad.map(l => svc.loadLocale(l)));
286
+ await svc.setLocale(effectiveLocale);
287
+ },
288
+ deps: [MnLanguageService],
289
+ },
290
+ ];
291
+ }
292
+
293
+ /**
294
+ * Pipe that translates a key via MnLanguageService.
295
+ *
296
+ * Usage in templates:
297
+ * {{ 'form.email.label' | mnTranslate }}
298
+ * {{ 'greeting' | mnTranslate:{ name: 'World' } }}
299
+ *
300
+ * Note: This pipe is impure so it re-evaluates when the locale changes.
301
+ */
302
+ class MnTranslatePipe {
303
+ lang = inject(MnLanguageService);
304
+ transform(key, params) {
305
+ return this.lang.translate(key, params);
306
+ }
307
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnTranslatePipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe });
308
+ static ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "21.1.3", ngImport: i0, type: MnTranslatePipe, isStandalone: true, name: "mnTranslate", pure: false });
309
+ }
310
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnTranslatePipe, decorators: [{
311
+ type: Pipe,
312
+ args: [{
313
+ name: 'mnTranslate',
314
+ standalone: true,
315
+ pure: false,
316
+ }]
317
+ }] });
318
+
319
+ function isPlainObject(value) {
320
+ return (typeof value === 'object' &&
321
+ value !== null &&
322
+ Object.prototype.toString.call(value) === '[object Object]');
323
+ }
324
+ /**
325
+ * Parses a config file. Strict JSON goes through `JSON.parse`; only a file that needs JSON5
326
+ * syntax (comments, unquoted keys, trailing commas) loads the `json5` parser, as its own chunk.
327
+ * A static import put the CommonJS `json5` package (~32 kB) into every consumer's startup bundle.
328
+ *
329
+ * @param text The raw file content.
330
+ * @returns The parsed value.
331
+ */
332
+ async function parseConfigText(text) {
333
+ try {
334
+ return JSON.parse(text);
335
+ }
336
+ catch {
337
+ const { default: JSON5 } = await import('json5');
338
+ return JSON5.parse(text);
339
+ }
340
+ }
341
+ class MnConfigService {
342
+ http = inject(HttpClient);
343
+ _config = null;
344
+ _settings = {};
345
+ _debugMode = false;
346
+ /** Reactive version counter — incremented on every config load. */
347
+ _configVersion = signal(0, ...(ngDevMode ? [{ debugName: "_configVersion" }] : []));
348
+ configVersion = this._configVersion.asReadonly();
349
+ lang = inject(MnLanguageService);
350
+ /** General settings from the config file (version, name, etc.). */
351
+ get settings() {
352
+ return this._settings;
353
+ }
354
+ /**
355
+ * Load the configuration JSON from the provided URL and cache it in memory.
356
+ * Consumers should typically call this via the APP_INITIALIZER helper.
357
+ */
358
+ async load(url, debugMode = false) {
359
+ this._debugMode = debugMode;
360
+ this.lang.setDebug(debugMode);
361
+ let text;
362
+ try {
363
+ text = await firstValueFrom(this.http.get(url, { responseType: 'text' }));
364
+ }
365
+ catch (err) {
366
+ console.warn(`[MnConfig] Failed to load config from ${url}`, err);
367
+ this._config = { defaults: {}, overrides: {} };
368
+ return;
369
+ }
370
+ let json;
371
+ try {
372
+ json = await parseConfigText(text);
373
+ }
374
+ catch (err) {
375
+ console.warn(`[MnConfig] Failed to parse JSON5 from ${url}`, err, text);
376
+ json = {};
377
+ }
378
+ const cfg = (isPlainObject(json) ? json : {});
379
+ const defaults = isPlainObject(cfg['defaults']) ? cfg['defaults'] : {};
380
+ const overrides = isPlainObject(cfg['overrides']) ? cfg['overrides'] : {};
381
+ const settings = isPlainObject(cfg['settings']) ? cfg['settings'] : {};
382
+ this._config = { settings, defaults, overrides };
383
+ this._settings = settings;
384
+ // Bootstrap language service from config if a "language" section is present.
385
+ // This avoids circular dependency: config reads raw language settings and
386
+ // pushes them into the language service (language service never imports config).
387
+ const langCfg = cfg['language'];
388
+ if (isPlainObject(langCfg) && typeof langCfg['urlPattern'] === 'string') {
389
+ const lc = langCfg;
390
+ if (this._debugMode) {
391
+ console.log(`[MnConfig] Applying language config from file`, lc);
392
+ }
393
+ this.lang.configure(lc.urlPattern);
394
+ const effectiveLocale = this.lang.resolveLocaleForDomain(lc.domainLocaleMap, lc.defaultLocale);
395
+ const localesToLoad = Array.from(new Set([...(lc.preload ?? []), effectiveLocale]));
396
+ await Promise.all(localesToLoad.map(l => this.lang.loadLocale(l)));
397
+ await this.lang.setLocale(effectiveLocale);
398
+ }
399
+ this._configVersion.update(v => v + 1);
400
+ }
401
+ /**
402
+ * Load configuration from a pre-parsed object (no HTTP fetch).
403
+ * Used for live preview scenarios where config is pushed via postMessage.
404
+ * Optionally re-bootstraps the language service if a `language` section is present.
405
+ */
406
+ async loadFromObject(config, bootstrapLanguage = false) {
407
+ const defaults = isPlainObject(config['defaults']) ? config['defaults'] : {};
408
+ const overrides = isPlainObject(config['overrides']) ? config['overrides'] : {};
409
+ const settings = isPlainObject(config['settings']) ? config['settings'] : {};
410
+ this._config = { settings, defaults, overrides };
411
+ this._settings = settings;
412
+ if (bootstrapLanguage) {
413
+ const langCfg = config['language'];
414
+ if (isPlainObject(langCfg) && typeof langCfg['urlPattern'] === 'string') {
415
+ const lc = langCfg;
416
+ if (this._debugMode) {
417
+ console.log(`[MnConfig] Applying language config from object`, lc);
418
+ }
419
+ this.lang.configure(lc.urlPattern);
420
+ const effectiveLocale = this.lang.resolveLocaleForDomain(lc.domainLocaleMap, lc.defaultLocale);
421
+ const localesToLoad = Array.from(new Set([...(lc.preload ?? []), effectiveLocale]));
422
+ await Promise.all(localesToLoad.map(l => this.lang.loadLocale(l)));
423
+ await this.lang.setLocale(effectiveLocale);
424
+ }
425
+ }
426
+ this._configVersion.update(v => v + 1);
427
+ }
428
+ /**
429
+ * Resolve a configuration object for a component, optionally scoped to a section path
430
+ * and optionally overridden by an instance id.
431
+ */
432
+ resolve(componentName, sectionPath = [], instanceId) {
433
+ const baseConfig = isPlainObject(this._config?.defaults)
434
+ ? (isPlainObject(this._config.defaults[componentName])
435
+ ? { ...this._config.defaults[componentName] }
436
+ : {})
437
+ : {};
438
+ const leaf = this.walkOverrides(this._config?.overrides ?? {}, sectionPath);
439
+ let resolved = baseConfig;
440
+ if (leaf && isPlainObject(leaf[componentName])) {
441
+ resolved = this.deepMerge(resolved, leaf[componentName]);
442
+ }
443
+ if (instanceId) {
444
+ const instKey = `#${instanceId}`;
445
+ if (leaf && isPlainObject(leaf[instKey])) {
446
+ resolved = this.deepMerge(resolved, leaf[instKey]);
447
+ }
448
+ }
449
+ if (this._debugMode) {
450
+ console.debug(`[MnConfig] Resolving for ${componentName}`, {
451
+ sectionPath,
452
+ instanceId,
453
+ resolved,
454
+ });
455
+ }
456
+ return this.resolveTranslatables(resolved);
457
+ }
458
+ /**
459
+ * Walk the overrides nested object using the provided section path and return the leaf node.
460
+ * If any segment is missing or the current node is not a plain object, returns undefined.
461
+ */
462
+ walkOverrides(overridesRoot, sectionPath) {
463
+ let node = overridesRoot;
464
+ for (const segment of sectionPath) {
465
+ if (!isPlainObject(node))
466
+ return undefined;
467
+ node = node[segment];
468
+ if (node === undefined)
469
+ return undefined;
470
+ }
471
+ return node;
472
+ }
473
+ /**
474
+ * Recursively walk a resolved config object and replace any `{ $translate: "key" }` markers
475
+ * with their translated values from MnLanguageService.
476
+ */
477
+ resolveTranslatables(obj) {
478
+ const out = {};
479
+ for (const [key, value] of Object.entries(obj)) {
480
+ if (isTranslatable(value)) {
481
+ out[key] = this.lang.translate(value.$translate, value.params);
482
+ }
483
+ else if (Array.isArray(value)) {
484
+ out[key] = value.map(item => {
485
+ if (isTranslatable(item)) {
486
+ return this.lang.translate(item.$translate, item.params);
487
+ }
488
+ else if (isPlainObject(item)) {
489
+ return this.resolveTranslatables(item);
490
+ }
491
+ return item;
492
+ });
493
+ }
494
+ else if (isPlainObject(value)) {
495
+ out[key] = this.resolveTranslatables(value);
496
+ }
497
+ else {
498
+ out[key] = value;
499
+ }
500
+ }
501
+ return out;
502
+ }
503
+ /**
504
+ * Deep merge two plain-object trees. Arrays and non-plain values are replaced by the patch.
505
+ * Does not mutate inputs; returns a new object.
506
+ */
507
+ deepMerge(base, patch) {
508
+ const out = { ...base };
509
+ for (const key of Object.keys(patch)) {
510
+ const bVal = base[key];
511
+ const pVal = patch[key];
512
+ if (isPlainObject(bVal) && isPlainObject(pVal)) {
513
+ out[key] = this.deepMerge(bVal, pVal);
514
+ }
515
+ else {
516
+ // replace for arrays, primitives, null, undefined, and non-plain objects
517
+ out[key] = pVal;
518
+ }
519
+ }
520
+ return out;
521
+ }
522
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnConfigService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
523
+ static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnConfigService, providedIn: 'root' });
524
+ }
525
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnConfigService, decorators: [{
526
+ type: Injectable,
527
+ args: [{ providedIn: 'root' }]
528
+ }] });
529
+
530
+ /**
531
+ * Provides an APP_INITIALIZER that loads the mn-lib configuration from the given URL
532
+ * during application bootstrap. The consuming application is responsible for providing
533
+ * HttpClient (e.g., via HttpClientModule or provideHttpClient()).
534
+ */
535
+ function provideMnConfig(url, debugMode = false) {
536
+ return [
537
+ {
538
+ provide: APP_INITIALIZER,
539
+ multi: true,
540
+ useFactory: (svc) => () => svc.load(url, debugMode),
541
+ deps: [MnConfigService],
542
+ },
543
+ ];
544
+ }
545
+
546
+ /**
547
+ * Represents the current section path based on nested mn-section directives.
548
+ */
549
+ const MN_SECTION_PATH = new InjectionToken('MN_SECTION_PATH', {
550
+ providedIn: 'root',
551
+ factory: () => [],
552
+ });
553
+ /**
554
+ * Represents the current component instance id provided by [mn-instance].
555
+ */
556
+ const MN_INSTANCE_ID = new InjectionToken('MN_INSTANCE_ID', {
557
+ providedIn: 'root',
558
+ factory: () => null,
559
+ });
560
+
561
+ /**
562
+ * Helper to provide a resolved, typed component config via DI.
563
+ *
564
+ * Usage in a component/module providers:
565
+ * const MY_CFG = new InjectionToken<MyCfg>('MY_CFG');
566
+ * providers: [ provideMnComponentConfig(MY_CFG, 'my-component') ]
567
+ * Then in the component:
568
+ * readonly cfg = inject(MY_CFG)
569
+ *
570
+ * The returned config object is **reactive**: when the active locale changes,
571
+ * all translatable values are re-resolved in place so that templates using
572
+ * `cfg.someLabel` automatically reflect the new language on the next change-detection cycle.
573
+ */
574
+ function provideMnComponentConfig(token, componentName, initial) {
575
+ return {
576
+ provide: token,
577
+ deps: [
578
+ MnConfigService,
579
+ MnLanguageService,
580
+ DestroyRef,
581
+ [new Optional(), MN_SECTION_PATH],
582
+ [new Optional(), MN_INSTANCE_ID],
583
+ ],
584
+ useFactory: (svc, lang, destroyRef, sectionPath, instanceId) => {
585
+ const resolveConfig = () => {
586
+ const resolved = svc.resolve(componentName, sectionPath ?? [], instanceId ?? undefined);
587
+ return Object.assign({}, initial ?? {}, resolved);
588
+ };
589
+ // Create the initial config object that will be shared by reference.
590
+ const cfg = resolveConfig();
591
+ // Re-resolve translatable values whenever the locale changes.
592
+ // skip(1) because the current locale was already used for the initial resolve.
593
+ const sub = lang.locale$.subscribe(() => {
594
+ const updated = resolveConfig();
595
+ // Mutate the existing object in place so all template bindings pick up the new values.
596
+ for (const key of Object.keys(updated)) {
597
+ cfg[key] = updated[key];
598
+ }
599
+ });
600
+ destroyRef.onDestroy(() => sub.unsubscribe());
601
+ return cfg;
602
+ },
603
+ };
604
+ }
605
+
606
+ class MnSectionDirective {
607
+ /** Section name contributed by this DOM node to the section path */
608
+ mnSection;
609
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnSectionDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
610
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.1.3", type: MnSectionDirective, isStandalone: true, selector: "[mn-section]", inputs: { mnSection: ["mn-section", "mnSection"] }, providers: [
611
+ {
612
+ provide: MN_SECTION_PATH,
613
+ // Read parent MN_SECTION_PATH from ancestor injector (skipSelf to avoid self-reference),
614
+ // and read the attribute value using Attribute so it's available at provider creation time.
615
+ deps: [[new Optional(), new SkipSelf(), MN_SECTION_PATH], new Attribute('mn-section')],
616
+ useFactory: (parentPath, attr) => {
617
+ const parent = Array.isArray(parentPath) ? parentPath : [];
618
+ const name = (attr ?? '').trim();
619
+ return name ? [...parent, name] : [...parent];
620
+ },
621
+ },
622
+ ], ngImport: i0 });
623
+ }
624
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnSectionDirective, decorators: [{
625
+ type: Directive,
626
+ args: [{
627
+ // eslint-disable-next-line @angular-eslint/directive-selector -- kebab-case is intentional: matches the Attribute() token and is stable public API
628
+ selector: '[mn-section]',
629
+ standalone: true,
630
+ providers: [
631
+ {
632
+ provide: MN_SECTION_PATH,
633
+ // Read parent MN_SECTION_PATH from ancestor injector (skipSelf to avoid self-reference),
634
+ // and read the attribute value using Attribute so it's available at provider creation time.
635
+ deps: [[new Optional(), new SkipSelf(), MN_SECTION_PATH], new Attribute('mn-section')],
636
+ useFactory: (parentPath, attr) => {
637
+ const parent = Array.isArray(parentPath) ? parentPath : [];
638
+ const name = (attr ?? '').trim();
639
+ return name ? [...parent, name] : [...parent];
640
+ },
641
+ },
642
+ ],
643
+ }]
644
+ }], propDecorators: { mnSection: [{
645
+ type: Input,
646
+ args: ['mn-section']
647
+ }] } });
648
+
649
+ class MnInstanceDirective {
650
+ /** Instance id for targeting per-component instance overrides */
651
+ mnInstance;
652
+ static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnInstanceDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive });
653
+ static ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.1.3", type: MnInstanceDirective, isStandalone: true, selector: "[mn-instance]", inputs: { mnInstance: ["mn-instance", "mnInstance"] }, providers: [
654
+ {
655
+ provide: MN_INSTANCE_ID,
656
+ // Read the attribute at provider creation time using Attribute token; Inputs may not be set yet.
657
+ deps: [new Attribute('mn-instance')],
658
+ useFactory: (attr) => (attr ?? '').trim() || null,
659
+ },
660
+ ], ngImport: i0 });
661
+ }
662
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.1.3", ngImport: i0, type: MnInstanceDirective, decorators: [{
663
+ type: Directive,
664
+ args: [{
665
+ // eslint-disable-next-line @angular-eslint/directive-selector -- kebab-case is intentional: matches the Attribute() token and is stable public API
666
+ selector: '[mn-instance]',
667
+ standalone: true,
668
+ providers: [
669
+ {
670
+ provide: MN_INSTANCE_ID,
671
+ // Read the attribute at provider creation time using Attribute token; Inputs may not be set yet.
672
+ deps: [new Attribute('mn-instance')],
673
+ useFactory: (attr) => (attr ?? '').trim() || null,
674
+ },
675
+ ],
676
+ }]
677
+ }], propDecorators: { mnInstance: [{
678
+ type: Input,
679
+ args: ['mn-instance']
680
+ }] } });
681
+
682
+ /**
683
+ * Injection token for the base URL used by all CRUD service requests.
684
+ *
685
+ * Provide this token at the application or module level to configure
686
+ * the root API URL that `CrudService` prepends to every endpoint.
687
+ */
688
+ const API_BASE_URL = new InjectionToken('API_BASE_URL');
689
+
690
+ /**
691
+ * Abstract base class for CRUD services.
692
+ * Provides standard HTTP operations with typed `Result<T>` responses.
693
+ *
694
+ * @template TEntity The entity type returned by single-item operations.
695
+ * @template TListResponse The response type for list operations (defaults to `TEntity[]`).
696
+ * @template TCreatePayload The payload type for create operations (defaults to `Partial<TEntity>`).
697
+ * @template TUpdatePayload The payload type for update operations (defaults to `Partial<TEntity>`).
698
+ * @template TId The type of the entity identifier (defaults to `number`).
699
+ * @template TGetByIdResponse The response type for getById (defaults to `TEntity`).
700
+ * @template TCreateResponse The response type for create (defaults to `TEntity`).
701
+ * @template TUpdateResponse The response type for update and patch (defaults to `TEntity`).
702
+ * @template TDeleteResponse The response type for delete (defaults to `void`).
703
+ */
704
+ class CrudService {
705
+ http = inject(HttpClient);
706
+ baseUrl = inject(API_BASE_URL);
707
+ endpoint;
708
+ constructor(config) {
709
+ this.endpoint = `${this.baseUrl}${config.endpoint}`;
710
+ }
711
+ /**
712
+ * Retrieves all entities from the configured endpoint.
713
+ *
714
+ * Sends a GET request to the base endpoint. Query values are
715
+ * converted to `HttpParams` before the request is sent.
716
+ *
717
+ * @param query Optional query parameters appended to the request URL.
718
+ * @returns An observable emitting a `Result` with the list response or a structured failure.
719
+ */
720
+ getAll(query) {
721
+ return this.http
722
+ .get(this.endpoint, {
723
+ params: this.toHttpParams(query)
724
+ })
725
+ .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
726
+ }
727
+ /**
728
+ * Retrieves a single entity by its identifier.
729
+ *
730
+ * Sends a GET request to `{endpoint}/{id}`.
731
+ *
732
+ * @param id The unique identifier of the entity to retrieve.
733
+ * @returns An observable emitting a `Result` with the entity or a structured failure.
734
+ */
735
+ getById(id) {
736
+ return this.http
737
+ .get(this.itemUrl(id))
738
+ .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
739
+ }
740
+ /**
741
+ * Creates a new entity at the configured endpoint.
742
+ *
743
+ * Sends a POST request with the provided payload as the request body.
744
+ *
745
+ * @param payload The data used to create the entity.
746
+ * @returns An observable emitting a `Result` with the created entity or a structured failure.
747
+ */
748
+ create(payload) {
749
+ return this.http
750
+ .post(this.endpoint, payload)
751
+ .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
752
+ }
753
+ /**
754
+ * Fully replaces an existing entity.
755
+ *
756
+ * Sends a PUT request to `{endpoint}/{id}` with the provided payload,
757
+ * replacing the entire entity.
758
+ *
759
+ * @param id The unique identifier of the entity to update.
760
+ * @param payload The complete data to replace the existing entity with.
761
+ * @returns An observable emitting a `Result` with the updated entity or a structured failure.
762
+ */
763
+ update(id, payload) {
764
+ return this.http
765
+ .put(this.itemUrl(id), payload)
766
+ .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
767
+ }
768
+ /**
769
+ * Partially updates an existing entity.
770
+ *
771
+ * Sends a PATCH request to `{endpoint}/{id}` with the provided payload,
772
+ * merging changes into the existing entity.
773
+ *
774
+ * @param id The unique identifier of the entity to patch.
775
+ * @param payload A partial set of fields to update on the existing entity.
776
+ * @returns An observable emitting a `Result` with the updated entity or a structured failure.
777
+ */
778
+ patch(id, payload) {
779
+ return this.http
780
+ .patch(this.itemUrl(id), payload)
781
+ .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
782
+ }
783
+ /**
784
+ * Deletes an entity by its identifier.
785
+ *
786
+ * Sends a DELETE request to `{endpoint}/{id}`.
787
+ *
788
+ * @param id The unique identifier of the entity to delete.
789
+ * @returns An observable emitting a `Result` with the delete response or a structured failure.
790
+ */
791
+ delete(id) {
792
+ return this.http
793
+ .delete(this.itemUrl(id))
794
+ .pipe(map((data) => this.success(data)), catchError((error) => of(this.failure(this.mapHttpError(error)))));
795
+ }
796
+ /**
797
+ * Retrieves all entities with the full `HttpResponse` wrapper.
798
+ *
799
+ * Behaves like {@link getAll} but observes the complete HTTP response,
800
+ * giving access to headers, status code, and URL alongside the body.
801
+ *
802
+ * @param query Optional query parameters appended to the request URL.
803
+ * @returns An observable emitting a `Result` with the full HTTP response or a structured failure.
804
+ */
805
+ getAllResponse(query) {
806
+ return this.http
807
+ .get(this.endpoint, {
808
+ params: this.toHttpParams(query),
809
+ observe: 'response',
810
+ })
811
+ .pipe(map((response) => this.success(response, {
812
+ statusCode: response.status,
813
+ headers: response.headers,
814
+ url: response.url ?? undefined,
815
+ })), catchError((error) => of(this.failure(this.mapHttpError(error)))));
816
+ }
817
+ /**
818
+ * Builds the URL for a single entity by appending the identifier to the endpoint.
819
+ *
820
+ * @param id The unique identifier to append.
821
+ * @returns The full URL targeting the specific entity.
822
+ */
823
+ itemUrl(id) {
824
+ return `${this.endpoint}/${id}`;
825
+ }
826
+ /**
827
+ * Wraps a value in a `SuccessResult`.
828
+ *
829
+ * @template T The type of the response data.
830
+ * @param data The response data to wrap.
831
+ * @param meta Optional metadata (status code, headers, URL) to attach.
832
+ * @returns A `SuccessResult` containing the provided data.
833
+ */
834
+ success(data, meta) {
835
+ return { ok: true, data, meta };
836
+ }
837
+ /**
838
+ * Wraps an error in a `FailureResult`.
839
+ *
840
+ * When no explicit metadata is provided, metadata is derived from
841
+ * the `ApiError` itself (status code, headers, URL).
842
+ *
843
+ * @param error The structured API error.
844
+ * @param meta Optional metadata to override the error-derived values.
845
+ * @returns A `FailureResult` containing the error and metadata.
846
+ */
847
+ failure(error, meta) {
848
+ return {
849
+ ok: false,
850
+ error,
851
+ meta: meta ?? {
852
+ statusCode: error.status ?? undefined,
853
+ headers: error.headers,
854
+ url: error.url ?? undefined,
855
+ },
856
+ };
857
+ }
858
+ /**
859
+ * Maps an unknown error into a structured `ApiError`.
860
+ *
861
+ * Handles both `HttpErrorResponse` instances and unexpected error types.
862
+ * Extracts backend messages, validation errors, and retry information
863
+ * so callers receive a consistent error shape.
864
+ *
865
+ * @param error The raw error caught from the HTTP pipeline.
866
+ * @returns A fully populated `ApiError` object.
867
+ */
868
+ mapHttpError(error) {
869
+ const timestamp = new Date().toISOString();
870
+ if (!(error instanceof HttpErrorResponse)) {
871
+ return {
872
+ status: null,
873
+ message: 'Unknown error',
874
+ original: error instanceof Error ? error : new Error(String(error)),
875
+ retryable: false,
876
+ timestamp,
877
+ };
878
+ }
879
+ const status = this.normalizeStatus(error.status);
880
+ const details = error.error;
881
+ const backendMessage = this.extractBackendMessage(details);
882
+ const validationErrors = this.extractValidationErrors(details);
883
+ return {
884
+ status,
885
+ message: backendMessage ?? this.defaultMessage(status),
886
+ details,
887
+ backendMessage,
888
+ validationErrors,
889
+ url: error.url,
890
+ headers: error.headers,
891
+ original: error,
892
+ retryable: this.isRetryable(status),
893
+ timestamp,
894
+ };
895
+ }
896
+ /**
897
+ * Extracts a human-readable message from the error response body.
898
+ *
899
+ * Checks common keys (`message`, `title`, `detail`, `error`) on the
900
+ * body object and returns the first non-empty string found.
901
+ *
902
+ * @param body The parsed error response body.
903
+ * @returns The extracted message, or `undefined` if none was found.
904
+ */
905
+ extractBackendMessage(body) {
906
+ if (typeof body === 'string' && body.trim()) {
907
+ return body;
908
+ }
909
+ if (!body || typeof body !== 'object') {
910
+ return undefined;
911
+ }
912
+ const obj = body;
913
+ for (const key of ['message', 'title', 'detail', 'error']) {
914
+ const value = obj[key];
915
+ if (typeof value === 'string' && value.trim()) {
916
+ return value;
917
+ }
918
+ }
919
+ return undefined;
920
+ }
921
+ /**
922
+ * Extracts field-level validation errors from the error response body.
923
+ *
924
+ * Expects an `errors` property on the body containing a record of
925
+ * field names to error messages (string or string array).
926
+ *
927
+ * @param body The parsed error response body.
928
+ * @returns A record mapping field names to their error messages, or `undefined` if none were found.
929
+ */
930
+ extractValidationErrors(body) {
931
+ if (!body || typeof body !== 'object') {
932
+ return undefined;
933
+ }
934
+ const obj = body;
935
+ const errors = obj['errors'];
936
+ if (!errors || typeof errors !== 'object') {
937
+ return undefined;
938
+ }
939
+ const result = {};
940
+ for (const [key, value] of Object.entries(errors)) {
941
+ if (Array.isArray(value)) {
942
+ result[key] = value.map(String);
943
+ }
944
+ else if (typeof value === 'string') {
945
+ result[key] = [value];
946
+ }
947
+ }
948
+ return Object.keys(result).length ? result : undefined;
949
+ }
950
+ /**
951
+ * Returns a default user-facing message for the given HTTP status code.
952
+ *
953
+ * Provides human-readable messages for common HTTP status codes.
954
+ * Override this method to customise messages.
955
+ *
956
+ * @param status The HTTP status code, or `null` when unknown.
957
+ * @returns A descriptive error message.
958
+ */
959
+ defaultMessage(status) {
960
+ switch (status) {
961
+ case HttpStatusCode.BadRequest:
962
+ return 'Bad request';
963
+ case HttpStatusCode.Unauthorized:
964
+ return 'Unauthorized';
965
+ case HttpStatusCode.Forbidden:
966
+ return 'Forbidden';
967
+ case HttpStatusCode.NotFound:
968
+ return 'Not found';
969
+ case HttpStatusCode.Conflict:
970
+ return 'Conflict';
971
+ case HttpStatusCode.UnprocessableEntity:
972
+ return 'Unprocessable entity';
973
+ case HttpStatusCode.InternalServerError:
974
+ return 'Internal server error';
975
+ case null:
976
+ return 'Unknown error';
977
+ default:
978
+ return `Request failed with status ${status}`;
979
+ }
980
+ }
981
+ /**
982
+ * Determines whether a request with the given status can be retried.
983
+ *
984
+ * Timeouts, rate-limiting responses, and server errors
985
+ * (5xx) are considered retryable by default.
986
+ *
987
+ * @param status The HTTP status code, or `null` when unknown.
988
+ * @returns `true` if the request is safe to retry.
989
+ */
990
+ isRetryable(status) {
991
+ if (status === HttpStatusCode.RequestTimeout)
992
+ return true;
993
+ if (status === HttpStatusCode.TooManyRequests)
994
+ return true;
995
+ if (typeof status === 'number' && status >= 500)
996
+ return true;
997
+ return false;
998
+ }
999
+ /**
1000
+ * Normalises a raw HTTP status into an `HttpStatusCode | null` value.
1001
+ *
1002
+ * Converts `undefined`, `NaN`, and `0` (network error) to `null`
1003
+ * so downstream code only needs to handle `HttpStatusCode | null`.
1004
+ *
1005
+ * @param status The raw status value from the HTTP response.
1006
+ * @returns The normalised status code, or `null` when indeterminate.
1007
+ */
1008
+ normalizeStatus(status) {
1009
+ if (status === null || status === undefined || status === 0 || Number.isNaN(status))
1010
+ return null;
1011
+ return status;
1012
+ }
1013
+ /**
1014
+ * Converts query parameters into Angular `HttpParams`.
1015
+ *
1016
+ * `null` and `undefined` values are silently skipped.
1017
+ * Array values are appended as multiple entries for the same key.
1018
+ *
1019
+ * @param query The query parameter record to convert.
1020
+ * @returns An `HttpParams` instance, or `undefined` when no parameters are provided.
1021
+ */
1022
+ toHttpParams(query) {
1023
+ if (!query)
1024
+ return undefined;
1025
+ let params = new HttpParams();
1026
+ for (const [key, rawValue] of Object.entries(query)) {
1027
+ if (rawValue === null || rawValue === undefined)
1028
+ continue;
1029
+ const values = Array.isArray(rawValue) ? rawValue : [rawValue];
1030
+ for (const value of values) {
1031
+ if (value === null || value === undefined)
1032
+ continue;
1033
+ params = params.append(key, String(value));
1034
+ }
1035
+ }
1036
+ return params;
1037
+ }
1038
+ }
1039
+
1040
+ /**
1041
+ * Lightweight abstract HTTP base class that removes common boilerplate
1042
+ * from API services.
1043
+ *
1044
+ * Provides typed `get`, `post`, `patch`, `put`, and `delete` methods
1045
+ * that return Promises, automatic query-param building, and base-URL
1046
+ * injection via the `API_BASE_URL` token.
1047
+ *
1048
+ * Subclass this directly for services with static or mixed endpoints.
1049
+ * No CRUD structure is imposed — every method accepts a free-form path.
1050
+ */
1051
+ class MnHttpService {
1052
+ /** Angular HTTP client injected automatically. */
1053
+ http = inject(HttpClient);
1054
+ /** Base API URL provided via the `API_BASE_URL` injection token. */
1055
+ baseUrl = inject(API_BASE_URL);
1056
+ /**
1057
+ * Sends a typed GET request.
1058
+ * @param path The path appended to the base URL.
1059
+ * @param query Optional query parameters.
1060
+ * @returns A promise resolving to the typed response body.
1061
+ */
1062
+ get(path, query) {
1063
+ return firstValueFrom(this.http.get(`${this.baseUrl}${path}`, {
1064
+ params: this.toHttpParams(query),
1065
+ }));
1066
+ }
1067
+ /**
1068
+ * Sends a typed POST request.
1069
+ * @param path The path appended to the base URL.
1070
+ * @param body Optional request body.
1071
+ * @param query Optional query parameters.
1072
+ * @returns A promise resolving to the typed response body.
1073
+ */
1074
+ post(path, body, query) {
1075
+ return firstValueFrom(this.http.post(`${this.baseUrl}${path}`, body ?? {}, {
1076
+ params: this.toHttpParams(query),
1077
+ }));
1078
+ }
1079
+ /**
1080
+ * Sends a typed PATCH request.
1081
+ * @param path The path appended to the base URL.
1082
+ * @param body Optional request body.
1083
+ * @param query Optional query parameters.
1084
+ * @returns A promise resolving to the typed response body.
1085
+ */
1086
+ patch(path, body, query) {
1087
+ return firstValueFrom(this.http.patch(`${this.baseUrl}${path}`, body ?? {}, {
1088
+ params: this.toHttpParams(query),
1089
+ }));
1090
+ }
1091
+ /**
1092
+ * Sends a typed PUT request.
1093
+ * @param path The path appended to the base URL.
1094
+ * @param body Optional request body.
1095
+ * @param query Optional query parameters.
1096
+ * @returns A promise resolving to the typed response body.
1097
+ */
1098
+ put(path, body, query) {
1099
+ return firstValueFrom(this.http.put(`${this.baseUrl}${path}`, body ?? {}, {
1100
+ params: this.toHttpParams(query),
1101
+ }));
1102
+ }
1103
+ /**
1104
+ * Sends a typed DELETE request.
1105
+ * @param path The path appended to the base URL.
1106
+ * @param query Optional query parameters.
1107
+ * @returns A promise resolving to the typed response body.
1108
+ */
1109
+ delete(path, query) {
1110
+ return firstValueFrom(this.http.delete(`${this.baseUrl}${path}`, {
1111
+ params: this.toHttpParams(query),
1112
+ }));
1113
+ }
1114
+ /**
1115
+ * Converts a query-params record to Angular `HttpParams`.
1116
+ * Null and undefined values are silently skipped.
1117
+ * Array values are appended as multiple entries for the same key.
1118
+ * @param query The query parameter record to convert.
1119
+ * @returns An `HttpParams` instance, or `undefined` when no parameters are provided.
1120
+ */
1121
+ toHttpParams(query) {
1122
+ if (!query)
1123
+ return undefined;
1124
+ let params = new HttpParams();
1125
+ for (const [key, rawValue] of Object.entries(query)) {
1126
+ if (rawValue === null || rawValue === undefined)
1127
+ continue;
1128
+ const values = Array.isArray(rawValue) ? rawValue : [rawValue];
1129
+ for (const value of values) {
1130
+ if (value === null || value === undefined)
1131
+ continue;
1132
+ params = params.append(key, String(value));
1133
+ }
1134
+ }
1135
+ return params;
1136
+ }
1137
+ }
1138
+
1139
+ /**
1140
+ * Turns icon nodes from the vanilla `lucide` package into the icon data that
1141
+ * `<svg [lucideIcon]>` (`LucideDynamicIcon`) and MnLib's icon inputs accept.
1142
+ *
1143
+ * Why not `@lucide/angular`'s per-icon components (`<svg lucideArrowLeft>`): that
1144
+ * package is a single module, and the Angular linker compiles a full copy of the
1145
+ * SVG template into every icon class, so each icon cost ~2.8 kB and all of them
1146
+ * landed in the startup chunk. With `lucide` an icon is a few hundred bytes of data, and
1147
+ * only the icons something imports are bundled. esbuild keeps all of them in one shared
1148
+ * chunk (they hang off the package's re-export barrel), about 30 kB for the whole app.
1149
+ *
1150
+ * Import the namespace and name each icon, so an icon called `Component`, `Map`
1151
+ * or `X` never shadows another import:
1152
+ *
1153
+ * ```ts
1154
+ * import * as lucide from 'lucide';
1155
+ * const ICONS = lucideIcons({ ArrowLeft: lucide.ArrowLeft, Trash2: lucide.Trash2 });
1156
+ * // template: <svg [lucideIcon]="icons.ArrowLeft" [size]="16"></svg>
1157
+ * ```
1158
+ *
1159
+ * @param nodes Icon nodes keyed by their PascalCase `lucide` export name.
1160
+ * @returns Icon data under the same keys, named `arrow-left`-style for the
1161
+ * `lucide-<name>` class the icon renders with.
1162
+ */
1163
+ function lucideIcons(nodes) {
1164
+ const icons = {};
1165
+ for (const key of Object.keys(nodes)) {
1166
+ // `lucide` types attribute values as optional; its generated icon data never omits one.
1167
+ icons[key] = { name: toKebabCase(key), node: nodes[key] };
1168
+ }
1169
+ return icons;
1170
+ }
1171
+ /**
1172
+ * Converts a PascalCase export name to Lucide's kebab-case icon name.
1173
+ * @param name Export name, e.g. `CircleCheck` or `Trash2`.
1174
+ * @returns The icon name, e.g. `circle-check` or `trash-2`.
1175
+ */
1176
+ function toKebabCase(name) {
1177
+ return name
1178
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
1179
+ .replace(/([a-zA-Z])(\d)/g, '$1-$2')
1180
+ .toLowerCase();
1181
+ }
1182
+
1183
+ /**
1184
+ * Enable live preview mode. Listens for postMessage events from
1185
+ * Mn Web Manager and hot-swaps config/translations at runtime.
1186
+ *
1187
+ * Call this once in your app's bootstrap (e.g., APP_INITIALIZER or root component).
1188
+ *
1189
+ * @param configService - The MnConfigService instance
1190
+ * @param langService - The MnLanguageService instance
1191
+ * @param allowedOrigins - Optional whitelist of allowed origins (security)
1192
+ */
1193
+ function enableMnPreviewMode(configService, langService, allowedOrigins) {
1194
+ window.addEventListener('message', async (event) => {
1195
+ if (allowedOrigins?.length && !allowedOrigins.includes(event.origin)) {
1196
+ return;
1197
+ }
1198
+ const data = event.data;
1199
+ if (!data?.type)
1200
+ return;
1201
+ switch (data.type) {
1202
+ case 'mn-config-update':
1203
+ if (data.config) {
1204
+ await configService.loadFromObject(data.config);
1205
+ }
1206
+ break;
1207
+ case 'mn-translations-update':
1208
+ if (data.translations) {
1209
+ for (const [locale, translations] of Object.entries(data.translations)) {
1210
+ langService.registerTranslations(locale, translations);
1211
+ }
1212
+ await langService.setLocale(langService.locale);
1213
+ }
1214
+ break;
1215
+ }
1216
+ });
1217
+ }
1218
+
1219
+ /**
1220
+ * Public API of the `mn-angular-lib/core` entry point: config, context, language, preview, HTTP/CRUD services, shared types and icon helpers.
1221
+ *
1222
+ * Each entry point is its own module in the published package, so a consumer's bundler
1223
+ * splits it into the chunk that uses it instead of loading the whole library at startup.
1224
+ * The root `mn-angular-lib` entry re-exports every entry point.
1225
+ */
1226
+
1227
+ /**
1228
+ * Generated bundle index. Do not edit.
1229
+ */
1230
+
1231
+ export { API_BASE_URL, CrudService, MN_INSTANCE_ID, MN_SECTION_PATH, MnConfigService, MnHttpService, MnInstanceDirective, MnLanguageService, MnSectionDirective, MnTranslatePipe, enableMnPreviewMode, isTranslatable, lucideIcons, parseConfigText, provideMnComponentConfig, provideMnConfig, provideMnLanguage };
1232
+ //# sourceMappingURL=mn-angular-lib-core.mjs.map