@rdlabo/ionic-angular-kit 0.0.2 → 0.0.3

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.
@@ -1,750 +0,0 @@
1
- import * as i0 from '@angular/core';
2
- import { inject, Injectable, InjectionToken, makeEnvironmentProviders, ElementRef, Directive } from '@angular/core';
3
- import { Storage } from '@ionic/storage-angular';
4
- import { ModalController, ToastController, AlertController, NavController } from '@ionic/angular/standalone';
5
- import { Capacitor } from '@capacitor/core';
6
- import { Keyboard } from '@capacitor/keyboard';
7
- import { ImpactStyle, Haptics } from '@capacitor/haptics';
8
- import { Router } from '@angular/router';
9
- import { map, mergeMap, tap, catchError } from 'rxjs/operators';
10
- import { HttpResponse } from '@angular/common/http';
11
- import { Network } from '@capacitor/network';
12
- import { from, retry, throwError, timer } from 'rxjs';
13
-
14
- /**
15
- * Thin, typed wrapper around `@ionic/storage-angular`.
16
- *
17
- * Starts `create()` exactly once and stores the resulting ready Promise. Every operation awaits
18
- * that Promise before touching the underlying store, so calls made before initialization completes
19
- * are queued rather than dropped.
20
- *
21
- * @remarks
22
- * A naive wrapper that reads the store synchronously would silently no-op (or throw) when invoked
23
- * before `create()` resolves, losing early writes. Awaiting the one-time ready Promise on every
24
- * operation removes that race without forcing callers to coordinate initialization themselves.
25
- *
26
- * @example
27
- * ```ts
28
- * constructor(private readonly storage: KitStorageService) {}
29
- *
30
- * async ngOnInit(): Promise<void> {
31
- * await this.storage.set('token', 'abc123');
32
- * const token = await this.storage.get<string>('token');
33
- * }
34
- * ```
35
- */
36
- class KitStorageService {
37
- /** One-time `create()` ready Promise; awaited before every operation so early calls are not lost. */
38
- #ready = inject(Storage).create();
39
- /**
40
- * Persist a value under the given key.
41
- *
42
- * @typeParam T - type of the value being stored
43
- * @param key - key to store the value under
44
- * @param value - value to persist; overwrites any existing value for the key
45
- * @returns a Promise that resolves once the value has been written
46
- * @example
47
- * ```ts
48
- * await storage.set('user', { id: 1, name: 'Ada' });
49
- * ```
50
- */
51
- async set(key, value) {
52
- await (await this.#ready).set(key, value);
53
- }
54
- /**
55
- * Read the value stored under the given key.
56
- *
57
- * @typeParam T - expected type of the stored value
58
- * @param key - key to read
59
- * @returns the stored value, or `null` when the key is absent
60
- * @example
61
- * ```ts
62
- * const user = await storage.get<{ id: number }>('user');
63
- * ```
64
- */
65
- async get(key) {
66
- return (await (await this.#ready).get(key)) ?? null;
67
- }
68
- /**
69
- * Remove the value stored under the given key.
70
- *
71
- * @param key - key to remove; a no-op when the key is absent
72
- * @returns a Promise that resolves once the key has been removed
73
- */
74
- async remove(key) {
75
- await (await this.#ready).remove(key);
76
- }
77
- /**
78
- * Remove every key/value pair from the store.
79
- *
80
- * @returns a Promise that resolves once the store has been emptied
81
- */
82
- async clear() {
83
- await (await this.#ready).clear();
84
- }
85
- /**
86
- * List every key currently present in the store.
87
- *
88
- * @returns an array of all stored keys
89
- */
90
- async keys() {
91
- return (await this.#ready).keys();
92
- }
93
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitStorageService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
94
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitStorageService, providedIn: 'root' }); }
95
- }
96
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitStorageService, decorators: [{
97
- type: Injectable,
98
- args: [{
99
- providedIn: 'root',
100
- }]
101
- }] });
102
-
103
- /**
104
- * Injection token carrying the {@link KitOverlayConfig} for `KitOverlayController`.
105
- *
106
- * @remarks
107
- * Provide it through {@link provideKitOverlay} rather than registering it directly.
108
- */
109
- const KIT_OVERLAY_CONFIG = new InjectionToken('@rdlabo/ionic-angular-kit:overlay');
110
- /**
111
- * Wire `KitOverlayController` into the application by providing its button labels.
112
- *
113
- * @param config - overlay configuration, including the button labels to inject
114
- * @returns environment providers to add to the application's provider list
115
- * @example
116
- * ```ts
117
- * bootstrapApplication(AppComponent, {
118
- * providers: [
119
- * provideKitOverlay({ labels: { close: $localize`Close`, cancel: $localize`Cancel` } }),
120
- * ],
121
- * });
122
- * ```
123
- */
124
- const provideKitOverlay = (config) => makeEnvironmentProviders([{ provide: KIT_OVERLAY_CONFIG, useValue: config }]);
125
-
126
- /**
127
- * Trigger native haptic impact feedback.
128
- *
129
- * Delegates to `@capacitor/haptics` `Haptics.impact()` when running on a native platform. On the
130
- * web (or any non-native platform) it is a no-op and resolves without doing anything.
131
- *
132
- * @remarks
133
- * This haptic side effect was previously bundled implicitly into toast/modal presentation. It has
134
- * been decoupled into this explicit function so callers opt in to the feedback deliberately, rather
135
- * than receiving it as a hidden side effect of presenting UI.
136
- *
137
- * @param style - The impact intensity to play. Defaults to {@link ImpactStyle.Light}.
138
- * @returns A promise that resolves once the feedback has been requested (immediately on the web).
139
- * @example
140
- * ```ts
141
- * import { ImpactStyle } from '@capacitor/haptics';
142
- *
143
- * // Light tap (default)
144
- * await kitImpact();
145
- *
146
- * // Stronger feedback, e.g. on a confirming action
147
- * await kitImpact(ImpactStyle.Heavy);
148
- * ```
149
- */
150
- const kitImpact = async (style = ImpactStyle.Light) => {
151
- if (Capacitor.isNativePlatform()) {
152
- await Haptics.impact({ style });
153
- }
154
- };
155
-
156
- /**
157
- * Attach a native keyboard listener that grows the modal to its maximum breakpoint when the
158
- * keyboard appears.
159
- *
160
- * @param modal - the presented modal element to resize
161
- * @returns a listener handle; on non-native platforms a no-op handle whose `remove()` does nothing
162
- * @internal
163
- */
164
- const watchModalKeyboard = async (modal) => {
165
- if (!Capacitor.isNativePlatform()) {
166
- return { remove: async () => undefined };
167
- }
168
- return Keyboard.addListener('keyboardDidShow', () => modal.setCurrentBreakpoint(1));
169
- };
170
- /**
171
- * Ergonomic wrapper that consolidates Ionic's overlay controllers (Modal / Toast / Alert).
172
- *
173
- * @remarks
174
- * Folds the repetitive create → present → onDidDismiss sequence into single calls and returns the
175
- * relevant result directly. It holds no application-specific policy such as navigation; compose
176
- * those concerns on the consuming side.
177
- *
178
- * @example
179
- * ```ts
180
- * constructor(private readonly overlay: KitOverlayController) {}
181
- *
182
- * async edit(): Promise<void> {
183
- * const result = await this.overlay.presentModal<EditResult>(EditPage, { id: 1 });
184
- * if (result) {
185
- * await this.overlay.presentToast({ message: 'Saved' });
186
- * }
187
- * }
188
- * ```
189
- */
190
- class KitOverlayController {
191
- #modalCtrl = inject(ModalController);
192
- #toastCtrl = inject(ToastController);
193
- #alertCtrl = inject(AlertController);
194
- #labels = inject(KIT_OVERLAY_CONFIG).labels;
195
- /**
196
- * Present a modal and resolve with the data passed to its dismissal.
197
- *
198
- * @typeParam O - type of the data returned when the modal is dismissed
199
- * @param component - the component to render inside the modal
200
- * @param componentProps - props to pass to the modal component
201
- * @param options - additional modal options, including {@link KitModalPresentOptions.watchKeyboard}
202
- * @returns the dismiss data, or `undefined` when the modal is dismissed without data
203
- * @example
204
- * ```ts
205
- * const data = await overlay.presentModal<{ saved: boolean }>(EditPage, { id: 1 }, { watchKeyboard: true });
206
- * ```
207
- */
208
- async presentModal(component, componentProps, options = {}) {
209
- const { watchKeyboard, ...modalOptions } = options;
210
- const modal = await this.#modalCtrl.create({ component, componentProps, ...modalOptions });
211
- await modal.present();
212
- const handle = watchKeyboard ? await watchModalKeyboard(modal) : null;
213
- const { data } = await modal.onDidDismiss();
214
- await handle?.remove();
215
- return data;
216
- }
217
- /**
218
- * Present a toast using kit defaults that the caller may override.
219
- *
220
- * @remarks
221
- * Defaults to a top position, a 2000ms duration, a vertical swipe gesture, and a close button
222
- * from the configured labels; any of these can be overridden via `options`. Presenting a toast
223
- * also triggers light native haptic feedback as an intentional kit UX choice.
224
- *
225
- * @param options - Ionic toast options that override the kit defaults
226
- * @returns the presented toast element
227
- * @example
228
- * ```ts
229
- * await overlay.presentToast({ message: 'Copied to clipboard' });
230
- * ```
231
- */
232
- async presentToast(options) {
233
- void kitImpact();
234
- const toast = await this.#toastCtrl.create({
235
- position: 'top',
236
- duration: 2000,
237
- buttons: [this.#labels.close],
238
- swipeGesture: 'vertical',
239
- ...options,
240
- });
241
- await toast.present();
242
- return toast;
243
- }
244
- /**
245
- * Present a notification alert with a single "close" button and wait for it to be dismissed.
246
- *
247
- * @param options - alert content (header, message, optional sub-header)
248
- * @returns a Promise that resolves once the alert has been dismissed
249
- * @example
250
- * ```ts
251
- * await overlay.alertClose({ header: 'Done', message: 'Your changes were saved.' });
252
- * ```
253
- */
254
- async alertClose(options) {
255
- const alert = await this.#alertCtrl.create({
256
- header: options.header,
257
- subHeader: options.subHeader,
258
- message: options.message,
259
- buttons: [this.#labels.close],
260
- });
261
- await alert.present();
262
- await alert.onWillDismiss();
263
- }
264
- /**
265
- * Present a confirmation alert with cancel and OK buttons.
266
- *
267
- * @param options - alert content plus the OK button text via {@link KitAlertConfirmOptions.okText}
268
- * @returns `true` when the user presses OK, `false` otherwise (cancel or backdrop dismissal)
269
- * @example
270
- * ```ts
271
- * const ok = await overlay.alertConfirm({
272
- * header: 'Delete item?',
273
- * message: 'This cannot be undone.',
274
- * okText: 'Delete',
275
- * });
276
- * if (ok) {
277
- * await remove();
278
- * }
279
- * ```
280
- */
281
- async alertConfirm(options) {
282
- const alert = await this.#alertCtrl.create({
283
- header: options.header,
284
- subHeader: options.subHeader,
285
- message: options.message,
286
- buttons: [
287
- { text: this.#labels.cancel, role: 'cancel' },
288
- { text: options.okText, role: 'confirm' },
289
- ],
290
- });
291
- await alert.present();
292
- const { role } = await alert.onWillDismiss();
293
- return role === 'confirm';
294
- }
295
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitOverlayController, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
296
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitOverlayController, providedIn: 'root' }); }
297
- }
298
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitOverlayController, decorators: [{
299
- type: Injectable,
300
- args: [{
301
- providedIn: 'root',
302
- }]
303
- }] });
304
-
305
- /**
306
- * Present the fleet's canonical "network error → offer to reload" confirmation.
307
- *
308
- * @remarks
309
- * Folds together the three copy-pasted concerns that every app duplicated around a network failure:
310
- *
311
- * 1. Suppress stacking — if an `ion-alert` is already on screen, do nothing.
312
- * 2. Ask the user to confirm via {@link KitOverlayController.alertConfirm}.
313
- * 3. Call `location.reload()` when the user confirms.
314
- *
315
- * All user-facing text (`header`, `message`, `okText`) is supplied by the caller so the kit stays
316
- * free of any hardcoded i18n. Typically wired from {@link KitHttpConfig.onNetworkError}, but it can
317
- * be called from anywhere an app wants the same behavior (e.g. an offline fallback).
318
- *
319
- * @param overlay - the kit overlay controller used to present the confirmation
320
- * @param options - alert content plus the confirm-button text (usually "Refresh")
321
- * @returns a Promise that resolves once the alert is dismissed (the page reloads on confirm)
322
- * @example
323
- * ```ts
324
- * provideKitHttp(() => {
325
- * const overlay = inject(KitOverlayController);
326
- * return {
327
- * getAuthHeaders: async () => ({ ... }),
328
- * onNetworkError: (status) =>
329
- * kitPresentReloadAlert(overlay, {
330
- * header: 'ネットワークエラー',
331
- * message: `通信できませんでした。リフレッシュしますか?(${status})`,
332
- * okText: 'リフレッシュ',
333
- * }),
334
- * };
335
- * });
336
- * ```
337
- */
338
- const kitPresentReloadAlert = async (overlay, options) => {
339
- // 既にアラート表示中なら多重表示しない。
340
- if (document.querySelector('ion-alert')) {
341
- return;
342
- }
343
- const reload = await overlay.alertConfirm(options);
344
- if (reload) {
345
- location.reload();
346
- }
347
- };
348
-
349
- /**
350
- * Work around iOS `ion-input` autofill values not propagating to the Angular form model.
351
- *
352
- * On iOS, when the browser autofills an `ion-input` (for example a saved password), the value
353
- * is written to the underlying native `<input>` element but the corresponding `change` event is
354
- * not forwarded to the host `ion-input`, so the Angular form control (and `ngModel`) never sees
355
- * the autofilled value. This directive listens for the first `change` event on the inner input
356
- * element and mirrors its value back onto the host element, restoring two-way binding.
357
- *
358
- * Apply it to any `ion-input` that participates in a form and may be autofilled by attaching the
359
- * `rdlaboAutofill` attribute.
360
- *
361
- * @remarks
362
- * The directive is a no-op on every platform other than iOS, where the value already propagates
363
- * correctly. A short timeout is used because `ion-input` creates its inner `<input>` element
364
- * asynchronously after the host element is initialized.
365
- *
366
- * @example
367
- * ```html
368
- * <ion-input rdlaboAutofill type="password" [(ngModel)]="password"></ion-input>
369
- * ```
370
- */
371
- class KitAutofillDirective {
372
- #el = inject(ElementRef);
373
- constructor() { }
374
- /**
375
- * Register the iOS autofill workaround once the directive is initialized.
376
- *
377
- * Returns immediately on non-iOS platforms. On iOS, after a short delay it attaches a one-shot,
378
- * passive `change` listener to the inner `<input>` element that `ion-input` renders, copying the
379
- * autofilled value back onto the host element so the Angular form model stays in sync. Any error
380
- * while locating the inner input (for example if the element is not yet present) is swallowed.
381
- *
382
- * @returns Nothing.
383
- */
384
- ngOnInit() {
385
- if (Capacitor.getPlatform() !== 'ios') {
386
- return;
387
- }
388
- setTimeout(() => {
389
- try {
390
- this.#el.nativeElement.children[0].addEventListener('change', (e) => {
391
- this.#el.nativeElement.value = e.target.value;
392
- }, {
393
- capture: false,
394
- once: true,
395
- passive: true,
396
- });
397
- }
398
- catch {
399
- /* empty */
400
- }
401
- }, 100); // Need some time for the ion-input to create the input element
402
- }
403
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAutofillDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
404
- static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "21.2.17", type: KitAutofillDirective, isStandalone: true, selector: "[rdlaboAutofill]", ngImport: i0 }); }
405
- }
406
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: KitAutofillDirective, decorators: [{
407
- type: Directive,
408
- args: [{
409
- selector: '[rdlaboAutofill]',
410
- standalone: true,
411
- }]
412
- }], ctorParameters: () => [] });
413
-
414
- /**
415
- * Injection token that carries the {@link KitAuthConfig} to the authentication guards.
416
- */
417
- const KIT_AUTH_CONFIG = new InjectionToken('@rdlabo/ionic-angular-kit:auth');
418
- /**
419
- * Wire the authentication guard configuration into the application's dependency injection.
420
- *
421
- * @remarks
422
- * The factory runs inside an injection context, so it may call `inject()` (for example
423
- * `inject(AuthService)`) to build the configuration.
424
- *
425
- * @param configFactory - Factory that returns the {@link KitAuthConfig} for the application.
426
- * @returns Environment providers to add to the application bootstrap.
427
- *
428
- * @example
429
- * ```ts
430
- * provideKitAuth(() => {
431
- * const auth = inject(AuthService);
432
- * return {
433
- * authState: () => auth.isAuth(),
434
- * onAuthorized: async () => true,
435
- * onUnauthenticated: async () => false,
436
- * redirects: {
437
- * whenAuthorized: '/',
438
- * whenConfirming: '/auth/confirm',
439
- * whenNotConfirming: '/auth/signin',
440
- * whenUnauthorized: 'auth',
441
- * },
442
- * };
443
- * });
444
- * ```
445
- */
446
- const provideKitAuth = (configFactory) => makeEnvironmentProviders([{ provide: KIT_AUTH_CONFIG, useFactory: configFactory }]);
447
- /**
448
- * Guard that requires the user to be unauthenticated (for example sign-in or sign-up pages).
449
- *
450
- * @remarks
451
- * Allows the `required` and `anonymous` states (an anonymous user is permitted to proceed to a
452
- * registration page). An authenticated user (`user`) is sent to `whenAuthorized`, and a user
453
- * awaiting confirmation (`confirm`) is sent to `whenConfirming`.
454
- *
455
- * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.
456
- *
457
- * @example
458
- * ```ts
459
- * const routes: Routes = [{ path: 'signin', component: SigninPage, canActivate: [kitRequiredUnauthorizedGuard] }];
460
- * ```
461
- */
462
- const kitRequiredUnauthorizedGuard = () => {
463
- const { authState, redirects } = inject(KIT_AUTH_CONFIG);
464
- const router = inject(Router);
465
- const navCtrl = inject(NavController);
466
- return authState().pipe(map((data) => {
467
- if (data === 'user') {
468
- navCtrl.setDirection('root');
469
- router.navigate([redirects.whenAuthorized]);
470
- return false;
471
- }
472
- else if (data === 'confirm') {
473
- router.navigate([redirects.whenConfirming]);
474
- return false;
475
- }
476
- // 'required' | 'anonymous'
477
- return true;
478
- }));
479
- };
480
- /**
481
- * Guard that requires the user to be awaiting email confirmation (`confirm`).
482
- *
483
- * @remarks
484
- * Any other state triggers a redirect: an `anonymous` user is sent to the authenticated area
485
- * (`whenAuthorized`), and every remaining state is sent to `whenNotConfirming`.
486
- *
487
- * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.
488
- *
489
- * @example
490
- * ```ts
491
- * const routes: Routes = [{ path: 'confirm', component: ConfirmPage, canActivate: [kitRequireConfirmingGuard] }];
492
- * ```
493
- */
494
- const kitRequireConfirmingGuard = () => {
495
- const { authState, redirects } = inject(KIT_AUTH_CONFIG);
496
- const router = inject(Router);
497
- const navCtrl = inject(NavController);
498
- return authState().pipe(map((data) => {
499
- if (data === 'confirm') {
500
- return true;
501
- }
502
- navCtrl.setDirection('root');
503
- router.navigate([data === 'anonymous' ? redirects.whenAuthorized : redirects.whenNotConfirming]);
504
- return false;
505
- }));
506
- };
507
- /**
508
- * Guard that requires the user to be fully authenticated (`user`).
509
- *
510
- * @remarks
511
- * - `user` — runs {@link KitAuthConfig.onAuthorized} (token login, permission checks, and so on).
512
- * - `anonymous` — allowed as-is, for applications that permit anonymous browsing.
513
- * - `required` / `confirm` — runs {@link KitAuthConfig.onUnauthenticated}; if it resolves to `false`,
514
- * the user is redirected to `whenUnauthorized`.
515
- *
516
- * @param _route - The activated route snapshot (unused).
517
- * @param state - The router state snapshot, forwarded to the configuration hooks.
518
- * @returns A stream emitting the activation result: `true`, a `UrlTree`, or `false` after a redirect.
519
- *
520
- * @example
521
- * ```ts
522
- * const routes: Routes = [{ path: 'home', component: HomePage, canActivate: [kitRequireAuthorizedGuard] }];
523
- * ```
524
- */
525
- const kitRequireAuthorizedGuard = (_route, state) => {
526
- const { authState, onAuthorized, onUnauthenticated, redirects } = inject(KIT_AUTH_CONFIG);
527
- const router = inject(Router);
528
- const navCtrl = inject(NavController);
529
- return authState().pipe(mergeMap(async (data) => {
530
- if (data === 'user') {
531
- return onAuthorized(state);
532
- }
533
- if (data === 'anonymous') {
534
- return true;
535
- }
536
- const fallback = await onUnauthenticated(state);
537
- if (fallback !== false) {
538
- return fallback;
539
- }
540
- navCtrl.setDirection('root');
541
- router.navigate([redirects.whenUnauthorized]);
542
- return false;
543
- }));
544
- };
545
-
546
- /**
547
- * HTTP status codes that must never be retried. `401` is handled separately and thrown immediately.
548
- *
549
- * @internal
550
- */
551
- const NON_RETRYABLE_STATUSES = [400, 403, 404, 418, 500, 502];
552
- /**
553
- * Injection token that carries the {@link KitHttpConfig} to {@link kitAuthInterceptor}.
554
- */
555
- const KIT_HTTP_CONFIG = new InjectionToken('@rdlabo/ionic-angular-kit:http');
556
- /**
557
- * Wire the {@link kitAuthInterceptor} configuration into the application's dependency injection.
558
- *
559
- * @remarks
560
- * Register the interceptor itself separately via `provideHttpClient(withInterceptors([kitAuthInterceptor]))`.
561
- * The factory runs inside an injection context, so it may call `inject()`.
562
- *
563
- * @param configFactory - Factory that returns the {@link KitHttpConfig} for the application.
564
- * @returns Environment providers to add to the application bootstrap.
565
- *
566
- * @example
567
- * ```ts
568
- * bootstrapApplication(AppComponent, {
569
- * providers: [
570
- * provideHttpClient(withInterceptors([kitAuthInterceptor])),
571
- * provideKitHttp(() => {
572
- * const auth = inject(AuthService);
573
- * const overlay = inject(KitOverlayController);
574
- * return {
575
- * // Only getAuthHeaders is required; every other hook is optional and defaults to a no-op.
576
- * getAuthHeaders: async () => ({ Authorization: `Bearer ${await auth.token()}` }),
577
- * onUnauthorized: () => auth.signOut(),
578
- * onNetworkError: (status) =>
579
- * kitPresentReloadAlert(overlay, { header: 'Network error', message: `Reload? (${status})`, okText: 'Reload' }),
580
- * };
581
- * }),
582
- * ],
583
- * });
584
- * ```
585
- */
586
- const provideKitHttp = (configFactory) => makeEnvironmentProviders([{ provide: KIT_HTTP_CONFIG, useFactory: configFactory }]);
587
- /**
588
- * Canonical functional HTTP interceptor that applies authentication, retries, and error handling.
589
- *
590
- * @remarks
591
- * Behavior, driven by the injected {@link KitHttpConfig}:
592
- *
593
- * 1. Requests for which `bypass` returns `true` are forwarded untouched.
594
- * 2. Otherwise the headers from `getAuthHeaders` and `buildExtraHeaders` are merged onto a cloned request.
595
- * 3. Failed requests are retried up to 2 times with a linearly increasing backoff of `500ms * (retryCount + 5)`,
596
- * except that `401` and any {@link NON_RETRYABLE_STATUSES | non-retryable status}
597
- * (`400`, `403`, `404`, `418`, `500`, `502`) are thrown immediately without retrying.
598
- * 4. On error, `offlineFallback` is consulted first; otherwise `401` calls `onUnauthorized`, `403`
599
- * calls `onForbidden`, network-class failures (anything other than `400`/`500`) call
600
- * `onNetworkError` when the device is connected, and `400`/`500` responses carrying a body
601
- * message call `onServerError`.
602
- *
603
- * @param request - The outgoing request.
604
- * @param next - The next handler in the interceptor chain.
605
- * @returns A stream of HTTP events for the (possibly modified, retried, or replaced) request.
606
- *
607
- * @example
608
- * ```ts
609
- * provideHttpClient(withInterceptors([kitAuthInterceptor]));
610
- * ```
611
- */
612
- const kitAuthInterceptor = (request, next) => {
613
- const config = inject(KIT_HTTP_CONFIG);
614
- if (config.bypass?.(request)) {
615
- return next(request);
616
- }
617
- return from(config.getAuthHeaders(request)).pipe(mergeMap((authHeaders) => {
618
- const req = request.clone({ setHeaders: { ...authHeaders, ...config.buildExtraHeaders?.(request) } });
619
- return next(req).pipe(retry({
620
- count: 2,
621
- delay: (e, retryCount) => {
622
- if (e.status === 401) {
623
- return throwError(() => e);
624
- }
625
- if (NON_RETRYABLE_STATUSES.includes(e.status)) {
626
- return throwError(() => e);
627
- }
628
- return timer((retryCount + 5) * 500);
629
- },
630
- }), tap((event) => {
631
- if (event instanceof HttpResponse) {
632
- config.onResponse?.(event);
633
- }
634
- }), catchError((e) => {
635
- const fallback = config.offlineFallback?.(req, e);
636
- if (fallback) {
637
- return fallback;
638
- }
639
- if (e.status === 401) {
640
- config.onUnauthorized?.(req);
641
- }
642
- else if (e.status === 403) {
643
- config.onForbidden?.(req);
644
- }
645
- else if (![400, 500].includes(e.status)) {
646
- void Network.getStatus().then((status) => {
647
- if (status.connected) {
648
- config.onNetworkError?.(e.status);
649
- }
650
- });
651
- }
652
- else if (e.error?.message) {
653
- config.onServerError?.(e.error.message);
654
- }
655
- return throwError(() => e);
656
- }));
657
- }));
658
- };
659
-
660
- /**
661
- * Merge a newly fetched page of items into an existing list by id, keeping the result sorted.
662
- *
663
- * Items are merged by the numeric `key` field. On a duplicate `key` the item from `arrayNew` wins
664
- * and replaces the one in `arrayOld`. Old items whose `key` falls *inside* the window spanned by
665
- * `arrayNew` (between its first and last `key`) are dropped, since the freshly fetched page is the
666
- * authoritative copy of that window; old items *outside* the window are kept. The merged items are
667
- * finally sorted by `key`, ascending or descending according to `order`.
668
- *
669
- * The algorithm is:
670
- * 1. If both inputs are empty, return an empty array.
671
- * 2. Read the first (`lead`) and last (`last`) `key` values of `arrayNew` as the bounds of the
672
- * page's window. Keep the old items whose `key` lies *outside* that window (at or beyond the
673
- * extremes) and drop those strictly inside it, handling both a high-to-low page (`lead > last`)
674
- * and a low-to-high page (`lead < last`). A single-value page (`lead === last`) keeps all old items.
675
- * 3. Remove old items whose `key` already exists in `arrayNew` (new wins on duplicates).
676
- * 4. Concatenate `arrayNew` with the surviving old items and sort by `key` in the requested
677
- * direction.
678
- *
679
- * @remarks
680
- * Designed for infinite-scroll / paginated list merging, where each fetched page may overlap the
681
- * previously held items and the server returns a contiguous, ordered window of records. The `key`
682
- * field is treated as a number for range comparison and sorting.
683
- *
684
- * @typeParam T - Element type of both arrays. Its `key` property must be a numeric value.
685
- * @param arrayOld - The previously accumulated list. May be empty or nullish-safe (empty when falsy).
686
- * @param arrayNew - The newly fetched page of items; its `key` range defines the window that its own
687
- * items replace, and its items take precedence on duplicates.
688
- * @param key - The property of `T` used as the unique, numeric id for matching, range filtering, and sorting.
689
- * @param order - Sort direction by `key`: `'ASC'` for ascending or `'DESC'` for descending. Defaults to `'DESC'`.
690
- * @returns A new array containing `arrayNew` merged with the out-of-window, non-duplicate old items, sorted by `key`.
691
- * @example
692
- * ```ts
693
- * interface Post {
694
- * id: number;
695
- * title: string;
696
- * }
697
- *
698
- * const loaded: Post[] = [
699
- * { id: 30, title: 'c' },
700
- * { id: 20, title: 'b' },
701
- * { id: 10, title: 'a' },
702
- * ];
703
- * const nextPage: Post[] = [
704
- * { id: 20, title: 'b (updated)' },
705
- * { id: 15, title: 'a.5' },
706
- * ];
707
- *
708
- * // Descending merge: id 30 lies above the new page's [15, 20] window so it is kept; id 20 is
709
- * // inside the window and is replaced by the new value; id 10 lies below the window and is kept.
710
- * const merged = arrayConcatById(loaded, nextPage, 'id', 'DESC');
711
- * // => [{ id: 30, title: 'c' }, { id: 20, title: 'b (updated)' }, { id: 15, title: 'a.5' }, { id: 10, title: 'a' }]
712
- * ```
713
- */
714
- const arrayConcatById = (arrayOld, arrayNew, key, order = 'DESC') => {
715
- if (!arrayNew.length && !arrayOld.length) {
716
- return [];
717
- }
718
- const lead = arrayNew[0][key];
719
- const last = arrayNew[arrayNew.length - 1][key];
720
- const filteredOld = (arrayOld || []).filter((vol) => {
721
- const value = vol[key];
722
- return (lead > last && (value >= lead || value <= last)) || (lead < last && (value <= lead || value >= last)) || lead === last;
723
- });
724
- const oldData = filteredOld.filter((vol) => !arrayNew.some((element) => element[key] === vol[key]));
725
- const data = arrayNew.concat(oldData);
726
- const direction = order === 'ASC' ? 1 : -1;
727
- return data.sort((a, b) => {
728
- const x = a[key];
729
- const y = b[key];
730
- if (x > y) {
731
- return direction;
732
- }
733
- if (x < y) {
734
- return direction * -1;
735
- }
736
- return 0;
737
- });
738
- };
739
-
740
- /*
741
- * Public API Surface of @rdlabo/ionic-angular-kit
742
- */
743
- // Storage: typed wrapper around the platform key/value store.
744
-
745
- /**
746
- * Generated bundle index. Do not edit.
747
- */
748
-
749
- export { KIT_AUTH_CONFIG, KIT_HTTP_CONFIG, KIT_OVERLAY_CONFIG, KitAutofillDirective, KitOverlayController, KitStorageService, arrayConcatById, kitAuthInterceptor, kitImpact, kitPresentReloadAlert, kitRequireAuthorizedGuard, kitRequireConfirmingGuard, kitRequiredUnauthorizedGuard, provideKitAuth, provideKitHttp, provideKitOverlay };
750
- //# sourceMappingURL=rdlabo-ionic-angular-kit.mjs.map