@rdlabo/ionic-angular-kit 22.0.6 → 22.0.7
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 +1 @@
|
|
|
1
|
-
{"version":3,"file":"rdlabo-ionic-angular-kit.mjs","sources":["../../../projects/kit/src/lib/storage/kit-storage.service.ts","../../../projects/kit/src/lib/storage/kit-auth-email-store.ts","../../../projects/kit/src/lib/storage/kit-storage-keys.ts","../../../projects/kit/src/lib/storage/kit-clear-storage.ts","../../../projects/kit/src/lib/overlay/overlay-config.ts","../../../projects/kit/src/lib/utils/haptics.ts","../../../projects/kit/src/lib/overlay/kit-overlay.controller.ts","../../../projects/kit/src/lib/overlay/kit-loading.controller.ts","../../../projects/kit/src/lib/overlay/kit-reload-alert.controller.ts","../../../projects/kit/src/lib/overlay/kit-maintenance.controller.ts","../../../projects/kit/src/lib/overlay/kit-auth-failed-alert.ts","../../../projects/kit/src/lib/overlay/kit-language-action-sheet.ts","../../../projects/kit/src/lib/directives/auth-input.directive.ts","../../../projects/kit/src/lib/keyboard/kit-keyboard.ts","../../../projects/kit/src/lib/auth/auth-access.service.ts","../../../projects/kit/src/lib/auth/auth-guards.ts","../../../projects/kit/src/lib/auth/auth-login-exchange.ts","../../../projects/kit/src/lib/http/kit-http.interceptor.ts","../../../projects/kit/src/lib/http/auth-failure.ts","../../../projects/kit/src/lib/realtime/kit-realtime-connection.ts","../../../projects/kit/src/lib/utils/array.ts","../../../projects/kit/src/lib/utils/object.ts","../../../projects/kit/src/lib/utils/dom.ts","../../../projects/kit/src/lib/utils/ionic-scroll-event.ts","../../../projects/kit/src/lib/utils/ionic-view-enter.ts","../../../projects/kit/src/lib/types/component.ts","../../../projects/kit/src/public-api.ts","../../../projects/kit/src/rdlabo-ionic-angular-kit.ts"],"sourcesContent":["import { inject, Injectable } from '@angular/core';\nimport { Storage } from '@ionic/storage-angular';\n\n/**\n * Thin, typed wrapper around `@ionic/storage-angular`.\n *\n * Starts `create()` exactly once and stores the resulting ready Promise. Every operation awaits\n * that Promise before touching the underlying store, so calls made before initialization completes\n * are queued rather than dropped.\n *\n * @remarks\n * A naive wrapper that reads the store synchronously would silently no-op (or throw) when invoked\n * before `create()` resolves, losing early writes. Awaiting the one-time ready Promise on every\n * operation removes that race without forcing callers to coordinate initialization themselves.\n *\n * @example\n * ```ts\n * constructor(private readonly storage: KitStorageService) {}\n *\n * async ngOnInit(): Promise<void> {\n * await this.storage.set('token', 'abc123');\n * const token = await this.storage.get<string>('token');\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitStorageService {\n /** One-time `create()` ready Promise; awaited before every operation so early calls are not lost. */\n readonly #ready: Promise<Storage> = inject(Storage).create();\n\n /**\n * Persist a value under the given key.\n *\n * @typeParam T - type of the value being stored\n * @param key - key to store the value under\n * @param value - value to persist; overwrites any existing value for the key\n * @returns a Promise that resolves once the value has been written\n * @example\n * ```ts\n * await storage.set('user', { id: 1, name: 'Ada' });\n * ```\n */\n async set<T>(key: string, value: T): Promise<void> {\n await (await this.#ready).set(key, value);\n }\n\n /**\n * Read the value stored under the given key.\n *\n * @typeParam T - expected type of the stored value\n * @param key - key to read\n * @returns the stored value, or `null` when the key is absent\n * @example\n * ```ts\n * const user = await storage.get<{ id: number }>('user');\n * ```\n */\n async get<T>(key: string): Promise<T | null> {\n return (await (await this.#ready).get(key)) ?? null;\n }\n\n /**\n * Remove the value stored under the given key.\n *\n * @param key - key to remove; a no-op when the key is absent\n * @returns a Promise that resolves once the key has been removed\n */\n async remove(key: string): Promise<void> {\n await (await this.#ready).remove(key);\n }\n\n /**\n * Remove every key/value pair from the store.\n *\n * @returns a Promise that resolves once the store has been emptied\n */\n async clear(): Promise<void> {\n await (await this.#ready).clear();\n }\n\n /**\n * List every key currently present in the store.\n *\n * @returns an array of all stored keys\n */\n async keys(): Promise<string[]> {\n return (await this.#ready).keys();\n }\n}\n","/**\n * Remember the email a user last entered on the sign-in form so the field can be prefilled next\n * time (the password is never stored).\n *\n * @remarks\n * Storage-agnostic: the helpers take a minimal async key/value store that {@link KitStorageService}\n * satisfies structurally, so they stay pure and unit-testable without DI. `kitRememberEmail`\n * **validates the address before persisting** — a malformed or partial string is silently ignored,\n * so a garbage entry (or a fat-fingered attempt) never becomes the next prefill. A well-formed email\n * that later fails to sign in is still remembered by design: the user simply re-enters/corrects it.\n *\n * These live in the main entry (next to {@link KitStorageService}) rather than in `auth-firebase`,\n * so `KitAuthInputDirective` can consume them without the main entry depending on the Firebase\n * entry.\n */\n\n/** Minimal async key/value store — structurally satisfied by `KitStorageService`. */\nexport interface KitEmailStore {\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n remove(key: string): Promise<void>;\n}\n\n/** Storage key under which the last entered sign-in email is kept. */\nexport const KIT_LAST_AUTH_EMAIL_KEY = 'kit:last-auth-email';\n\n/**\n * Angular's `Validators.email` pattern — a pragmatic, RFC-5322-inspired address check. Kept in sync\n * with `@angular/forms` so a value we persist would also pass the form's own email validation.\n */\nconst EMAIL_REGEXP =\n /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(?:\\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;\n\n/** Whether `email` is a well-formed address (matches `@angular/forms` `Validators.email`). */\nexport const kitIsValidEmail = (email: string): boolean => EMAIL_REGEXP.test(email);\n\n/**\n * Persist the entered email for next time — but only when it is a well-formed address.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @param email - the entered email; ignored (not stored) when malformed\n * @returns `true` when the value passed validation and was stored, `false` when it was ignored\n */\nexport const kitRememberEmail = async (store: KitEmailStore, email: string): Promise<boolean> => {\n if (!kitIsValidEmail(email)) {\n return false;\n }\n await store.set(KIT_LAST_AUTH_EMAIL_KEY, email);\n return true;\n};\n\n/**\n * Recall the last remembered email.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @returns the stored email, or `null` when none has been remembered\n */\nexport const kitRecallEmail = (store: KitEmailStore): Promise<string | null> => store.get<string>(KIT_LAST_AUTH_EMAIL_KEY);\n\n/**\n * Forget the remembered email.\n *\n * @remarks\n * Called when the user intentionally clears or invalidates the field, so a stale prefill is not\n * resurrected next time.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n */\nexport const kitForgetEmail = (store: KitEmailStore): Promise<void> => store.remove(KIT_LAST_AUTH_EMAIL_KEY);\n","/**\n * Canonical storage keys persisted via {@link KitStorageService} that fleet apps often need to\n * keep across a sign-out `clear()`.\n *\n * @remarks\n * `KIT_LAST_AUTH_EMAIL_KEY` lives in `kit-auth-email-store` and is exported from the package root.\n * Import both keys from `@rdlabo/ionic-angular-kit` alongside {@link kitClearStoragePreservingKeys}.\n */\n\n/**\n * Light/dark preference for `provideKitTheme` / `KitThemeController`.\n *\n * @remarks\n * Pass this as `provideKitTheme({ storageKey: KIT_THEME_STORAGE_KEY, … })` and include it in\n * {@link kitClearStoragePreservingKeys} so logout does not reset the user's theme.\n */\nexport const KIT_THEME_STORAGE_KEY = 'theme';\n","/**\n * Clear a key/value store while restoring selected keys afterward.\n *\n * @remarks\n * Fleet apps often call `storage.clear()` on sign-out to drop session/token state. Values that\n * should survive logout (for example {@link KIT_LAST_AUTH_EMAIL_KEY}) are passed in `keys`.\n * Missing keys are skipped — only non-null values are written back.\n */\n\n/** Minimal clearable store — structurally satisfied by {@link KitStorageService}. */\nexport interface KitClearableStore {\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n clear(): Promise<void>;\n}\n\n/**\n * Wipe the store, then restore the given keys to their pre-clear values (when present).\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @param keys - keys whose values should survive the clear\n *\n * @example\n * ```ts\n * import { KIT_LAST_AUTH_EMAIL_KEY, KIT_THEME_STORAGE_KEY, kitClearStoragePreservingKeys } from '@rdlabo/ionic-angular-kit';\n *\n * await kitSignOut(auth, {\n * success: () =>\n * kitClearStoragePreservingKeys(this.storage, [KIT_LAST_AUTH_EMAIL_KEY, KIT_THEME_STORAGE_KEY]),\n * });\n * ```\n */\nexport const kitClearStoragePreservingKeys = async (\n store: KitClearableStore,\n keys: readonly string[],\n): Promise<void> => {\n const preserved = await Promise.all(keys.map(async (key) => ({ key, value: await store.get<unknown>(key) })));\n await store.clear();\n for (const { key, value } of preserved) {\n if (value !== null) {\n await store.set(key, value);\n }\n }\n};\n","import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\n\n/**\n * User-visible button labels consumed by `KitOverlayController`.\n *\n * @remarks\n * The kit deliberately ships no i18n strings of its own and has no hard dependency on\n * `@angular/localize`. The consuming application always provides these labels: multilingual apps\n * pass `$localize`-resolved strings, single-language apps pass plain literals.\n */\nexport interface KitLabels {\n /** Text for the \"close\" button used by alerts and toasts. */\n readonly close: string;\n /** Text for the \"cancel\" button used by confirmation alerts. */\n readonly cancel: string;\n}\n\n/**\n * Overlay configuration injected via `provideKitOverlay()`.\n *\n * @remarks\n * All fields are required; the consuming application must supply a complete configuration.\n */\nexport interface KitOverlayConfig {\n /** Button labels used across the overlays presented by `KitOverlayController`. */\n readonly labels: KitLabels;\n}\n\n/**\n * Injection token carrying the {@link KitOverlayConfig} for `KitOverlayController`.\n *\n * @remarks\n * Provide it through {@link provideKitOverlay} rather than registering it directly.\n */\nexport const KIT_OVERLAY_CONFIG = new InjectionToken<KitOverlayConfig>('@rdlabo/ionic-angular-kit:overlay');\n\n/**\n * Wire `KitOverlayController` into the application by providing its button labels.\n *\n * @param config - overlay configuration, including the button labels to inject\n * @returns environment providers to add to the application's provider list\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideKitOverlay({ labels: { close: $localize`Close`, cancel: $localize`Cancel` } }),\n * ],\n * });\n * ```\n */\nexport const provideKitOverlay = (config: KitOverlayConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_OVERLAY_CONFIG, useValue: config }]);\n","import { Capacitor } from '@capacitor/core';\nimport { Haptics, ImpactStyle } from '@capacitor/haptics';\n\n/**\n * Trigger native haptic impact feedback.\n *\n * Delegates to `@capacitor/haptics` `Haptics.impact()` when running on a native platform. On the\n * web (or any non-native platform) it is a no-op and resolves without doing anything.\n *\n * @remarks\n * This haptic side effect was previously bundled implicitly into toast/modal presentation. It has\n * been decoupled into this explicit function so callers opt in to the feedback deliberately, rather\n * than receiving it as a hidden side effect of presenting UI.\n *\n * @param style - The impact intensity to play. Defaults to {@link ImpactStyle.Light}.\n * @returns A promise that resolves once the feedback has been requested (immediately on the web).\n * @example\n * ```ts\n * import { ImpactStyle } from '@capacitor/haptics';\n *\n * // Light tap (default)\n * await kitImpact();\n *\n * // Stronger feedback, e.g. on a confirming action\n * await kitImpact(ImpactStyle.Heavy);\n * ```\n */\nexport const kitImpact = async (style: ImpactStyle = ImpactStyle.Light): Promise<void> => {\n if (Capacitor.isNativePlatform()) {\n await Haptics.impact({ style });\n }\n};\n","import { inject, Injectable } from '@angular/core';\nimport type { InputSignalWithTransform } from '@angular/core';\nimport type { ModalOptions, PopoverOptions, ToastOptions } from '@ionic/angular';\nimport { AlertController } from '@ionic/angular/alert-controller';\nimport { ModalController } from '@ionic/angular/modal-controller';\nimport { PopoverController } from '@ionic/angular/popover-controller';\nimport { ToastController } from '@ionic/angular/toast-controller';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Capacitor } from '@capacitor/core';\nimport { Keyboard } from '@capacitor/keyboard';\nimport { KIT_OVERLAY_CONFIG } from './overlay-config';\nimport { kitImpact } from '../utils/haptics';\n\n/**\n * Options for {@link KitOverlayController.presentModal}.\n *\n * @remarks\n * Extends Ionic's `ModalOptions` but omits `component` and `componentProps`, which are passed as\n * dedicated arguments instead.\n */\nexport interface KitModalPresentOptions extends Omit<ModalOptions, 'component' | 'componentProps'> {\n /**\n * When `true`, expand the sheet to its maximum breakpoint while the native keyboard is shown.\n *\n * @remarks\n * Only has an effect on native platforms; ignored on the web.\n */\n watchKeyboard?: boolean;\n}\n\n/**\n * Optional static metadata a modal component may declare to make {@link KitOverlayController.presentModal}\n * type-safe in its dismiss data: the value passed to `dismiss()` is inferred from `modalReturn`.\n *\n * @remarks\n * Props do *not* need to be declared here — {@link KitOverlayController.presentModal} infers them directly\n * from the component's `input()` fields (see {@link ModalPropsOf}), so `input()` stays the single source of\n * truth and can never drift from a hand-written declaration. Only the dismiss-data shape, which has no\n * counterpart on the component, is declared — as a `declare static modalReturn` phantom type with no runtime\n * value, so it adds nothing to the bundle.\n *\n * @example\n * ```ts\n * export class EditPage {\n * declare static modalReturn: { saved: boolean };\n * readonly id = input.required<number>(); // props are inferred from here\n * readonly note = input<string>(); // default-less input() → optional prop\n * }\n *\n * // Caller — `id` is required (input.required), `note` optional; result is `{ saved: boolean } | undefined`:\n * const result = await overlay.presentModal(EditPage, { id: 1 });\n * ```\n */\nexport interface ModalMetadata<R = unknown> {\n /** Shape of the data the modal resolves with when dismissed. */\n modalReturn?: R;\n}\n\n/**\n * Write type of a signal `input()` field (unwraps `input.required`, `input()` and transform inputs).\n *\n * @remarks\n * Matched with `any` (not `unknown`): `InputSignalWithTransform`'s `TransformT` is contravariant, so\n * `InputSignal<number>` is not assignable to `InputSignalWithTransform<unknown, unknown>`.\n */\ntype InputWriteType<F> = F extends InputSignalWithTransform<any, infer W> ? W : never;\n\n/** Instance type of a component constructor; `never` for non-class components (string / HTMLElement refs). */\ntype InstanceOf<C> = C extends abstract new (...args: never[]) => infer I ? I : never;\n\n/** Keys of the `input()` signal fields on a component instance. */\ntype InputFieldKeys<I> = { [K in keyof I]-?: I[K] extends InputSignalWithTransform<any, any> ? K : never }[keyof I];\n\n/**\n * Props object inferred from a component's `input()` fields. Required vs. optional is decided by the write\n * type: `input.required<T>()` / `input<T>(default)` yield `T` (no `undefined`) → required prop, while a\n * default-less `input<T>()` yields `T | undefined` → optional prop.\n *\n * @remarks\n * Angular's types cannot distinguish `input.required<T>()` from a defaulted `input<T>(default)` — both are\n * `InputSignal<T>` — so a defaulted input is (safely) treated as required. Declare inputs you want to omit at\n * the call site as default-less `input<T>()`.\n */\ntype ModalPropsOf<I> = { [K in InputFieldKeys<I> as undefined extends InputWriteType<I[K]> ? never : K]: InputWriteType<I[K]> } & {\n [K in InputFieldKeys<I> as undefined extends InputWriteType<I[K]> ? K : never]?: InputWriteType<I[K]>;\n};\n\n/** `input()` keys whose write type excludes `undefined` (required / defaulted inputs). Empty when none. */\ntype RequiredInputKeys<I> = { [K in InputFieldKeys<I>]: undefined extends InputWriteType<I[K]> ? never : K }[InputFieldKeys<I>];\n\n/**\n * Dismiss-data type inferred from a component's static {@link ModalMetadata.modalReturn}. A component that\n * declares no `modalReturn` resolves to `void`: it is treated as returning no dismiss data, so the compiler\n * rejects any attempt to read the result. Declare `modalReturn` on modals that do resolve with data.\n */\ntype ModalReturnOf<C> = C extends { modalReturn: infer R } ? R : void;\n\n/** Loose trailing args (optional, untyped props) — used when a component exposes no signal `input()` fields. */\ntype LooseModalPresentArgs = [componentProps?: ModalOptions['componentProps'], options?: KitModalPresentOptions];\n\n/**\n * Trailing `presentModal` args derived from a component's `input()` fields: props are inferred and typed via\n * {@link ModalPropsOf}. When the component declares at least one required input the props argument is required;\n * when every input is optional the props argument itself is optional. Components with no signal inputs (plain\n * classes, `@Input()`-decorator components, or non-class refs) fall back to loose, untyped props.\n */\ntype ModalPresentArgs<C, I = InstanceOf<C>> = [I] extends [never]\n ? LooseModalPresentArgs\n : [InputFieldKeys<I>] extends [never]\n ? LooseModalPresentArgs\n : [RequiredInputKeys<I>] extends [never]\n ? [componentProps?: ModalPropsOf<I>, options?: KitModalPresentOptions]\n : [componentProps: ModalPropsOf<I>, options?: KitModalPresentOptions];\n\nconst BOTTOM_TAB_BAR_VIEWPORT_MARGIN_PX = 8;\n\n/**\n * Returns a visible `ion-tab-bar` suitable for anchoring a bottom toast above it.\n *\n * Skips `slot=\"top\"` bars (e.g. airlec desktop layout) and prefers the bar closest to the viewport bottom\n * when multiple candidates exist.\n */\nfunction findVisibleBottomTabBar(): HTMLElement | undefined {\n let best: HTMLElement | undefined;\n let bestBottom = -1;\n\n for (const tabBar of Array.from(document.querySelectorAll('ion-tab-bar'))) {\n if (!(tabBar instanceof HTMLElement)) continue;\n if (tabBar.getAttribute('slot') === 'top') continue;\n\n const rect = tabBar.getBoundingClientRect();\n if (rect.height <= 0) continue;\n\n const slot = tabBar.getAttribute('slot');\n const isBottom = slot === 'bottom' || (slot === null && rect.bottom >= window.innerHeight - BOTTOM_TAB_BAR_VIEWPORT_MARGIN_PX);\n if (!isBottom) continue;\n\n if (rect.bottom > bestBottom) {\n bestBottom = rect.bottom;\n best = tabBar;\n }\n }\n\n return best;\n}\n\n/**\n * Options for {@link KitOverlayController.alertClose}.\n */\nexport interface KitAlertCloseOptions {\n /** Alert header text. */\n header: string;\n /** Alert body message. */\n message: string;\n /** Optional alert sub-header text shown beneath the header. */\n subHeader?: string;\n}\n\n/**\n * Options for {@link KitOverlayController.alertConfirm}.\n *\n * @remarks\n * Extends {@link KitAlertCloseOptions} with the confirm-button text.\n */\nexport interface KitAlertConfirmOptions extends KitAlertCloseOptions {\n /**\n * Text for the OK (confirm) button.\n *\n * @remarks\n * Action-specific, so it is supplied by the caller rather than taken from the shared labels.\n */\n okText: string;\n}\n\n/**\n * Attach a native keyboard listener that grows the modal to its maximum breakpoint when the\n * keyboard appears.\n *\n * @param modal - the presented modal element to resize\n * @returns a listener handle; on non-native platforms a no-op handle whose `remove()` does nothing\n * @internal\n */\nconst watchModalKeyboard = async (modal: HTMLIonModalElement): Promise<PluginListenerHandle> => {\n if (!Capacitor.isNativePlatform()) {\n return { remove: async () => undefined };\n }\n return Keyboard.addListener('keyboardDidShow', () => modal.setCurrentBreakpoint(1));\n};\n\n/**\n * Ergonomic wrapper that consolidates Ionic's overlay controllers (Modal / Toast / Alert).\n *\n * @remarks\n * Folds the repetitive create → present → onDidDismiss sequence into single calls and returns the\n * relevant result directly. It holds no application-specific policy such as navigation; compose\n * those concerns on the consuming side.\n *\n * @example\n * ```ts\n * constructor(private readonly overlay: KitOverlayController) {}\n *\n * async edit(): Promise<void> {\n * const result = await this.overlay.presentModal(EditPage, { id: 1 });\n * if (result) {\n * await this.overlay.presentToast({ message: 'Saved' });\n * }\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitOverlayController {\n readonly #modalCtrl = inject(ModalController);\n readonly #popoverCtrl = inject(PopoverController);\n readonly #toastCtrl = inject(ToastController);\n readonly #alertCtrl = inject(AlertController);\n readonly #labels = inject(KIT_OVERLAY_CONFIG).labels;\n\n /**\n * Guards against stacking alerts: while one {@link alertClose} / {@link alertConfirm} is on screen,\n * a concurrent call resolves immediately (close: no-op, confirm: `false`) instead of presenting a\n * second alert on top of the first. Shared across both methods so a confirm cannot stack over a close.\n */\n #alertPresenting = false;\n\n /**\n * Present a modal and resolve with the data passed to its dismissal.\n *\n * @typeParam O - type of the data returned when the modal is dismissed\n * @param component - the component to render inside the modal\n * @param componentProps - props to pass to the modal component\n * @param options - additional modal options, including {@link KitModalPresentOptions.watchKeyboard}\n * @returns the dismiss data, or `undefined` when the modal is dismissed without data\n * @remarks\n * Presenting a modal triggers light native haptic feedback as an intentional kit UX choice,\n * consistent with {@link presentPopover} and {@link presentToast}.\n *\n * Props are inferred from the component's `input()` fields (see {@link ModalPropsOf}): required inputs\n * become required props, so the compiler rejects a call that omits them. The return type is inferred from\n * a static `modalReturn` (see {@link ModalMetadata}); a component with no `modalReturn` resolves to `void`\n * — the modal is treated as returning no dismiss data.\n * @example\n * ```ts\n * // Inferred — `id` required (input.required), `note` optional; result is `{ saved: boolean } | undefined`:\n * const result = await overlay.presentModal(EditPage, { id: 1 });\n * ```\n */\n presentModal<C extends ModalOptions['component']>(component: C, ...args: ModalPresentArgs<C>): Promise<ModalReturnOf<C> | undefined>;\n async presentModal(\n component: ModalOptions['component'],\n componentProps?: ModalOptions['componentProps'],\n options: KitModalPresentOptions = {},\n ): Promise<unknown> {\n void kitImpact();\n const { watchKeyboard, ...modalOptions } = options;\n const modal = await this.#modalCtrl.create({ component, componentProps, ...modalOptions });\n await modal.present();\n const handle = watchKeyboard ? await watchModalKeyboard(modal) : null;\n const { data } = await modal.onDidDismiss<unknown>();\n await handle?.remove();\n return data;\n }\n\n /**\n * Present a popover and resolve with the data passed to its dismissal.\n *\n * @typeParam O - type of the data returned when the popover is dismissed\n * @param component - the component to render inside the popover\n * @param componentProps - props to pass to the popover component\n * @param options - additional popover options (for example `event` to anchor it, or `cssClass`)\n * @returns the dismiss data, or `undefined` when the popover is dismissed without data\n * @remarks\n * Presenting a popover triggers light native haptic feedback as an intentional kit UX choice,\n * consistent with {@link presentModal} and {@link presentToast}.\n * @example\n * ```ts\n * const choice = await overlay.presentPopover<MenuChoice>(MenuPopover, { items }, { event });\n * ```\n */\n async presentPopover<O = unknown>(\n component: PopoverOptions['component'],\n componentProps?: PopoverOptions['componentProps'],\n options: Omit<PopoverOptions, 'component' | 'componentProps'> = {},\n ): Promise<O | undefined> {\n void kitImpact();\n const popover = await this.#popoverCtrl.create({ component, componentProps, ...options });\n await popover.present();\n const { data } = await popover.onDidDismiss<O>();\n return data;\n }\n\n /**\n * Present a toast using kit defaults that the caller may override.\n *\n * @remarks\n * Defaults to a bottom position, a 2000ms duration, a vertical swipe gesture, and a close button\n * from the configured labels; any of these can be overridden via `options`. Presenting a toast\n * also triggers light native haptic feedback as an intentional kit UX choice.\n *\n * Bottom is the fleet-wide default (top left the toast fighting the tab bar and the keyboard).\n * For a bottom toast with no explicit `positionAnchor`, if a visible bottom `ion-tab-bar` is present the\n * toast is automatically anchored above it (Ionic places a bottom toast above its `positionAnchor`),\n * so the toast never sits behind the tabs. Bars with `slot=\"top\"` are ignored (desktop layouts that move\n * tabs to the header). Avoiding the on-screen keyboard is handled by the native keyboard resize — the\n * anchored/bottom toast rides the shrinking viewport above the keyboard;\n * Ionic itself has no toast keyboard-avoidance option. An app can override either via `options`.\n *\n * @param options - Ionic toast options that override the kit defaults\n * @returns the presented toast element\n * @example\n * ```ts\n * await overlay.presentToast({ message: 'Copied to clipboard' });\n * ```\n */\n async presentToast(options: ToastOptions): Promise<HTMLIonToastElement> {\n void kitImpact();\n const merged: ToastOptions = {\n position: 'bottom',\n duration: 2000,\n buttons: [this.#labels.close],\n swipeGesture: 'vertical',\n ...options,\n };\n // Anchor a bottom toast above the tab bar when a bottom bar is visibly present and the caller did not\n // set an explicit anchor, so the toast clears the tabs (and rides the keyboard-resized viewport).\n if (merged.position === 'bottom' && merged.positionAnchor === undefined) {\n const tabBar = findVisibleBottomTabBar();\n if (tabBar) {\n merged.positionAnchor = tabBar;\n }\n }\n const toast = await this.#toastCtrl.create(merged);\n await toast.present();\n return toast;\n }\n\n /**\n * Present a notification alert with a single \"close\" button and wait for it to be dismissed.\n *\n * @param options - alert content (header, message, optional sub-header)\n * @returns a Promise that resolves once the alert has been dismissed\n * @remarks\n * No-ops when another alert is already presenting (see {@link alertClose} / {@link alertConfirm}\n * stacking guard).\n * @example\n * ```ts\n * await overlay.alertClose({ header: 'Done', message: 'Your changes were saved.' });\n * ```\n */\n async alertClose(options: KitAlertCloseOptions): Promise<void> {\n if (this.#alertPresenting) {\n return;\n }\n this.#alertPresenting = true;\n const present = async (): Promise<void> => {\n const alert = await this.#alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [this.#labels.close],\n });\n await alert.present();\n await alert.onWillDismiss();\n };\n await present().finally(() => (this.#alertPresenting = false));\n }\n\n /**\n * Present a confirmation alert with cancel and OK buttons.\n *\n * @param options - alert content plus the OK button text via {@link KitAlertConfirmOptions.okText}\n * @returns `true` when the user presses OK, `false` otherwise (cancel or backdrop dismissal)\n * @example\n * ```ts\n * const ok = await overlay.alertConfirm({\n * header: 'Delete item?',\n * message: 'This cannot be undone.',\n * okText: 'Delete',\n * });\n * if (ok) {\n * await remove();\n * }\n * ```\n * @remarks\n * Returns `false` immediately when another alert is already presenting (see {@link alertClose} /\n * {@link alertConfirm} stacking guard).\n */\n async alertConfirm(options: KitAlertConfirmOptions): Promise<boolean> {\n if (this.#alertPresenting) {\n return false;\n }\n return this.#presentAlertConfirm(options);\n }\n\n /**\n * Try to present a confirmation alert without stacking it over another alert.\n *\n * @returns `true` for confirmation, `false` for explicit cancellation or backdrop dismissal, and `undefined` when\n * another alert prevented this one from being presented.\n */\n async tryAlertConfirm(options: KitAlertConfirmOptions): Promise<boolean | undefined> {\n if (this.#alertPresenting) {\n return undefined;\n }\n const activeAlert = await this.#alertCtrl.getTop();\n if (activeAlert || this.#alertPresenting) {\n return undefined;\n }\n return this.#presentAlertConfirm(options);\n }\n\n async #presentAlertConfirm(options: KitAlertConfirmOptions): Promise<boolean> {\n this.#alertPresenting = true;\n const present = async (): Promise<boolean> => {\n const alert = await this.#alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [\n { text: this.#labels.cancel, role: 'cancel' },\n { text: options.okText, role: 'confirm' },\n ],\n });\n await alert.present();\n const { role } = await alert.onWillDismiss();\n return role === 'confirm';\n };\n return present().finally(() => (this.#alertPresenting = false));\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport type { LoadingOptions } from '@ionic/angular';\nimport { LoadingController } from '@ionic/angular/loading-controller';\n\nconst settledLoadingOperation = async (): Promise<void> => undefined;\n\n/**\n * Reference-counted wrapper around Ionic's `LoadingController` that keeps at most one loading\n * indicator on screen across concurrent async work.\n *\n * @remarks\n * Each {@link presentLoading} increments a counter and each {@link dismissLoading} decrements it; the\n * indicator is presented on the `0 → 1` transition and dismissed on the `N → 0` transition. This\n * removes the flicker / \"stuck spinner\" bugs that come from every service calling\n * `LoadingController.create/dismiss` independently.\n *\n * All operations are serialized through an internal promise chain, so a `create → present` sequence\n * can never interleave with a concurrent `dismiss`. That is what makes the counter race-safe: a\n * dismiss that arrives while the indicator is still being presented runs *after* `present()` settles\n * and therefore tears the element down instead of leaving it orphaned on screen.\n *\n * Always pair every `presentLoading()` with exactly one `dismissLoading()` — a `try/finally` is the\n * safest shape.\n *\n * @example\n * ```ts\n * constructor(private readonly loading: KitLoadingController) {}\n *\n * async save(): Promise<void> {\n * await this.loading.presentLoading({ message: 'Saving…' });\n * try {\n * await this.api.save();\n * } finally {\n * await this.loading.dismissLoading();\n * }\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitLoadingController {\n readonly #loadingCtrl = inject(LoadingController);\n\n /** Outstanding {@link presentLoading} calls not yet balanced by {@link dismissLoading}. */\n #count = 0;\n\n /** The single presented loading element, or `null` when none is on screen. */\n #loading: HTMLIonLoadingElement | null = null;\n\n /**\n * Serializes present/dismiss operations. Each call chains onto this promise, runs after the\n * previous operation has fully settled, then reads {@link #count} and acts accordingly.\n */\n #queue: Promise<void> = settledLoadingOperation();\n\n /**\n * Show the loading indicator, or join the one already on screen.\n *\n * @param options - Ionic loading options; only applied by the call that actually creates the\n * indicator (the `0 → 1` transition). Ignored while an indicator is already present.\n * @returns a Promise that resolves once the indicator is on screen (or immediately when one already is)\n */\n presentLoading(options: LoadingOptions = {}): Promise<void> {\n this.#count++;\n return this.#enqueue(async () => {\n // Create only on the transition into \"something is loading\"; concurrent callers ride the same\n // element. Re-check the count in case a dismiss already balanced this call while queued.\n if (this.#count > 0 && this.#loading === null) {\n const loading = await this.#loadingCtrl.create(options);\n await loading.present();\n this.#loading = loading;\n }\n }).catch((error: unknown) => {\n // Roll back the reference this call took: a failed create/present must not leave the counter\n // elevated, otherwise a later cycle never reaches N → 0 and the spinner stays stuck on screen.\n this.#count--;\n throw error;\n });\n }\n\n /**\n * Release one reference; dismiss the indicator once the last reference is gone.\n *\n * @returns a Promise that resolves once the reference is released (and the indicator dismissed if\n * this was the last one). No-ops when the counter is already at zero.\n */\n async dismissLoading(): Promise<void> {\n if (this.#count === 0) {\n return;\n }\n this.#count--;\n await this.#enqueue(async () => {\n // Tear down only when the last consumer is gone. Because this runs after any in-flight\n // present() has settled (via the queue), there is never an orphaned loading element.\n if (this.#count === 0 && this.#loading !== null) {\n const loading = this.#loading;\n this.#loading = null;\n await loading.dismiss();\n }\n });\n }\n\n /**\n * Append `task` to the serialization chain and return its completion.\n *\n * @remarks\n * The stored chain swallows rejections so a single failing operation cannot wedge every future\n * overlay; the returned promise still rejects so the caller observes the error.\n */\n #enqueue(task: () => Promise<void>): Promise<void> {\n const run = this.#queue.then(task);\n this.#queue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { AlertController } from '@ionic/angular/alert-controller';\nimport { KIT_OVERLAY_CONFIG } from './overlay-config';\n\n/**\n * Content for {@link KitReloadAlertController.present}.\n */\nexport interface KitReloadAlertOptions {\n /** Alert header text. */\n header: string;\n /** Alert body message. */\n message: string;\n /**\n * Text for the reload (confirm) button, e.g. \"リフレッシュ\".\n *\n * @remarks\n * Action-specific, so it is supplied by the caller rather than taken from the shared labels.\n * The cancel button uses the configured {@link KitLabels.cancel}.\n */\n okText: string;\n}\n\n/**\n * The fleet's canonical \"network error → offer to reload\" alert, as a stateful controller.\n *\n * @remarks\n * Consolidates the good-UX variant that had drifted across the fleet into one behavior:\n *\n * - **De-dup** — never stacks; a second {@link present} while an alert is already shown is a no-op.\n * - **Backdrop lock** — `backdropDismiss: false`, so a critical network error can't be dismissed by\n * an accidental backdrop tap; the user consciously chooses cancel or reload.\n * - **Auto-dismiss on reconnect** — the presented alert is tracked, so {@link dismiss} (called from a\n * later successful response) clears a now-stale error alert instead of leaving it on screen.\n * - **Reload on confirm** — the confirm button calls `location.reload()`.\n *\n * All user-facing text is supplied by the caller so the kit stays free of any hardcoded i18n; the\n * cancel button reuses {@link KitOverlayConfig.labels}. Because it performs navigation\n * (`location.reload()`) and holds state, it is a dedicated controller rather than part of\n * {@link KitOverlayController}, which stays free of navigation policy.\n *\n * @example\n * ```ts\n * // In an HTTP interceptor:\n * const reload = inject(KitReloadAlertController);\n * // ...on a network-class error while connected:\n * await reload.present({ header: 'ネットワークエラー', message: `…(${status})`, okText: 'リフレッシュ' });\n * // ...on any later successful response:\n * await reload.dismiss();\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitReloadAlertController {\n readonly #alertCtrl = inject(AlertController);\n readonly #labels = inject(KIT_OVERLAY_CONFIG).labels;\n #alert: HTMLIonAlertElement | null = null;\n\n /**\n * Present the reload alert, unless one is already on screen.\n *\n * @param options - alert content plus the reload-button text\n * @returns a Promise that resolves once the alert has been presented (or immediately if suppressed)\n */\n async present(options: KitReloadAlertOptions): Promise<void> {\n // この controller 経由でも直書き ion-alert でも、多重表示しない。\n if (this.#alert || document.querySelector('ion-alert')) {\n return;\n }\n const alert = await this.#alertCtrl.create({\n header: options.header,\n message: options.message,\n backdropDismiss: false,\n buttons: [\n { text: this.#labels.cancel, role: 'cancel' },\n {\n text: options.okText,\n handler: () => {\n location.reload();\n },\n },\n ],\n });\n this.#alert = alert;\n void alert.onDidDismiss().then(() => {\n // 別の present で置き換わっていない限り、追跡を解除する。\n if (this.#alert === alert) {\n this.#alert = null;\n }\n });\n await alert.present();\n }\n\n /**\n * Dismiss the tracked reload alert if one is showing.\n *\n * @remarks\n * Typically called from a later successful response so a stale \"network error\" alert clears once\n * connectivity is restored. A no-op when nothing is showing.\n *\n * @returns a Promise that resolves once the alert has been dismissed (or immediately if none)\n */\n async dismiss(): Promise<void> {\n const alert = this.#alert;\n this.#alert = null;\n await alert?.dismiss();\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { AlertController } from '@ionic/angular/alert-controller';\n\n/**\n * Content for {@link KitMaintenanceController.present}.\n */\nexport interface KitMaintenanceOptions {\n /** Alert header, e.g. \"メンテナンス中です\". */\n header: string;\n /** Alert body; keep short — the user cannot dismiss until maintenance ends. */\n message: string;\n /**\n * Absolute URL of the fleet maintenance wait SSE (`GET /public/maintenance/wait`).\n *\n * @remarks\n * Typically `environment.api + 'public/maintenance/wait'`. While the overlay is shown the\n * controller opens an {@link EventSource} on this URL and dismisses on `event: ended`.\n */\n waitUrl: string;\n}\n\n/**\n * Singleton \"maintenance lock\" overlay: backdrop-locked, no dismiss buttons, auto-clears via SSE.\n *\n * @remarks\n * Mirrors {@link KitReloadAlertController} as a de-duped stateful controller, but the user cannot\n * cancel or reload out of it — only the server `event: ended` on {@link KitMaintenanceOptions.waitUrl}\n * (or an explicit {@link dismiss}) clears it. Uses Ionic's `AlertController` (not a feature modal)\n * so the kit stays free of page components / i18n; all copy is supplied by the caller.\n *\n * Wire from {@link KitHttpConfig.onMaintenance} when the API returns `503` with\n * `error.error?.code === 'MAINTENANCE'`.\n *\n * @example\n * ```ts\n * provideKitHttp(() => {\n * const maintenance = inject(KitMaintenanceController);\n * return {\n * getAuthHeaders: async () => ({}),\n * onMaintenance: () =>\n * void maintenance.present({\n * header: 'メンテナンス中です',\n * message: 'しばらくお待ちください。終了次第、自動で閉じます。',\n * waitUrl: environment.api + 'public/maintenance/wait',\n * }),\n * };\n * });\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitMaintenanceController {\n readonly #alertCtrl = inject(AlertController);\n #alert: HTMLIonAlertElement | null = null;\n #source: EventSource | null = null;\n #reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n #reconnectAttempt = 0;\n #waitUrl: string | null = null;\n /** When true, EventSource errors must not schedule reconnect (ended / dismiss). */\n #closed = false;\n\n /**\n * Present the lock overlay and start waiting on the maintenance SSE, unless one is already showing.\n *\n * @param options - overlay copy plus the wait SSE URL\n */\n async present(options: KitMaintenanceOptions): Promise<void> {\n if (this.#alert || document.querySelector('ion-alert.kit-maintenance-alert')) {\n return;\n }\n this.#closed = false;\n this.#waitUrl = options.waitUrl;\n const alert = await this.#alertCtrl.create({\n header: options.header,\n message: options.message,\n backdropDismiss: false,\n // No buttons — dismissal is server-driven via SSE (or an explicit dismiss()).\n buttons: [],\n cssClass: 'kit-maintenance-alert',\n });\n this.#alert = alert;\n void alert.onDidDismiss().then(() => {\n if (this.#alert === alert) {\n this.#alert = null;\n }\n this.#stopWait();\n });\n await alert.present();\n this.#startWait(options.waitUrl);\n }\n\n /**\n * Dismiss the tracked overlay and tear down the wait SSE.\n *\n * @remarks\n * Normally called when the wait stream emits `ended`. A no-op when nothing is showing.\n */\n async dismiss(): Promise<void> {\n this.#stopWait();\n const alert = this.#alert;\n this.#alert = null;\n await alert?.dismiss();\n }\n\n #startWait(waitUrl: string): void {\n this.#stopSourceOnly();\n if (this.#closed) {\n return;\n }\n const source = new EventSource(waitUrl);\n this.#source = source;\n\n source.addEventListener('ended', () => {\n void this.dismiss();\n });\n\n source.addEventListener('ping', () => {\n // Keepalive — resets reconnect backoff so a lively stream does not treat the next pause as failure.\n this.#reconnectAttempt = 0;\n });\n\n source.onerror = () => {\n // EventSource auto-reconnects, but after a deploy the old isolate may hang; force a clean\n // reconnect with exponential backoff once the browser surfaces an error.\n if (this.#closed || this.#waitUrl !== waitUrl) {\n return;\n }\n this.#stopSourceOnly();\n this.#scheduleReconnect();\n };\n\n source.onopen = () => {\n this.#reconnectAttempt = 0;\n };\n }\n\n #scheduleReconnect(): void {\n if (this.#closed || !this.#waitUrl) {\n return;\n }\n if (this.#reconnectTimer) {\n clearTimeout(this.#reconnectTimer);\n }\n const delay = Math.min(30_000, 500 * 2 ** this.#reconnectAttempt);\n this.#reconnectAttempt += 1;\n const waitUrl = this.#waitUrl;\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = null;\n if (!this.#closed && this.#waitUrl === waitUrl) {\n this.#startWait(waitUrl);\n }\n }, delay);\n }\n\n #stopWait(): void {\n this.#closed = true;\n this.#waitUrl = null;\n this.#reconnectAttempt = 0;\n if (this.#reconnectTimer) {\n clearTimeout(this.#reconnectTimer);\n this.#reconnectTimer = null;\n }\n this.#stopSourceOnly();\n }\n\n #stopSourceOnly(): void {\n const source = this.#source;\n this.#source = null;\n if (source) {\n source.onerror = null;\n source.onopen = null;\n source.close();\n }\n }\n}\n","import type { AlertController } from '@ionic/angular/alert-controller';\n\n/**\n * Content for {@link kitPresentAuthFailedAlert}.\n */\nexport interface KitAuthFailedAlertOptions {\n /** Alert header, e.g. \"ログインできませんでした\". */\n header: string;\n /** Optional sub-header; typically the short server error code/name. */\n subHeader?: string;\n /** Alert body message; typically the server-provided detail. */\n message: string;\n /** Text for the single close button, e.g. \"閉じる\". */\n closeText: string;\n}\n\n/**\n * Present the fleet's canonical \"sign-in / token exchange failed\" alert.\n *\n * @remarks\n * Folds together the alert every token-exchange app duplicated verbatim when a startup re-login\n * fails: an informative alert (header + optional server error as sub-header + detail message) with a\n * single close button that reloads the app (`location.reload()`) so the user restarts cleanly. The\n * caller is still responsible for signing the user out around this call.\n *\n * All user-facing text is supplied by the caller so the kit stays free of any hardcoded i18n. Kept\n * as a standalone helper (taking the `AlertController`) rather than a method on\n * {@link KitOverlayController}, which holds no navigation policy such as `location.reload()`.\n *\n * @param alertCtrl - Ionic's `AlertController`\n * @param options - alert content plus the close-button text\n * @returns a Promise that resolves once the alert has been presented\n * @example\n * ```ts\n * onAuthorized: async () => {\n * const logged = await auth.tokenLogin().catch(async (e) => {\n * await kitPresentAuthFailedAlert(alertCtrl, {\n * header: 'ログインできませんでした',\n * subHeader: e.error.error,\n * message: e.error.detail,\n * closeText: '閉じる',\n * });\n * await auth.signOut();\n * return undefined;\n * });\n * // ...\n * };\n * ```\n */\nexport const kitPresentAuthFailedAlert = async (\n alertCtrl: AlertController,\n options: KitAuthFailedAlertOptions,\n): Promise<void> => {\n const alert = await alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [\n {\n text: options.closeText,\n role: 'cancel',\n handler: () => {\n location.reload();\n },\n },\n ],\n });\n await alert.present();\n};\n","import { ActionSheetController } from '@ionic/angular/action-sheet-controller';\n\n/** One selectable language in {@link kitPresentLanguageActionSheet}. */\nexport interface KitLanguageOption {\n /** Button label shown to the user (e.g. `English`, `日本語`). */\n readonly text: string;\n /** Locale identifier returned when this option is chosen (e.g. `en-US`, `ja`). */\n readonly data: string;\n}\n\n/**\n * Options for {@link kitPresentLanguageActionSheet}.\n *\n * @remarks\n * The kit ships no strings or URLs of its own: labels, the locale list, and the redirect-URL mapping\n * are all supplied by the caller, so a multilingual app passes `$localize`-resolved text and its own\n * per-locale build paths.\n */\nexport interface KitLanguageActionSheetOptions {\n /** Action-sheet header text. */\n readonly header: string;\n /** Selectable languages, in display order. */\n readonly locales: readonly KitLanguageOption[];\n /** Text for the cancel button. */\n readonly cancelText: string;\n /** The currently active locale; selecting the same value is a no-op. Normalize before passing. */\n readonly currentLocale: string;\n /** The current in-app path (e.g. `router.url`), stashed so the app can restore it after the reload. */\n readonly currentPath: string;\n /** `sessionStorage` key under which {@link currentPath} is stored. */\n readonly pathnameStorageKey: string;\n /** Maps a chosen locale to the URL to navigate to (the app's per-locale build entry point). */\n readonly buildRedirectUrl: (locale: string) => string;\n /** Gate for the redirect — pass `false` (e.g. outside production) to present without navigating. */\n readonly enabled: boolean;\n}\n\n/**\n * Present a language picker and, on a new selection, reload the app at that locale's entry point.\n *\n * @remarks\n * A plain function (the `ActionSheetController` is passed in, so nothing is injected) that unifies the\n * language-switch flow duplicated across apps. On a changed selection while {@link enabled} it stashes\n * the current path in `sessionStorage` (so the app can return the user to where they were), records the\n * chosen locale in `localStorage` under `'locale'`, and calls `window.location.replace()` with the\n * app-provided URL. Because it performs navigation, it is a standalone helper rather than part of a\n * controller (mirroring `kitPresentReloadAlert` / `kitPresentAuthFailedAlert`). Centralizing it means a\n * future improvement to the switch flow lands in every app at once.\n *\n * @param actionSheetCtrl - the Ionic `ActionSheetController`\n * @param options - labels, locale list, and redirect configuration; see {@link KitLanguageActionSheetOptions}\n * @returns a Promise that resolves once presented (and, on a new selection, after the reload is triggered)\n * @example\n * ```ts\n * await kitPresentLanguageActionSheet(inject(ActionSheetController), {\n * header: $localize`言語設定`,\n * locales: [{ text: 'English', data: 'en-US' }, { text: '日本語', data: 'ja' }],\n * cancelText: $localize`キャンセル`,\n * currentLocale: normalizedLocale,\n * currentPath: this.#router.url,\n * pathnameStorageKey: StorageKeyEnum.pathnameBeforeRedirect,\n * buildRedirectUrl: (locale) => location.origin + (localePath[locale.toLowerCase()] ?? '/index.html'),\n * enabled: environment.production,\n * });\n * ```\n */\nexport const kitPresentLanguageActionSheet = async (\n actionSheetCtrl: ActionSheetController,\n options: KitLanguageActionSheetOptions,\n): Promise<void> => {\n const actionSheet = await actionSheetCtrl.create({\n header: options.header,\n buttons: [\n ...options.locales.map((locale) => ({ text: locale.text, data: locale.data })),\n { text: options.cancelText, role: 'cancel' },\n ],\n });\n await actionSheet.present();\n\n const { data } = await actionSheet.onDidDismiss();\n if (options.enabled && data && data !== options.currentLocale) {\n sessionStorage.setItem(options.pathnameStorageKey, options.currentPath);\n localStorage.setItem('locale', data);\n window.location.replace(options.buildRedirectUrl(data));\n }\n};\n","import type { OnInit } from '@angular/core';\nimport { computed, Directive, HostListener, inject, Injector, input } from '@angular/core';\nimport { FORM_FIELD } from '@angular/forms/signals';\nimport { KitStorageService } from '../storage/kit-storage.service';\nimport { kitForgetEmail, kitIsValidEmail, kitRecallEmail, kitRememberEmail } from '../storage/kit-auth-email-store';\n\n/**\n * The email persistence mode of {@link KitAuthInputDirective}.\n *\n * - `'email'` — sign-in email: prefill from storage, remember on change, and forget when cleared.\n * - `'email-remember'` — sign-up email: remember on change only, with no prefill or forget behavior.\n */\nexport type KitAuthInputMode = 'email' | 'email-remember';\n\n/**\n * Email persistence conveniences for an `ion-input`, applied via the `kitAuthInput` attribute.\n *\n * The `'email'` mode recalls the last entered address and seeds an empty Signal Forms field. Both\n * modes remember a well-formed address on `ionChange`; only `'email'` forgets a stored value when\n * the field is cleared or invalid. Browser and OS autofill always wins over an asynchronous prefill.\n *\n * @example\n * ```html\n * <ion-input type=\"email\" autocomplete=\"email\" kitAuthInput=\"email\" [formField]=\"form.email\" />\n * <ion-input type=\"email\" autocomplete=\"email\" kitAuthInput=\"email-remember\" [formField]=\"form.email\" />\n * ```\n *\n * @remarks\n * Prefill writes through the Signal Forms `FORM_FIELD` bound on the same element. With no field,\n * prefill is skipped while remember/forget still work from the DOM event. Storage is resolved lazily\n * so applications that do not configure `@ionic/storage` remain unaffected.\n */\n@Directive({\n selector: '[kitAuthInput]',\n standalone: true,\n})\nexport class KitAuthInputDirective implements OnInit {\n readonly #injector = inject(Injector);\n readonly #field = inject(FORM_FIELD, { optional: true, self: true });\n\n /** Required persistence mode; see {@link KitAuthInputMode}. */\n readonly kitAuthInput = input.required<KitAuthInputMode>();\n\n /** Seeds an empty sign-in email field from storage. */\n ngOnInit(): void {\n if (this.#prefills()) {\n void this.#prefillEmail();\n }\n }\n\n /** Remembers a valid committed email and applies the selected clearing policy. */\n @HostListener('ionChange', ['$event'])\n onIonChange(event: Event): void {\n const storage = this.#resolveStorage();\n if (!storage) {\n return;\n }\n const value = (event as CustomEvent<{ value?: string | null }>).detail?.value ?? '';\n if (value.trim().length > 0 && kitIsValidEmail(value)) {\n void kitRememberEmail(storage, value);\n } else if (this.#forgetsOnClear()) {\n void kitForgetEmail(storage);\n }\n }\n\n readonly #prefills = computed(() => this.kitAuthInput() === 'email');\n readonly #forgetsOnClear = computed(() => this.kitAuthInput() === 'email');\n\n #resolveStorage(): KitStorageService | null {\n try {\n return this.#injector.get(KitStorageService);\n } catch {\n return null;\n }\n }\n\n async #prefillEmail(): Promise<void> {\n const field = this.#field;\n if (!field) {\n return;\n }\n const storage = this.#resolveStorage();\n if (!storage) {\n return;\n }\n const last = await kitRecallEmail(storage);\n const state = field.state();\n if (last && !state.value()) {\n state.value.set(last);\n }\n }\n}\n","import type { ElementRef } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Keyboard } from '@capacitor/keyboard';\n\n/**\n * How {@link kitKeyboardInit} adjusts the target element when the native keyboard appears.\n *\n * - `transform` — CSS `translateY(-keyboardHeight + safeAreaBottom)` for a smooth iOS animation\n * (typical for an `ion-footer`).\n * - `offset` — set the `--offset-bottom` custom property to the negative keyboard height.\n * - `keyboard-offset` — set the `--padding-bottom` custom property to the keyboard height.\n */\nexport type KitKeyboardAdjust = 'transform' | 'offset' | 'keyboard-offset';\n\nconst keyboardWillShow = (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardWillShow', (info) => {\n if (Capacitor.getPlatform() === 'android') {\n if (elementRef.nativeElement.tagName === 'ION-FOOTER' && type === 'transform') {\n // https://github.com/ionic-team/ionic-framework/blob/main/core/src/components/footer/footer.tsx\n elementRef.nativeElement.classList.remove('footer-toolbar-padding');\n }\n return;\n }\n\n elementRef.nativeElement.classList.add('show-keyboard');\n // SSR-safe: this callback only runs on a native keyboard event, so the global `document` /\n // `window` are never touched on the server (kitKeyboardInit returns early when not native).\n const bodyStyleDeclaration = window.getComputedStyle(document.querySelector('body') as Element);\n const safeArea = parseInt(bodyStyleDeclaration.getPropertyValue('--ion-safe-area-bottom'), 10);\n\n if (type === 'transform') {\n elementRef.nativeElement.style.transition = 'transform 420ms';\n elementRef.nativeElement.style.willChange = 'transform';\n requestAnimationFrame(() => (elementRef.nativeElement.style.transform = `translateY(${info.keyboardHeight * -1 + safeArea}px)`));\n } else {\n const property = type === 'offset' ? '--offset-bottom' : '--padding-bottom';\n const height = type === 'offset' ? info.keyboardHeight * -1 : info.keyboardHeight;\n requestAnimationFrame(() => {\n const keyboardOffset = elementRef.nativeElement.style.getPropertyValue('--keyboard-offset');\n if (!keyboardOffset || parseInt(keyboardOffset, 10) === 0) {\n elementRef.nativeElement.style.setProperty(property, `${height}px`);\n }\n });\n }\n });\n\nconst keyboardWillHide = (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardWillHide', () => {\n if (Capacitor.getPlatform() === 'android') {\n if (elementRef.nativeElement.tagName === 'ION-FOOTER' && type === 'transform') {\n elementRef.nativeElement.classList.add('footer-toolbar-padding');\n }\n return;\n }\n\n elementRef.nativeElement.classList.remove('show-keyboard');\n\n if (type === 'transform') {\n elementRef.nativeElement.style.transition = 'transform 0ms';\n elementRef.nativeElement.style.transform = `translateY(0px)`;\n elementRef.nativeElement.style.willChange = 'transform';\n } else {\n const property = type === 'offset' ? '--offset-bottom' : '--padding-bottom';\n elementRef.nativeElement.style.setProperty(property, '0px');\n }\n });\n\nconst keyboardDidShow = (elementRef: ElementRef): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardDidShow', () => {\n elementRef.nativeElement.style.willChange = 'auto';\n });\n\nconst keyboardDidHide = (elementRef: ElementRef): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardDidHide', () => {\n elementRef.nativeElement.style.willChange = 'auto';\n });\n\n/**\n * Register native keyboard listeners that reposition an element when the keyboard shows/hides.\n *\n * @remarks\n * A plain function — no DI needed (it reads the platform from `Capacitor` and uses the global\n * `document`), so a component calls it directly instead of injecting a controller. SSR-safe: the\n * global `document` / `window` are only read inside native keyboard-event callbacks, which never\n * fire on the server — the `Capacitor.isNativePlatform()` guard returns `[]` first, and nothing is\n * touched at module load. A no-op on non-native platforms (returns `[]`). On native it handles the\n * iOS/Android differences (Android\n * only toggles the `footer-toolbar-padding` class on an `ion-footer` for the `transform` mode,\n * working around an Ionic footer bug). The caller owns the returned handles and must `remove()`\n * them when the view is destroyed.\n *\n * @param elementRef - The element to reposition (e.g. an `ion-footer`).\n * @param type - The adjustment strategy; see {@link KitKeyboardAdjust}.\n * @returns The registered listener handles (empty on non-native platforms).\n * @example\n * ```ts\n * export class ComposePage {\n * readonly #footer = viewChild.required<ElementRef>('footer');\n * #handles: PluginListenerHandle[] = [];\n *\n * async ngAfterViewInit() {\n * this.#handles = await kitKeyboardInit(this.#footer(), 'transform');\n * }\n * ngOnDestroy() {\n * this.#handles.forEach((h) => h.remove());\n * }\n * }\n * ```\n */\nexport const kitKeyboardInit = async (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle[]> => {\n if (!Capacitor.isNativePlatform()) {\n return [];\n }\n return [\n await keyboardWillShow(elementRef, type),\n await keyboardWillHide(elementRef, type),\n await keyboardDidShow(elementRef),\n await keyboardDidHide(elementRef),\n ];\n};\n","import { DestroyRef, ErrorHandler, inject, Injectable, InjectionToken } from '@angular/core';\nimport type { Observable } from 'rxjs';\nimport { BehaviorSubject, Subscription } from 'rxjs';\n\n/** Access level currently granted to the application runtime. */\nexport type KitAuthAccessMode = 'none' | 'local' | 'remote';\n\n/** Generation lease that becomes stale as soon as a newer access transition starts. */\nexport interface KitAuthAccessLease {\n /** Whether work owned by this transition may still publish or persist access. */\n isCurrent(): boolean;\n}\n\n/**\n * Result of remote reauthentication, split into ordered activation and resume phases.\n *\n * @remarks\n * `activate` installs the remotely authenticated identity without starting transport. The kit then\n * publishes `remote` access and invokes `resume`, which may start pull, outbox replay, and realtime\n * work.\n */\nexport interface KitRemoteAccessRecovery {\n /**\n * Install the remotely verified identity, checking the lease again immediately before commit.\n *\n * @returns `false` when a newer logout or identity transition superseded this activation.\n */\n activate(lease: KitAuthAccessLease): Promise<boolean>;\n /**\n * Resume remote-only work after access has been published.\n *\n * @param lease - Post-grant lease supplied by the kit. Check it after every await before\n * navigation or other user-visible side effects, because logout or a newer identity transition\n * may supersede this resume while transport work is settling. Optional for source compatibility\n * with callers that manually resumed a recovery result before leases were introduced.\n */\n resume(lease?: KitAuthAccessLease): Promise<void>;\n /**\n * Whether route activation must wait for {@link resume} to settle.\n *\n * @remarks\n * Use `background` only when {@link activate} has already installed every identity and local\n * capability boundary required to render the route safely. Authentication denial still revokes\n * access; transport unavailability is handled by the configured recovery policy.\n *\n * @defaultValue 'blocking'\n */\n resumeMode?: 'blocking' | 'background';\n}\n\n/** Recovery-specific authentication configuration consumed by {@link KitAuthRecoveryService}. */\nexport interface KitAuthRecoveryConfig {\n /** Classifies transport unavailability; HTTP 401/403 are always denied before this callback. */\n isUnavailableError?(error: unknown): boolean;\n /** Optional online-recovery lifecycle used after local-only route access. */\n remoteRecovery?: {\n /**\n * Delay before probing authentication again while local access remains active.\n *\n * @defaultValue 30000\n */\n retryDelayMs?: number;\n availability(): Observable<boolean>;\n reauthenticate(lease: KitAuthAccessLease): Promise<KitRemoteAccessRecovery | false>;\n };\n}\n\n/** Internal alias of the application auth config used without a module cycle. */\nexport const KIT_AUTH_RECOVERY_CONFIG = new InjectionToken<KitAuthRecoveryConfig>('@rdlabo/ionic-angular-kit:auth-recovery');\n\n/** Shared runtime access state consumed by guards, UI, HTTP, and realtime connections. */\n@Injectable({ providedIn: 'root' })\nexport class KitAuthAccessService {\n readonly #mode = new BehaviorSubject<KitAuthAccessMode>('none');\n #revision = 0;\n\n /** Emits the current access mode and every later transition. */\n readonly mode$: Observable<KitAuthAccessMode> = this.#mode.asObservable();\n\n /** Current synchronous access mode. */\n get mode(): KitAuthAccessMode {\n return this.#mode.value;\n }\n\n /**\n * Monotonic runtime revision used to invalidate an in-flight access transition.\n *\n * @internal\n */\n get revision(): number {\n return this.#revision;\n }\n\n /**\n * Start a transition and invalidate every older asynchronous access decision.\n *\n * @param options - Set `suspendRemote` when the new decision must revoke published remote\n * capabilities immediately while keeping this new lease valid.\n */\n beginTransition(options: { suspendRemote?: boolean } = {}): KitAuthAccessLease {\n this.#revision += 1;\n const revision = this.#revision;\n if (options.suspendRemote && this.#mode.value === 'remote') {\n this.#mode.next('none');\n }\n return { isCurrent: () => this.#revision === revision };\n }\n\n /** Revoke published capabilities without invalidating the transition that owns `lease`. */\n suspend(lease: KitAuthAccessLease): boolean {\n if (!lease.isCurrent()) return false;\n if (this.#mode.value !== 'none') this.#mode.next('none');\n return true;\n }\n\n /** Publish a verified local-replica-only session. */\n grantLocal(): void {\n this.#publish('local');\n }\n\n /**\n * Publish a remotely authenticated session and return the lease that owns that publication.\n *\n * The revision is fixed before synchronous `mode$` subscribers run. A subscriber that starts a\n * newer logout or identity transition therefore makes the returned lease stale.\n */\n grantRemote(): KitAuthAccessLease {\n return this.#publish('remote');\n }\n\n /** Revoke both local and remote access. */\n clear(): void {\n this.#publish('none');\n }\n\n #publish(mode: KitAuthAccessMode): KitAuthAccessLease {\n this.#revision += 1;\n const revision = this.#revision;\n this.#mode.next(mode);\n return { isCurrent: () => this.#revision === revision };\n }\n}\n\n/** Coordinates single-flight recovery from local-only mode to remote access. */\n@Injectable({ providedIn: 'root' })\nexport class KitAuthRecoveryService {\n readonly #access = inject(KitAuthAccessService);\n readonly #config = inject(KIT_AUTH_RECOVERY_CONFIG);\n readonly #errorHandler = inject(ErrorHandler);\n readonly #destroyRef = inject(DestroyRef);\n #subscription: Subscription | null = null;\n #recovery: Promise<void> | null = null;\n #recoveryRevision: number | null = null;\n #retryTimer: ReturnType<typeof setTimeout> | null = null;\n #available = false;\n #retryRequested = false;\n #destroyed = false;\n\n constructor() {\n this.#destroyRef.onDestroy(() => {\n this.#destroyed = true;\n this.#clearRetry();\n this.#subscription?.unsubscribe();\n this.#subscription = null;\n });\n }\n\n /** Subscribe to the configured remote-availability stream once. */\n initialize(): void {\n if (this.#destroyed) return;\n const recovery = this.#config.remoteRecovery;\n if (!recovery || this.#subscription) return;\n this.#subscription = new Subscription();\n this.#subscription.add(\n recovery.availability().subscribe({\n next: (available) => {\n this.#available = available;\n if (available && this.#access.mode === 'local') {\n this.#clearRetry();\n void this.recover();\n } else if (this.#access.mode === 'local') {\n this.#scheduleRetry();\n }\n },\n error: (error) => this.#errorHandler.handleError(error),\n }),\n );\n this.#subscription.add(\n this.#access.mode$.subscribe((mode) => {\n if (mode !== 'local') {\n this.#clearRetry();\n return;\n }\n if (this.#available) {\n void this.recover();\n } else {\n this.#scheduleRetry();\n }\n }),\n );\n }\n\n /** Run one ordered remote recovery attempt, coalescing concurrent triggers. */\n async recover(): Promise<void> {\n if (this.#destroyed) return;\n if (this.#recovery) {\n if (this.#access.mode === 'local' && this.#recoveryRevision !== null && this.#access.revision > this.#recoveryRevision) {\n this.#retryRequested = true;\n }\n return this.#recovery;\n }\n const running = this.#runRecovery();\n this.#recoveryRevision = this.#access.revision;\n const promise = running.finally(() => {\n if (this.#recovery !== promise) return;\n this.#recovery = null;\n this.#recoveryRevision = null;\n if (this.#destroyed) return;\n if (!this.#retryRequested) return;\n this.#retryRequested = false;\n if (this.#access.mode !== 'local') return;\n if (this.#available) {\n void this.recover();\n } else {\n this.#scheduleRetry();\n }\n });\n this.#recovery = promise;\n return promise;\n }\n\n async #runRecovery(): Promise<void> {\n const recovery = this.#config.remoteRecovery;\n if (this.#destroyed || !recovery || this.#access.mode !== 'local') return;\n const lease = this.#access.beginTransition();\n let currentLease = lease;\n const isCurrent = (): boolean => currentLease.isCurrent();\n const executeRecovery = async (): Promise<void> => {\n const result = await recovery.reauthenticate(lease);\n if (this.#destroyed || !isCurrent() || this.#access.mode !== 'local') return;\n if (result === false) {\n this.#clearRetry();\n this.#access.clear();\n return;\n }\n if (!(await result.activate(lease)) || this.#destroyed || !isCurrent() || this.#access.mode !== 'local') {\n return;\n }\n this.#clearRetry();\n currentLease = this.#access.grantRemote();\n if (!currentLease.isCurrent()) return;\n await result.resume(currentLease);\n };\n await executeRecovery().catch((error: unknown) => {\n if (this.#destroyed || !isCurrent()) return;\n if (isExplicitAuthDenial(error)) {\n this.#clearRetry();\n this.#access.clear();\n } else if (this.#config.isUnavailableError?.(error)) {\n this.#scheduleRetry();\n } else {\n this.#errorHandler.handleError(error);\n }\n });\n }\n\n #scheduleRetry(): void {\n const recovery = this.#config.remoteRecovery;\n if (this.#destroyed || !recovery || this.#retryTimer || this.#access.mode !== 'local') return;\n this.#retryTimer = setTimeout(() => {\n this.#retryTimer = null;\n if (this.#access.mode === 'local') void this.recover();\n }, this.#retryDelayMs(recovery.retryDelayMs));\n }\n\n #clearRetry(): void {\n if (!this.#retryTimer) return;\n clearTimeout(this.#retryTimer);\n this.#retryTimer = null;\n }\n\n #retryDelayMs(configured: number | undefined): number {\n if (configured === undefined || !Number.isFinite(configured)) return 30_000;\n return Math.max(1_000, configured);\n }\n}\n\n/** Returns true for authoritative authentication denials that must never use local fallback. */\nexport function isExplicitAuthDenial(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const status = (error as { status?: unknown }).status;\n return status === 401 || status === 403;\n}\n","import type { EnvironmentProviders } from '@angular/core';\nimport { ErrorHandler, inject, InjectionToken, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';\nimport type { CanActivateFn, RouterStateSnapshot, UrlTree } from '@angular/router';\nimport { Router } from '@angular/router';\nimport { NavController } from '@ionic/angular/common';\nimport type { Observable } from 'rxjs';\nimport { of, throwError } from 'rxjs';\nimport { catchError, map, mergeMap } from 'rxjs/operators';\nimport {\n isExplicitAuthDenial,\n type KitAuthAccessLease,\n type KitAuthRecoveryConfig,\n type KitRemoteAccessRecovery,\n KitAuthAccessService,\n KIT_AUTH_RECOVERY_CONFIG,\n KitAuthRecoveryService,\n} from './auth-access.service';\n\n/**\n * Discriminated set of authentication states the guards react to.\n *\n * @remarks\n * The application is responsible for emitting these values through {@link KitAuthConfig.authState}.\n * An application that does not use a value (for example email confirmation) simply never emits it.\n *\n * - `user` — fully authenticated and verified.\n * - `confirm` — awaiting email confirmation.\n * - `required` — not authenticated.\n * - `anonymous` — signed in anonymously; the user can still be guided toward full registration.\n */\nexport type KitAuthState = 'user' | 'confirm' | 'required' | 'anonymous';\n\n/**\n * Authentication states accepted by route guards.\n *\n * @remarks\n * `unavailable` means the authentication authority cannot currently be reached; this is distinct\n * from an explicit signed-out result. {@link KitAuthState} remains the original four-state union\n * so existing exhaustive consumers remain source-compatible.\n */\nexport type KitAuthGuardState = KitAuthState | 'unavailable';\n\n/**\n * Redirect targets (route paths) used by the guards when access is denied.\n *\n * @remarks\n * Every field is required and must be provided per application, because the guards have no\n * knowledge of the host application's route layout.\n */\nexport interface KitAuthRedirects {\n /** Used by {@link kitRequiredUnauthorizedGuard}: where to navigate when the user is already authenticated (`user`). */\n readonly whenAuthorized: string;\n /** Used by {@link kitRequiredUnauthorizedGuard}: where to navigate when the user is awaiting email confirmation (`confirm`). */\n readonly whenConfirming: string;\n /** Used by {@link kitRequireConfirmingGuard}: where to navigate when the state is not `confirm`. */\n readonly whenNotConfirming: string;\n /** Used by {@link kitRequireAuthorizedGuard}: where to navigate when the state is not `user` and the fallback is not allowed. */\n readonly whenUnauthorized: string;\n}\n\n/**\n * Configuration consumed by the authentication guards, injected through {@link provideKitAuth}.\n *\n * @remarks\n * `authState` and `redirects` are required. The `onAuthorized`, `onUnauthenticated`, and\n * `onUnavailable` hooks are optional. Without them the guard allows an authenticated user and\n * redirects unauthenticated or unavailable states, so an app only supplies hooks with real logic.\n */\nexport interface KitAuthConfig extends KitAuthRecoveryConfig {\n /**\n * Source of the current authentication state.\n *\n * @remarks\n * Typically backed by the application's own auth service (for example `AuthService.isAuth()`).\n *\n * @returns A stream of {@link KitAuthState} values.\n */\n authState(): Observable<KitAuthGuardState>;\n /**\n * Application-specific work that runs in {@link kitRequireAuthorizedGuard} after the state is confirmed to be `user`.\n *\n * @remarks\n * Typical responsibilities include token login, permission checks, terms-of-service acceptance,\n * or restoring a previously requested redirect. Optional; defaults to `true` (allow activation).\n *\n * @param state - The router state snapshot of the route being activated.\n * @param lease - Transition lease that product persistence must verify immediately before commit.\n * @returns `true` to allow activation, a `UrlTree` to perform a custom redirect, or a phased\n * remote activation that installs the session before transport work resumes.\n */\n onAuthorized?(state: RouterStateSnapshot, lease: KitAuthAccessLease): Promise<boolean | UrlTree | KitRemoteAccessRecovery>;\n /**\n * Fallback that runs in {@link kitRequireAuthorizedGuard} when the state is `required` (not authenticated).\n *\n * @remarks\n * For example, attempt an anonymous sign-in and allow the route. Optional; defaults to `false`\n * (fall through to the default `whenUnauthorized` redirect).\n *\n * @param state - The router state snapshot of the route being activated.\n * @param lease - Transition lease that product persistence must verify immediately before commit.\n * @returns `true` to allow activation, a `UrlTree` for a custom redirect, a phased remote\n * activation, or `false` to use the default redirect.\n */\n onUnauthenticated?(state: RouterStateSnapshot, lease: KitAuthAccessLease): Promise<boolean | UrlTree | KitRemoteAccessRecovery>;\n /**\n * Fallback that runs only when authentication is unavailable, never for an explicit\n * unauthenticated result.\n *\n * @remarks\n * This hook may authorize read/write access to a previously verified local replica. It must not\n * provide credentials to HTTP or realtime transports. Explicit sign-out and HTTP 401/403 must\n * remain unauthorized.\n *\n * @param state - The router state snapshot of the route being activated.\n * @param error - The classified transport error, or `undefined` when `authState` emitted\n * `unavailable`.\n * @param lease - Transition lease that local-session activation must verify before commit.\n * @returns `true` to allow local route activation, a `UrlTree` for a custom redirect, or `false`\n * to use the default redirect.\n */\n onUnavailable?(state: RouterStateSnapshot, error: unknown | undefined, lease: KitAuthAccessLease): Promise<boolean | UrlTree>;\n /** Redirect targets used by the guards. */\n redirects: KitAuthRedirects;\n}\n\n/**\n * Injection token that carries the {@link KitAuthConfig} to the authentication guards.\n */\nexport const KIT_AUTH_CONFIG = new InjectionToken<KitAuthConfig>('@rdlabo/ionic-angular-kit:auth');\n\n/**\n * Wire the authentication guard configuration into the application's dependency injection.\n *\n * @remarks\n * The factory runs inside an injection context, so it may call `inject()` (for example\n * `inject(AuthService)`) to build the configuration.\n *\n * @param configFactory - Factory that returns the {@link KitAuthConfig} for the application.\n * @returns Environment providers to add to the application bootstrap.\n *\n * @example\n * ```ts\n * provideKitAuth(() => {\n * const auth = inject(AuthService);\n * return {\n * // onAuthorized / onUnauthenticated are optional (default: allow / fall through to redirect).\n * authState: () => auth.isAuth(),\n * redirects: {\n * whenAuthorized: '/',\n * whenConfirming: '/auth/confirm',\n * whenNotConfirming: '/auth/signin',\n * whenUnauthorized: 'auth',\n * },\n * };\n * });\n * ```\n */\nexport const provideKitAuth = (configFactory: () => KitAuthConfig): EnvironmentProviders =>\n makeEnvironmentProviders([\n { provide: KIT_AUTH_CONFIG, useFactory: configFactory },\n { provide: KIT_AUTH_RECOVERY_CONFIG, useExisting: KIT_AUTH_CONFIG },\n provideAppInitializer(() => inject(KitAuthRecoveryService).initialize()),\n ]);\n\n/**\n * Guard that requires the user to be unauthenticated (for example sign-in or sign-up pages).\n *\n * @remarks\n * Allows the `required`, `anonymous`, and `unavailable` states (an anonymous user is permitted to\n * proceed to a registration page). An authenticated user (`user`) is sent to `whenAuthorized`, and\n * a user awaiting confirmation (`confirm`) is sent to `whenConfirming`.\n *\n * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'signin', component: SigninPage, canActivate: [kitRequiredUnauthorizedGuard] }];\n * ```\n */\nexport const kitRequiredUnauthorizedGuard: CanActivateFn = () => {\n const { authState, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n const access = inject(KitAuthAccessService);\n const lease = access.beginTransition({ suspendRemote: true });\n\n return authState().pipe(\n catchError((error) => {\n if (lease.isCurrent() && isExplicitAuthDenial(error)) access.clear();\n return throwError(() => error);\n }),\n map((data) => {\n if (!lease.isCurrent()) return false;\n if (data !== 'unavailable') access.clear();\n if (data === 'user') {\n navCtrl.setDirection('root');\n router.navigate([redirects.whenAuthorized]);\n return false;\n } else if (data === 'confirm') {\n router.navigate([redirects.whenConfirming]);\n return false;\n }\n // 'required' | 'anonymous' | 'unavailable'\n return true;\n }),\n );\n};\n\n/**\n * Guard that requires the user to be awaiting email confirmation (`confirm`).\n *\n * @remarks\n * Any other state triggers a redirect: an `anonymous` user is sent to the authenticated area\n * (`whenAuthorized`), and every remaining state is sent to `whenNotConfirming`.\n *\n * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'confirm', component: ConfirmPage, canActivate: [kitRequireConfirmingGuard] }];\n * ```\n */\nexport const kitRequireConfirmingGuard: CanActivateFn = () => {\n const { authState, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n const access = inject(KitAuthAccessService);\n const lease = access.beginTransition({ suspendRemote: true });\n\n return authState().pipe(\n catchError((error) => {\n if (lease.isCurrent() && isExplicitAuthDenial(error)) access.clear();\n return throwError(() => error);\n }),\n map((data) => {\n if (!lease.isCurrent()) return false;\n if (data !== 'unavailable') access.clear();\n if (data === 'confirm') {\n return true;\n }\n navCtrl.setDirection('root');\n router.navigate([data === 'anonymous' ? redirects.whenAuthorized : redirects.whenNotConfirming]);\n return false;\n }),\n );\n};\n\n/**\n * Guard that requires the user to be fully authenticated (`user`).\n *\n * @remarks\n * - `user` — runs {@link KitAuthConfig.onAuthorized} (token login, permission checks, and so on).\n * - `anonymous` — allowed as-is, for applications that permit anonymous browsing.\n * - `unavailable` — runs {@link KitAuthConfig.onUnavailable}; this is the only state intended for\n * restored local-replica access.\n * - `required` / `confirm` — runs {@link KitAuthConfig.onUnauthenticated}; if it resolves to `false`,\n * the user is redirected to `whenUnauthorized`.\n *\n * @param _route - The activated route snapshot (unused).\n * @param state - The router state snapshot, forwarded to the configuration hooks.\n * @returns A stream emitting the activation result: `true`, a `UrlTree`, or `false` after a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'home', component: HomePage, canActivate: [kitRequireAuthorizedGuard] }];\n * ```\n */\nexport const kitRequireAuthorizedGuard: CanActivateFn = (_route, state) => {\n const { authState, onAuthorized, onUnauthenticated, onUnavailable, isUnavailableError, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n const access = inject(KitAuthAccessService);\n const errorHandler = inject(ErrorHandler);\n const lease = access.beginTransition({ suspendRemote: true });\n\n const reportError = (error: unknown): void => {\n try {\n errorHandler.handleError(error);\n } catch {\n // Error reporting must not create an unhandled background rejection.\n }\n };\n\n const redirectUnauthorized = (currentLease: KitAuthAccessLease = lease): false => {\n if (!currentLease.isCurrent()) return false;\n access.clear();\n navCtrl.setDirection('root');\n router.navigate([redirects.whenUnauthorized]);\n return false;\n };\n const resolveUnavailable = async (error?: unknown): Promise<boolean | UrlTree> => {\n const resolveFallback = async (): Promise<boolean | UrlTree> => {\n const fallback = onUnavailable ? await onUnavailable(state, error, lease) : false;\n if (!lease.isCurrent()) return false;\n if (fallback === true) {\n access.grantLocal();\n return true;\n }\n if (fallback === false) return redirectUnauthorized();\n access.clear();\n return fallback;\n };\n return resolveFallback().catch((fallbackError: unknown) => {\n if (!lease.isCurrent()) return false;\n access.clear();\n throw fallbackError;\n });\n };\n const resolveRemote = async (result: boolean | UrlTree | KitRemoteAccessRecovery): Promise<boolean | UrlTree> => {\n if (!lease.isCurrent()) return false;\n if (isRemoteAccessActivation(result)) {\n if (!(await result.activate(lease)) || !lease.isCurrent()) return false;\n const resumeLease = access.grantRemote();\n if (!resumeLease.isCurrent()) return false;\n const resume = async (): Promise<void> => result.resume(resumeLease);\n const handleResumeError = (error: unknown): void => {\n if (!resumeLease.isCurrent()) return;\n if (isExplicitAuthDenial(error)) {\n if (result.resumeMode === 'background') {\n redirectUnauthorized(resumeLease);\n reportError(error);\n return;\n }\n access.clear();\n throw error;\n }\n if (!isUnavailableError?.(error)) throw error;\n };\n if (result.resumeMode === 'background') {\n void resume().catch((error: unknown) => {\n try {\n handleResumeError(error);\n } catch (unhandledError: unknown) {\n reportError(unhandledError);\n }\n });\n return resumeLease.isCurrent();\n }\n await resume().catch(handleResumeError);\n return resumeLease.isCurrent();\n }\n if (result === true) access.grantRemote();\n else access.clear();\n return result;\n };\n\n interface AuthEmission {\n authState: KitAuthGuardState;\n error?: unknown;\n }\n return authState().pipe(\n map((authState): AuthEmission => ({ authState })),\n catchError((error): Observable<AuthEmission> => {\n if (!lease.isCurrent()) return of({ authState: 'required' });\n if (isExplicitAuthDenial(error)) {\n access.clear();\n return throwError(() => error);\n }\n return isUnavailableError?.(error) ? of({ authState: 'unavailable', error }) : throwError(() => error);\n }),\n mergeMap(async ({ authState: data, error: authStateError }) => {\n if (!lease.isCurrent()) return false;\n if (data === 'user') {\n // 既定は「許可」。tokenLogin / 権限確認等が必要なアプリだけ onAuthorized を渡す。\n if (!onAuthorized) {\n if (!lease.isCurrent()) return false;\n access.grantRemote();\n return true;\n }\n const resolveAuthorized = async (): Promise<boolean | UrlTree> => {\n const result = await onAuthorized(state, lease);\n if (!lease.isCurrent()) return false;\n return resolveRemote(result);\n };\n return resolveAuthorized().catch((error: unknown) => {\n if (!lease.isCurrent()) return false;\n if (isExplicitAuthDenial(error)) {\n access.clear();\n throw error;\n }\n if (!isUnavailableError?.(error)) throw error;\n return resolveUnavailable(error);\n });\n }\n if (data === 'anonymous') {\n if (!lease.isCurrent()) return false;\n access.grantRemote();\n return true;\n }\n if (data === 'unavailable') {\n return resolveUnavailable(authStateError);\n }\n // `required` / `confirm` are authoritative denials. Revoke a previously verified local\n // capability before an anonymous-sign-in fallback (if any) is allowed to await.\n if (!access.suspend(lease)) return false;\n // 既定は false(whenUnauthorized へ)。匿名ログイン等のフォールバックが要るアプリだけ渡す。\n const fallback = onUnauthenticated ? await onUnauthenticated(state, lease) : false;\n if (!lease.isCurrent()) return false;\n if (fallback !== false) {\n return resolveRemote(fallback);\n }\n return redirectUnauthorized();\n }),\n );\n};\n\nfunction isRemoteAccessActivation(value: boolean | UrlTree | KitRemoteAccessRecovery): value is KitRemoteAccessRecovery {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'activate' in value &&\n typeof value.activate === 'function' &&\n 'resume' in value &&\n typeof value.resume === 'function'\n );\n}\n","import { NavigationCancel, NavigationEnd, NavigationError } from '@angular/router';\nimport type { Router } from '@angular/router';\nimport { filter, take } from 'rxjs';\n\ninterface LoginExchange<Identity, Result> {\n readonly identity: Identity;\n readonly promise: Promise<Result>;\n handoff: (() => boolean) | null;\n settledAt: number | null;\n}\n\n/** Shares an in-flight login and hands its startup result to authorization exactly once. */\nexport class KitAuthLoginExchange<Identity, Result> {\n #startedFor: Identity | undefined;\n #exchange: LoginExchange<Identity, Result> | null = null;\n\n /** Start once per signed-in identity; discard an unconsumed result when its navigation ends. */\n preload(identity: Identity, request: () => Promise<Result>, isCurrent: () => boolean): (() => void) | undefined {\n if (this.#startedFor === identity) return undefined;\n const exchange = this.#start(identity, request, isCurrent);\n void exchange.promise.catch(() => undefined);\n return () => {\n if (this.#exchange === exchange) this.clear();\n };\n }\n\n /** Consume a current startup result, share pending work, or perform a fresh login. */\n run(identity: Identity, request: () => Promise<Result>): Promise<Result> {\n const exchange = this.#exchange;\n if (\n exchange &&\n exchange.identity === identity &&\n (!exchange.handoff || (exchange.handoff() && (exchange.settledAt === null || Date.now() - exchange.settledAt < 30_000)))\n ) {\n exchange.handoff = null;\n if (exchange.settledAt !== null) this.#exchange = null;\n return exchange.promise;\n }\n return this.#start(identity, request, null).promise;\n }\n\n /** Forget startup state on sign-out; a later sign-in may preload again. */\n clear(): void {\n this.#exchange = null;\n this.#startedFor = undefined;\n }\n\n #start(identity: Identity, request: () => Promise<Result>, handoff: (() => boolean) | null): LoginExchange<Identity, Result> {\n const exchange: LoginExchange<Identity, Result> = {\n identity,\n handoff,\n settledAt: null,\n promise: request().finally(() => {\n exchange.settledAt = Date.now();\n if (!exchange.handoff && this.#exchange === exchange) this.#exchange = null;\n }),\n };\n this.#startedFor = identity;\n this.#exchange = exchange;\n return exchange;\n }\n}\n\n/** Bind an optional login preload to the active navigation and return cleanup for initialization failure. */\nexport function kitPreloadAuthLoginForNavigation(\n router: Pick<Router, 'currentNavigation' | 'events'>,\n preload: (isCurrent: () => boolean) => (() => void) | undefined,\n): () => void {\n const navigation = router.currentNavigation();\n const cancel = navigation ? preload(() => router.currentNavigation() === navigation) : undefined;\n const subscription = cancel\n ? router.events\n .pipe(\n filter(\n (event) =>\n (event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError) &&\n event.id === navigation?.id,\n ),\n take(1),\n )\n .subscribe(() => cancel())\n : undefined;\n return () => {\n subscription?.unsubscribe();\n cancel?.();\n };\n}\n","import type { EnvironmentProviders } from '@angular/core';\nimport { inject, InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport type { HttpEvent, HttpInterceptorFn, HttpRequest } from '@angular/common/http';\nimport { HttpContextToken, HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Network } from '@capacitor/network';\nimport type { Observable } from 'rxjs';\nimport { from, retry, throwError, timer } from 'rxjs';\nimport { catchError, map, mergeMap, tap, timeout } from 'rxjs/operators';\nimport { isExplicitAuthDenial, KitAuthAccessService } from '../auth/auth-access.service';\n\n/**\n * Marks the narrowly scoped credential-exchange request that establishes remote access.\n *\n * @remarks\n * When shared auth access enforcement is enabled, the application starts in `none` (or may be\n * recovering from `local`) and therefore cannot make ordinary authenticated requests. The one\n * server request that verifies the current provider credential must set this context token. It\n * still runs the complete header, retry, denial, and error pipeline; only the pre-existing\n * `remote` access requirement is deferred until that exchange succeeds.\n */\nexport const KIT_AUTH_BOOTSTRAP_REQUEST = new HttpContextToken<boolean>(() => false);\n\n/**\n * Marks an auth-recovery replay so {@link KitHttpConfig.recoverAuthAccess} is not invoked again.\n *\n * @internal\n */\nconst KIT_AUTH_RECOVERY_REPLAY = new HttpContextToken<boolean>(() => false);\n\n/**\n * HTTP methods that are safe to retry automatically.\n *\n * @remarks\n * Non-idempotent methods (`POST` / `PATCH` / `DELETE`) are never auto-retried, because a response\n * lost *after* the server processed the write would be replayed into a duplicate write (\"saved twice\n * from one tap\"). A non-idempotent request that is genuinely safe to replay opts in by carrying an\n * `Idempotency-Key` header (which the server must honor).\n *\n * @internal\n */\nconst RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'];\n\n/**\n * Transient HTTP statuses worth retrying: `0` (network/transport failure), `408` (request timeout),\n * `429` (rate limited), and the `502` / `503` / `504` gateway-availability family. Every other status\n * is thrown immediately — a whitelist is safer than a blacklist for deciding what to replay.\n *\n * @internal\n */\nconst RETRYABLE_STATUSES = [0, 408, 429, 502, 503, 504];\n\n/**\n * Maximum number of automatic retries for a retryable request.\n *\n * @internal\n */\nconst MAX_RETRIES = 2;\n\n/**\n * Fleet-wide per-request timeout. A request with no response within this window fails with a\n * synthetic `408` (a {@link RETRYABLE_STATUSES | retryable status}). Deliberately generous — it\n * catches a genuinely hung request (dead server) without cutting off legitimately slow work such as\n * a large upload or an AI generation. `timeout({ each })` resets on every emission, so a streaming\n * response that keeps emitting is unaffected.\n *\n * @internal\n */\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * True when the error is the fleet maintenance short-circuit (`503` + body `code: 'MAINTENANCE'`).\n *\n * @remarks\n * Matches Angular `HttpErrorResponse` as `error.error?.code === 'MAINTENANCE'` (body top-level\n * `code`). Must not be retried and must not fall through to {@link KitHttpConfig.onServerBusy}.\n *\n * @param error - The failed response.\n * @returns Whether this is a maintenance response.\n */\nexport const isMaintenanceError = (error: HttpErrorResponse): boolean => error.status === 503 && error.error?.code === 'MAINTENANCE';\n\n/**\n * Parse a `Retry-After` header (delta-seconds or an HTTP-date) into milliseconds, or `null` when it\n * is absent or unparseable.\n *\n * @internal\n */\nconst parseRetryAfterMs = (error: HttpErrorResponse): number | null => {\n const header = error.headers?.get('Retry-After');\n if (!header) {\n return null;\n }\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * 1000);\n }\n const dateMs = Date.parse(header);\n return Number.isNaN(dateMs) ? null : Math.max(0, dateMs - Date.now());\n};\n\n/**\n * Configuration that customizes the behavior of {@link kitAuthInterceptor}, injected through {@link provideKitHttp}.\n *\n * @remarks\n * The interceptor fixes the retry policy and control flow; only the hooks below are app-specific:\n *\n * - Retries only {@link RETRYABLE_METHODS | idempotent methods} (or a request bearing an\n * `Idempotency-Key`) on a {@link RETRYABLE_STATUSES | transient status}, up to {@link MAX_RETRIES}\n * times with a short jittered backoff (honoring `Retry-After`). Writes are never auto-retried.\n * - When the device is offline it fails fast to {@link KitHttpConfig.offlineFallback} instead of\n * waiting out the retries.\n * - On a final error it classifies by status and calls the matching hook (see each hook below).\n *\n * Only {@link KitHttpConfig.getAuthHeaders} is required — it has no safe default. Every other hook is\n * optional and defaults to a no-op (or `{}` / `false` / `null` as appropriate), so an app configures\n * only the behavior that actually differs from the canonical baseline.\n */\nexport interface KitHttpConfig {\n /**\n * Enforce the shared auth access mode before generating headers or using transport.\n *\n * @remarks\n * Optional and `false` by default for backward compatibility. In `local` mode the interceptor\n * consults `offlineFallback` without calling `getAuthHeaders` or transport. In `none` mode it\n * rejects without exposing local data. Real HTTP/auth-header 401/403 responses revoke access and\n * bypass `offlineFallback`.\n */\n enforceAuthAccessMode?: boolean;\n /**\n * Produce authentication and metadata headers for the outgoing request.\n *\n * @param request - The outgoing request about to be sent.\n * @returns A map of header names to values, resolved asynchronously.\n */\n getAuthHeaders(request: HttpRequest<unknown>): Promise<Record<string, string>>;\n /**\n * Produce additional headers for the outgoing request.\n *\n * @remarks\n * Optional; defaults to adding no extra headers.\n *\n * @param request - The outgoing request about to be sent.\n * @returns A map of header names to values; return `{}` when none are needed.\n */\n buildExtraHeaders?(request: HttpRequest<unknown>): Record<string, string>;\n /**\n * Treat an otherwise-successful response as an error.\n *\n * @remarks\n * Optional. Some backends use a 2xx status (for example `204` / `206`) to signal a condition the\n * app wants to surface as an error rather than a success. Return `true` to throw the response so it\n * flows through the error path; the status is not in {@link RETRYABLE_STATUSES}, so it is not\n * retried and propagates to the caller. Defaults to treating every 2xx as a success.\n *\n * @param response - The successful `HttpResponse` about to be delivered.\n * @returns `true` to reject the response as an error.\n */\n treatAsError?(response: HttpResponse<unknown>): boolean;\n /**\n * Called for every successful response that completed an actual network round trip.\n *\n * @remarks\n * Responses synthesized by {@link KitHttpConfig.offlineFallback} are produced after `catchError`\n * and therefore never reach this hook, so it observes genuine successes only. A typical use is to\n * reset an \"offline\" flag once connectivity is restored. Optional; defaults to a no-op.\n *\n * @param event - The successful `HttpResponse`.\n */\n onResponse?(event: HttpResponse<unknown>): void;\n /**\n * Decide whether to pass the request straight through, skipping auth, retry, and error handling.\n *\n * @remarks\n * Useful for external URLs such as S3 or a CDN. Optional; defaults to `false` (never bypass).\n *\n * @param request - The outgoing request.\n * @returns `true` to bypass the interceptor pipeline.\n */\n bypass?(request: HttpRequest<unknown>): boolean;\n /**\n * Provide an offline short-circuit when a request fails.\n *\n * @remarks\n * Returning a non-null observable replaces the error with that response (for example a queued\n * offline result). Optional; defaults to `null` (no fallback, normal error handling proceeds).\n * With shared access enforcement enabled, explicit 401/403 denials are never passed here.\n *\n * @param request - The request that failed (after headers were applied).\n * @param error - The error response that triggered the fallback.\n * @returns A replacement event stream, or `null` for no fallback.\n */\n offlineFallback?(request: HttpRequest<unknown>, error: HttpErrorResponse): Observable<HttpEvent<unknown>> | null;\n /**\n * Side effect to run on a `401` response (for example an expired token).\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param request - The request that received the `401`.\n * @param error - The complete response, including any explicit authentication failure scope.\n */\n onUnauthorized?(request: HttpRequest<unknown>, error: HttpErrorResponse): void;\n /**\n * Side effect to run on a `403` response (a permission error).\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param request - The request that received the `403`.\n * @param error - The complete permission-error response.\n */\n onForbidden?(request: HttpRequest<unknown>, error: HttpErrorResponse): void;\n /**\n * UX hook for a genuine network / transport failure (status `0`) while the device reports itself\n * connected — i.e. the server is unreachable rather than the phone being offline.\n *\n * @remarks\n * Optional; defaults to a no-op. Narrow by design: it fires only for status `0` (not for `404`,\n * `429`, `5xx`, …, which have their own hooks), so a \"connection lost, reload?\" prompt is not shown\n * for server-side problems. When the device is offline it is not called at all — `offlineFallback`\n * owns that path. The kit ships {@link KitReloadAlertController} as the canonical implementation\n * (with de-dup so concurrent failures show a single alert, and auto-dismiss on reconnect).\n *\n * @param status - The HTTP status code (`0`), or a string descriptor for non-HTTP failures.\n * @returns Optionally a promise to await before continuing.\n */\n onNetworkError?(status: number | string): Promise<void> | void;\n /**\n * UX hook for a transient server-availability failure (`502` / `503` / `504`), fired after retries\n * are exhausted.\n *\n * @remarks\n * Optional; defaults to a no-op. Distinct from {@link KitHttpConfig.onNetworkError} — the device's\n * connection is fine, the server is momentarily unavailable — so the app can say \"server busy, try\n * again shortly\" rather than prompt a reload. **Not** called for fleet maintenance (`503` with\n * `error.error?.code === 'MAINTENANCE'`) — that uses {@link KitHttpConfig.onMaintenance}.\n *\n * @param status - `502`, `503`, or `504`.\n * @param retryAfterSeconds - The server's `Retry-After` hint in seconds, when provided.\n */\n onServerBusy?(status: number, retryAfterSeconds?: number): void;\n /**\n * UX hook for fleet maintenance: HTTP `503` whose body has `code: 'MAINTENANCE'`.\n *\n * @remarks\n * Optional; defaults to a no-op. Fired **without retries** (maintenance is intentional, not\n * transient). Wire to {@link KitMaintenanceController.present} with the wait SSE URL so the lock\n * overlay auto-dismisses when maintenance ends.\n */\n onMaintenance?(): void;\n /**\n * UX hook for a `429 Too Many Requests` response, fired after retries are exhausted.\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param retryAfterSeconds - The server's `Retry-After` hint in seconds, when provided.\n */\n onRateLimited?(retryAfterSeconds?: number): void;\n /**\n * UX hook for `400` / `422` / `500` responses that carry a server-provided message.\n *\n * @remarks\n * Optional; defaults to a no-op. Note that the message comes straight from the API; prefer a\n * user-facing `userMessage` / `code` in your error contract over showing a raw developer message.\n *\n * @param message - The message extracted from the error body.\n */\n onServerError?(message: string): void;\n /**\n * Side effect for a failure while *producing* the auth headers (`getAuthHeaders` rejected).\n *\n * @remarks\n * Optional; defaults to a no-op. Because the request is never sent in this case, it does not reach\n * the response-error hooks; classify it here (for example a failed token refresh) so it does not\n * fail silently.\n *\n * @param request - The request whose headers could not be produced.\n * @param error - The error thrown by `getAuthHeaders`.\n */\n onAuthError?(request: HttpRequest<unknown>, error: unknown): void;\n /**\n * Called when {@link KitHttpConfig.isAuthAccessDenial} classifies a failure as\n * global identity loss and shared remote access is revoked.\n *\n * @remarks\n * This hook is status-independent so an explicitly tagged historical 403\n * identity response reaches the same cleanup as a new 401 identity response.\n * Status hooks still run afterward for response-specific UX. Optional and\n * backward compatible.\n */\n onAuthAccessDenial?(request: HttpRequest<unknown>, error: unknown): void;\n /**\n * Classify whether an auth-related failure should revoke shared remote access.\n *\n * @remarks\n * Consulted only when {@link KitHttpConfig.enforceAuthAccessMode} is enabled and the failure is\n * an explicit authentication denial ({@link isExplicitAuthDenial | HTTP 401/403} or the same\n * status shape from {@link KitHttpConfig.getAuthHeaders}). Return `true` to call\n * {@link KitAuthAccessService.clear}; return `false` to keep the current access mode (for example\n * when a `403` is a resource permission error rather than a lost session). When omitted, both\n * `401` and `403` revoke access — the historical default.\n *\n * Regardless of the return value, explicit `401`/`403` responses never reach\n * {@link KitHttpConfig.offlineFallback}; the matching response hook\n * ({@link KitHttpConfig.onUnauthorized} / {@link KitHttpConfig.onForbidden}) still runs and the\n * error is rethrown. A rejection from `getAuthHeaders` has no response, so it calls only\n * {@link KitHttpConfig.onAuthError}.\n *\n * @param request - The outgoing request that failed (or whose headers could not be produced).\n * @param error - The `HttpErrorResponse` or header-production rejection.\n * @returns `true` when shared remote access should be cleared.\n */\n isAuthAccessDenial?(request: HttpRequest<unknown>, error: unknown): boolean;\n /**\n * Attempt to recover credentials after an explicit HTTP `401` / `403` before denial hooks run.\n *\n * @remarks\n * Invoked at most once per original request — only on the first explicit auth denial from the\n * server, and never on a recovery replay (which carries {@link KIT_AUTH_RECOVERY_REPLAY}). When\n * this hook resolves `true`, {@link KitHttpConfig.getAuthHeaders} is called again and the\n * original request is sent exactly once more with fresh auth and extra headers. A second denial\n * follows the normal revocation / status-hook path with no further recovery.\n *\n * Unlike transient transport retries, this replay is allowed for writes (`POST` / `PATCH` /\n * `DELETE`) because the server returned an explicit auth denial — the request was rejected\n * before (or without) being processed, not lost after a successful write. Apps must still ensure\n * {@link KitHttpConfig.recoverAuthAccess} only returns `true` when credentials were refreshed\n * and a single replay is safe for the endpoint.\n *\n * When the hook is absent, resolves `false`, or throws, the original {@link HttpErrorResponse}\n * is preserved and the existing denial / fallback pipeline runs unchanged; hook failures do not\n * replace the server error.\n *\n * @param request - The outgoing request that received the denial (before header merge).\n * @param error - The explicit `401` / `403` response.\n * @returns `true` to replay once with regenerated headers; `false` to proceed with normal denial handling.\n */\n recoverAuthAccess?(request: HttpRequest<unknown>, error: HttpErrorResponse): Promise<boolean>;\n}\n\n/**\n * Injection token that carries the {@link KitHttpConfig} to {@link kitAuthInterceptor}.\n */\nexport const KIT_HTTP_CONFIG = new InjectionToken<KitHttpConfig>('@rdlabo/ionic-angular-kit:http');\n\n/**\n * Wire the {@link kitAuthInterceptor} configuration into the application's dependency injection.\n *\n * @remarks\n * Register the interceptor itself separately via `provideHttpClient(withInterceptors([kitAuthInterceptor]))`.\n * The factory runs inside an injection context, so it may call `inject()`.\n *\n * @param configFactory - Factory that returns the {@link KitHttpConfig} for the application.\n * @returns Environment providers to add to the application bootstrap.\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideHttpClient(withInterceptors([kitAuthInterceptor])),\n * provideKitHttp(() => {\n * const auth = inject(AuthService);\n * const reload = inject(KitReloadAlertController);\n * return {\n * // Only getAuthHeaders is required; every other hook is optional and defaults to a no-op.\n * getAuthHeaders: async () => ({ Authorization: `Bearer ${await auth.token()}` }),\n * onUnauthorized: () => auth.signOut(),\n * onNetworkError: (status) =>\n * reload.present({ header: 'Network error', message: `Reload? (${status})`, okText: 'Reload' }),\n * onResponse: () => void reload.dismiss(),\n * };\n * }),\n * ],\n * });\n * ```\n */\nexport const provideKitHttp = (configFactory: () => KitHttpConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_HTTP_CONFIG, useFactory: configFactory }]);\n\n/**\n * True when shared remote access should be revoked for an auth-related failure.\n *\n * @remarks\n * Only meaningful when {@link KitHttpConfig.enforceAuthAccessMode} is enabled and\n * {@link isExplicitAuthDenial} already matched. When {@link KitHttpConfig.isAuthAccessDenial} is\n * omitted, every explicit denial revokes access (legacy default).\n *\n * @internal\n */\nconst shouldRevokeAuthAccess = (config: KitHttpConfig, req: HttpRequest<unknown>, error: unknown): boolean =>\n config.isAuthAccessDenial?.(req, error) ?? isExplicitAuthDenial(error);\n\n/**\n * Invoke {@link KitHttpConfig.recoverAuthAccess} without letting hook failures replace the server error.\n *\n * @internal\n */\nconst tryRecoverAuthAccess = async (\n config: KitHttpConfig,\n request: HttpRequest<unknown>,\n error: HttpErrorResponse,\n): Promise<boolean> => {\n if (!config.recoverAuthAccess) {\n return false;\n }\n const recover = async (): Promise<boolean | void> => config.recoverAuthAccess?.(request, error);\n return recover()\n .then((recovered) => recovered === true)\n .catch(() => false);\n};\n\n/**\n * Final error handling after retries and optional auth recovery have been exhausted.\n *\n * @internal\n */\nconst handleTransportError = (\n config: KitHttpConfig,\n access: KitAuthAccessService,\n req: HttpRequest<unknown>,\n error: HttpErrorResponse,\n isAuthBootstrap: boolean,\n): Observable<HttpEvent<unknown>> => {\n if (config.enforceAuthAccessMode && isExplicitAuthDenial(error)) {\n if (shouldRevokeAuthAccess(config, req, error)) {\n access.clear();\n config.onAuthAccessDenial?.(req, error);\n }\n dispatchError(config, req, error);\n return throwError(() => error);\n }\n if (!isAuthBootstrap) {\n const fallback = config.offlineFallback?.(req, error);\n if (fallback) {\n return fallback;\n }\n }\n dispatchError(config, req, error);\n return throwError(() => error);\n};\n\n/**\n * Classify a final (post-retry) error and invoke the matching {@link KitHttpConfig} hook.\n *\n * @internal\n */\nconst dispatchError = (config: KitHttpConfig, req: HttpRequest<unknown>, error: HttpErrorResponse): void => {\n const status = error.status;\n const retryAfterMs = parseRetryAfterMs(error);\n const retryAfterSeconds = retryAfterMs === null ? undefined : Math.round(retryAfterMs / 1000);\n\n if (status === 401) {\n config.onUnauthorized?.(req, error);\n } else if (status === 403) {\n config.onForbidden?.(req, error);\n } else if (status === 0) {\n // Genuine network/transport failure. Only surface it when the device is actually connected\n // (server unreachable); when offline, offlineFallback owns the UX — a reload prompt won't help.\n void Network.getStatus().then((network) => {\n if (network.connected) {\n config.onNetworkError?.(status);\n }\n });\n } else if (status === 429) {\n config.onRateLimited?.(retryAfterSeconds);\n } else if (isMaintenanceError(error)) {\n config.onMaintenance?.();\n } else if ([502, 503, 504].includes(status)) {\n config.onServerBusy?.(status, retryAfterSeconds);\n } else if ([400, 422, 500].includes(status) && error.error?.message) {\n config.onServerError?.(error.error.message);\n }\n // Every other status (404, 418, …) is left to the caller — no generic alert.\n};\n\n/**\n * Canonical functional HTTP interceptor that applies authentication, retries, and error handling.\n *\n * @remarks\n * Behavior, driven by the injected {@link KitHttpConfig}:\n *\n * 1. Requests for which `bypass` returns `true` are forwarded untouched.\n * 2. If `getAuthHeaders` rejects, `onAuthError` is called and the request is not sent.\n * 3. Otherwise the headers from `getAuthHeaders` and `buildExtraHeaders` are merged onto a cloned request.\n * 4. On failure the request is retried up to {@link MAX_RETRIES} times, but **only** when the device\n * is online, the method is a {@link RETRYABLE_METHODS | retryable method} (or carries an\n * `Idempotency-Key`), and the status is a {@link RETRYABLE_STATUSES | transient status}. The\n * backoff is `retryCount * 500ms` plus up to 250ms of jitter, or the server's `Retry-After`.\n * When the device is offline it stops retrying immediately.\n * 5. On the first explicit HTTP `401`/`403`, {@link KitHttpConfig.recoverAuthAccess} may replay the\n * request once with regenerated headers before denial hooks run; recovery replays never recurse.\n * 6. On the final error, enforced 401/403 revokes shared access and is rejected before fallback.\n * For every other error, `offlineFallback` is consulted first; otherwise the error is classified by\n * status (see {@link dispatchError}): `401`→`onUnauthorized`, `403`→`onForbidden`, `0`→\n * `onNetworkError` (when connected), `429`→`onRateLimited`, maintenance `503`→`onMaintenance`,\n * other `502`/`503`/`504`→`onServerBusy`, and `400`/`422`/`500` with a body message→`onServerError`.\n *\n * @param request - The outgoing request.\n * @param next - The next handler in the interceptor chain.\n * @returns A stream of HTTP events for the (possibly modified, retried, or replaced) request.\n *\n * @example\n * ```ts\n * provideHttpClient(withInterceptors([kitAuthInterceptor]));\n * ```\n */\nexport const kitAuthInterceptor: HttpInterceptorFn = (request, next) => {\n const config = inject(KIT_HTTP_CONFIG);\n const access = inject(KitAuthAccessService);\n const isAuthBootstrap = request.context.get(KIT_AUTH_BOOTSTRAP_REQUEST);\n\n if (config.bypass?.(request)) {\n return next(request);\n }\n\n if (config.enforceAuthAccessMode && access.mode !== 'remote' && !isAuthBootstrap) {\n const error = new HttpErrorResponse({\n // `local` deliberately looks like a transport failure so an outer offline read interceptor\n // may resolve it. `none` must not use status 0, otherwise that interceptor could expose a\n // persisted replica before authentication.\n status: access.mode === 'local' ? 0 : 401,\n statusText: access.mode === 'local' ? 'Local access only' : 'Authentication required',\n url: request.url,\n });\n if (access.mode === 'local') {\n const fallback = config.offlineFallback?.(request, error);\n if (fallback) return fallback;\n }\n return throwError(() => error);\n }\n\n const sendAuthenticated = (outgoing: HttpRequest<unknown>, allowAuthRecovery: boolean): Observable<HttpEvent<unknown>> =>\n from(config.getAuthHeaders(outgoing)).pipe(\n catchError((headerError: unknown) => {\n // getAuthHeaders failed → the request is never sent; classify it instead of failing silently.\n if (config.enforceAuthAccessMode && isExplicitAuthDenial(headerError) && shouldRevokeAuthAccess(config, outgoing, headerError)) {\n access.clear();\n config.onAuthAccessDenial?.(outgoing, headerError);\n }\n config.onAuthError?.(outgoing, headerError);\n return throwError(() => headerError);\n }),\n mergeMap((authHeaders) => {\n const req = outgoing.clone({ setHeaders: { ...authHeaders, ...config.buildExtraHeaders?.(outgoing) } });\n const retryable = RETRYABLE_METHODS.includes(req.method) || req.headers.has('Idempotency-Key');\n\n const base = next(req).pipe(\n timeout({\n each: DEFAULT_TIMEOUT_MS,\n with: () => throwError(() => new HttpErrorResponse({ status: 408, statusText: 'Request Timeout', url: req.url })),\n }),\n );\n\n return base.pipe(\n map((event) => {\n // A backend may signal an error condition with a 2xx status (e.g. 204/206); surface it as an error.\n if (event instanceof HttpResponse && config.treatAsError?.(event)) {\n throw event;\n }\n return event;\n }),\n retry({\n count: MAX_RETRIES,\n delay: (error: HttpErrorResponse, retryCount: number) =>\n from(Network.getStatus()).pipe(\n mergeMap((network) => {\n // Offline → don't wait out the retries; fail fast so offlineFallback can take over.\n if (!network.connected) {\n return throwError(() => error);\n }\n // Only replay idempotent requests, and only on a transient status.\n // Maintenance 503 is intentional — never retry; go straight to onMaintenance.\n if (!retryable || !RETRYABLE_STATUSES.includes(error.status) || isMaintenanceError(error)) {\n return throwError(() => error);\n }\n // Short linear backoff (500ms, 1000ms, …) plus jitter to de-correlate a fleet of\n // clients reconnecting at once; the server's Retry-After wins when present.\n const backoff = parseRetryAfterMs(error) ?? retryCount * 500 + Math.random() * 250;\n return timer(backoff);\n }),\n ),\n }),\n tap((event) => {\n if (event instanceof HttpResponse) {\n config.onResponse?.(event);\n }\n }),\n catchError((error: HttpErrorResponse) => {\n const mayRecover =\n allowAuthRecovery &&\n isExplicitAuthDenial(error) &&\n !outgoing.context.get(KIT_AUTH_RECOVERY_REPLAY) &&\n config.recoverAuthAccess;\n\n if (mayRecover) {\n return from(tryRecoverAuthAccess(config, outgoing, error)).pipe(\n mergeMap((recovered) => {\n if (recovered) {\n const replay = outgoing.clone({\n context: outgoing.context.set(KIT_AUTH_RECOVERY_REPLAY, true),\n });\n return sendAuthenticated(replay, false);\n }\n return handleTransportError(config, access, req, error, isAuthBootstrap);\n }),\n );\n }\n return handleTransportError(config, access, req, error, isAuthBootstrap);\n }),\n );\n }),\n );\n\n return sendAuthenticated(request, true);\n};\n","/**\n * Shared lifecycle boundary carried by an authentication failure response.\n *\n * Only `identity` invalidates the application's global authenticated identity.\n * The other scopes retain it and let the owning feature handle recovery.\n */\nexport const AUTH_FAILURE_SCOPES = {\n identity: 'identity',\n reauthentication: 'reauthentication',\n credential: 'credential',\n} as const;\n\nexport type AuthFailureScope = (typeof AUTH_FAILURE_SCOPES)[keyof typeof AUTH_FAILURE_SCOPES];\n\nexport const AUTH_IDENTITY_INVALID_CODE = 'AUTH_IDENTITY_INVALID';\n\nexport interface AuthFailureBody {\n statusCode: 401 | 403;\n message: string;\n code: string;\n authFailureScope: AuthFailureScope;\n}\n\ntype UnknownRecord = Record<string, unknown>;\n\nconst isRecord = (value: unknown): value is UnknownRecord => typeof value === 'object' && value !== null;\n\nconst isAuthFailureScope = (value: unknown): value is AuthFailureScope =>\n Object.values(AUTH_FAILURE_SCOPES).some((scope) => scope === value);\n\n/**\n * Reads the explicit auth-failure scope from an Angular `HttpErrorResponse` or\n * from a body-like value. Tagged historical 403 identity responses are\n * supported for installed-client compatibility. Untagged 401/403 responses\n * intentionally return `null`.\n */\nexport const getAuthFailureScope = (error: unknown): AuthFailureScope | null => {\n if (!isRecord(error)) return null;\n\n const body = isRecord(error['error']) ? error['error'] : error;\n const status = typeof error['status'] === 'number' ? error['status'] : body['statusCode'];\n if (status !== 401 && status !== 403) return null;\n if (body['statusCode'] !== status || typeof body['code'] !== 'string') return null;\n\n const scope = body['authFailureScope'];\n if (!isAuthFailureScope(scope)) return null;\n if (status === 403 && scope !== AUTH_FAILURE_SCOPES.identity) return null;\n if (scope === AUTH_FAILURE_SCOPES.identity && body['code'] !== AUTH_IDENTITY_INVALID_CODE) return null;\n return scope;\n};\n\n/** True only for an explicitly tagged global identity failure. */\nexport const isIdentityAuthFailure = (error: unknown): boolean => getAuthFailureScope(error) === AUTH_FAILURE_SCOPES.identity;\n","import { App } from '@capacitor/app';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Network } from '@capacitor/network';\nimport { Injectable, Optional } from '@angular/core';\nimport type { Observable } from 'rxjs';\nimport { Subject, Subscription } from 'rxjs';\nimport { KitAuthAccessService } from '../auth/auth-access.service';\n\n/** One WebSocket endpoint and its ordered subprotocol list. URLs must be unique within a target set. */\nexport interface KitRealtimeSocketTarget {\n url: string;\n protocols: string[];\n}\n\n/** Realtime event shape required for self-echo identification. */\nexport interface KitRealtimeEvent {\n originId?: string;\n}\n\n/** An application event annotated with whether it originated from this client. */\nexport type KitClientRealtimeEvent<TEvent extends KitRealtimeEvent> = TEvent & { isSelf: boolean };\n\n/** Timing and protocol options for {@link KitRealtimeConnection}. */\nexport interface KitRealtimeConnectionOptions {\n clientId?: string;\n ping?: string;\n pong?: string;\n maxBackoffMs?: number;\n openTimeoutMs?: number;\n pingIntervalMs?: number;\n livenessTimeoutMs?: number;\n /** Require shared `remote` auth access before opening or retaining sockets. */\n requireRemoteAccess?: boolean;\n}\n\ninterface SocketHealth {\n key: string;\n lastActivityAt: number;\n openTimer: ReturnType<typeof setTimeout> | null;\n watchdog: KitRealtimeLivenessWatchdog;\n}\n\n/** Stable per-tab/application-run ID shared by realtime connections and write headers. */\nexport const KIT_REALTIME_CLIENT_ID = crypto.randomUUID();\n\n/** Convert an HTTP(S) endpoint to its WebSocket equivalent. */\nexport function toKitWebSocketUrl(url: string): string {\n const parsed = new URL(url);\n if (parsed.protocol === 'https:') {\n parsed.protocol = 'wss:';\n } else if (parsed.protocol === 'http:') {\n parsed.protocol = 'ws:';\n }\n return parsed.toString();\n}\n\n/** Build the standard application/auth/client WebSocket subprotocol list. */\nexport function kitRealtimeProtocols(\n protocol: string,\n options: { clientId?: string; authToken?: string; authPrefix?: string; clientPrefix?: string } = {},\n): string[] {\n const protocols = [protocol];\n if (options.authToken) {\n protocols.push(`${options.authPrefix ?? 'auth.'}${options.authToken}`);\n }\n protocols.push(`${options.clientPrefix ?? 'client.'}${options.clientId ?? KIT_REALTIME_CLIENT_ID}`);\n return protocols;\n}\n\n/** Detect a half-open WebSocket when no pong or event arrives before the timeout. */\nexport class KitRealtimeLivenessWatchdog {\n #timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n private readonly timeoutMs: number,\n private readonly onTimeout: () => void,\n ) {}\n\n /** Restart the liveness deadline after receiving server activity. */\n reset(): void {\n this.clear();\n this.#timer = setTimeout(() => {\n this.#timer = null;\n this.onTimeout();\n }, this.timeoutMs);\n }\n\n /** Cancel the current liveness deadline. */\n clear(): void {\n if (!this.#timer) {\n return;\n }\n clearTimeout(this.#timer);\n this.#timer = null;\n }\n}\n\n/**\n * Reconnecting Hibernation WebSocket client for Ionic/Capacitor applications.\n *\n * Subclasses provide connection intent and one or more targets. The base owns foreground/network\n * suspension, exponential backoff, open/liveness timeouts, runtime-friendly application pings,\n * target-scoped reconnect, and a resync signal after connectivity is restored.\n */\n@Injectable()\nexport abstract class KitRealtimeConnection<TEvent extends KitRealtimeEvent> {\n readonly #events$ = new Subject<KitClientRealtimeEvent<TEvent>>();\n readonly #reconnected$ = new Subject<void>();\n\n /** Client ID used to classify self echoes. */\n protected readonly listeners: PluginListenerHandle[] = [];\n\n #sockets = new Map<string, WebSocket>();\n readonly #health = new Map<WebSocket, SocketHealth>();\n #targets = new Map<string, KitRealtimeSocketTarget>();\n #opening = false;\n #generation = 0;\n #reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n #reconnectPendingGeneration: number | null = null;\n #pingTimer: ReturnType<typeof setInterval> | null = null;\n #reconnectAttempt = 0;\n #isAppActive = true;\n #isNetworkConnected = true;\n #lifecycleRegistration: Promise<void> | null = null;\n #lifecycleGeneration = 0;\n #accessSubscription: Subscription | null = null;\n\n // Constructor injection keeps direct `new` compatibility for existing subclasses and tests.\n // eslint-disable-next-line @angular-eslint/prefer-inject\n constructor(@Optional() private readonly authAccess: KitAuthAccessService | null = null) {}\n\n /** All parsed events received by this connection. */\n readonly events$: Observable<KitClientRealtimeEvent<TEvent>> = this.#events$.asObservable();\n /** Emits after every fully established connection cycle, including the first, prompting a REST resync. */\n readonly reconnected$: Observable<void> = this.#reconnected$.asObservable();\n\n /** Override timing/protocol defaults in specialized clients or tests. */\n protected get realtimeOptions(): KitRealtimeConnectionOptions {\n return {};\n }\n\n get #options(): Required<KitRealtimeConnectionOptions> {\n const options = this.realtimeOptions;\n return {\n clientId: options.clientId ?? KIT_REALTIME_CLIENT_ID,\n ping: options.ping ?? 'ping',\n pong: options.pong ?? 'pong',\n maxBackoffMs: options.maxBackoffMs ?? 30_000,\n openTimeoutMs: options.openTimeoutMs ?? 15_000,\n pingIntervalMs: options.pingIntervalMs ?? 30_000,\n livenessTimeoutMs: options.livenessTimeoutMs ?? 70_000,\n requireRemoteAccess: options.requireRemoteAccess ?? false,\n };\n }\n\n /** Client ID used to classify self echoes. */\n get id(): string {\n return this.#options.clientId;\n }\n\n /** Whether every configured socket is currently open. */\n get isStreamOpen(): boolean {\n return (\n this.#targets.size > 0 &&\n this.#sockets.size === this.#targets.size &&\n [...this.#sockets.values()].every((socket) => socket.readyState === WebSocket.OPEN)\n );\n }\n\n /** Whether every configured socket has produced recent server activity. */\n get isStreamHealthy(): boolean {\n return (\n this.isStreamOpen &&\n [...this.#health.values()].every(({ lastActivityAt }) => Date.now() - lastActivityAt < this.#options.livenessTimeoutMs)\n );\n }\n\n protected abstract get shouldConnect(): boolean;\n protected abstract buildSocketTargets(): Promise<KitRealtimeSocketTarget[]>;\n\n get #canOpen(): boolean {\n const hasRemoteAccess = !this.#options.requireRemoteAccess || (this.authAccess !== null && this.authAccess.mode === 'remote');\n return this.shouldConnect && this.#isAppActive && this.#isNetworkConnected && hasRemoteAccess;\n }\n\n /** Hook used by authenticated clients to invalidate a token after handshake failure. */\n protected async handleConnectionFailure(): Promise<void> {\n return;\n }\n\n /** Parse a text WebSocket message into one or more domain events. */\n protected parseMessage(data: string): TEvent[] {\n const parsed = JSON.parse(data) as TEvent | TEvent[];\n return Array.isArray(parsed) ? parsed : [parsed];\n }\n\n /** Factory seam for platform-specific WebSocket implementations and unit tests. */\n protected createWebSocket(url: string, protocols: string[]): WebSocket {\n return new WebSocket(url, protocols);\n }\n\n /** Factory seam for Capacitor app-state listeners. */\n protected addAppStateListener(listener: (state: { isActive: boolean }) => void): Promise<PluginListenerHandle> {\n return App.addListener('appStateChange', listener);\n }\n\n /** Factory seam for Capacitor network-status listeners. */\n protected addNetworkStatusListener(listener: (status: { connected: boolean }) => void): Promise<PluginListenerHandle> {\n return Network.addListener('networkStatusChange', listener);\n }\n\n /** Register foreground/network listeners exactly once, cleaning up handles that resolve after disconnect. */\n protected async registerLifecycleListeners(): Promise<void> {\n if (this.listeners.length > 0) {\n return;\n }\n if (this.#lifecycleRegistration) {\n return this.#lifecycleRegistration;\n }\n const generation = this.#lifecycleGeneration;\n this.#lifecycleRegistration = (async () => {\n const appHandle = await this.addAppStateListener(({ isActive }) => {\n this.#isAppActive = isActive;\n if (this.#canOpen) {\n void this.open();\n } else {\n this.suspend();\n }\n });\n if (generation !== this.#lifecycleGeneration) {\n await appHandle.remove();\n return;\n }\n this.listeners.push(appHandle);\n\n const networkHandle = await this.addNetworkStatusListener(({ connected }) => {\n this.#isNetworkConnected = connected;\n if (this.#canOpen) {\n void this.open();\n } else {\n this.suspend();\n }\n });\n if (generation !== this.#lifecycleGeneration) {\n await networkHandle.remove();\n return;\n }\n this.listeners.push(networkHandle);\n })();\n await this.#lifecycleRegistration.finally(() => {\n this.#lifecycleRegistration = null;\n });\n }\n\n /** Remove all lifecycle listeners, including listeners whose async registration has not completed yet. */\n protected removeLifecycleListeners(): void {\n this.#lifecycleGeneration += 1;\n this.listeners.forEach((handle) => void handle.remove());\n this.listeners.length = 0;\n }\n\n /** Suspend sockets without changing the subclass connection intent. */\n protected suspend(): void {\n this.#clearReconnectTimer();\n this.#closeSockets();\n }\n\n /** Reset resync and backoff history when the owning session ends. */\n protected resetConnectionState(): void {\n this.#reconnectAttempt = 0;\n }\n\n /** Register lifecycle listeners and establish the currently requested targets. */\n protected async startConnection(): Promise<void> {\n this.#registerAccessListener();\n await this.registerLifecycleListeners();\n if (!this.shouldConnect) {\n this.removeLifecycleListeners();\n return;\n }\n await this.open();\n }\n\n /** End the current connection session and release all lifecycle resources. */\n protected stopConnection(): void {\n this.resetConnectionState();\n this.suspend();\n this.removeLifecycleListeners();\n this.#accessSubscription?.unsubscribe();\n this.#accessSubscription = null;\n }\n\n /** Rebuild targets while preserving the owning session's connection intent and listeners. */\n protected async refreshConnectionTargets(): Promise<void> {\n if (!this.shouldConnect) {\n return;\n }\n this.suspend();\n await this.open();\n }\n\n /** Open missing targets, preserving healthy sockets when another target fails. */\n protected async open(): Promise<void> {\n const hasMissingTarget = this.#targets.size === 0 || [...this.#targets.keys()].some((key) => !this.#sockets.has(key));\n if (!this.#canOpen || this.#opening || (this.#sockets.size > 0 && !hasMissingTarget)) {\n return;\n }\n this.#clearReconnectTimer();\n this.#opening = true;\n const generation = this.#generation;\n await this.#openGeneration(generation)\n .catch(() => this.#requestReconnect())\n .finally(() => {\n if (generation === this.#generation) this.#opening = false;\n });\n }\n\n /** Build and attach the sockets for one lifecycle generation. */\n async #openGeneration(generation: number): Promise<void> {\n const targets = await this.buildSocketTargets();\n if (!this.#canOpen || generation !== this.#generation) {\n return;\n }\n const nextTargets = new Map(targets.map((target) => [toKitWebSocketUrl(target.url), target]));\n for (const [key, socket] of this.#sockets) {\n if (nextTargets.has(key)) {\n continue;\n }\n const health = this.#health.get(socket);\n if (health) {\n this.#removeSocket(socket, health);\n }\n }\n this.#targets = nextTargets;\n if (this.#sockets.size === 0) {\n this.#clearPingTimer();\n }\n for (const target of targets) {\n const key = toKitWebSocketUrl(target.url);\n if (this.#sockets.has(key)) {\n continue;\n }\n const socket = this.createWebSocket(key, target.protocols);\n const health: SocketHealth = {\n key,\n lastActivityAt: 0,\n openTimer: null,\n watchdog: new KitRealtimeLivenessWatchdog(this.#options.livenessTimeoutMs, () => this.#connectionFailed(generation, socket)),\n };\n this.#sockets.set(key, socket);\n this.#health.set(socket, health);\n health.openTimer = setTimeout(() => this.#connectionFailed(generation, socket), this.#options.openTimeoutMs);\n\n socket.onopen = () => {\n if (generation !== this.#generation || this.#sockets.get(key) !== socket) {\n return;\n }\n this.#clearOpenTimer(health);\n this.#markActivity(health);\n this.#startPing();\n if (this.isStreamOpen) {\n this.#reconnectAttempt = 0;\n this.#reconnected$.next();\n }\n };\n socket.onmessage = ({ data }) => {\n if (generation !== this.#generation || this.#sockets.get(key) !== socket || typeof data !== 'string') {\n return;\n }\n this.#markActivity(health);\n if (data === this.#options.pong) {\n return;\n }\n let events: TEvent[];\n try {\n events = this.parseMessage(data);\n } catch {\n // Ignore malformed application messages while retaining the healthy socket.\n return;\n }\n for (const event of events) {\n this.#events$.next({ ...event, isSelf: event.originId === this.id });\n }\n };\n socket.onerror = () => this.#connectionFailed(generation, socket);\n socket.onclose = () => this.#connectionFailed(generation, socket);\n }\n }\n\n #registerAccessListener(): void {\n if (!this.#options.requireRemoteAccess || !this.authAccess || this.#accessSubscription) return;\n this.#accessSubscription = this.authAccess.mode$.subscribe((mode) => {\n if (mode === 'remote' && this.#canOpen) {\n void this.open();\n } else {\n this.suspend();\n }\n });\n }\n\n #connectionFailed(generation: number, socket: WebSocket): void {\n const health = this.#health.get(socket);\n if (generation !== this.#generation || !health || this.#sockets.get(health.key) !== socket) {\n return;\n }\n this.#removeSocket(socket, health);\n if (this.#sockets.size === 0) {\n this.#clearPingTimer();\n }\n this.#requestReconnect();\n }\n\n #requestReconnect(): void {\n const generation = this.#generation;\n if (!this.#canOpen || this.#reconnectPendingGeneration === generation || this.#reconnectTimer) {\n return;\n }\n this.#reconnectPendingGeneration = generation;\n void this.handleConnectionFailure()\n .catch((error: unknown) => console.error('[kitRealtime] connection failure hook failed', error))\n .finally(() => {\n if (this.#reconnectPendingGeneration === generation) {\n this.#reconnectPendingGeneration = null;\n }\n if (generation === this.#generation) {\n this.#scheduleReconnect();\n }\n });\n }\n\n #markActivity(health: SocketHealth): void {\n health.lastActivityAt = Date.now();\n health.watchdog.reset();\n }\n\n #startPing(): void {\n if (this.#pingTimer) {\n return;\n }\n this.#pingTimer = setInterval(() => {\n for (const socket of this.#sockets.values()) {\n if (socket.readyState === WebSocket.OPEN) {\n socket.send(this.#options.ping);\n }\n }\n }, this.#options.pingIntervalMs);\n }\n\n #closeSockets(): void {\n this.#generation += 1;\n this.#opening = false;\n this.#clearPingTimer();\n const sockets = this.#sockets;\n this.#sockets = new Map();\n this.#targets = new Map();\n for (const socket of sockets.values()) {\n const health = this.#health.get(socket);\n if (health) {\n this.#removeSocket(socket, health, false);\n }\n }\n }\n\n #removeSocket(socket: WebSocket, health: SocketHealth, removeFromCurrent = true): void {\n health.watchdog.clear();\n this.#clearOpenTimer(health);\n this.#health.delete(socket);\n if (removeFromCurrent && this.#sockets.get(health.key) === socket) {\n this.#sockets.delete(health.key);\n }\n socket.onopen = null;\n socket.onmessage = null;\n socket.onerror = null;\n socket.onclose = null;\n try {\n socket.close(1000, 'client suspended');\n } catch {\n // Reconnect processing continues even if a CONNECTING socket cannot close cleanly.\n }\n }\n\n #scheduleReconnect(): void {\n if (!this.#canOpen || this.#reconnectTimer) {\n return;\n }\n const delay = Math.min(1000 * 2 ** this.#reconnectAttempt, this.#options.maxBackoffMs);\n this.#reconnectAttempt += 1;\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = null;\n void this.open();\n }, delay);\n }\n\n #clearOpenTimer(health: SocketHealth): void {\n if (!health.openTimer) {\n return;\n }\n clearTimeout(health.openTimer);\n health.openTimer = null;\n }\n\n #clearPingTimer(): void {\n if (!this.#pingTimer) {\n return;\n }\n clearInterval(this.#pingTimer);\n this.#pingTimer = null;\n }\n\n #clearReconnectTimer(): void {\n if (!this.#reconnectTimer) {\n return;\n }\n clearTimeout(this.#reconnectTimer);\n this.#reconnectTimer = null;\n }\n}\n","/**\n * Merge a newly fetched page of items into an existing list by id, keeping the result sorted.\n *\n * Items are merged by the numeric `key` field. On a duplicate `key` the item from `arrayNew` wins\n * and replaces the one in `arrayOld`. Old items whose `key` falls *inside* the window spanned by\n * `arrayNew` (between its first and last `key`) are dropped, since the freshly fetched page is the\n * authoritative copy of that window; old items *outside* the window are kept. The merged items are\n * finally sorted by `key`, ascending or descending according to `order`.\n *\n * The algorithm is:\n * 1. If both inputs are empty, return an empty array.\n * 2. Read the first (`lead`) and last (`last`) `key` values of `arrayNew` as the bounds of the\n * page's window. Keep the old items whose `key` lies *outside* that window (at or beyond the\n * extremes) and drop those strictly inside it, handling both a high-to-low page (`lead > last`)\n * and a low-to-high page (`lead < last`). A single-value page (`lead === last`) keeps all old items.\n * 3. Remove old items whose `key` already exists in `arrayNew` (new wins on duplicates).\n * 4. Concatenate `arrayNew` with the surviving old items and sort by `key` in the requested\n * direction.\n *\n * @remarks\n * Designed for infinite-scroll / paginated list merging, where each fetched page may overlap the\n * previously held items and the server returns a contiguous, ordered window of records. The `key`\n * field is treated as a number for range comparison and sorting.\n *\n * @typeParam T - Element type of both arrays. Its `key` property must be a numeric value.\n * @param arrayOld - The previously accumulated list. May be empty or nullish-safe (empty when falsy).\n * @param arrayNew - The newly fetched page of items; its `key` range defines the window that its own\n * items replace, and its items take precedence on duplicates.\n * @param key - The property of `T` used as the unique, numeric id for matching, range filtering, and sorting.\n * @param order - Sort direction by `key`: `'ASC'` for ascending or `'DESC'` for descending. Defaults to `'DESC'`.\n * @param secondaryKey - Optional second property for extra de-duplication. When provided, any\n * surviving old item whose `secondaryKey` value matches that of *any* new item is dropped before\n * the `key` merge. Useful when a record keeps a stable `key` but its secondary identity changes\n * between pages (e.g. items keyed by `id` but also grouped by `parentId`). Omit to skip this step.\n * @returns A new array containing `arrayNew` merged with the out-of-window, non-duplicate old items, sorted by `key`.\n * @example\n * ```ts\n * interface Post {\n * id: number;\n * title: string;\n * }\n *\n * const loaded: Post[] = [\n * { id: 30, title: 'c' },\n * { id: 20, title: 'b' },\n * { id: 10, title: 'a' },\n * ];\n * const nextPage: Post[] = [\n * { id: 20, title: 'b (updated)' },\n * { id: 15, title: 'a.5' },\n * ];\n *\n * // Descending merge: id 30 lies above the new page's [15, 20] window so it is kept; id 20 is\n * // inside the window and is replaced by the new value; id 10 lies below the window and is kept.\n * const merged = arrayConcatById(loaded, nextPage, 'id', 'DESC');\n * // => [{ id: 30, title: 'c' }, { id: 20, title: 'b (updated)' }, { id: 15, title: 'a.5' }, { id: 10, title: 'a' }]\n * ```\n */\nexport const arrayConcatById = <T>(\n arrayOld: T[],\n arrayNew: T[],\n key: keyof T,\n order: 'ASC' | 'DESC' = 'DESC',\n secondaryKey?: keyof T,\n): T[] => {\n if (!arrayNew.length && !arrayOld.length) {\n return [];\n }\n const lead = arrayNew[0][key] as number;\n const last = arrayNew[arrayNew.length - 1][key] as number;\n\n const filteredOld = (arrayOld || []).filter((vol) => {\n const value = vol[key] as number;\n return (lead > last && (value >= lead || value <= last)) || (lead < last && (value <= lead || value >= last)) || lead === last;\n });\n\n const secondaryFilteredOld = secondaryKey\n ? filteredOld.filter((vol) => !arrayNew.some((element) => element[secondaryKey] === vol[secondaryKey]))\n : filteredOld;\n\n const oldData = secondaryFilteredOld.filter((vol) => !arrayNew.some((element) => element[key] === vol[key]));\n const data = arrayNew.concat(oldData);\n\n const direction = order === 'ASC' ? 1 : -1;\n return data.sort((a, b) => {\n const x = a[key] as number;\n const y = b[key] as number;\n if (x > y) {\n return direction;\n }\n if (x < y) {\n return direction * -1;\n }\n return 0;\n });\n};\n","/**\n * Order-independent deep equality check.\n *\n * @remarks\n * Returns `true` when `a` and `b` serialize to the same value after their (nested) object entries are\n * sorted by key, so property order does not affect the result. Intended for cheap \"did this state\n * object change?\" comparisons.\n *\n * Caveats of the JSON-serialization approach: values that JSON drops or coerces (`undefined`,\n * functions, `NaN`, `Date`, `Map`/`Set`) are compared by their serialized form, and array element\n * order is treated as significant (arrays are not reordered in a meaningful way). Use a structural\n * deep-equal library when those cases matter.\n *\n * @param a - First object.\n * @param b - Second object.\n * @returns `true` when the two objects are deeply equal ignoring key order.\n * @example\n * ```ts\n * objectEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // => true\n * objectEqual({ a: 1 }, { a: 2 }); // => false\n * ```\n */\nexport const objectEqual = (a: object, b: object): boolean => {\n if (Object.is(a, b)) {\n return true;\n }\n const sortDeep = (obj: unknown): unknown => {\n if (typeof obj !== 'object' || !obj) {\n return undefined;\n }\n return Object.entries(obj)\n .sort()\n .map(([entryKey, value]) => [entryKey, typeof value === 'object' ? sortDeep(value) : value]);\n };\n return JSON.stringify(sortDeep(a)) === JSON.stringify(sortDeep(b));\n};\n","type DisableableElement = HTMLElement & { disabled: boolean };\ninterface DisableState {\n count: number;\n original: boolean;\n}\n\nconst disableStates = new WeakMap<DisableableElement, DisableState>();\n\nconst isDisableable = (element: EventTarget | null): element is DisableableElement =>\n element instanceof HTMLElement && 'disabled' in element;\n\nconst getIonicSubmitButtons = (form: HTMLFormElement): DisableableElement[] =>\n Array.from(document.querySelectorAll<HTMLElement>('ion-button[type=\"submit\"]')).filter((button): button is DisableableElement => {\n if (!isDisableable(button)) return false;\n\n const associatedForm = (button as HTMLElement & { form?: HTMLFormElement | string }).form;\n return (\n associatedForm === form ||\n (typeof associatedForm === 'string' && associatedForm === form.id) ||\n (form.id !== '' && button.getAttribute('form') === form.id) ||\n button.closest('form') === form\n );\n });\n\nconst getDisableTargets = (event: Event): DisableableElement[] => {\n const submitter = 'submitter' in event ? (event as SubmitEvent).submitter : null;\n const form = event.target instanceof HTMLFormElement ? event.target : null;\n const targets: DisableableElement[] = [];\n\n if (event.type === 'submit' && form) {\n targets.push(...getIonicSubmitButtons(form));\n }\n\n if (isDisableable(submitter)) {\n const root = submitter.getRootNode();\n const target = root instanceof ShadowRoot ? root.host : submitter;\n if (isDisableable(target)) targets.push(target);\n }\n\n if (targets.length === 0 && isDisableable(event.currentTarget)) targets.push(event.currentTarget);\n if (targets.length === 0 && isDisableable(event.target)) targets.push(event.target);\n return [...new Set(targets)];\n};\n\nconst acquireDisableTarget = (target: DisableableElement): void => {\n const state = disableStates.get(target);\n if (state) {\n state.count += 1;\n return;\n }\n disableStates.set(target, { count: 1, original: target.disabled });\n target.disabled = true;\n};\n\nconst releaseDisableTarget = (target: DisableableElement): void => {\n const state = disableStates.get(target);\n if (!state) return;\n state.count -= 1;\n if (state.count > 0) return;\n target.disabled = state.original;\n disableStates.delete(target);\n};\n\n/**\n * Disable the controls that triggered an event while an async operation runs.\n *\n * @remarks\n * For a click event, the clicked control is disabled. For a submit event, the submitter is\n * disabled and the browser's default form navigation is prevented. Ionic's external\n * `ion-button[form]` uses a hidden native submitter, so buttons associated with the submitted form\n * are resolved through their `form` property and disabled instead. Rejections are swallowed so\n * controls always recover; handle errors inside `work` when the caller needs to react.\n *\n * @param event - The click or submit event that triggered the operation.\n * @param work - The operation result. Promise-like work keeps controls disabled until it settles;\n * void work still shares this entry point and submit prevention without a synthetic async boundary.\n * @returns A Promise for asynchronous work, otherwise void.\n * @example\n * ```html\n * <form #formRef (submit)=\"helper.disableHandler($event, save())\"></form>\n * <ion-button type=\"submit\" [form]=\"formRef\">Save</ion-button>\n * ```\n */\nexport function disableHandler(event: Event, work: void): void;\nexport function disableHandler(event: Event, work: PromiseLike<unknown>): Promise<void>;\nexport function disableHandler(event: Event, work: void | PromiseLike<unknown>): void | Promise<void>;\nexport function disableHandler(event: Event, work: void | PromiseLike<unknown>): void | Promise<void> {\n if (event.type === 'submit') event.preventDefault();\n\n if (work === undefined) return;\n\n const targets = getDisableTargets(event);\n targets.forEach(acquireDisableTarget);\n\n const restore = () => targets.forEach(releaseDisableTarget);\n return new Promise<unknown>((resolve) => resolve(work)).then(restore, restore);\n}\n","import { WritableSignal } from '@angular/core';\n\n/**\n * Toggle the `disabled` flag of a signal-held `ion-infinite-scroll` / `ion-refresher` element.\n *\n * @remarks\n * A tiny pure helper for the common pattern of stashing the completing scroll/refresher element in a\n * signal (e.g. captured from the event) and later enabling/disabling it — for instance disabling\n * infinite scroll once the last page has loaded. A no-op when the signal holds no element.\n *\n * @param completeEvent - a writable signal holding the infinite-scroll / refresher element (or nullish)\n * @param disabled - the value to set on the element's `disabled` property\n * @example\n * ```ts\n * const infinite = signal<HTMLIonInfiniteScrollElement | null>(null);\n * // ...on ionInfinite: infinite.set(ev.target); ...when no more pages:\n * kitChangeEventDisabled(infinite, true);\n * ```\n */\nexport const kitChangeEventDisabled = (\n completeEvent: WritableSignal<HTMLIonInfiniteScrollElement | HTMLIonRefresherElement | null | undefined>,\n disabled: boolean,\n): void => {\n const event = completeEvent();\n if (event) {\n event.disabled = disabled;\n }\n};\n","import { ElementRef } from '@angular/core';\nimport { Observable, startWith } from 'rxjs';\n\n/**\n * Observe an Ionic page's \"is currently entered\" state from its lifecycle DOM events.\n *\n * @remarks\n * Emits `true` on `ionViewDidEnter` and `false` on `ionViewWillEnter` / `ionViewWillLeave`, seeded\n * with `false` via `startWith`. Useful to pause/resume work (timers, video, expensive rendering)\n * while a page is off-screen in Ionic's stack navigation, without wiring the four lifecycle hooks by\n * hand. The listeners are removed when the Observable is unsubscribed.\n *\n * @param el - an `ElementRef` for the page host element (the `ion-page`)\n * @returns an Observable that emits whether the page is currently entered\n * @example\n * ```ts\n * export class FeedPage {\n * readonly #host = inject(ElementRef);\n * readonly isEntered = toSignal(kitCreateDidEnter(this.#host), { initialValue: false });\n * }\n * ```\n */\nexport const kitCreateDidEnter = (el: ElementRef): Observable<boolean> => {\n return new Observable<boolean>((observer) => {\n const willEnter = () => observer.next(false);\n const didEnter = () => observer.next(true);\n const willLeave = () => observer.next(false);\n\n el.nativeElement.addEventListener('ionViewWillEnter', willEnter);\n el.nativeElement.addEventListener('ionViewDidEnter', didEnter);\n el.nativeElement.addEventListener('ionViewWillLeave', willLeave);\n\n return () => {\n el.nativeElement.removeEventListener('ionViewWillEnter', willEnter);\n el.nativeElement.removeEventListener('ionViewDidEnter', didEnter);\n el.nativeElement.removeEventListener('ionViewWillLeave', willLeave);\n };\n }).pipe(startWith(false));\n};\n","import { afterNextRender } from '@angular/core';\nimport type { InputSignal, InputSignalWithTransform, OutputEmitterRef, Signal } from '@angular/core';\n\n/**\n * Component のうち Signal(computed / input / viewChild 等)と `output()` だけを\n * ViewModel から見えるようにする型。`vm` は循環参照になるため除外する。\n *\n * 注意: `new ViewModel(this)` の引数型に直接使うと、vm 依存 computed の推論と循環する。\n * ViewModelStore 側は constructor(host: Component) で受け、`mountViewModel()` により\n * `ViewModelHost<Component, Keys>` へ絞り込むこと(呼び出し点では mapped type を展開しない)。\n */\nexport type ReactiveHost<T> = Pick<\n T,\n {\n [K in Exclude<keyof T, 'vm'>]-?: T[K] extends Signal<unknown> ? K : T[K] extends OutputEmitterRef<any> ? K : never;\n }[Exclude<keyof T, 'vm'>]\n>;\n\n/**\n * ViewModel に公開する Component の Signal と、明示的に許可した非 Signal property。\n */\nexport type ViewModelHost<T, K extends keyof T = never> = ReactiveHost<T> & Pick<T, K>;\n\n/**\n * Component host を ViewModel 用に絞り込み、初回 render 後の mount hook を登録する。\n */\nexport function mountViewModel<T, K extends keyof T = never>(host: T, onMount?: () => void): ViewModelHost<T, K> {\n if (onMount) {\n afterNextRender(onMount);\n }\n return host as ViewModelHost<T, K>;\n}\n\n/**\n * Modal / page に渡す props オブジェクトを、Angular `input()` の InputSignal 形に写す型。\n * `implements ComponentPropsType<Props>` で component 側の input 宣言を揃える。\n */\nexport type ComponentPropsType<T> = {\n [K in keyof T]: InputSignal<T[K]> | InputSignalWithTransform<T[K], any>;\n};\n","/*\n * Public API Surface of @rdlabo/ionic-angular-kit\n */\n\n// Storage: typed wrapper around the platform key/value store.\nexport * from './lib/storage/kit-storage.service';\n// Remember/recall the last entered sign-in email (validated; storage-agnostic helpers).\nexport * from './lib/storage/kit-auth-email-store';\n// Canonical keys (email + theme) for clear-preserving lists.\nexport * from './lib/storage/kit-storage-keys';\n// Clear storage while restoring selected keys (e.g. last sign-in email on logout).\nexport * from './lib/storage/kit-clear-storage';\n\n// Overlay: wrapper around the Ionic Modal / Toast / Alert controllers.\nexport * from './lib/overlay/overlay-config';\nexport * from './lib/overlay/kit-overlay.controller';\nexport * from './lib/overlay/kit-loading.controller';\nexport * from './lib/overlay/kit-reload-alert.controller';\nexport * from './lib/overlay/kit-maintenance.controller';\nexport * from './lib/overlay/kit-auth-failed-alert';\nexport * from './lib/overlay/kit-language-action-sheet';\n\n// Directives.\nexport * from './lib/directives/auth-input.directive';\n\n// Keyboard: native keyboard reposition listeners.\nexport * from './lib/keyboard/kit-keyboard';\n\n// Theme (`@rdlabo/ionic-angular-kit/theme`), Review (`.../review`), Printer (`.../printer`),\n// Offline (`.../offline`) and\n// Firebase auth (`.../auth-firebase`) are separate secondary entry points so their heavy native peers\n// (status-bar / in-app-review+preferences / brotherprint+dom-to-image / firebase) are\n// only pulled in by apps that import those subpaths.\n\n// Auth: functional route guards.\nexport * from './lib/auth/auth-access.service';\nexport * from './lib/auth/auth-guards';\nexport * from './lib/auth/auth-login-exchange';\n\n// HTTP: functional interceptor.\nexport * from './lib/http/kit-http.interceptor';\nexport * from './lib/http/auth-failure';\n\n// Realtime: reconnecting Hibernation WebSocket client infrastructure.\nexport * from './lib/realtime/kit-realtime-connection';\n\n// Utils: framework-agnostic pure helpers.\nexport * from './lib/utils/haptics';\nexport * from './lib/utils/array';\nexport * from './lib/utils/object';\nexport * from './lib/utils/dom';\nexport * from './lib/utils/ionic-scroll-event';\nexport * from './lib/utils/ionic-view-enter';\n\n// Types: shared Component / ViewModel helpers.\nexport * from './lib/types/component';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["i1.KitAuthAccessService"],"mappings":";;;;;;;;;;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;AAqBG;MAIU,iBAAiB,CAAA;;IAEnB,MAAM,GAAqB,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE;AAE5D;;;;;;;;;;;AAWG;AACH,IAAA,MAAM,GAAG,CAAI,GAAW,EAAE,KAAQ,EAAA;AAChC,QAAA,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC;IAC3C;AAEA;;;;;;;;;;AAUG;IACH,MAAM,GAAG,CAAI,GAAW,EAAA;AACtB,QAAA,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI;IACrD;AAEA;;;;;AAKG;IACH,MAAM,MAAM,CAAC,GAAW,EAAA;QACtB,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC;IACvC;AAEA;;;;AAIG;AACH,IAAA,MAAM,KAAK,GAAA;QACT,MAAM,CAAC,MAAM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AI,CAAC,KAAK,CAAC;QAE5C,EAAE,CAAC,aAAa,CAAC,gBAAgB,CAAC,kBAAkB,EAAE,SAAS,CAAC;QAChE,EAAE,CAAC,aAAa,CAAC,gBAAgB,CAAC,iBAAiB,EAAE,QAAQ,CAAC;QAC9D,EAAE,CAAC,aAAa,CAAC,gBAAgB,CAAC,kBAAkB,EAAE,SAAS,CAAC;AAEhE,QAAA,OAAO,MAAK;YACV,EAAE,CAAC,aAAa,CAAC,mBAAmB,CAAC,kBAAkB,EAAE,SAAS,CAAC;YACnE,EAAE,CAAC,aAAa,CAAC,mBAAmB,CAAC,iBAAiB,EAAE,QAAQ,CAAC;YACjE,EAAE,CAAC,aAAa,CAAC,mBAAmB,CAAC,kBAAkB,EAAE,SAAS,CAAC;AACrE,QAAA,CAAC;IACH,CAAC,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,CAAC;AAC3B;;ACfA;;AAEG;AACG,SAAU,cAAc,CAA+B,IAAO,EAAE,OAAoB,EAAA;IACxF,IAAI,OAAO,EAAE;QACX,eAAe,CAAC,OAAO,CAAC;IAC1B;AACA,IAAA,OAAO,IAA2B;AACpC;;AC/BA;;AAEG;AAEH;;ACJA;;AAEG;;;;"}
|
|
1
|
+
{"version":3,"file":"rdlabo-ionic-angular-kit.mjs","sources":["../../../projects/kit/src/lib/storage/kit-storage.service.ts","../../../projects/kit/src/lib/storage/kit-auth-email-store.ts","../../../projects/kit/src/lib/storage/kit-storage-keys.ts","../../../projects/kit/src/lib/storage/kit-clear-storage.ts","../../../projects/kit/src/lib/overlay/overlay-config.ts","../../../projects/kit/src/lib/utils/haptics.ts","../../../projects/kit/src/lib/overlay/kit-overlay.controller.ts","../../../projects/kit/src/lib/overlay/kit-loading.controller.ts","../../../projects/kit/src/lib/overlay/kit-reload-alert.controller.ts","../../../projects/kit/src/lib/overlay/kit-maintenance.controller.ts","../../../projects/kit/src/lib/overlay/kit-auth-failed-alert.ts","../../../projects/kit/src/lib/overlay/kit-language-action-sheet.ts","../../../projects/kit/src/lib/directives/auth-input.directive.ts","../../../projects/kit/src/lib/keyboard/kit-keyboard.ts","../../../projects/kit/src/lib/auth/auth-access.service.ts","../../../projects/kit/src/lib/auth/auth-guards.ts","../../../projects/kit/src/lib/auth/auth-login-exchange.ts","../../../projects/kit/src/lib/http/kit-http.interceptor.ts","../../../projects/kit/src/lib/http/auth-failure.ts","../../../projects/kit/src/lib/realtime/kit-realtime-connection.ts","../../../projects/kit/src/lib/utils/array.ts","../../../projects/kit/src/lib/utils/object.ts","../../../projects/kit/src/lib/utils/dom.ts","../../../projects/kit/src/lib/utils/ionic-scroll-event.ts","../../../projects/kit/src/lib/utils/ionic-view-enter.ts","../../../projects/kit/src/lib/types/component.ts","../../../projects/kit/src/public-api.ts","../../../projects/kit/src/rdlabo-ionic-angular-kit.ts"],"sourcesContent":["import { inject, Injectable } from '@angular/core';\nimport { Storage } from '@ionic/storage-angular';\n\n/**\n * Thin, typed wrapper around `@ionic/storage-angular`.\n *\n * Starts `create()` exactly once and stores the resulting ready Promise. Every operation awaits\n * that Promise before touching the underlying store, so calls made before initialization completes\n * are queued rather than dropped.\n *\n * @remarks\n * A naive wrapper that reads the store synchronously would silently no-op (or throw) when invoked\n * before `create()` resolves, losing early writes. Awaiting the one-time ready Promise on every\n * operation removes that race without forcing callers to coordinate initialization themselves.\n *\n * @example\n * ```ts\n * constructor(private readonly storage: KitStorageService) {}\n *\n * async ngOnInit(): Promise<void> {\n * await this.storage.set('token', 'abc123');\n * const token = await this.storage.get<string>('token');\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitStorageService {\n /** One-time `create()` ready Promise; awaited before every operation so early calls are not lost. */\n readonly #ready: Promise<Storage> = inject(Storage).create();\n\n /**\n * Persist a value under the given key.\n *\n * @typeParam T - type of the value being stored\n * @param key - key to store the value under\n * @param value - value to persist; overwrites any existing value for the key\n * @returns a Promise that resolves once the value has been written\n * @example\n * ```ts\n * await storage.set('user', { id: 1, name: 'Ada' });\n * ```\n */\n async set<T>(key: string, value: T): Promise<void> {\n await (await this.#ready).set(key, value);\n }\n\n /**\n * Read the value stored under the given key.\n *\n * @typeParam T - expected type of the stored value\n * @param key - key to read\n * @returns the stored value, or `null` when the key is absent\n * @example\n * ```ts\n * const user = await storage.get<{ id: number }>('user');\n * ```\n */\n async get<T>(key: string): Promise<T | null> {\n return (await (await this.#ready).get(key)) ?? null;\n }\n\n /**\n * Remove the value stored under the given key.\n *\n * @param key - key to remove; a no-op when the key is absent\n * @returns a Promise that resolves once the key has been removed\n */\n async remove(key: string): Promise<void> {\n await (await this.#ready).remove(key);\n }\n\n /**\n * Remove every key/value pair from the store.\n *\n * @returns a Promise that resolves once the store has been emptied\n */\n async clear(): Promise<void> {\n await (await this.#ready).clear();\n }\n\n /**\n * List every key currently present in the store.\n *\n * @returns an array of all stored keys\n */\n async keys(): Promise<string[]> {\n return (await this.#ready).keys();\n }\n}\n","/**\n * Remember the email a user last entered on the sign-in form so the field can be prefilled next\n * time (the password is never stored).\n *\n * @remarks\n * Storage-agnostic: the helpers take a minimal async key/value store that {@link KitStorageService}\n * satisfies structurally, so they stay pure and unit-testable without DI. `kitRememberEmail`\n * **validates the address before persisting** — a malformed or partial string is silently ignored,\n * so a garbage entry (or a fat-fingered attempt) never becomes the next prefill. A well-formed email\n * that later fails to sign in is still remembered by design: the user simply re-enters/corrects it.\n *\n * These live in the main entry (next to {@link KitStorageService}) rather than in `auth-firebase`,\n * so `KitAuthInputDirective` can consume them without the main entry depending on the Firebase\n * entry.\n */\n\n/** Minimal async key/value store — structurally satisfied by `KitStorageService`. */\nexport interface KitEmailStore {\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n remove(key: string): Promise<void>;\n}\n\n/** Storage key under which the last entered sign-in email is kept. */\nexport const KIT_LAST_AUTH_EMAIL_KEY = 'kit:last-auth-email';\n\n/**\n * Angular's `Validators.email` pattern — a pragmatic, RFC-5322-inspired address check. Kept in sync\n * with `@angular/forms` so a value we persist would also pass the form's own email validation.\n */\nconst EMAIL_REGEXP =\n /^(?=.{1,254}$)(?=.{1,64}@)[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+(?:\\.[-!#$%&'*+/0-9=?A-Z^_`a-z{|}~]+)*@[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?(?:\\.[A-Za-z0-9](?:[A-Za-z0-9-]{0,61}[A-Za-z0-9])?)*$/;\n\n/** Whether `email` is a well-formed address (matches `@angular/forms` `Validators.email`). */\nexport const kitIsValidEmail = (email: string): boolean => EMAIL_REGEXP.test(email);\n\n/**\n * Persist the entered email for next time — but only when it is a well-formed address.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @param email - the entered email; ignored (not stored) when malformed\n * @returns `true` when the value passed validation and was stored, `false` when it was ignored\n */\nexport const kitRememberEmail = async (store: KitEmailStore, email: string): Promise<boolean> => {\n if (!kitIsValidEmail(email)) {\n return false;\n }\n await store.set(KIT_LAST_AUTH_EMAIL_KEY, email);\n return true;\n};\n\n/**\n * Recall the last remembered email.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @returns the stored email, or `null` when none has been remembered\n */\nexport const kitRecallEmail = (store: KitEmailStore): Promise<string | null> => store.get<string>(KIT_LAST_AUTH_EMAIL_KEY);\n\n/**\n * Forget the remembered email.\n *\n * @remarks\n * Called when the user intentionally clears or invalidates the field, so a stale prefill is not\n * resurrected next time.\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n */\nexport const kitForgetEmail = (store: KitEmailStore): Promise<void> => store.remove(KIT_LAST_AUTH_EMAIL_KEY);\n","/**\n * Canonical storage keys persisted via {@link KitStorageService} that fleet apps often need to\n * keep across a sign-out `clear()`.\n *\n * @remarks\n * `KIT_LAST_AUTH_EMAIL_KEY` lives in `kit-auth-email-store` and is exported from the package root.\n * Import both keys from `@rdlabo/ionic-angular-kit` alongside {@link kitClearStoragePreservingKeys}.\n */\n\n/**\n * Light/dark preference for `provideKitTheme` / `KitThemeController`.\n *\n * @remarks\n * Pass this as `provideKitTheme({ storageKey: KIT_THEME_STORAGE_KEY, … })` and include it in\n * {@link kitClearStoragePreservingKeys} so logout does not reset the user's theme.\n */\nexport const KIT_THEME_STORAGE_KEY = 'theme';\n","/**\n * Clear a key/value store while restoring selected keys afterward.\n *\n * @remarks\n * Fleet apps often call `storage.clear()` on sign-out to drop session/token state. Values that\n * should survive logout (for example {@link KIT_LAST_AUTH_EMAIL_KEY}) are passed in `keys`.\n * Missing keys are skipped — only non-null values are written back.\n */\n\n/** Minimal clearable store — structurally satisfied by {@link KitStorageService}. */\nexport interface KitClearableStore {\n get<T>(key: string): Promise<T | null>;\n set<T>(key: string, value: T): Promise<void>;\n clear(): Promise<void>;\n}\n\n/**\n * Wipe the store, then restore the given keys to their pre-clear values (when present).\n *\n * @param store - the app's storage (e.g. `KitStorageService`)\n * @param keys - keys whose values should survive the clear\n *\n * @example\n * ```ts\n * import { KIT_LAST_AUTH_EMAIL_KEY, KIT_THEME_STORAGE_KEY, kitClearStoragePreservingKeys } from '@rdlabo/ionic-angular-kit';\n *\n * await kitSignOut(auth, {\n * success: () =>\n * kitClearStoragePreservingKeys(this.storage, [KIT_LAST_AUTH_EMAIL_KEY, KIT_THEME_STORAGE_KEY]),\n * });\n * ```\n */\nexport const kitClearStoragePreservingKeys = async (\n store: KitClearableStore,\n keys: readonly string[],\n): Promise<void> => {\n const preserved = await Promise.all(keys.map(async (key) => ({ key, value: await store.get<unknown>(key) })));\n await store.clear();\n for (const { key, value } of preserved) {\n if (value !== null) {\n await store.set(key, value);\n }\n }\n};\n","import type { EnvironmentProviders } from '@angular/core';\nimport { InjectionToken, makeEnvironmentProviders } from '@angular/core';\n\n/**\n * User-visible button labels consumed by `KitOverlayController`.\n *\n * @remarks\n * The kit deliberately ships no i18n strings of its own and has no hard dependency on\n * `@angular/localize`. The consuming application always provides these labels: multilingual apps\n * pass `$localize`-resolved strings, single-language apps pass plain literals.\n */\nexport interface KitLabels {\n /** Text for the \"close\" button used by alerts and toasts. */\n readonly close: string;\n /** Text for the \"cancel\" button used by confirmation alerts. */\n readonly cancel: string;\n}\n\n/**\n * Overlay configuration injected via `provideKitOverlay()`.\n *\n * @remarks\n * All fields are required; the consuming application must supply a complete configuration.\n */\nexport interface KitOverlayConfig {\n /** Button labels used across the overlays presented by `KitOverlayController`. */\n readonly labels: KitLabels;\n}\n\n/**\n * Injection token carrying the {@link KitOverlayConfig} for `KitOverlayController`.\n *\n * @remarks\n * Provide it through {@link provideKitOverlay} rather than registering it directly.\n */\nexport const KIT_OVERLAY_CONFIG = new InjectionToken<KitOverlayConfig>('@rdlabo/ionic-angular-kit:overlay');\n\n/**\n * Wire `KitOverlayController` into the application by providing its button labels.\n *\n * @param config - overlay configuration, including the button labels to inject\n * @returns environment providers to add to the application's provider list\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideKitOverlay({ labels: { close: $localize`Close`, cancel: $localize`Cancel` } }),\n * ],\n * });\n * ```\n */\nexport const provideKitOverlay = (config: KitOverlayConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_OVERLAY_CONFIG, useValue: config }]);\n","import { Capacitor } from '@capacitor/core';\nimport { Haptics, ImpactStyle } from '@capacitor/haptics';\n\n/**\n * Trigger native haptic impact feedback.\n *\n * Delegates to `@capacitor/haptics` `Haptics.impact()` when running on a native platform. On the\n * web (or any non-native platform) it is a no-op and resolves without doing anything.\n *\n * @remarks\n * This haptic side effect was previously bundled implicitly into toast/modal presentation. It has\n * been decoupled into this explicit function so callers opt in to the feedback deliberately, rather\n * than receiving it as a hidden side effect of presenting UI.\n *\n * @param style - The impact intensity to play. Defaults to {@link ImpactStyle.Light}.\n * @returns A promise that resolves once the feedback has been requested (immediately on the web).\n * @example\n * ```ts\n * import { ImpactStyle } from '@capacitor/haptics';\n *\n * // Light tap (default)\n * await kitImpact();\n *\n * // Stronger feedback, e.g. on a confirming action\n * await kitImpact(ImpactStyle.Heavy);\n * ```\n */\nexport const kitImpact = async (style: ImpactStyle = ImpactStyle.Light): Promise<void> => {\n if (Capacitor.isNativePlatform()) {\n await Haptics.impact({ style });\n }\n};\n","import { inject, Injectable } from '@angular/core';\nimport type { InputSignalWithTransform } from '@angular/core';\nimport type { ModalOptions, PopoverOptions, ToastOptions } from '@ionic/angular';\nimport { AlertController } from '@ionic/angular/alert-controller';\nimport { ModalController } from '@ionic/angular/modal-controller';\nimport { PopoverController } from '@ionic/angular/popover-controller';\nimport { ToastController } from '@ionic/angular/toast-controller';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Capacitor } from '@capacitor/core';\nimport { Keyboard } from '@capacitor/keyboard';\nimport { KIT_OVERLAY_CONFIG } from './overlay-config';\nimport { kitImpact } from '../utils/haptics';\n\n/**\n * Options for {@link KitOverlayController.presentModal}.\n *\n * @remarks\n * Extends Ionic's `ModalOptions` but omits `component` and `componentProps`, which are passed as\n * dedicated arguments instead.\n */\nexport interface KitModalPresentOptions extends Omit<ModalOptions, 'component' | 'componentProps'> {\n /**\n * When `true`, expand the sheet to its maximum breakpoint while the native keyboard is shown.\n *\n * @remarks\n * Only has an effect on native platforms; ignored on the web.\n */\n watchKeyboard?: boolean;\n}\n\n/**\n * Optional static metadata a modal component may declare to make {@link KitOverlayController.presentModal}\n * type-safe in its dismiss data: the value passed to `dismiss()` is inferred from `modalReturn`.\n *\n * @remarks\n * Props do *not* need to be declared here — {@link KitOverlayController.presentModal} infers them directly\n * from the component's `input()` fields (see {@link ModalPropsOf}), so `input()` stays the single source of\n * truth and can never drift from a hand-written declaration. Only the dismiss-data shape, which has no\n * counterpart on the component, is declared — as a `declare static modalReturn` phantom type with no runtime\n * value, so it adds nothing to the bundle.\n *\n * @example\n * ```ts\n * export class EditPage {\n * declare static modalReturn: { saved: boolean };\n * readonly id = input.required<number>(); // props are inferred from here\n * readonly note = input<string>(); // default-less input() → optional prop\n * }\n *\n * // Caller — `id` is required (input.required), `note` optional; result is `{ saved: boolean } | undefined`:\n * const result = await overlay.presentModal(EditPage, { id: 1 });\n * ```\n */\nexport interface ModalMetadata<R = unknown> {\n /** Shape of the data the modal resolves with when dismissed. */\n modalReturn?: R;\n}\n\n/**\n * Write type of a signal `input()` field (unwraps `input.required`, `input()` and transform inputs).\n *\n * @remarks\n * Matched with `any` (not `unknown`): `InputSignalWithTransform`'s `TransformT` is contravariant, so\n * `InputSignal<number>` is not assignable to `InputSignalWithTransform<unknown, unknown>`.\n */\ntype InputWriteType<F> = F extends InputSignalWithTransform<any, infer W> ? W : never;\n\n/** Instance type of a component constructor; `never` for non-class components (string / HTMLElement refs). */\ntype InstanceOf<C> = C extends abstract new (...args: never[]) => infer I ? I : never;\n\n/** Keys of the `input()` signal fields on a component instance. */\ntype InputFieldKeys<I> = { [K in keyof I]-?: I[K] extends InputSignalWithTransform<any, any> ? K : never }[keyof I];\n\n/**\n * Props object inferred from a component's `input()` fields. Required vs. optional is decided by the write\n * type: `input.required<T>()` / `input<T>(default)` yield `T` (no `undefined`) → required prop, while a\n * default-less `input<T>()` yields `T | undefined` → optional prop.\n *\n * @remarks\n * Angular's types cannot distinguish `input.required<T>()` from a defaulted `input<T>(default)` — both are\n * `InputSignal<T>` — so a defaulted input is (safely) treated as required. Declare inputs you want to omit at\n * the call site as default-less `input<T>()`.\n */\ntype ModalPropsOf<I> = { [K in InputFieldKeys<I> as undefined extends InputWriteType<I[K]> ? never : K]: InputWriteType<I[K]> } & {\n [K in InputFieldKeys<I> as undefined extends InputWriteType<I[K]> ? K : never]?: InputWriteType<I[K]>;\n};\n\n/** `input()` keys whose write type excludes `undefined` (required / defaulted inputs). Empty when none. */\ntype RequiredInputKeys<I> = { [K in InputFieldKeys<I>]: undefined extends InputWriteType<I[K]> ? never : K }[InputFieldKeys<I>];\n\n/**\n * Dismiss-data type inferred from a component's static {@link ModalMetadata.modalReturn}. A component that\n * declares no `modalReturn` resolves to `void`: it is treated as returning no dismiss data, so the compiler\n * rejects any attempt to read the result. Declare `modalReturn` on modals that do resolve with data.\n */\ntype ModalReturnOf<C> = C extends { modalReturn: infer R } ? R : void;\n\n/** Loose trailing args (optional, untyped props) — used when a component exposes no signal `input()` fields. */\ntype LooseModalPresentArgs = [componentProps?: ModalOptions['componentProps'], options?: KitModalPresentOptions];\n\n/**\n * Trailing `presentModal` args derived from a component's `input()` fields: props are inferred and typed via\n * {@link ModalPropsOf}. When the component declares at least one required input the props argument is required;\n * when every input is optional the props argument itself is optional. Components with no signal inputs (plain\n * classes, `@Input()`-decorator components, or non-class refs) fall back to loose, untyped props.\n */\ntype ModalPresentArgs<C, I = InstanceOf<C>> = [I] extends [never]\n ? LooseModalPresentArgs\n : [InputFieldKeys<I>] extends [never]\n ? LooseModalPresentArgs\n : [RequiredInputKeys<I>] extends [never]\n ? [componentProps?: ModalPropsOf<I>, options?: KitModalPresentOptions]\n : [componentProps: ModalPropsOf<I>, options?: KitModalPresentOptions];\n\nconst BOTTOM_TAB_BAR_VIEWPORT_MARGIN_PX = 8;\n\n/**\n * Returns a visible `ion-tab-bar` suitable for anchoring a bottom toast above it.\n *\n * Skips `slot=\"top\"` bars (e.g. airlec desktop layout) and prefers the bar closest to the viewport bottom\n * when multiple candidates exist.\n */\nfunction findVisibleBottomTabBar(): HTMLElement | undefined {\n let best: HTMLElement | undefined;\n let bestBottom = -1;\n\n for (const tabBar of Array.from(document.querySelectorAll('ion-tab-bar'))) {\n if (!(tabBar instanceof HTMLElement)) continue;\n if (tabBar.getAttribute('slot') === 'top') continue;\n\n const rect = tabBar.getBoundingClientRect();\n if (rect.height <= 0) continue;\n\n const slot = tabBar.getAttribute('slot');\n const isBottom = slot === 'bottom' || (slot === null && rect.bottom >= window.innerHeight - BOTTOM_TAB_BAR_VIEWPORT_MARGIN_PX);\n if (!isBottom) continue;\n\n if (rect.bottom > bestBottom) {\n bestBottom = rect.bottom;\n best = tabBar;\n }\n }\n\n return best;\n}\n\n/**\n * Options for {@link KitOverlayController.alertClose}.\n */\nexport interface KitAlertCloseOptions {\n /** Alert header text. */\n header: string;\n /** Alert body message. */\n message: string;\n /** Optional alert sub-header text shown beneath the header. */\n subHeader?: string;\n}\n\n/**\n * Options for {@link KitOverlayController.alertConfirm}.\n *\n * @remarks\n * Extends {@link KitAlertCloseOptions} with the confirm-button text.\n */\nexport interface KitAlertConfirmOptions extends KitAlertCloseOptions {\n /**\n * Text for the OK (confirm) button.\n *\n * @remarks\n * Action-specific, so it is supplied by the caller rather than taken from the shared labels.\n */\n okText: string;\n}\n\n/**\n * Attach a native keyboard listener that grows the modal to its maximum breakpoint when the\n * keyboard appears.\n *\n * @param modal - the presented modal element to resize\n * @returns a listener handle; on non-native platforms a no-op handle whose `remove()` does nothing\n * @internal\n */\nconst watchModalKeyboard = async (modal: HTMLIonModalElement): Promise<PluginListenerHandle> => {\n if (!Capacitor.isNativePlatform()) {\n return { remove: async () => undefined };\n }\n return Keyboard.addListener('keyboardDidShow', () => modal.setCurrentBreakpoint(1));\n};\n\n/**\n * Ergonomic wrapper that consolidates Ionic's overlay controllers (Modal / Toast / Alert).\n *\n * @remarks\n * Folds the repetitive create → present → onDidDismiss sequence into single calls and returns the\n * relevant result directly. It holds no application-specific policy such as navigation; compose\n * those concerns on the consuming side.\n *\n * @example\n * ```ts\n * constructor(private readonly overlay: KitOverlayController) {}\n *\n * async edit(): Promise<void> {\n * const result = await this.overlay.presentModal(EditPage, { id: 1 });\n * if (result) {\n * await this.overlay.presentToast({ message: 'Saved' });\n * }\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitOverlayController {\n readonly #modalCtrl = inject(ModalController);\n readonly #popoverCtrl = inject(PopoverController);\n readonly #toastCtrl = inject(ToastController);\n readonly #alertCtrl = inject(AlertController);\n readonly #labels = inject(KIT_OVERLAY_CONFIG).labels;\n\n /**\n * Guards against stacking alerts: while one {@link alertClose} / {@link alertConfirm} is on screen,\n * a concurrent call resolves immediately (close: no-op, confirm: `false`) instead of presenting a\n * second alert on top of the first. Shared across both methods so a confirm cannot stack over a close.\n */\n #alertPresenting = false;\n\n /**\n * Present a modal and resolve with the data passed to its dismissal.\n *\n * @typeParam O - type of the data returned when the modal is dismissed\n * @param component - the component to render inside the modal\n * @param componentProps - props to pass to the modal component\n * @param options - additional modal options, including {@link KitModalPresentOptions.watchKeyboard}\n * @returns the dismiss data, or `undefined` when the modal is dismissed without data\n * @remarks\n * Presenting a modal triggers light native haptic feedback as an intentional kit UX choice,\n * consistent with {@link presentPopover} and {@link presentToast}.\n *\n * Props are inferred from the component's `input()` fields (see {@link ModalPropsOf}): required inputs\n * become required props, so the compiler rejects a call that omits them. The return type is inferred from\n * a static `modalReturn` (see {@link ModalMetadata}); a component with no `modalReturn` resolves to `void`\n * — the modal is treated as returning no dismiss data.\n * @example\n * ```ts\n * // Inferred — `id` required (input.required), `note` optional; result is `{ saved: boolean } | undefined`:\n * const result = await overlay.presentModal(EditPage, { id: 1 });\n * ```\n */\n presentModal<C extends ModalOptions['component']>(component: C, ...args: ModalPresentArgs<C>): Promise<ModalReturnOf<C> | undefined>;\n async presentModal(\n component: ModalOptions['component'],\n componentProps?: ModalOptions['componentProps'],\n options: KitModalPresentOptions = {},\n ): Promise<unknown> {\n void kitImpact();\n const { watchKeyboard, ...modalOptions } = options;\n const modal = await this.#modalCtrl.create({ component, componentProps, ...modalOptions });\n await modal.present();\n const handle = watchKeyboard ? await watchModalKeyboard(modal) : null;\n const { data } = await modal.onDidDismiss<unknown>();\n await handle?.remove();\n return data;\n }\n\n /**\n * Present a popover and resolve with the data passed to its dismissal.\n *\n * @typeParam O - type of the data returned when the popover is dismissed\n * @param component - the component to render inside the popover\n * @param componentProps - props to pass to the popover component\n * @param options - additional popover options (for example `event` to anchor it, or `cssClass`)\n * @returns the dismiss data, or `undefined` when the popover is dismissed without data\n * @remarks\n * Presenting a popover triggers light native haptic feedback as an intentional kit UX choice,\n * consistent with {@link presentModal} and {@link presentToast}.\n * @example\n * ```ts\n * const choice = await overlay.presentPopover<MenuChoice>(MenuPopover, { items }, { event });\n * ```\n */\n async presentPopover<O = unknown>(\n component: PopoverOptions['component'],\n componentProps?: PopoverOptions['componentProps'],\n options: Omit<PopoverOptions, 'component' | 'componentProps'> = {},\n ): Promise<O | undefined> {\n void kitImpact();\n const popover = await this.#popoverCtrl.create({ component, componentProps, ...options });\n await popover.present();\n const { data } = await popover.onDidDismiss<O>();\n return data;\n }\n\n /**\n * Present a toast using kit defaults that the caller may override.\n *\n * @remarks\n * Defaults to a bottom position, a 2000ms duration, a vertical swipe gesture, and a close button\n * from the configured labels; any of these can be overridden via `options`. Presenting a toast\n * also triggers light native haptic feedback as an intentional kit UX choice.\n *\n * Bottom is the fleet-wide default (top left the toast fighting the tab bar and the keyboard).\n * For a bottom toast with no explicit `positionAnchor`, if a visible bottom `ion-tab-bar` is present the\n * toast is automatically anchored above it (Ionic places a bottom toast above its `positionAnchor`),\n * so the toast never sits behind the tabs. Bars with `slot=\"top\"` are ignored (desktop layouts that move\n * tabs to the header). Avoiding the on-screen keyboard is handled by the native keyboard resize — the\n * anchored/bottom toast rides the shrinking viewport above the keyboard;\n * Ionic itself has no toast keyboard-avoidance option. An app can override either via `options`.\n *\n * @param options - Ionic toast options that override the kit defaults\n * @returns the presented toast element\n * @example\n * ```ts\n * await overlay.presentToast({ message: 'Copied to clipboard' });\n * ```\n */\n async presentToast(options: ToastOptions): Promise<HTMLIonToastElement> {\n void kitImpact();\n const merged: ToastOptions = {\n position: 'bottom',\n duration: 2000,\n buttons: [this.#labels.close],\n swipeGesture: 'vertical',\n ...options,\n };\n // Anchor a bottom toast above the tab bar when a bottom bar is visibly present and the caller did not\n // set an explicit anchor, so the toast clears the tabs (and rides the keyboard-resized viewport).\n if (merged.position === 'bottom' && merged.positionAnchor === undefined) {\n const tabBar = findVisibleBottomTabBar();\n if (tabBar) {\n merged.positionAnchor = tabBar;\n }\n }\n const toast = await this.#toastCtrl.create(merged);\n await toast.present();\n return toast;\n }\n\n /**\n * Present a notification alert with a single \"close\" button and wait for it to be dismissed.\n *\n * @param options - alert content (header, message, optional sub-header)\n * @returns a Promise that resolves once the alert has been dismissed\n * @remarks\n * No-ops when another alert is already presenting (see {@link alertClose} / {@link alertConfirm}\n * stacking guard).\n * @example\n * ```ts\n * await overlay.alertClose({ header: 'Done', message: 'Your changes were saved.' });\n * ```\n */\n async alertClose(options: KitAlertCloseOptions): Promise<void> {\n if (this.#alertPresenting) {\n return;\n }\n this.#alertPresenting = true;\n const present = async (): Promise<void> => {\n const alert = await this.#alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [this.#labels.close],\n });\n await alert.present();\n await alert.onWillDismiss();\n };\n await present().finally(() => (this.#alertPresenting = false));\n }\n\n /**\n * Present a confirmation alert with cancel and OK buttons.\n *\n * @param options - alert content plus the OK button text via {@link KitAlertConfirmOptions.okText}\n * @returns `true` when the user presses OK, `false` otherwise (cancel or backdrop dismissal)\n * @example\n * ```ts\n * const ok = await overlay.alertConfirm({\n * header: 'Delete item?',\n * message: 'This cannot be undone.',\n * okText: 'Delete',\n * });\n * if (ok) {\n * await remove();\n * }\n * ```\n * @remarks\n * Returns `false` immediately when another alert is already presenting (see {@link alertClose} /\n * {@link alertConfirm} stacking guard).\n */\n async alertConfirm(options: KitAlertConfirmOptions): Promise<boolean> {\n if (this.#alertPresenting) {\n return false;\n }\n return this.#presentAlertConfirm(options);\n }\n\n /**\n * Try to present a confirmation alert without stacking it over another alert.\n *\n * @returns `true` for confirmation, `false` for explicit cancellation or backdrop dismissal, and `undefined` when\n * another alert prevented this one from being presented.\n */\n async tryAlertConfirm(options: KitAlertConfirmOptions): Promise<boolean | undefined> {\n if (this.#alertPresenting) {\n return undefined;\n }\n const activeAlert = await this.#alertCtrl.getTop();\n if (activeAlert || this.#alertPresenting) {\n return undefined;\n }\n return this.#presentAlertConfirm(options);\n }\n\n async #presentAlertConfirm(options: KitAlertConfirmOptions): Promise<boolean> {\n this.#alertPresenting = true;\n const present = async (): Promise<boolean> => {\n const alert = await this.#alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [\n { text: this.#labels.cancel, role: 'cancel' },\n { text: options.okText, role: 'confirm' },\n ],\n });\n await alert.present();\n const { role } = await alert.onWillDismiss();\n return role === 'confirm';\n };\n return present().finally(() => (this.#alertPresenting = false));\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport type { LoadingOptions } from '@ionic/angular';\nimport { LoadingController } from '@ionic/angular/loading-controller';\n\nconst settledLoadingOperation = async (): Promise<void> => undefined;\n\n/**\n * Reference-counted wrapper around Ionic's `LoadingController` that keeps at most one loading\n * indicator on screen across concurrent async work.\n *\n * @remarks\n * Each {@link presentLoading} increments a counter and each {@link dismissLoading} decrements it; the\n * indicator is presented on the `0 → 1` transition and dismissed on the `N → 0` transition. This\n * removes the flicker / \"stuck spinner\" bugs that come from every service calling\n * `LoadingController.create/dismiss` independently.\n *\n * All operations are serialized through an internal promise chain, so a `create → present` sequence\n * can never interleave with a concurrent `dismiss`. That is what makes the counter race-safe: a\n * dismiss that arrives while the indicator is still being presented runs *after* `present()` settles\n * and therefore tears the element down instead of leaving it orphaned on screen.\n *\n * Always pair every `presentLoading()` with exactly one `dismissLoading()` — a `try/finally` is the\n * safest shape.\n *\n * @example\n * ```ts\n * constructor(private readonly loading: KitLoadingController) {}\n *\n * async save(): Promise<void> {\n * await this.loading.presentLoading({ message: 'Saving…' });\n * try {\n * await this.api.save();\n * } finally {\n * await this.loading.dismissLoading();\n * }\n * }\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitLoadingController {\n readonly #loadingCtrl = inject(LoadingController);\n\n /** Outstanding {@link presentLoading} calls not yet balanced by {@link dismissLoading}. */\n #count = 0;\n\n /** The single presented loading element, or `null` when none is on screen. */\n #loading: HTMLIonLoadingElement | null = null;\n\n /**\n * Serializes present/dismiss operations. Each call chains onto this promise, runs after the\n * previous operation has fully settled, then reads {@link #count} and acts accordingly.\n */\n #queue: Promise<void> = settledLoadingOperation();\n\n /**\n * Show the loading indicator, or join the one already on screen.\n *\n * @param options - Ionic loading options; only applied by the call that actually creates the\n * indicator (the `0 → 1` transition). Ignored while an indicator is already present.\n * @returns a Promise that resolves once the indicator is on screen (or immediately when one already is)\n */\n presentLoading(options: LoadingOptions = {}): Promise<void> {\n this.#count++;\n return this.#enqueue(async () => {\n // Create only on the transition into \"something is loading\"; concurrent callers ride the same\n // element. Re-check the count in case a dismiss already balanced this call while queued.\n if (this.#count > 0 && this.#loading === null) {\n const loading = await this.#loadingCtrl.create(options);\n await loading.present();\n this.#loading = loading;\n }\n }).catch((error: unknown) => {\n // Roll back the reference this call took: a failed create/present must not leave the counter\n // elevated, otherwise a later cycle never reaches N → 0 and the spinner stays stuck on screen.\n this.#count--;\n throw error;\n });\n }\n\n /**\n * Release one reference; dismiss the indicator once the last reference is gone.\n *\n * @returns a Promise that resolves once the reference is released (and the indicator dismissed if\n * this was the last one). No-ops when the counter is already at zero.\n */\n async dismissLoading(): Promise<void> {\n if (this.#count === 0) {\n return;\n }\n this.#count--;\n await this.#enqueue(async () => {\n // Tear down only when the last consumer is gone. Because this runs after any in-flight\n // present() has settled (via the queue), there is never an orphaned loading element.\n if (this.#count === 0 && this.#loading !== null) {\n const loading = this.#loading;\n this.#loading = null;\n await loading.dismiss();\n }\n });\n }\n\n /**\n * Append `task` to the serialization chain and return its completion.\n *\n * @remarks\n * The stored chain swallows rejections so a single failing operation cannot wedge every future\n * overlay; the returned promise still rejects so the caller observes the error.\n */\n #enqueue(task: () => Promise<void>): Promise<void> {\n const run = this.#queue.then(task);\n this.#queue = run.then(\n () => undefined,\n () => undefined,\n );\n return run;\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { AlertController } from '@ionic/angular/alert-controller';\nimport { KIT_OVERLAY_CONFIG } from './overlay-config';\n\n/**\n * Content for {@link KitReloadAlertController.present}.\n */\nexport interface KitReloadAlertOptions {\n /** Alert header text. */\n header: string;\n /** Alert body message. */\n message: string;\n /**\n * Text for the reload (confirm) button, e.g. \"リフレッシュ\".\n *\n * @remarks\n * Action-specific, so it is supplied by the caller rather than taken from the shared labels.\n * The cancel button uses the configured {@link KitLabels.cancel}.\n */\n okText: string;\n}\n\n/**\n * The fleet's canonical \"network error → offer to reload\" alert, as a stateful controller.\n *\n * @remarks\n * Consolidates the good-UX variant that had drifted across the fleet into one behavior:\n *\n * - **De-dup** — never stacks; a second {@link present} while an alert is already shown is a no-op.\n * - **Backdrop lock** — `backdropDismiss: false`, so a critical network error can't be dismissed by\n * an accidental backdrop tap; the user consciously chooses cancel or reload.\n * - **Auto-dismiss on reconnect** — the presented alert is tracked, so {@link dismiss} (called from a\n * later successful response) clears a now-stale error alert instead of leaving it on screen.\n * - **Reload on confirm** — the confirm button calls `location.reload()`.\n *\n * All user-facing text is supplied by the caller so the kit stays free of any hardcoded i18n; the\n * cancel button reuses {@link KitOverlayConfig.labels}. Because it performs navigation\n * (`location.reload()`) and holds state, it is a dedicated controller rather than part of\n * {@link KitOverlayController}, which stays free of navigation policy.\n *\n * @example\n * ```ts\n * // In an HTTP interceptor:\n * const reload = inject(KitReloadAlertController);\n * // ...on a network-class error while connected:\n * await reload.present({ header: 'ネットワークエラー', message: `…(${status})`, okText: 'リフレッシュ' });\n * // ...on any later successful response:\n * await reload.dismiss();\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitReloadAlertController {\n readonly #alertCtrl = inject(AlertController);\n readonly #labels = inject(KIT_OVERLAY_CONFIG).labels;\n #alert: HTMLIonAlertElement | null = null;\n\n /**\n * Present the reload alert, unless one is already on screen.\n *\n * @param options - alert content plus the reload-button text\n * @returns a Promise that resolves once the alert has been presented (or immediately if suppressed)\n */\n async present(options: KitReloadAlertOptions): Promise<void> {\n // この controller 経由でも直書き ion-alert でも、多重表示しない。\n if (this.#alert || document.querySelector('ion-alert')) {\n return;\n }\n const alert = await this.#alertCtrl.create({\n header: options.header,\n message: options.message,\n backdropDismiss: false,\n buttons: [\n { text: this.#labels.cancel, role: 'cancel' },\n {\n text: options.okText,\n handler: () => {\n location.reload();\n },\n },\n ],\n });\n this.#alert = alert;\n void alert.onDidDismiss().then(() => {\n // 別の present で置き換わっていない限り、追跡を解除する。\n if (this.#alert === alert) {\n this.#alert = null;\n }\n });\n await alert.present();\n }\n\n /**\n * Dismiss the tracked reload alert if one is showing.\n *\n * @remarks\n * Typically called from a later successful response so a stale \"network error\" alert clears once\n * connectivity is restored. A no-op when nothing is showing.\n *\n * @returns a Promise that resolves once the alert has been dismissed (or immediately if none)\n */\n async dismiss(): Promise<void> {\n const alert = this.#alert;\n this.#alert = null;\n await alert?.dismiss();\n }\n}\n","import { inject, Injectable } from '@angular/core';\nimport { AlertController } from '@ionic/angular/alert-controller';\n\n/**\n * Content for {@link KitMaintenanceController.present}.\n */\nexport interface KitMaintenanceOptions {\n /** Alert header, e.g. \"メンテナンス中です\". */\n header: string;\n /** Alert body; keep short — the user cannot dismiss until maintenance ends. */\n message: string;\n /**\n * Absolute URL of the fleet maintenance wait SSE (`GET /public/maintenance/wait`).\n *\n * @remarks\n * Typically `environment.api + 'public/maintenance/wait'`. While the overlay is shown the\n * controller opens an {@link EventSource} on this URL and dismisses on `event: ended`.\n */\n waitUrl: string;\n}\n\n/**\n * Singleton \"maintenance lock\" overlay: backdrop-locked, no dismiss buttons, auto-clears via SSE.\n *\n * @remarks\n * Mirrors {@link KitReloadAlertController} as a de-duped stateful controller, but the user cannot\n * cancel or reload out of it — only the server `event: ended` on {@link KitMaintenanceOptions.waitUrl}\n * (or an explicit {@link dismiss}) clears it. Uses Ionic's `AlertController` (not a feature modal)\n * so the kit stays free of page components / i18n; all copy is supplied by the caller.\n *\n * Wire from {@link KitHttpConfig.onMaintenance} when the API returns `503` with\n * `error.error?.code === 'MAINTENANCE'`.\n *\n * @example\n * ```ts\n * provideKitHttp(() => {\n * const maintenance = inject(KitMaintenanceController);\n * return {\n * getAuthHeaders: async () => ({}),\n * onMaintenance: () =>\n * void maintenance.present({\n * header: 'メンテナンス中です',\n * message: 'しばらくお待ちください。終了次第、自動で閉じます。',\n * waitUrl: environment.api + 'public/maintenance/wait',\n * }),\n * };\n * });\n * ```\n */\n@Injectable({\n providedIn: 'root',\n})\nexport class KitMaintenanceController {\n readonly #alertCtrl = inject(AlertController);\n #alert: HTMLIonAlertElement | null = null;\n #source: EventSource | null = null;\n #reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n #reconnectAttempt = 0;\n #waitUrl: string | null = null;\n /** When true, EventSource errors must not schedule reconnect (ended / dismiss). */\n #closed = false;\n\n /**\n * Present the lock overlay and start waiting on the maintenance SSE, unless one is already showing.\n *\n * @param options - overlay copy plus the wait SSE URL\n */\n async present(options: KitMaintenanceOptions): Promise<void> {\n if (this.#alert || document.querySelector('ion-alert.kit-maintenance-alert')) {\n return;\n }\n this.#closed = false;\n this.#waitUrl = options.waitUrl;\n const alert = await this.#alertCtrl.create({\n header: options.header,\n message: options.message,\n backdropDismiss: false,\n // No buttons — dismissal is server-driven via SSE (or an explicit dismiss()).\n buttons: [],\n cssClass: 'kit-maintenance-alert',\n });\n this.#alert = alert;\n void alert.onDidDismiss().then(() => {\n if (this.#alert === alert) {\n this.#alert = null;\n }\n this.#stopWait();\n });\n await alert.present();\n this.#startWait(options.waitUrl);\n }\n\n /**\n * Dismiss the tracked overlay and tear down the wait SSE.\n *\n * @remarks\n * Normally called when the wait stream emits `ended`. A no-op when nothing is showing.\n */\n async dismiss(): Promise<void> {\n this.#stopWait();\n const alert = this.#alert;\n this.#alert = null;\n await alert?.dismiss();\n }\n\n #startWait(waitUrl: string): void {\n this.#stopSourceOnly();\n if (this.#closed) {\n return;\n }\n const source = new EventSource(waitUrl);\n this.#source = source;\n\n source.addEventListener('ended', () => {\n void this.dismiss();\n });\n\n source.addEventListener('ping', () => {\n // Keepalive — resets reconnect backoff so a lively stream does not treat the next pause as failure.\n this.#reconnectAttempt = 0;\n });\n\n source.onerror = () => {\n // EventSource auto-reconnects, but after a deploy the old isolate may hang; force a clean\n // reconnect with exponential backoff once the browser surfaces an error.\n if (this.#closed || this.#waitUrl !== waitUrl) {\n return;\n }\n this.#stopSourceOnly();\n this.#scheduleReconnect();\n };\n\n source.onopen = () => {\n this.#reconnectAttempt = 0;\n };\n }\n\n #scheduleReconnect(): void {\n if (this.#closed || !this.#waitUrl) {\n return;\n }\n if (this.#reconnectTimer) {\n clearTimeout(this.#reconnectTimer);\n }\n const delay = Math.min(30_000, 500 * 2 ** this.#reconnectAttempt);\n this.#reconnectAttempt += 1;\n const waitUrl = this.#waitUrl;\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = null;\n if (!this.#closed && this.#waitUrl === waitUrl) {\n this.#startWait(waitUrl);\n }\n }, delay);\n }\n\n #stopWait(): void {\n this.#closed = true;\n this.#waitUrl = null;\n this.#reconnectAttempt = 0;\n if (this.#reconnectTimer) {\n clearTimeout(this.#reconnectTimer);\n this.#reconnectTimer = null;\n }\n this.#stopSourceOnly();\n }\n\n #stopSourceOnly(): void {\n const source = this.#source;\n this.#source = null;\n if (source) {\n source.onerror = null;\n source.onopen = null;\n source.close();\n }\n }\n}\n","import type { AlertController } from '@ionic/angular/alert-controller';\n\n/**\n * Content for {@link kitPresentAuthFailedAlert}.\n */\nexport interface KitAuthFailedAlertOptions {\n /** Alert header, e.g. \"ログインできませんでした\". */\n header: string;\n /** Optional sub-header; typically the short server error code/name. */\n subHeader?: string;\n /** Alert body message; typically the server-provided detail. */\n message: string;\n /** Text for the single close button, e.g. \"閉じる\". */\n closeText: string;\n}\n\n/**\n * Present the fleet's canonical \"sign-in / token exchange failed\" alert.\n *\n * @remarks\n * Folds together the alert every token-exchange app duplicated verbatim when a startup re-login\n * fails: an informative alert (header + optional server error as sub-header + detail message) with a\n * single close button that reloads the app (`location.reload()`) so the user restarts cleanly. The\n * caller is still responsible for signing the user out around this call.\n *\n * All user-facing text is supplied by the caller so the kit stays free of any hardcoded i18n. Kept\n * as a standalone helper (taking the `AlertController`) rather than a method on\n * {@link KitOverlayController}, which holds no navigation policy such as `location.reload()`.\n *\n * @param alertCtrl - Ionic's `AlertController`\n * @param options - alert content plus the close-button text\n * @returns a Promise that resolves once the alert has been presented\n * @example\n * ```ts\n * onAuthorized: async () => {\n * const logged = await auth.tokenLogin().catch(async (e) => {\n * await kitPresentAuthFailedAlert(alertCtrl, {\n * header: 'ログインできませんでした',\n * subHeader: e.error.error,\n * message: e.error.detail,\n * closeText: '閉じる',\n * });\n * await auth.signOut();\n * return undefined;\n * });\n * // ...\n * };\n * ```\n */\nexport const kitPresentAuthFailedAlert = async (\n alertCtrl: AlertController,\n options: KitAuthFailedAlertOptions,\n): Promise<void> => {\n const alert = await alertCtrl.create({\n header: options.header,\n subHeader: options.subHeader,\n message: options.message,\n buttons: [\n {\n text: options.closeText,\n role: 'cancel',\n handler: () => {\n location.reload();\n },\n },\n ],\n });\n await alert.present();\n};\n","import { ActionSheetController } from '@ionic/angular/action-sheet-controller';\n\n/** One selectable language in {@link kitPresentLanguageActionSheet}. */\nexport interface KitLanguageOption {\n /** Button label shown to the user (e.g. `English`, `日本語`). */\n readonly text: string;\n /** Locale identifier returned when this option is chosen (e.g. `en-US`, `ja`). */\n readonly data: string;\n}\n\n/**\n * Options for {@link kitPresentLanguageActionSheet}.\n *\n * @remarks\n * The kit ships no strings or URLs of its own: labels, the locale list, and the redirect-URL mapping\n * are all supplied by the caller, so a multilingual app passes `$localize`-resolved text and its own\n * per-locale build paths.\n */\nexport interface KitLanguageActionSheetOptions {\n /** Action-sheet header text. */\n readonly header: string;\n /** Selectable languages, in display order. */\n readonly locales: readonly KitLanguageOption[];\n /** Text for the cancel button. */\n readonly cancelText: string;\n /** The currently active locale; selecting the same value is a no-op. Normalize before passing. */\n readonly currentLocale: string;\n /** The current in-app path (e.g. `router.url`), stashed so the app can restore it after the reload. */\n readonly currentPath: string;\n /** `sessionStorage` key under which {@link currentPath} is stored. */\n readonly pathnameStorageKey: string;\n /** Maps a chosen locale to the URL to navigate to (the app's per-locale build entry point). */\n readonly buildRedirectUrl: (locale: string) => string;\n /** Gate for the redirect — pass `false` (e.g. outside production) to present without navigating. */\n readonly enabled: boolean;\n}\n\n/**\n * Present a language picker and, on a new selection, reload the app at that locale's entry point.\n *\n * @remarks\n * A plain function (the `ActionSheetController` is passed in, so nothing is injected) that unifies the\n * language-switch flow duplicated across apps. On a changed selection while {@link enabled} it stashes\n * the current path in `sessionStorage` (so the app can return the user to where they were), records the\n * chosen locale in `localStorage` under `'locale'`, and calls `window.location.replace()` with the\n * app-provided URL. Because it performs navigation, it is a standalone helper rather than part of a\n * controller (mirroring `kitPresentReloadAlert` / `kitPresentAuthFailedAlert`). Centralizing it means a\n * future improvement to the switch flow lands in every app at once.\n *\n * @param actionSheetCtrl - the Ionic `ActionSheetController`\n * @param options - labels, locale list, and redirect configuration; see {@link KitLanguageActionSheetOptions}\n * @returns a Promise that resolves once presented (and, on a new selection, after the reload is triggered)\n * @example\n * ```ts\n * await kitPresentLanguageActionSheet(inject(ActionSheetController), {\n * header: $localize`言語設定`,\n * locales: [{ text: 'English', data: 'en-US' }, { text: '日本語', data: 'ja' }],\n * cancelText: $localize`キャンセル`,\n * currentLocale: normalizedLocale,\n * currentPath: this.#router.url,\n * pathnameStorageKey: StorageKeyEnum.pathnameBeforeRedirect,\n * buildRedirectUrl: (locale) => location.origin + (localePath[locale.toLowerCase()] ?? '/index.html'),\n * enabled: environment.production,\n * });\n * ```\n */\nexport const kitPresentLanguageActionSheet = async (\n actionSheetCtrl: ActionSheetController,\n options: KitLanguageActionSheetOptions,\n): Promise<void> => {\n const actionSheet = await actionSheetCtrl.create({\n header: options.header,\n buttons: [\n ...options.locales.map((locale) => ({ text: locale.text, data: locale.data })),\n { text: options.cancelText, role: 'cancel' },\n ],\n });\n await actionSheet.present();\n\n const { data } = await actionSheet.onDidDismiss();\n if (options.enabled && data && data !== options.currentLocale) {\n sessionStorage.setItem(options.pathnameStorageKey, options.currentPath);\n localStorage.setItem('locale', data);\n window.location.replace(options.buildRedirectUrl(data));\n }\n};\n","import type { OnInit } from '@angular/core';\nimport { computed, Directive, HostListener, inject, Injector, input } from '@angular/core';\nimport { FORM_FIELD } from '@angular/forms/signals';\nimport { KitStorageService } from '../storage/kit-storage.service';\nimport { kitForgetEmail, kitIsValidEmail, kitRecallEmail, kitRememberEmail } from '../storage/kit-auth-email-store';\n\n/**\n * The email persistence mode of {@link KitAuthInputDirective}.\n *\n * - `'email'` — sign-in email: prefill from storage, remember on change, and forget when cleared.\n * - `'email-remember'` — sign-up email: remember on change only, with no prefill or forget behavior.\n */\nexport type KitAuthInputMode = 'email' | 'email-remember';\n\n/**\n * Email persistence conveniences for an `ion-input`, applied via the `kitAuthInput` attribute.\n *\n * The `'email'` mode recalls the last entered address and seeds an empty Signal Forms field. Both\n * modes remember a well-formed address on `ionChange`; only `'email'` forgets a stored value when\n * the field is cleared or invalid. Browser and OS autofill always wins over an asynchronous prefill.\n *\n * @example\n * ```html\n * <ion-input type=\"email\" autocomplete=\"email\" kitAuthInput=\"email\" [formField]=\"form.email\" />\n * <ion-input type=\"email\" autocomplete=\"email\" kitAuthInput=\"email-remember\" [formField]=\"form.email\" />\n * ```\n *\n * @remarks\n * Prefill writes through the Signal Forms `FORM_FIELD` bound on the same element. With no field,\n * prefill is skipped while remember/forget still work from the DOM event. Storage is resolved lazily\n * so applications that do not configure `@ionic/storage` remain unaffected.\n */\n@Directive({\n selector: '[kitAuthInput]',\n standalone: true,\n})\nexport class KitAuthInputDirective implements OnInit {\n readonly #injector = inject(Injector);\n readonly #field = inject(FORM_FIELD, { optional: true, self: true });\n\n /** Required persistence mode; see {@link KitAuthInputMode}. */\n readonly kitAuthInput = input.required<KitAuthInputMode>();\n\n /** Seeds an empty sign-in email field from storage. */\n ngOnInit(): void {\n if (this.#prefills()) {\n void this.#prefillEmail();\n }\n }\n\n /** Remembers a valid committed email and applies the selected clearing policy. */\n @HostListener('ionChange', ['$event'])\n onIonChange(event: Event): void {\n const storage = this.#resolveStorage();\n if (!storage) {\n return;\n }\n const value = (event as CustomEvent<{ value?: string | null }>).detail?.value ?? '';\n if (value.trim().length > 0 && kitIsValidEmail(value)) {\n void kitRememberEmail(storage, value);\n } else if (this.#forgetsOnClear()) {\n void kitForgetEmail(storage);\n }\n }\n\n readonly #prefills = computed(() => this.kitAuthInput() === 'email');\n readonly #forgetsOnClear = computed(() => this.kitAuthInput() === 'email');\n\n #resolveStorage(): KitStorageService | null {\n try {\n return this.#injector.get(KitStorageService);\n } catch {\n return null;\n }\n }\n\n async #prefillEmail(): Promise<void> {\n const field = this.#field;\n if (!field) {\n return;\n }\n const storage = this.#resolveStorage();\n if (!storage) {\n return;\n }\n const last = await kitRecallEmail(storage);\n const state = field.state();\n if (last && !state.value()) {\n state.value.set(last);\n }\n }\n}\n","import type { ElementRef } from '@angular/core';\nimport { Capacitor } from '@capacitor/core';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Keyboard } from '@capacitor/keyboard';\n\n/**\n * How {@link kitKeyboardInit} adjusts the target element when the native keyboard appears.\n *\n * - `transform` — CSS `translateY(-keyboardHeight + safeAreaBottom)` for a smooth iOS animation\n * (typical for an `ion-footer`).\n * - `offset` — set the `--offset-bottom` custom property to the negative keyboard height.\n * - `keyboard-offset` — set the `--padding-bottom` custom property to the keyboard height.\n */\nexport type KitKeyboardAdjust = 'transform' | 'offset' | 'keyboard-offset';\n\nconst keyboardWillShow = (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardWillShow', (info) => {\n if (Capacitor.getPlatform() === 'android') {\n if (elementRef.nativeElement.tagName === 'ION-FOOTER' && type === 'transform') {\n // https://github.com/ionic-team/ionic-framework/blob/main/core/src/components/footer/footer.tsx\n elementRef.nativeElement.classList.remove('footer-toolbar-padding');\n }\n return;\n }\n\n elementRef.nativeElement.classList.add('show-keyboard');\n // SSR-safe: this callback only runs on a native keyboard event, so the global `document` /\n // `window` are never touched on the server (kitKeyboardInit returns early when not native).\n const bodyStyleDeclaration = window.getComputedStyle(document.querySelector('body') as Element);\n const safeArea = parseInt(bodyStyleDeclaration.getPropertyValue('--ion-safe-area-bottom'), 10);\n\n if (type === 'transform') {\n elementRef.nativeElement.style.transition = 'transform 420ms';\n elementRef.nativeElement.style.willChange = 'transform';\n requestAnimationFrame(() => (elementRef.nativeElement.style.transform = `translateY(${info.keyboardHeight * -1 + safeArea}px)`));\n } else {\n const property = type === 'offset' ? '--offset-bottom' : '--padding-bottom';\n const height = type === 'offset' ? info.keyboardHeight * -1 : info.keyboardHeight;\n requestAnimationFrame(() => {\n const keyboardOffset = elementRef.nativeElement.style.getPropertyValue('--keyboard-offset');\n if (!keyboardOffset || parseInt(keyboardOffset, 10) === 0) {\n elementRef.nativeElement.style.setProperty(property, `${height}px`);\n }\n });\n }\n });\n\nconst keyboardWillHide = (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardWillHide', () => {\n if (Capacitor.getPlatform() === 'android') {\n if (elementRef.nativeElement.tagName === 'ION-FOOTER' && type === 'transform') {\n elementRef.nativeElement.classList.add('footer-toolbar-padding');\n }\n return;\n }\n\n elementRef.nativeElement.classList.remove('show-keyboard');\n\n if (type === 'transform') {\n elementRef.nativeElement.style.transition = 'transform 0ms';\n elementRef.nativeElement.style.transform = `translateY(0px)`;\n elementRef.nativeElement.style.willChange = 'transform';\n } else {\n const property = type === 'offset' ? '--offset-bottom' : '--padding-bottom';\n elementRef.nativeElement.style.setProperty(property, '0px');\n }\n });\n\nconst keyboardDidShow = (elementRef: ElementRef): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardDidShow', () => {\n elementRef.nativeElement.style.willChange = 'auto';\n });\n\nconst keyboardDidHide = (elementRef: ElementRef): Promise<PluginListenerHandle> =>\n Keyboard.addListener('keyboardDidHide', () => {\n elementRef.nativeElement.style.willChange = 'auto';\n });\n\n/**\n * Register native keyboard listeners that reposition an element when the keyboard shows/hides.\n *\n * @remarks\n * A plain function — no DI needed (it reads the platform from `Capacitor` and uses the global\n * `document`), so a component calls it directly instead of injecting a controller. SSR-safe: the\n * global `document` / `window` are only read inside native keyboard-event callbacks, which never\n * fire on the server — the `Capacitor.isNativePlatform()` guard returns `[]` first, and nothing is\n * touched at module load. A no-op on non-native platforms (returns `[]`). On native it handles the\n * iOS/Android differences (Android\n * only toggles the `footer-toolbar-padding` class on an `ion-footer` for the `transform` mode,\n * working around an Ionic footer bug). The caller owns the returned handles and must `remove()`\n * them when the view is destroyed.\n *\n * @param elementRef - The element to reposition (e.g. an `ion-footer`).\n * @param type - The adjustment strategy; see {@link KitKeyboardAdjust}.\n * @returns The registered listener handles (empty on non-native platforms).\n * @example\n * ```ts\n * export class ComposePage {\n * readonly #footer = viewChild.required<ElementRef>('footer');\n * #handles: PluginListenerHandle[] = [];\n *\n * async ngAfterViewInit() {\n * this.#handles = await kitKeyboardInit(this.#footer(), 'transform');\n * }\n * ngOnDestroy() {\n * this.#handles.forEach((h) => h.remove());\n * }\n * }\n * ```\n */\nexport const kitKeyboardInit = async (elementRef: ElementRef, type: KitKeyboardAdjust): Promise<PluginListenerHandle[]> => {\n if (!Capacitor.isNativePlatform()) {\n return [];\n }\n return [\n await keyboardWillShow(elementRef, type),\n await keyboardWillHide(elementRef, type),\n await keyboardDidShow(elementRef),\n await keyboardDidHide(elementRef),\n ];\n};\n","import { DestroyRef, ErrorHandler, inject, Injectable, InjectionToken } from '@angular/core';\nimport type { Observable } from 'rxjs';\nimport { BehaviorSubject, Subscription } from 'rxjs';\n\n/** Access level currently granted to the application runtime. */\nexport type KitAuthAccessMode = 'none' | 'local' | 'remote';\n\n/** Generation lease that becomes stale as soon as a newer access transition starts. */\nexport interface KitAuthAccessLease {\n /** Whether work owned by this transition may still publish or persist access. */\n isCurrent(): boolean;\n}\n\n/**\n * Result of remote reauthentication, split into ordered activation and resume phases.\n *\n * @remarks\n * `activate` installs the remotely authenticated identity without starting transport. The kit then\n * publishes `remote` access and invokes `resume`, which may start pull, outbox replay, and realtime\n * work.\n */\nexport interface KitRemoteAccessRecovery {\n /**\n * Install the remotely verified identity, checking the lease again immediately before commit.\n *\n * @returns `false` when a newer logout or identity transition superseded this activation.\n */\n activate(lease: KitAuthAccessLease): Promise<boolean>;\n /**\n * Resume remote-only work after access has been published.\n *\n * @param lease - Post-grant lease supplied by the kit. Check it after every await before\n * navigation or other user-visible side effects, because logout or a newer identity transition\n * may supersede this resume while transport work is settling. Optional for source compatibility\n * with callers that manually resumed a recovery result before leases were introduced.\n */\n resume(lease?: KitAuthAccessLease): Promise<void>;\n /**\n * Whether route activation must wait for {@link resume} to settle.\n *\n * @remarks\n * Use `background` only when {@link activate} has already installed every identity and local\n * capability boundary required to render the route safely. Authentication denial still revokes\n * access; transport unavailability is handled by the configured recovery policy.\n *\n * @defaultValue 'blocking'\n */\n resumeMode?: 'blocking' | 'background';\n}\n\n/** Recovery-specific authentication configuration consumed by {@link KitAuthRecoveryService}. */\nexport interface KitAuthRecoveryConfig {\n /** Classifies transport unavailability; HTTP 401/403 are always denied before this callback. */\n isUnavailableError?(error: unknown): boolean;\n /** Optional online-recovery lifecycle used after local-only route access. */\n remoteRecovery?: {\n /**\n * Delay before probing authentication again while local access remains active.\n *\n * @defaultValue 30000\n */\n retryDelayMs?: number;\n availability(): Observable<boolean>;\n reauthenticate(lease: KitAuthAccessLease): Promise<KitRemoteAccessRecovery | false>;\n };\n}\n\n/** Internal alias of the application auth config used without a module cycle. */\nexport const KIT_AUTH_RECOVERY_CONFIG = new InjectionToken<KitAuthRecoveryConfig>('@rdlabo/ionic-angular-kit:auth-recovery');\n\n/** Shared runtime access state consumed by guards, UI, HTTP, and realtime connections. */\n@Injectable({ providedIn: 'root' })\nexport class KitAuthAccessService {\n readonly #mode = new BehaviorSubject<KitAuthAccessMode>('none');\n #revision = 0;\n\n /** Emits the current access mode and every later transition. */\n readonly mode$: Observable<KitAuthAccessMode> = this.#mode.asObservable();\n\n /** Current synchronous access mode. */\n get mode(): KitAuthAccessMode {\n return this.#mode.value;\n }\n\n /**\n * Monotonic runtime revision used to invalidate an in-flight access transition.\n *\n * @internal\n */\n get revision(): number {\n return this.#revision;\n }\n\n /**\n * Start a transition and invalidate every older asynchronous access decision.\n *\n * @param options - Set `suspendRemote` when the new decision must revoke published remote\n * capabilities immediately while keeping this new lease valid.\n */\n beginTransition(options: { suspendRemote?: boolean } = {}): KitAuthAccessLease {\n this.#revision += 1;\n const revision = this.#revision;\n if (options.suspendRemote && this.#mode.value === 'remote') {\n this.#mode.next('none');\n }\n return { isCurrent: () => this.#revision === revision };\n }\n\n /** Revoke published capabilities without invalidating the transition that owns `lease`. */\n suspend(lease: KitAuthAccessLease): boolean {\n if (!lease.isCurrent()) return false;\n if (this.#mode.value !== 'none') this.#mode.next('none');\n return true;\n }\n\n /** Publish a verified local-replica-only session. */\n grantLocal(): void {\n this.#publish('local');\n }\n\n /**\n * Publish a remotely authenticated session and return the lease that owns that publication.\n *\n * The revision is fixed before synchronous `mode$` subscribers run. A subscriber that starts a\n * newer logout or identity transition therefore makes the returned lease stale.\n */\n grantRemote(): KitAuthAccessLease {\n return this.#publish('remote');\n }\n\n /** Revoke both local and remote access. */\n clear(): void {\n this.#publish('none');\n }\n\n #publish(mode: KitAuthAccessMode): KitAuthAccessLease {\n this.#revision += 1;\n const revision = this.#revision;\n this.#mode.next(mode);\n return { isCurrent: () => this.#revision === revision };\n }\n}\n\n/** Coordinates single-flight recovery from local-only mode to remote access. */\n@Injectable({ providedIn: 'root' })\nexport class KitAuthRecoveryService {\n readonly #access = inject(KitAuthAccessService);\n readonly #config = inject(KIT_AUTH_RECOVERY_CONFIG);\n readonly #errorHandler = inject(ErrorHandler);\n readonly #destroyRef = inject(DestroyRef);\n #subscription: Subscription | null = null;\n #recovery: Promise<void> | null = null;\n #recoveryRevision: number | null = null;\n #retryTimer: ReturnType<typeof setTimeout> | null = null;\n #available = false;\n #retryRequested = false;\n #destroyed = false;\n\n constructor() {\n this.#destroyRef.onDestroy(() => {\n this.#destroyed = true;\n this.#clearRetry();\n this.#subscription?.unsubscribe();\n this.#subscription = null;\n });\n }\n\n /** Subscribe to the configured remote-availability stream once. */\n initialize(): void {\n if (this.#destroyed) return;\n const recovery = this.#config.remoteRecovery;\n if (!recovery || this.#subscription) return;\n this.#subscription = new Subscription();\n this.#subscription.add(\n recovery.availability().subscribe({\n next: (available) => {\n this.#available = available;\n if (available && this.#access.mode === 'local') {\n this.#clearRetry();\n void this.recover();\n } else if (this.#access.mode === 'local') {\n this.#scheduleRetry();\n }\n },\n error: (error) => this.#errorHandler.handleError(error),\n }),\n );\n this.#subscription.add(\n this.#access.mode$.subscribe((mode) => {\n if (mode !== 'local') {\n this.#clearRetry();\n return;\n }\n if (this.#available) {\n void this.recover();\n } else {\n this.#scheduleRetry();\n }\n }),\n );\n }\n\n /** Run one ordered remote recovery attempt, coalescing concurrent triggers. */\n async recover(): Promise<void> {\n if (this.#destroyed) return;\n if (this.#recovery) {\n if (this.#access.mode === 'local' && this.#recoveryRevision !== null && this.#access.revision > this.#recoveryRevision) {\n this.#retryRequested = true;\n }\n return this.#recovery;\n }\n const running = this.#runRecovery();\n this.#recoveryRevision = this.#access.revision;\n const promise = running.finally(() => {\n if (this.#recovery !== promise) return;\n this.#recovery = null;\n this.#recoveryRevision = null;\n if (this.#destroyed) return;\n if (!this.#retryRequested) return;\n this.#retryRequested = false;\n if (this.#access.mode !== 'local') return;\n if (this.#available) {\n void this.recover();\n } else {\n this.#scheduleRetry();\n }\n });\n this.#recovery = promise;\n return promise;\n }\n\n async #runRecovery(): Promise<void> {\n const recovery = this.#config.remoteRecovery;\n if (this.#destroyed || !recovery || this.#access.mode !== 'local') return;\n const lease = this.#access.beginTransition();\n let currentLease = lease;\n const isCurrent = (): boolean => currentLease.isCurrent();\n const executeRecovery = async (): Promise<void> => {\n const result = await recovery.reauthenticate(lease);\n if (this.#destroyed || !isCurrent() || this.#access.mode !== 'local') return;\n if (result === false) {\n this.#clearRetry();\n this.#access.clear();\n return;\n }\n if (!(await result.activate(lease)) || this.#destroyed || !isCurrent() || this.#access.mode !== 'local') {\n return;\n }\n this.#clearRetry();\n currentLease = this.#access.grantRemote();\n if (!currentLease.isCurrent()) return;\n await result.resume(currentLease);\n };\n await executeRecovery().catch((error: unknown) => {\n if (this.#destroyed || !isCurrent()) return;\n if (isExplicitAuthDenial(error)) {\n this.#clearRetry();\n this.#access.clear();\n } else if (this.#config.isUnavailableError?.(error)) {\n this.#scheduleRetry();\n } else {\n this.#errorHandler.handleError(error);\n }\n });\n }\n\n #scheduleRetry(): void {\n const recovery = this.#config.remoteRecovery;\n if (this.#destroyed || !recovery || this.#retryTimer || this.#access.mode !== 'local') return;\n this.#retryTimer = setTimeout(() => {\n this.#retryTimer = null;\n if (this.#access.mode === 'local') void this.recover();\n }, this.#retryDelayMs(recovery.retryDelayMs));\n }\n\n #clearRetry(): void {\n if (!this.#retryTimer) return;\n clearTimeout(this.#retryTimer);\n this.#retryTimer = null;\n }\n\n #retryDelayMs(configured: number | undefined): number {\n if (configured === undefined || !Number.isFinite(configured)) return 30_000;\n return Math.max(1_000, configured);\n }\n}\n\n/** Returns true for authoritative authentication denials that must never use local fallback. */\nexport function isExplicitAuthDenial(error: unknown): boolean {\n if (typeof error !== 'object' || error === null) return false;\n const status = (error as { status?: unknown }).status;\n return status === 401 || status === 403;\n}\n","import type { EnvironmentProviders } from '@angular/core';\nimport { ErrorHandler, inject, InjectionToken, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';\nimport type { CanActivateFn, RouterStateSnapshot, UrlTree } from '@angular/router';\nimport { Router } from '@angular/router';\nimport { NavController } from '@ionic/angular/common';\nimport type { Observable } from 'rxjs';\nimport { of, throwError } from 'rxjs';\nimport { catchError, map, mergeMap } from 'rxjs/operators';\nimport {\n isExplicitAuthDenial,\n type KitAuthAccessLease,\n type KitAuthRecoveryConfig,\n type KitRemoteAccessRecovery,\n KitAuthAccessService,\n KIT_AUTH_RECOVERY_CONFIG,\n KitAuthRecoveryService,\n} from './auth-access.service';\n\n/**\n * Discriminated set of authentication states the guards react to.\n *\n * @remarks\n * The application is responsible for emitting these values through {@link KitAuthConfig.authState}.\n * An application that does not use a value (for example email confirmation) simply never emits it.\n *\n * - `user` — fully authenticated and verified.\n * - `confirm` — awaiting email confirmation.\n * - `required` — not authenticated.\n * - `anonymous` — signed in anonymously; the user can still be guided toward full registration.\n */\nexport type KitAuthState = 'user' | 'confirm' | 'required' | 'anonymous';\n\n/**\n * Authentication states accepted by route guards.\n *\n * @remarks\n * `unavailable` means the authentication authority cannot currently be reached; this is distinct\n * from an explicit signed-out result. {@link KitAuthState} remains the original four-state union\n * so existing exhaustive consumers remain source-compatible.\n */\nexport type KitAuthGuardState = KitAuthState | 'unavailable';\n\n/**\n * Redirect targets (route paths) used by the guards when access is denied.\n *\n * @remarks\n * Every field is required and must be provided per application, because the guards have no\n * knowledge of the host application's route layout.\n */\nexport interface KitAuthRedirects {\n /** Used by {@link kitRequiredUnauthorizedGuard}: where to navigate when the user is already authenticated (`user`). */\n readonly whenAuthorized: string;\n /** Used by {@link kitRequiredUnauthorizedGuard}: where to navigate when the user is awaiting email confirmation (`confirm`). */\n readonly whenConfirming: string;\n /** Used by {@link kitRequireConfirmingGuard}: where to navigate when the state is not `confirm`. */\n readonly whenNotConfirming: string;\n /** Used by {@link kitRequireAuthorizedGuard}: where to navigate when the state is not `user` and the fallback is not allowed. */\n readonly whenUnauthorized: string;\n}\n\n/**\n * Configuration consumed by the authentication guards, injected through {@link provideKitAuth}.\n *\n * @remarks\n * `authState` and `redirects` are required. The `onAuthorized`, `onUnauthenticated`, and\n * `onUnavailable` hooks are optional. Without them the guard allows an authenticated user and\n * redirects unauthenticated or unavailable states, so an app only supplies hooks with real logic.\n */\nexport interface KitAuthConfig extends KitAuthRecoveryConfig {\n /**\n * Source of the current authentication state.\n *\n * @remarks\n * Typically backed by the application's own auth service (for example `AuthService.isAuth()`).\n *\n * @returns A stream of {@link KitAuthState} values.\n */\n authState(): Observable<KitAuthGuardState>;\n /**\n * Application-specific work that runs in {@link kitRequireAuthorizedGuard} after the state is confirmed to be `user`.\n *\n * @remarks\n * Typical responsibilities include token login, permission checks, terms-of-service acceptance,\n * or restoring a previously requested redirect. Optional; defaults to `true` (allow activation).\n *\n * @param state - The router state snapshot of the route being activated.\n * @param lease - Transition lease that product persistence must verify immediately before commit.\n * @returns `true` to allow activation, a `UrlTree` to perform a custom redirect, or a phased\n * remote activation that installs the session before transport work resumes.\n */\n onAuthorized?(state: RouterStateSnapshot, lease: KitAuthAccessLease): Promise<boolean | UrlTree | KitRemoteAccessRecovery>;\n /**\n * Fallback that runs in {@link kitRequireAuthorizedGuard} when the state is `required` (not authenticated).\n *\n * @remarks\n * For example, attempt an anonymous sign-in and allow the route. Optional; defaults to `false`\n * (fall through to the default `whenUnauthorized` redirect).\n *\n * @param state - The router state snapshot of the route being activated.\n * @param lease - Transition lease that product persistence must verify immediately before commit.\n * @returns `true` to allow activation, a `UrlTree` for a custom redirect, a phased remote\n * activation, or `false` to use the default redirect.\n */\n onUnauthenticated?(state: RouterStateSnapshot, lease: KitAuthAccessLease): Promise<boolean | UrlTree | KitRemoteAccessRecovery>;\n /**\n * Fallback that runs only when authentication is unavailable, never for an explicit\n * unauthenticated result.\n *\n * @remarks\n * This hook may authorize read/write access to a previously verified local replica. It must not\n * provide credentials to HTTP or realtime transports. Explicit sign-out and HTTP 401/403 must\n * remain unauthorized.\n *\n * @param state - The router state snapshot of the route being activated.\n * @param error - The classified transport error, or `undefined` when `authState` emitted\n * `unavailable`.\n * @param lease - Transition lease that local-session activation must verify before commit.\n * @returns `true` to allow local route activation, a `UrlTree` for a custom redirect, or `false`\n * to use the default redirect.\n */\n onUnavailable?(state: RouterStateSnapshot, error: unknown | undefined, lease: KitAuthAccessLease): Promise<boolean | UrlTree>;\n /** Redirect targets used by the guards. */\n redirects: KitAuthRedirects;\n}\n\n/**\n * Injection token that carries the {@link KitAuthConfig} to the authentication guards.\n */\nexport const KIT_AUTH_CONFIG = new InjectionToken<KitAuthConfig>('@rdlabo/ionic-angular-kit:auth');\n\n/**\n * Wire the authentication guard configuration into the application's dependency injection.\n *\n * @remarks\n * The factory runs inside an injection context, so it may call `inject()` (for example\n * `inject(AuthService)`) to build the configuration.\n *\n * @param configFactory - Factory that returns the {@link KitAuthConfig} for the application.\n * @returns Environment providers to add to the application bootstrap.\n *\n * @example\n * ```ts\n * provideKitAuth(() => {\n * const auth = inject(AuthService);\n * return {\n * // onAuthorized / onUnauthenticated are optional (default: allow / fall through to redirect).\n * authState: () => auth.isAuth(),\n * redirects: {\n * whenAuthorized: '/',\n * whenConfirming: '/auth/confirm',\n * whenNotConfirming: '/auth/signin',\n * whenUnauthorized: 'auth',\n * },\n * };\n * });\n * ```\n */\nexport const provideKitAuth = (configFactory: () => KitAuthConfig): EnvironmentProviders =>\n makeEnvironmentProviders([\n { provide: KIT_AUTH_CONFIG, useFactory: configFactory },\n { provide: KIT_AUTH_RECOVERY_CONFIG, useExisting: KIT_AUTH_CONFIG },\n provideAppInitializer(() => inject(KitAuthRecoveryService).initialize()),\n ]);\n\n/**\n * Guard that requires the user to be unauthenticated (for example sign-in or sign-up pages).\n *\n * @remarks\n * Allows the `required`, `anonymous`, and `unavailable` states (an anonymous user is permitted to\n * proceed to a registration page). An authenticated user (`user`) is sent to `whenAuthorized`, and\n * a user awaiting confirmation (`confirm`) is sent to `whenConfirming`.\n *\n * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'signin', component: SigninPage, canActivate: [kitRequiredUnauthorizedGuard] }];\n * ```\n */\nexport const kitRequiredUnauthorizedGuard: CanActivateFn = () => {\n const { authState, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n const access = inject(KitAuthAccessService);\n const lease = access.beginTransition({ suspendRemote: true });\n\n return authState().pipe(\n catchError((error) => {\n if (lease.isCurrent() && isExplicitAuthDenial(error)) access.clear();\n return throwError(() => error);\n }),\n map((data) => {\n if (!lease.isCurrent()) return false;\n if (data !== 'unavailable') access.clear();\n if (data === 'user') {\n navCtrl.setDirection('root');\n router.navigate([redirects.whenAuthorized]);\n return false;\n } else if (data === 'confirm') {\n router.navigate([redirects.whenConfirming]);\n return false;\n }\n // 'required' | 'anonymous' | 'unavailable'\n return true;\n }),\n );\n};\n\n/**\n * Guard that requires the user to be awaiting email confirmation (`confirm`).\n *\n * @remarks\n * Any other state triggers a redirect: an `anonymous` user is sent to the authenticated area\n * (`whenAuthorized`), and every remaining state is sent to `whenNotConfirming`.\n *\n * @returns A stream emitting `true` to allow activation, or `false` after triggering a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'confirm', component: ConfirmPage, canActivate: [kitRequireConfirmingGuard] }];\n * ```\n */\nexport const kitRequireConfirmingGuard: CanActivateFn = () => {\n const { authState, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n const access = inject(KitAuthAccessService);\n const lease = access.beginTransition({ suspendRemote: true });\n\n return authState().pipe(\n catchError((error) => {\n if (lease.isCurrent() && isExplicitAuthDenial(error)) access.clear();\n return throwError(() => error);\n }),\n map((data) => {\n if (!lease.isCurrent()) return false;\n if (data !== 'unavailable') access.clear();\n if (data === 'confirm') {\n return true;\n }\n navCtrl.setDirection('root');\n router.navigate([data === 'anonymous' ? redirects.whenAuthorized : redirects.whenNotConfirming]);\n return false;\n }),\n );\n};\n\n/**\n * Guard that requires the user to be fully authenticated (`user`).\n *\n * @remarks\n * - `user` — runs {@link KitAuthConfig.onAuthorized} (token login, permission checks, and so on).\n * - `anonymous` — allowed as-is, for applications that permit anonymous browsing.\n * - `unavailable` — runs {@link KitAuthConfig.onUnavailable}; this is the only state intended for\n * restored local-replica access.\n * - `required` / `confirm` — runs {@link KitAuthConfig.onUnauthenticated}; if it resolves to `false`,\n * the user is redirected to `whenUnauthorized`.\n *\n * @param _route - The activated route snapshot (unused).\n * @param state - The router state snapshot, forwarded to the configuration hooks.\n * @returns A stream emitting the activation result: `true`, a `UrlTree`, or `false` after a redirect.\n *\n * @example\n * ```ts\n * const routes: Routes = [{ path: 'home', component: HomePage, canActivate: [kitRequireAuthorizedGuard] }];\n * ```\n */\nexport const kitRequireAuthorizedGuard: CanActivateFn = (_route, state) => {\n const { authState, onAuthorized, onUnauthenticated, onUnavailable, isUnavailableError, redirects } = inject(KIT_AUTH_CONFIG);\n const router = inject(Router);\n const navCtrl = inject(NavController);\n const access = inject(KitAuthAccessService);\n const errorHandler = inject(ErrorHandler);\n const lease = access.beginTransition({ suspendRemote: true });\n\n const reportError = (error: unknown): void => {\n try {\n errorHandler.handleError(error);\n } catch {\n // Error reporting must not create an unhandled background rejection.\n }\n };\n\n const redirectUnauthorized = (currentLease: KitAuthAccessLease = lease): false => {\n if (!currentLease.isCurrent()) return false;\n access.clear();\n navCtrl.setDirection('root');\n router.navigate([redirects.whenUnauthorized]);\n return false;\n };\n const resolveUnavailable = async (error?: unknown): Promise<boolean | UrlTree> => {\n const resolveFallback = async (): Promise<boolean | UrlTree> => {\n const fallback = onUnavailable ? await onUnavailable(state, error, lease) : false;\n if (!lease.isCurrent()) return false;\n if (fallback === true) {\n access.grantLocal();\n return true;\n }\n if (fallback === false) return redirectUnauthorized();\n access.clear();\n return fallback;\n };\n return resolveFallback().catch((fallbackError: unknown) => {\n if (!lease.isCurrent()) return false;\n access.clear();\n throw fallbackError;\n });\n };\n const resolveRemote = async (result: boolean | UrlTree | KitRemoteAccessRecovery): Promise<boolean | UrlTree> => {\n if (!lease.isCurrent()) return false;\n if (isRemoteAccessActivation(result)) {\n if (!(await result.activate(lease)) || !lease.isCurrent()) return false;\n const resumeLease = access.grantRemote();\n if (!resumeLease.isCurrent()) return false;\n const resume = async (): Promise<void> => result.resume(resumeLease);\n const handleResumeError = (error: unknown): void => {\n if (!resumeLease.isCurrent()) return;\n if (isExplicitAuthDenial(error)) {\n if (result.resumeMode === 'background') {\n redirectUnauthorized(resumeLease);\n reportError(error);\n return;\n }\n access.clear();\n throw error;\n }\n if (!isUnavailableError?.(error)) throw error;\n };\n if (result.resumeMode === 'background') {\n void resume().catch((error: unknown) => {\n try {\n handleResumeError(error);\n } catch (unhandledError: unknown) {\n reportError(unhandledError);\n }\n });\n return resumeLease.isCurrent();\n }\n await resume().catch(handleResumeError);\n return resumeLease.isCurrent();\n }\n if (result === true) access.grantRemote();\n else access.clear();\n return result;\n };\n\n interface AuthEmission {\n authState: KitAuthGuardState;\n error?: unknown;\n }\n return authState().pipe(\n map((authState): AuthEmission => ({ authState })),\n catchError((error): Observable<AuthEmission> => {\n if (!lease.isCurrent()) return of({ authState: 'required' });\n if (isExplicitAuthDenial(error)) {\n access.clear();\n return throwError(() => error);\n }\n return isUnavailableError?.(error) ? of({ authState: 'unavailable', error }) : throwError(() => error);\n }),\n mergeMap(async ({ authState: data, error: authStateError }) => {\n if (!lease.isCurrent()) return false;\n if (data === 'user') {\n // 既定は「許可」。tokenLogin / 権限確認等が必要なアプリだけ onAuthorized を渡す。\n if (!onAuthorized) {\n if (!lease.isCurrent()) return false;\n access.grantRemote();\n return true;\n }\n const resolveAuthorized = async (): Promise<boolean | UrlTree> => {\n const result = await onAuthorized(state, lease);\n if (!lease.isCurrent()) return false;\n return resolveRemote(result);\n };\n return resolveAuthorized().catch((error: unknown) => {\n if (!lease.isCurrent()) return false;\n if (isExplicitAuthDenial(error)) {\n access.clear();\n throw error;\n }\n if (!isUnavailableError?.(error)) throw error;\n return resolveUnavailable(error);\n });\n }\n if (data === 'anonymous') {\n if (!lease.isCurrent()) return false;\n access.grantRemote();\n return true;\n }\n if (data === 'unavailable') {\n return resolveUnavailable(authStateError);\n }\n // `required` / `confirm` are authoritative denials. Revoke a previously verified local\n // capability before an anonymous-sign-in fallback (if any) is allowed to await.\n if (!access.suspend(lease)) return false;\n // 既定は false(whenUnauthorized へ)。匿名ログイン等のフォールバックが要るアプリだけ渡す。\n const fallback = onUnauthenticated ? await onUnauthenticated(state, lease) : false;\n if (!lease.isCurrent()) return false;\n if (fallback !== false) {\n return resolveRemote(fallback);\n }\n return redirectUnauthorized();\n }),\n );\n};\n\nfunction isRemoteAccessActivation(value: boolean | UrlTree | KitRemoteAccessRecovery): value is KitRemoteAccessRecovery {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'activate' in value &&\n typeof value.activate === 'function' &&\n 'resume' in value &&\n typeof value.resume === 'function'\n );\n}\n","import { NavigationCancel, NavigationEnd, NavigationError } from '@angular/router';\nimport type { Router } from '@angular/router';\nimport { filter, take } from 'rxjs';\n\ninterface LoginExchange<Identity, Result> {\n readonly identity: Identity;\n readonly promise: Promise<Result>;\n handoff: (() => boolean) | null;\n settledAt: number | null;\n}\n\n/** Shares an in-flight login and hands its startup result to authorization exactly once. */\nexport class KitAuthLoginExchange<Identity, Result> {\n #startedFor: Identity | undefined;\n #exchange: LoginExchange<Identity, Result> | null = null;\n\n /** Start once per signed-in identity; discard an unconsumed result when its navigation ends. */\n preload(identity: Identity, request: () => Promise<Result>, isCurrent: () => boolean): (() => void) | undefined {\n if (this.#startedFor === identity) return undefined;\n const exchange = this.#start(identity, request, isCurrent);\n void exchange.promise.catch(() => undefined);\n return () => {\n if (this.#exchange === exchange) this.clear();\n };\n }\n\n /** Consume a current startup result, share pending work, or perform a fresh login. */\n run(identity: Identity, request: () => Promise<Result>): Promise<Result> {\n const exchange = this.#exchange;\n if (\n exchange &&\n exchange.identity === identity &&\n (!exchange.handoff || (exchange.handoff() && (exchange.settledAt === null || Date.now() - exchange.settledAt < 30_000)))\n ) {\n exchange.handoff = null;\n if (exchange.settledAt !== null) this.#exchange = null;\n return exchange.promise;\n }\n return this.#start(identity, request, null).promise;\n }\n\n /** Forget startup state on sign-out; a later sign-in may preload again. */\n clear(): void {\n this.#exchange = null;\n this.#startedFor = undefined;\n }\n\n #start(identity: Identity, request: () => Promise<Result>, handoff: (() => boolean) | null): LoginExchange<Identity, Result> {\n const exchange: LoginExchange<Identity, Result> = {\n identity,\n handoff,\n settledAt: null,\n promise: request().finally(() => {\n exchange.settledAt = Date.now();\n if (!exchange.handoff && this.#exchange === exchange) this.#exchange = null;\n }),\n };\n this.#startedFor = identity;\n this.#exchange = exchange;\n return exchange;\n }\n}\n\n/** Bind an optional login preload to the active navigation and return cleanup for initialization failure. */\nexport function kitPreloadAuthLoginForNavigation(\n router: Pick<Router, 'currentNavigation' | 'events'>,\n preload: (isCurrent: () => boolean) => (() => void) | undefined,\n): () => void {\n const navigation = router.currentNavigation();\n const cancel = navigation ? preload(() => router.currentNavigation() === navigation) : undefined;\n const subscription = cancel\n ? router.events\n .pipe(\n filter(\n (event) =>\n (event instanceof NavigationEnd || event instanceof NavigationCancel || event instanceof NavigationError) &&\n event.id === navigation?.id,\n ),\n take(1),\n )\n .subscribe(() => cancel())\n : undefined;\n return () => {\n subscription?.unsubscribe();\n cancel?.();\n };\n}\n","import type { EnvironmentProviders } from '@angular/core';\nimport { inject, InjectionToken, makeEnvironmentProviders } from '@angular/core';\nimport type { HttpEvent, HttpInterceptorFn, HttpRequest } from '@angular/common/http';\nimport { HttpContextToken, HttpErrorResponse, HttpResponse } from '@angular/common/http';\nimport { Network } from '@capacitor/network';\nimport type { Observable } from 'rxjs';\nimport { from, retry, throwError, timer } from 'rxjs';\nimport { catchError, map, mergeMap, tap, timeout } from 'rxjs/operators';\nimport { isExplicitAuthDenial, KitAuthAccessService } from '../auth/auth-access.service';\n\n/**\n * Marks the narrowly scoped credential-exchange request that establishes remote access.\n *\n * @remarks\n * When shared auth access enforcement is enabled, the application starts in `none` (or may be\n * recovering from `local`) and therefore cannot make ordinary authenticated requests. The one\n * server request that verifies the current provider credential must set this context token. It\n * still runs the complete header, retry, denial, and error pipeline; only the pre-existing\n * `remote` access requirement is deferred until that exchange succeeds.\n */\nexport const KIT_AUTH_BOOTSTRAP_REQUEST = new HttpContextToken<boolean>(() => false);\n\n/**\n * Suppresses response-error notification hooks for requests whose caller owns the error UI.\n * Defaults to false. Errors still propagate unchanged; authentication recovery/replay,\n * access revocation, auth-header failure hooks, retries, and offline fallback remain active.\n */\nexport const KIT_SKIP_ERROR_NOTIFICATIONS = new HttpContextToken<boolean>(() => false);\n\n/**\n * Marks an auth-recovery replay so {@link KitHttpConfig.recoverAuthAccess} is not invoked again.\n *\n * @internal\n */\nconst KIT_AUTH_RECOVERY_REPLAY = new HttpContextToken<boolean>(() => false);\n\n/**\n * HTTP methods that are safe to retry automatically.\n *\n * @remarks\n * Non-idempotent methods (`POST` / `PATCH` / `DELETE`) are never auto-retried, because a response\n * lost *after* the server processed the write would be replayed into a duplicate write (\"saved twice\n * from one tap\"). A non-idempotent request that is genuinely safe to replay opts in by carrying an\n * `Idempotency-Key` header (which the server must honor).\n *\n * @internal\n */\nconst RETRYABLE_METHODS = ['GET', 'HEAD', 'OPTIONS'];\n\n/**\n * Transient HTTP statuses worth retrying: `0` (network/transport failure), `408` (request timeout),\n * `429` (rate limited), and the `502` / `503` / `504` gateway-availability family. Every other status\n * is thrown immediately — a whitelist is safer than a blacklist for deciding what to replay.\n *\n * @internal\n */\nconst RETRYABLE_STATUSES = [0, 408, 429, 502, 503, 504];\n\n/**\n * Maximum number of automatic retries for a retryable request.\n *\n * @internal\n */\nconst MAX_RETRIES = 2;\n\n/**\n * Fleet-wide per-request timeout. A request with no response within this window fails with a\n * synthetic `408` (a {@link RETRYABLE_STATUSES | retryable status}). Deliberately generous — it\n * catches a genuinely hung request (dead server) without cutting off legitimately slow work such as\n * a large upload or an AI generation. `timeout({ each })` resets on every emission, so a streaming\n * response that keeps emitting is unaffected.\n *\n * @internal\n */\nconst DEFAULT_TIMEOUT_MS = 60_000;\n\n/**\n * True when the error is the fleet maintenance short-circuit (`503` + body `code: 'MAINTENANCE'`).\n *\n * @remarks\n * Matches Angular `HttpErrorResponse` as `error.error?.code === 'MAINTENANCE'` (body top-level\n * `code`). Must not be retried and must not fall through to {@link KitHttpConfig.onServerBusy}.\n *\n * @param error - The failed response.\n * @returns Whether this is a maintenance response.\n */\nexport const isMaintenanceError = (error: HttpErrorResponse): boolean => error.status === 503 && error.error?.code === 'MAINTENANCE';\n\n/**\n * Parse a `Retry-After` header (delta-seconds or an HTTP-date) into milliseconds, or `null` when it\n * is absent or unparseable.\n *\n * @internal\n */\nconst parseRetryAfterMs = (error: HttpErrorResponse): number | null => {\n const header = error.headers?.get('Retry-After');\n if (!header) {\n return null;\n }\n const seconds = Number(header);\n if (Number.isFinite(seconds)) {\n return Math.max(0, seconds * 1000);\n }\n const dateMs = Date.parse(header);\n return Number.isNaN(dateMs) ? null : Math.max(0, dateMs - Date.now());\n};\n\n/**\n * Configuration that customizes the behavior of {@link kitAuthInterceptor}, injected through {@link provideKitHttp}.\n *\n * @remarks\n * The interceptor fixes the retry policy and control flow; only the hooks below are app-specific:\n *\n * - Retries only {@link RETRYABLE_METHODS | idempotent methods} (or a request bearing an\n * `Idempotency-Key`) on a {@link RETRYABLE_STATUSES | transient status}, up to {@link MAX_RETRIES}\n * times with a short jittered backoff (honoring `Retry-After`). Writes are never auto-retried.\n * - When the device is offline it fails fast to {@link KitHttpConfig.offlineFallback} instead of\n * waiting out the retries.\n * - On a final error it classifies by status and calls the matching hook (see each hook below).\n *\n * Only {@link KitHttpConfig.getAuthHeaders} is required — it has no safe default. Every other hook is\n * optional and defaults to a no-op (or `{}` / `false` / `null` as appropriate), so an app configures\n * only the behavior that actually differs from the canonical baseline.\n */\nexport interface KitHttpConfig {\n /**\n * Enforce the shared auth access mode before generating headers or using transport.\n *\n * @remarks\n * Optional and `false` by default for backward compatibility. In `local` mode the interceptor\n * consults `offlineFallback` without calling `getAuthHeaders` or transport. In `none` mode it\n * rejects without exposing local data. Real HTTP/auth-header 401/403 responses revoke access and\n * bypass `offlineFallback`.\n */\n enforceAuthAccessMode?: boolean;\n /**\n * Produce authentication and metadata headers for the outgoing request.\n *\n * @param request - The outgoing request about to be sent.\n * @returns A map of header names to values, resolved asynchronously.\n */\n getAuthHeaders(request: HttpRequest<unknown>): Promise<Record<string, string>>;\n /**\n * Produce additional headers for the outgoing request.\n *\n * @remarks\n * Optional; defaults to adding no extra headers.\n *\n * @param request - The outgoing request about to be sent.\n * @returns A map of header names to values; return `{}` when none are needed.\n */\n buildExtraHeaders?(request: HttpRequest<unknown>): Record<string, string>;\n /**\n * Treat an otherwise-successful response as an error.\n *\n * @remarks\n * Optional. Some backends use a 2xx status (for example `204` / `206`) to signal a condition the\n * app wants to surface as an error rather than a success. Return `true` to throw the response so it\n * flows through the error path; the status is not in {@link RETRYABLE_STATUSES}, so it is not\n * retried and propagates to the caller. Defaults to treating every 2xx as a success.\n *\n * @param response - The successful `HttpResponse` about to be delivered.\n * @returns `true` to reject the response as an error.\n */\n treatAsError?(response: HttpResponse<unknown>): boolean;\n /**\n * Called for every successful response that completed an actual network round trip.\n *\n * @remarks\n * Responses synthesized by {@link KitHttpConfig.offlineFallback} are produced after `catchError`\n * and therefore never reach this hook, so it observes genuine successes only. A typical use is to\n * reset an \"offline\" flag once connectivity is restored. Optional; defaults to a no-op.\n *\n * @param event - The successful `HttpResponse`.\n */\n onResponse?(event: HttpResponse<unknown>): void;\n /**\n * Decide whether to pass the request straight through, skipping auth, retry, and error handling.\n *\n * @remarks\n * Useful for external URLs such as S3 or a CDN. Optional; defaults to `false` (never bypass).\n *\n * @param request - The outgoing request.\n * @returns `true` to bypass the interceptor pipeline.\n */\n bypass?(request: HttpRequest<unknown>): boolean;\n /**\n * Provide an offline short-circuit when a request fails.\n *\n * @remarks\n * Returning a non-null observable replaces the error with that response (for example a queued\n * offline result). Optional; defaults to `null` (no fallback, normal error handling proceeds).\n * With shared access enforcement enabled, explicit 401/403 denials are never passed here.\n *\n * @param request - The request that failed (after headers were applied).\n * @param error - The error response that triggered the fallback.\n * @returns A replacement event stream, or `null` for no fallback.\n */\n offlineFallback?(request: HttpRequest<unknown>, error: HttpErrorResponse): Observable<HttpEvent<unknown>> | null;\n /**\n * Side effect to run on a `401` response (for example an expired token).\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param request - The request that received the `401`.\n * @param error - The complete response, including any explicit authentication failure scope.\n */\n onUnauthorized?(request: HttpRequest<unknown>, error: HttpErrorResponse): void;\n /**\n * Side effect to run on a `403` response (a permission error).\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param request - The request that received the `403`.\n * @param error - The complete permission-error response.\n */\n onForbidden?(request: HttpRequest<unknown>, error: HttpErrorResponse): void;\n /**\n * UX hook for a genuine network / transport failure (status `0`) while the device reports itself\n * connected — i.e. the server is unreachable rather than the phone being offline.\n *\n * @remarks\n * Optional; defaults to a no-op. Narrow by design: it fires only for status `0` (not for `404`,\n * `429`, `5xx`, …, which have their own hooks), so a \"connection lost, reload?\" prompt is not shown\n * for server-side problems. When the device is offline it is not called at all — `offlineFallback`\n * owns that path. The kit ships {@link KitReloadAlertController} as the canonical implementation\n * (with de-dup so concurrent failures show a single alert, and auto-dismiss on reconnect).\n *\n * @param status - The HTTP status code (`0`), or a string descriptor for non-HTTP failures.\n * @returns Optionally a promise to await before continuing.\n */\n onNetworkError?(status: number | string): Promise<void> | void;\n /**\n * UX hook for a transient server-availability failure (`502` / `503` / `504`), fired after retries\n * are exhausted.\n *\n * @remarks\n * Optional; defaults to a no-op. Distinct from {@link KitHttpConfig.onNetworkError} — the device's\n * connection is fine, the server is momentarily unavailable — so the app can say \"server busy, try\n * again shortly\" rather than prompt a reload. **Not** called for fleet maintenance (`503` with\n * `error.error?.code === 'MAINTENANCE'`) — that uses {@link KitHttpConfig.onMaintenance}.\n *\n * @param status - `502`, `503`, or `504`.\n * @param retryAfterSeconds - The server's `Retry-After` hint in seconds, when provided.\n */\n onServerBusy?(status: number, retryAfterSeconds?: number): void;\n /**\n * UX hook for fleet maintenance: HTTP `503` whose body has `code: 'MAINTENANCE'`.\n *\n * @remarks\n * Optional; defaults to a no-op. Fired **without retries** (maintenance is intentional, not\n * transient). Wire to {@link KitMaintenanceController.present} with the wait SSE URL so the lock\n * overlay auto-dismisses when maintenance ends.\n */\n onMaintenance?(): void;\n /**\n * UX hook for a `429 Too Many Requests` response, fired after retries are exhausted.\n *\n * @remarks\n * Optional; defaults to a no-op.\n *\n * @param retryAfterSeconds - The server's `Retry-After` hint in seconds, when provided.\n */\n onRateLimited?(retryAfterSeconds?: number): void;\n /**\n * UX hook for `400` / `409` / `422` / `500` responses that carry a server-provided message.\n *\n * @remarks\n * Optional; defaults to a no-op. Note that the message comes straight from the API; prefer a\n * user-facing `userMessage` / `code` in your error contract over showing a raw developer message.\n *\n * @param message - The message extracted from the error body.\n */\n onServerError?(message: string): void;\n /**\n * Side effect for a failure while *producing* the auth headers (`getAuthHeaders` rejected).\n *\n * @remarks\n * Optional; defaults to a no-op. Because the request is never sent in this case, it does not reach\n * the response-error hooks; classify it here (for example a failed token refresh) so it does not\n * fail silently.\n *\n * @param request - The request whose headers could not be produced.\n * @param error - The error thrown by `getAuthHeaders`.\n */\n onAuthError?(request: HttpRequest<unknown>, error: unknown): void;\n /**\n * Called when {@link KitHttpConfig.isAuthAccessDenial} classifies a failure as\n * global identity loss and shared remote access is revoked.\n *\n * @remarks\n * This hook is status-independent so an explicitly tagged historical 403\n * identity response reaches the same cleanup as a new 401 identity response.\n * Status hooks still run afterward for response-specific UX. Optional and\n * backward compatible.\n */\n onAuthAccessDenial?(request: HttpRequest<unknown>, error: unknown): void;\n /**\n * Classify whether an auth-related failure should revoke shared remote access.\n *\n * @remarks\n * Consulted only when {@link KitHttpConfig.enforceAuthAccessMode} is enabled and the failure is\n * an explicit authentication denial ({@link isExplicitAuthDenial | HTTP 401/403} or the same\n * status shape from {@link KitHttpConfig.getAuthHeaders}). Return `true` to call\n * {@link KitAuthAccessService.clear}; return `false` to keep the current access mode (for example\n * when a `403` is a resource permission error rather than a lost session). When omitted, both\n * `401` and `403` revoke access — the historical default.\n *\n * Regardless of the return value, explicit `401`/`403` responses never reach\n * {@link KitHttpConfig.offlineFallback}; the matching response hook\n * ({@link KitHttpConfig.onUnauthorized} / {@link KitHttpConfig.onForbidden}) still runs and the\n * error is rethrown. A rejection from `getAuthHeaders` has no response, so it calls only\n * {@link KitHttpConfig.onAuthError}.\n *\n * @param request - The outgoing request that failed (or whose headers could not be produced).\n * @param error - The `HttpErrorResponse` or header-production rejection.\n * @returns `true` when shared remote access should be cleared.\n */\n isAuthAccessDenial?(request: HttpRequest<unknown>, error: unknown): boolean;\n /**\n * Attempt to recover credentials after an explicit HTTP `401` / `403` before denial hooks run.\n *\n * @remarks\n * Invoked at most once per original request — only on the first explicit auth denial from the\n * server, and never on a recovery replay (which carries {@link KIT_AUTH_RECOVERY_REPLAY}). When\n * this hook resolves `true`, {@link KitHttpConfig.getAuthHeaders} is called again and the\n * original request is sent exactly once more with fresh auth and extra headers. A second denial\n * follows the normal revocation / status-hook path with no further recovery.\n *\n * Unlike transient transport retries, this replay is allowed for writes (`POST` / `PATCH` /\n * `DELETE`) because the server returned an explicit auth denial — the request was rejected\n * before (or without) being processed, not lost after a successful write. Apps must still ensure\n * {@link KitHttpConfig.recoverAuthAccess} only returns `true` when credentials were refreshed\n * and a single replay is safe for the endpoint.\n *\n * When the hook is absent, resolves `false`, or throws, the original {@link HttpErrorResponse}\n * is preserved and the existing denial / fallback pipeline runs unchanged; hook failures do not\n * replace the server error.\n *\n * @param request - The outgoing request that received the denial (before header merge).\n * @param error - The explicit `401` / `403` response.\n * @returns `true` to replay once with regenerated headers; `false` to proceed with normal denial handling.\n */\n recoverAuthAccess?(request: HttpRequest<unknown>, error: HttpErrorResponse): Promise<boolean>;\n}\n\n/**\n * Injection token that carries the {@link KitHttpConfig} to {@link kitAuthInterceptor}.\n */\nexport const KIT_HTTP_CONFIG = new InjectionToken<KitHttpConfig>('@rdlabo/ionic-angular-kit:http');\n\n/**\n * Wire the {@link kitAuthInterceptor} configuration into the application's dependency injection.\n *\n * @remarks\n * Register the interceptor itself separately via `provideHttpClient(withInterceptors([kitAuthInterceptor]))`.\n * The factory runs inside an injection context, so it may call `inject()`.\n *\n * @param configFactory - Factory that returns the {@link KitHttpConfig} for the application.\n * @returns Environment providers to add to the application bootstrap.\n *\n * @example\n * ```ts\n * bootstrapApplication(AppComponent, {\n * providers: [\n * provideHttpClient(withInterceptors([kitAuthInterceptor])),\n * provideKitHttp(() => {\n * const auth = inject(AuthService);\n * const reload = inject(KitReloadAlertController);\n * return {\n * // Only getAuthHeaders is required; every other hook is optional and defaults to a no-op.\n * getAuthHeaders: async () => ({ Authorization: `Bearer ${await auth.token()}` }),\n * onUnauthorized: () => auth.signOut(),\n * onNetworkError: (status) =>\n * reload.present({ header: 'Network error', message: `Reload? (${status})`, okText: 'Reload' }),\n * onResponse: () => void reload.dismiss(),\n * };\n * }),\n * ],\n * });\n * ```\n */\nexport const provideKitHttp = (configFactory: () => KitHttpConfig): EnvironmentProviders =>\n makeEnvironmentProviders([{ provide: KIT_HTTP_CONFIG, useFactory: configFactory }]);\n\n/**\n * True when shared remote access should be revoked for an auth-related failure.\n *\n * @remarks\n * Only meaningful when {@link KitHttpConfig.enforceAuthAccessMode} is enabled and\n * {@link isExplicitAuthDenial} already matched. When {@link KitHttpConfig.isAuthAccessDenial} is\n * omitted, every explicit denial revokes access (legacy default).\n *\n * @internal\n */\nconst shouldRevokeAuthAccess = (config: KitHttpConfig, req: HttpRequest<unknown>, error: unknown): boolean =>\n config.isAuthAccessDenial?.(req, error) ?? isExplicitAuthDenial(error);\n\n/**\n * Invoke {@link KitHttpConfig.recoverAuthAccess} without letting hook failures replace the server error.\n *\n * @internal\n */\nconst tryRecoverAuthAccess = async (\n config: KitHttpConfig,\n request: HttpRequest<unknown>,\n error: HttpErrorResponse,\n): Promise<boolean> => {\n if (!config.recoverAuthAccess) {\n return false;\n }\n const recover = async (): Promise<boolean | void> => config.recoverAuthAccess?.(request, error);\n return recover()\n .then((recovered) => recovered === true)\n .catch(() => false);\n};\n\n/**\n * Final error handling after retries and optional auth recovery have been exhausted.\n *\n * @internal\n */\nconst handleTransportError = (\n config: KitHttpConfig,\n access: KitAuthAccessService,\n req: HttpRequest<unknown>,\n error: HttpErrorResponse,\n isAuthBootstrap: boolean,\n): Observable<HttpEvent<unknown>> => {\n if (config.enforceAuthAccessMode && isExplicitAuthDenial(error)) {\n if (shouldRevokeAuthAccess(config, req, error)) {\n access.clear();\n config.onAuthAccessDenial?.(req, error);\n }\n dispatchError(config, req, error);\n return throwError(() => error);\n }\n if (!isAuthBootstrap) {\n const fallback = config.offlineFallback?.(req, error);\n if (fallback) {\n return fallback;\n }\n }\n dispatchError(config, req, error);\n return throwError(() => error);\n};\n\n/**\n * Classify a final (post-retry) error and invoke the matching {@link KitHttpConfig} hook.\n *\n * @internal\n */\nconst dispatchError = (config: KitHttpConfig, req: HttpRequest<unknown>, error: HttpErrorResponse): void => {\n if (req.context.get(KIT_SKIP_ERROR_NOTIFICATIONS)) return;\n\n const status = error.status;\n const retryAfterMs = parseRetryAfterMs(error);\n const retryAfterSeconds = retryAfterMs === null ? undefined : Math.round(retryAfterMs / 1000);\n\n if (status === 401) {\n config.onUnauthorized?.(req, error);\n } else if (status === 403) {\n config.onForbidden?.(req, error);\n } else if (status === 0) {\n // Genuine network/transport failure. Only surface it when the device is actually connected\n // (server unreachable); when offline, offlineFallback owns the UX — a reload prompt won't help.\n void Network.getStatus().then((network) => {\n if (network.connected) {\n config.onNetworkError?.(status);\n }\n });\n } else if (status === 429) {\n config.onRateLimited?.(retryAfterSeconds);\n } else if (isMaintenanceError(error)) {\n config.onMaintenance?.();\n } else if ([502, 503, 504].includes(status)) {\n config.onServerBusy?.(status, retryAfterSeconds);\n } else if ([400, 409, 422, 500].includes(status) && error.error?.message) {\n config.onServerError?.(error.error.message);\n }\n // Every other status (404, 418, …) is left to the caller — no generic alert.\n};\n\n/**\n * Canonical functional HTTP interceptor that applies authentication, retries, and error handling.\n *\n * @remarks\n * Behavior, driven by the injected {@link KitHttpConfig}:\n *\n * 1. Requests for which `bypass` returns `true` are forwarded untouched.\n * 2. If `getAuthHeaders` rejects, `onAuthError` is called and the request is not sent.\n * 3. Otherwise the headers from `getAuthHeaders` and `buildExtraHeaders` are merged onto a cloned request.\n * 4. On failure the request is retried up to {@link MAX_RETRIES} times, but **only** when the device\n * is online, the method is a {@link RETRYABLE_METHODS | retryable method} (or carries an\n * `Idempotency-Key`), and the status is a {@link RETRYABLE_STATUSES | transient status}. The\n * backoff is `retryCount * 500ms` plus up to 250ms of jitter, or the server's `Retry-After`.\n * When the device is offline it stops retrying immediately.\n * 5. On the first explicit HTTP `401`/`403`, {@link KitHttpConfig.recoverAuthAccess} may replay the\n * request once with regenerated headers before denial hooks run; recovery replays never recurse.\n * 6. On the final error, enforced 401/403 revokes shared access and is rejected before fallback.\n * For every other error, `offlineFallback` is consulted first; otherwise the error is classified by\n * status (see {@link dispatchError}): `401`→`onUnauthorized`, `403`→`onForbidden`, `0`→\n * `onNetworkError` (when connected), `429`→`onRateLimited`, maintenance `503`→`onMaintenance`,\n * other `502`/`503`/`504`→`onServerBusy`, and `400`/`409`/`422`/`500` with a body message→`onServerError`.\n *\n * @param request - The outgoing request.\n * @param next - The next handler in the interceptor chain.\n * @returns A stream of HTTP events for the (possibly modified, retried, or replaced) request.\n *\n * @example\n * ```ts\n * provideHttpClient(withInterceptors([kitAuthInterceptor]));\n * ```\n */\nexport const kitAuthInterceptor: HttpInterceptorFn = (request, next) => {\n const config = inject(KIT_HTTP_CONFIG);\n const access = inject(KitAuthAccessService);\n const isAuthBootstrap = request.context.get(KIT_AUTH_BOOTSTRAP_REQUEST);\n\n if (config.bypass?.(request)) {\n return next(request);\n }\n\n if (config.enforceAuthAccessMode && access.mode !== 'remote' && !isAuthBootstrap) {\n const error = new HttpErrorResponse({\n // `local` deliberately looks like a transport failure so an outer offline read interceptor\n // may resolve it. `none` must not use status 0, otherwise that interceptor could expose a\n // persisted replica before authentication.\n status: access.mode === 'local' ? 0 : 401,\n statusText: access.mode === 'local' ? 'Local access only' : 'Authentication required',\n url: request.url,\n });\n if (access.mode === 'local') {\n const fallback = config.offlineFallback?.(request, error);\n if (fallback) return fallback;\n }\n return throwError(() => error);\n }\n\n const sendAuthenticated = (outgoing: HttpRequest<unknown>, allowAuthRecovery: boolean): Observable<HttpEvent<unknown>> =>\n from(config.getAuthHeaders(outgoing)).pipe(\n catchError((headerError: unknown) => {\n // getAuthHeaders failed → the request is never sent; classify it instead of failing silently.\n if (config.enforceAuthAccessMode && isExplicitAuthDenial(headerError) && shouldRevokeAuthAccess(config, outgoing, headerError)) {\n access.clear();\n config.onAuthAccessDenial?.(outgoing, headerError);\n }\n config.onAuthError?.(outgoing, headerError);\n return throwError(() => headerError);\n }),\n mergeMap((authHeaders) => {\n const req = outgoing.clone({ setHeaders: { ...authHeaders, ...config.buildExtraHeaders?.(outgoing) } });\n const retryable = RETRYABLE_METHODS.includes(req.method) || req.headers.has('Idempotency-Key');\n\n const base = next(req).pipe(\n timeout({\n each: DEFAULT_TIMEOUT_MS,\n with: () => throwError(() => new HttpErrorResponse({ status: 408, statusText: 'Request Timeout', url: req.url })),\n }),\n );\n\n return base.pipe(\n map((event) => {\n // A backend may signal an error condition with a 2xx status (e.g. 204/206); surface it as an error.\n if (event instanceof HttpResponse && config.treatAsError?.(event)) {\n throw event;\n }\n return event;\n }),\n retry({\n count: MAX_RETRIES,\n delay: (error: HttpErrorResponse, retryCount: number) =>\n from(Network.getStatus()).pipe(\n mergeMap((network) => {\n // Offline → don't wait out the retries; fail fast so offlineFallback can take over.\n if (!network.connected) {\n return throwError(() => error);\n }\n // Only replay idempotent requests, and only on a transient status.\n // Maintenance 503 is intentional — never retry; go straight to onMaintenance.\n if (!retryable || !RETRYABLE_STATUSES.includes(error.status) || isMaintenanceError(error)) {\n return throwError(() => error);\n }\n // Short linear backoff (500ms, 1000ms, …) plus jitter to de-correlate a fleet of\n // clients reconnecting at once; the server's Retry-After wins when present.\n const backoff = parseRetryAfterMs(error) ?? retryCount * 500 + Math.random() * 250;\n return timer(backoff);\n }),\n ),\n }),\n tap((event) => {\n if (event instanceof HttpResponse) {\n config.onResponse?.(event);\n }\n }),\n catchError((error: HttpErrorResponse) => {\n const mayRecover =\n allowAuthRecovery &&\n isExplicitAuthDenial(error) &&\n !outgoing.context.get(KIT_AUTH_RECOVERY_REPLAY) &&\n config.recoverAuthAccess;\n\n if (mayRecover) {\n return from(tryRecoverAuthAccess(config, outgoing, error)).pipe(\n mergeMap((recovered) => {\n if (recovered) {\n const replay = outgoing.clone({\n context: outgoing.context.set(KIT_AUTH_RECOVERY_REPLAY, true),\n });\n return sendAuthenticated(replay, false);\n }\n return handleTransportError(config, access, req, error, isAuthBootstrap);\n }),\n );\n }\n return handleTransportError(config, access, req, error, isAuthBootstrap);\n }),\n );\n }),\n );\n\n return sendAuthenticated(request, true);\n};\n","/**\n * Shared lifecycle boundary carried by an authentication failure response.\n *\n * Only `identity` invalidates the application's global authenticated identity.\n * The other scopes retain it and let the owning feature handle recovery.\n */\nexport const AUTH_FAILURE_SCOPES = {\n identity: 'identity',\n reauthentication: 'reauthentication',\n credential: 'credential',\n} as const;\n\nexport type AuthFailureScope = (typeof AUTH_FAILURE_SCOPES)[keyof typeof AUTH_FAILURE_SCOPES];\n\nexport const AUTH_IDENTITY_INVALID_CODE = 'AUTH_IDENTITY_INVALID';\n\nexport interface AuthFailureBody {\n statusCode: 401 | 403;\n message: string;\n code: string;\n authFailureScope: AuthFailureScope;\n}\n\ntype UnknownRecord = Record<string, unknown>;\n\nconst isRecord = (value: unknown): value is UnknownRecord => typeof value === 'object' && value !== null;\n\nconst isAuthFailureScope = (value: unknown): value is AuthFailureScope =>\n Object.values(AUTH_FAILURE_SCOPES).some((scope) => scope === value);\n\n/**\n * Reads the explicit auth-failure scope from an Angular `HttpErrorResponse` or\n * from a body-like value. Tagged historical 403 identity responses are\n * supported for installed-client compatibility. Untagged 401/403 responses\n * intentionally return `null`.\n */\nexport const getAuthFailureScope = (error: unknown): AuthFailureScope | null => {\n if (!isRecord(error)) return null;\n\n const body = isRecord(error['error']) ? error['error'] : error;\n const status = typeof error['status'] === 'number' ? error['status'] : body['statusCode'];\n if (status !== 401 && status !== 403) return null;\n if (body['statusCode'] !== status || typeof body['code'] !== 'string') return null;\n\n const scope = body['authFailureScope'];\n if (!isAuthFailureScope(scope)) return null;\n if (status === 403 && scope !== AUTH_FAILURE_SCOPES.identity) return null;\n if (scope === AUTH_FAILURE_SCOPES.identity && body['code'] !== AUTH_IDENTITY_INVALID_CODE) return null;\n return scope;\n};\n\n/** True only for an explicitly tagged global identity failure. */\nexport const isIdentityAuthFailure = (error: unknown): boolean => getAuthFailureScope(error) === AUTH_FAILURE_SCOPES.identity;\n","import { App } from '@capacitor/app';\nimport type { PluginListenerHandle } from '@capacitor/core';\nimport { Network } from '@capacitor/network';\nimport { Injectable, Optional } from '@angular/core';\nimport type { Observable } from 'rxjs';\nimport { Subject, Subscription } from 'rxjs';\nimport { KitAuthAccessService } from '../auth/auth-access.service';\n\n/** One WebSocket endpoint and its ordered subprotocol list. URLs must be unique within a target set. */\nexport interface KitRealtimeSocketTarget {\n url: string;\n protocols: string[];\n}\n\n/** Realtime event shape required for self-echo identification. */\nexport interface KitRealtimeEvent {\n originId?: string;\n}\n\n/** An application event annotated with whether it originated from this client. */\nexport type KitClientRealtimeEvent<TEvent extends KitRealtimeEvent> = TEvent & { isSelf: boolean };\n\n/** Timing and protocol options for {@link KitRealtimeConnection}. */\nexport interface KitRealtimeConnectionOptions {\n clientId?: string;\n ping?: string;\n pong?: string;\n maxBackoffMs?: number;\n openTimeoutMs?: number;\n pingIntervalMs?: number;\n livenessTimeoutMs?: number;\n /** Require shared `remote` auth access before opening or retaining sockets. */\n requireRemoteAccess?: boolean;\n}\n\ninterface SocketHealth {\n key: string;\n lastActivityAt: number;\n openTimer: ReturnType<typeof setTimeout> | null;\n watchdog: KitRealtimeLivenessWatchdog;\n}\n\n/** Stable per-tab/application-run ID shared by realtime connections and write headers. */\nexport const KIT_REALTIME_CLIENT_ID = crypto.randomUUID();\n\n/** Convert an HTTP(S) endpoint to its WebSocket equivalent. */\nexport function toKitWebSocketUrl(url: string): string {\n const parsed = new URL(url);\n if (parsed.protocol === 'https:') {\n parsed.protocol = 'wss:';\n } else if (parsed.protocol === 'http:') {\n parsed.protocol = 'ws:';\n }\n return parsed.toString();\n}\n\n/** Build the standard application/auth/client WebSocket subprotocol list. */\nexport function kitRealtimeProtocols(\n protocol: string,\n options: { clientId?: string; authToken?: string; authPrefix?: string; clientPrefix?: string } = {},\n): string[] {\n const protocols = [protocol];\n if (options.authToken) {\n protocols.push(`${options.authPrefix ?? 'auth.'}${options.authToken}`);\n }\n protocols.push(`${options.clientPrefix ?? 'client.'}${options.clientId ?? KIT_REALTIME_CLIENT_ID}`);\n return protocols;\n}\n\n/** Detect a half-open WebSocket when no pong or event arrives before the timeout. */\nexport class KitRealtimeLivenessWatchdog {\n #timer: ReturnType<typeof setTimeout> | null = null;\n\n constructor(\n private readonly timeoutMs: number,\n private readonly onTimeout: () => void,\n ) {}\n\n /** Restart the liveness deadline after receiving server activity. */\n reset(): void {\n this.clear();\n this.#timer = setTimeout(() => {\n this.#timer = null;\n this.onTimeout();\n }, this.timeoutMs);\n }\n\n /** Cancel the current liveness deadline. */\n clear(): void {\n if (!this.#timer) {\n return;\n }\n clearTimeout(this.#timer);\n this.#timer = null;\n }\n}\n\n/**\n * Reconnecting Hibernation WebSocket client for Ionic/Capacitor applications.\n *\n * Subclasses provide connection intent and one or more targets. The base owns foreground/network\n * suspension, exponential backoff, open/liveness timeouts, runtime-friendly application pings,\n * target-scoped reconnect, and a resync signal after connectivity is restored.\n */\n@Injectable()\nexport abstract class KitRealtimeConnection<TEvent extends KitRealtimeEvent> {\n readonly #events$ = new Subject<KitClientRealtimeEvent<TEvent>>();\n readonly #reconnected$ = new Subject<void>();\n\n /** Client ID used to classify self echoes. */\n protected readonly listeners: PluginListenerHandle[] = [];\n\n #sockets = new Map<string, WebSocket>();\n readonly #health = new Map<WebSocket, SocketHealth>();\n #targets = new Map<string, KitRealtimeSocketTarget>();\n #opening = false;\n #generation = 0;\n #reconnectTimer: ReturnType<typeof setTimeout> | null = null;\n #reconnectPendingGeneration: number | null = null;\n #pingTimer: ReturnType<typeof setInterval> | null = null;\n #reconnectAttempt = 0;\n #isAppActive = true;\n #isNetworkConnected = true;\n #lifecycleRegistration: Promise<void> | null = null;\n #lifecycleGeneration = 0;\n #accessSubscription: Subscription | null = null;\n\n // Constructor injection keeps direct `new` compatibility for existing subclasses and tests.\n // eslint-disable-next-line @angular-eslint/prefer-inject\n constructor(@Optional() private readonly authAccess: KitAuthAccessService | null = null) {}\n\n /** All parsed events received by this connection. */\n readonly events$: Observable<KitClientRealtimeEvent<TEvent>> = this.#events$.asObservable();\n /** Emits after every fully established connection cycle, including the first, prompting a REST resync. */\n readonly reconnected$: Observable<void> = this.#reconnected$.asObservable();\n\n /** Override timing/protocol defaults in specialized clients or tests. */\n protected get realtimeOptions(): KitRealtimeConnectionOptions {\n return {};\n }\n\n get #options(): Required<KitRealtimeConnectionOptions> {\n const options = this.realtimeOptions;\n return {\n clientId: options.clientId ?? KIT_REALTIME_CLIENT_ID,\n ping: options.ping ?? 'ping',\n pong: options.pong ?? 'pong',\n maxBackoffMs: options.maxBackoffMs ?? 30_000,\n openTimeoutMs: options.openTimeoutMs ?? 15_000,\n pingIntervalMs: options.pingIntervalMs ?? 30_000,\n livenessTimeoutMs: options.livenessTimeoutMs ?? 70_000,\n requireRemoteAccess: options.requireRemoteAccess ?? false,\n };\n }\n\n /** Client ID used to classify self echoes. */\n get id(): string {\n return this.#options.clientId;\n }\n\n /** Whether every configured socket is currently open. */\n get isStreamOpen(): boolean {\n return (\n this.#targets.size > 0 &&\n this.#sockets.size === this.#targets.size &&\n [...this.#sockets.values()].every((socket) => socket.readyState === WebSocket.OPEN)\n );\n }\n\n /** Whether every configured socket has produced recent server activity. */\n get isStreamHealthy(): boolean {\n return (\n this.isStreamOpen &&\n [...this.#health.values()].every(({ lastActivityAt }) => Date.now() - lastActivityAt < this.#options.livenessTimeoutMs)\n );\n }\n\n protected abstract get shouldConnect(): boolean;\n protected abstract buildSocketTargets(): Promise<KitRealtimeSocketTarget[]>;\n\n get #canOpen(): boolean {\n const hasRemoteAccess = !this.#options.requireRemoteAccess || (this.authAccess !== null && this.authAccess.mode === 'remote');\n return this.shouldConnect && this.#isAppActive && this.#isNetworkConnected && hasRemoteAccess;\n }\n\n /** Hook used by authenticated clients to invalidate a token after handshake failure. */\n protected async handleConnectionFailure(): Promise<void> {\n return;\n }\n\n /** Parse a text WebSocket message into one or more domain events. */\n protected parseMessage(data: string): TEvent[] {\n const parsed = JSON.parse(data) as TEvent | TEvent[];\n return Array.isArray(parsed) ? parsed : [parsed];\n }\n\n /** Factory seam for platform-specific WebSocket implementations and unit tests. */\n protected createWebSocket(url: string, protocols: string[]): WebSocket {\n return new WebSocket(url, protocols);\n }\n\n /** Factory seam for Capacitor app-state listeners. */\n protected addAppStateListener(listener: (state: { isActive: boolean }) => void): Promise<PluginListenerHandle> {\n return App.addListener('appStateChange', listener);\n }\n\n /** Factory seam for Capacitor network-status listeners. */\n protected addNetworkStatusListener(listener: (status: { connected: boolean }) => void): Promise<PluginListenerHandle> {\n return Network.addListener('networkStatusChange', listener);\n }\n\n /** Register foreground/network listeners exactly once, cleaning up handles that resolve after disconnect. */\n protected async registerLifecycleListeners(): Promise<void> {\n if (this.listeners.length > 0) {\n return;\n }\n if (this.#lifecycleRegistration) {\n return this.#lifecycleRegistration;\n }\n const generation = this.#lifecycleGeneration;\n this.#lifecycleRegistration = (async () => {\n const appHandle = await this.addAppStateListener(({ isActive }) => {\n this.#isAppActive = isActive;\n if (this.#canOpen) {\n void this.open();\n } else {\n this.suspend();\n }\n });\n if (generation !== this.#lifecycleGeneration) {\n await appHandle.remove();\n return;\n }\n this.listeners.push(appHandle);\n\n const networkHandle = await this.addNetworkStatusListener(({ connected }) => {\n this.#isNetworkConnected = connected;\n if (this.#canOpen) {\n void this.open();\n } else {\n this.suspend();\n }\n });\n if (generation !== this.#lifecycleGeneration) {\n await networkHandle.remove();\n return;\n }\n this.listeners.push(networkHandle);\n })();\n await this.#lifecycleRegistration.finally(() => {\n this.#lifecycleRegistration = null;\n });\n }\n\n /** Remove all lifecycle listeners, including listeners whose async registration has not completed yet. */\n protected removeLifecycleListeners(): void {\n this.#lifecycleGeneration += 1;\n this.listeners.forEach((handle) => void handle.remove());\n this.listeners.length = 0;\n }\n\n /** Suspend sockets without changing the subclass connection intent. */\n protected suspend(): void {\n this.#clearReconnectTimer();\n this.#closeSockets();\n }\n\n /** Reset resync and backoff history when the owning session ends. */\n protected resetConnectionState(): void {\n this.#reconnectAttempt = 0;\n }\n\n /** Register lifecycle listeners and establish the currently requested targets. */\n protected async startConnection(): Promise<void> {\n this.#registerAccessListener();\n await this.registerLifecycleListeners();\n if (!this.shouldConnect) {\n this.removeLifecycleListeners();\n return;\n }\n await this.open();\n }\n\n /** End the current connection session and release all lifecycle resources. */\n protected stopConnection(): void {\n this.resetConnectionState();\n this.suspend();\n this.removeLifecycleListeners();\n this.#accessSubscription?.unsubscribe();\n this.#accessSubscription = null;\n }\n\n /** Rebuild targets while preserving the owning session's connection intent and listeners. */\n protected async refreshConnectionTargets(): Promise<void> {\n if (!this.shouldConnect) {\n return;\n }\n this.suspend();\n await this.open();\n }\n\n /** Open missing targets, preserving healthy sockets when another target fails. */\n protected async open(): Promise<void> {\n const hasMissingTarget = this.#targets.size === 0 || [...this.#targets.keys()].some((key) => !this.#sockets.has(key));\n if (!this.#canOpen || this.#opening || (this.#sockets.size > 0 && !hasMissingTarget)) {\n return;\n }\n this.#clearReconnectTimer();\n this.#opening = true;\n const generation = this.#generation;\n await this.#openGeneration(generation)\n .catch(() => this.#requestReconnect())\n .finally(() => {\n if (generation === this.#generation) this.#opening = false;\n });\n }\n\n /** Build and attach the sockets for one lifecycle generation. */\n async #openGeneration(generation: number): Promise<void> {\n const targets = await this.buildSocketTargets();\n if (!this.#canOpen || generation !== this.#generation) {\n return;\n }\n const nextTargets = new Map(targets.map((target) => [toKitWebSocketUrl(target.url), target]));\n for (const [key, socket] of this.#sockets) {\n if (nextTargets.has(key)) {\n continue;\n }\n const health = this.#health.get(socket);\n if (health) {\n this.#removeSocket(socket, health);\n }\n }\n this.#targets = nextTargets;\n if (this.#sockets.size === 0) {\n this.#clearPingTimer();\n }\n for (const target of targets) {\n const key = toKitWebSocketUrl(target.url);\n if (this.#sockets.has(key)) {\n continue;\n }\n const socket = this.createWebSocket(key, target.protocols);\n const health: SocketHealth = {\n key,\n lastActivityAt: 0,\n openTimer: null,\n watchdog: new KitRealtimeLivenessWatchdog(this.#options.livenessTimeoutMs, () => this.#connectionFailed(generation, socket)),\n };\n this.#sockets.set(key, socket);\n this.#health.set(socket, health);\n health.openTimer = setTimeout(() => this.#connectionFailed(generation, socket), this.#options.openTimeoutMs);\n\n socket.onopen = () => {\n if (generation !== this.#generation || this.#sockets.get(key) !== socket) {\n return;\n }\n this.#clearOpenTimer(health);\n this.#markActivity(health);\n this.#startPing();\n if (this.isStreamOpen) {\n this.#reconnectAttempt = 0;\n this.#reconnected$.next();\n }\n };\n socket.onmessage = ({ data }) => {\n if (generation !== this.#generation || this.#sockets.get(key) !== socket || typeof data !== 'string') {\n return;\n }\n this.#markActivity(health);\n if (data === this.#options.pong) {\n return;\n }\n let events: TEvent[];\n try {\n events = this.parseMessage(data);\n } catch {\n // Ignore malformed application messages while retaining the healthy socket.\n return;\n }\n for (const event of events) {\n this.#events$.next({ ...event, isSelf: event.originId === this.id });\n }\n };\n socket.onerror = () => this.#connectionFailed(generation, socket);\n socket.onclose = () => this.#connectionFailed(generation, socket);\n }\n }\n\n #registerAccessListener(): void {\n if (!this.#options.requireRemoteAccess || !this.authAccess || this.#accessSubscription) return;\n this.#accessSubscription = this.authAccess.mode$.subscribe((mode) => {\n if (mode === 'remote' && this.#canOpen) {\n void this.open();\n } else {\n this.suspend();\n }\n });\n }\n\n #connectionFailed(generation: number, socket: WebSocket): void {\n const health = this.#health.get(socket);\n if (generation !== this.#generation || !health || this.#sockets.get(health.key) !== socket) {\n return;\n }\n this.#removeSocket(socket, health);\n if (this.#sockets.size === 0) {\n this.#clearPingTimer();\n }\n this.#requestReconnect();\n }\n\n #requestReconnect(): void {\n const generation = this.#generation;\n if (!this.#canOpen || this.#reconnectPendingGeneration === generation || this.#reconnectTimer) {\n return;\n }\n this.#reconnectPendingGeneration = generation;\n void this.handleConnectionFailure()\n .catch((error: unknown) => console.error('[kitRealtime] connection failure hook failed', error))\n .finally(() => {\n if (this.#reconnectPendingGeneration === generation) {\n this.#reconnectPendingGeneration = null;\n }\n if (generation === this.#generation) {\n this.#scheduleReconnect();\n }\n });\n }\n\n #markActivity(health: SocketHealth): void {\n health.lastActivityAt = Date.now();\n health.watchdog.reset();\n }\n\n #startPing(): void {\n if (this.#pingTimer) {\n return;\n }\n this.#pingTimer = setInterval(() => {\n for (const socket of this.#sockets.values()) {\n if (socket.readyState === WebSocket.OPEN) {\n socket.send(this.#options.ping);\n }\n }\n }, this.#options.pingIntervalMs);\n }\n\n #closeSockets(): void {\n this.#generation += 1;\n this.#opening = false;\n this.#clearPingTimer();\n const sockets = this.#sockets;\n this.#sockets = new Map();\n this.#targets = new Map();\n for (const socket of sockets.values()) {\n const health = this.#health.get(socket);\n if (health) {\n this.#removeSocket(socket, health, false);\n }\n }\n }\n\n #removeSocket(socket: WebSocket, health: SocketHealth, removeFromCurrent = true): void {\n health.watchdog.clear();\n this.#clearOpenTimer(health);\n this.#health.delete(socket);\n if (removeFromCurrent && this.#sockets.get(health.key) === socket) {\n this.#sockets.delete(health.key);\n }\n socket.onopen = null;\n socket.onmessage = null;\n socket.onerror = null;\n socket.onclose = null;\n try {\n socket.close(1000, 'client suspended');\n } catch {\n // Reconnect processing continues even if a CONNECTING socket cannot close cleanly.\n }\n }\n\n #scheduleReconnect(): void {\n if (!this.#canOpen || this.#reconnectTimer) {\n return;\n }\n const delay = Math.min(1000 * 2 ** this.#reconnectAttempt, this.#options.maxBackoffMs);\n this.#reconnectAttempt += 1;\n this.#reconnectTimer = setTimeout(() => {\n this.#reconnectTimer = null;\n void this.open();\n }, delay);\n }\n\n #clearOpenTimer(health: SocketHealth): void {\n if (!health.openTimer) {\n return;\n }\n clearTimeout(health.openTimer);\n health.openTimer = null;\n }\n\n #clearPingTimer(): void {\n if (!this.#pingTimer) {\n return;\n }\n clearInterval(this.#pingTimer);\n this.#pingTimer = null;\n }\n\n #clearReconnectTimer(): void {\n if (!this.#reconnectTimer) {\n return;\n }\n clearTimeout(this.#reconnectTimer);\n this.#reconnectTimer = null;\n }\n}\n","/**\n * Merge a newly fetched page of items into an existing list by id, keeping the result sorted.\n *\n * Items are merged by the numeric `key` field. On a duplicate `key` the item from `arrayNew` wins\n * and replaces the one in `arrayOld`. Old items whose `key` falls *inside* the window spanned by\n * `arrayNew` (between its first and last `key`) are dropped, since the freshly fetched page is the\n * authoritative copy of that window; old items *outside* the window are kept. The merged items are\n * finally sorted by `key`, ascending or descending according to `order`.\n *\n * The algorithm is:\n * 1. If both inputs are empty, return an empty array.\n * 2. Read the first (`lead`) and last (`last`) `key` values of `arrayNew` as the bounds of the\n * page's window. Keep the old items whose `key` lies *outside* that window (at or beyond the\n * extremes) and drop those strictly inside it, handling both a high-to-low page (`lead > last`)\n * and a low-to-high page (`lead < last`). A single-value page (`lead === last`) keeps all old items.\n * 3. Remove old items whose `key` already exists in `arrayNew` (new wins on duplicates).\n * 4. Concatenate `arrayNew` with the surviving old items and sort by `key` in the requested\n * direction.\n *\n * @remarks\n * Designed for infinite-scroll / paginated list merging, where each fetched page may overlap the\n * previously held items and the server returns a contiguous, ordered window of records. The `key`\n * field is treated as a number for range comparison and sorting.\n *\n * @typeParam T - Element type of both arrays. Its `key` property must be a numeric value.\n * @param arrayOld - The previously accumulated list. May be empty or nullish-safe (empty when falsy).\n * @param arrayNew - The newly fetched page of items; its `key` range defines the window that its own\n * items replace, and its items take precedence on duplicates.\n * @param key - The property of `T` used as the unique, numeric id for matching, range filtering, and sorting.\n * @param order - Sort direction by `key`: `'ASC'` for ascending or `'DESC'` for descending. Defaults to `'DESC'`.\n * @param secondaryKey - Optional second property for extra de-duplication. When provided, any\n * surviving old item whose `secondaryKey` value matches that of *any* new item is dropped before\n * the `key` merge. Useful when a record keeps a stable `key` but its secondary identity changes\n * between pages (e.g. items keyed by `id` but also grouped by `parentId`). Omit to skip this step.\n * @returns A new array containing `arrayNew` merged with the out-of-window, non-duplicate old items, sorted by `key`.\n * @example\n * ```ts\n * interface Post {\n * id: number;\n * title: string;\n * }\n *\n * const loaded: Post[] = [\n * { id: 30, title: 'c' },\n * { id: 20, title: 'b' },\n * { id: 10, title: 'a' },\n * ];\n * const nextPage: Post[] = [\n * { id: 20, title: 'b (updated)' },\n * { id: 15, title: 'a.5' },\n * ];\n *\n * // Descending merge: id 30 lies above the new page's [15, 20] window so it is kept; id 20 is\n * // inside the window and is replaced by the new value; id 10 lies below the window and is kept.\n * const merged = arrayConcatById(loaded, nextPage, 'id', 'DESC');\n * // => [{ id: 30, title: 'c' }, { id: 20, title: 'b (updated)' }, { id: 15, title: 'a.5' }, { id: 10, title: 'a' }]\n * ```\n */\nexport const arrayConcatById = <T>(\n arrayOld: T[],\n arrayNew: T[],\n key: keyof T,\n order: 'ASC' | 'DESC' = 'DESC',\n secondaryKey?: keyof T,\n): T[] => {\n if (!arrayNew.length && !arrayOld.length) {\n return [];\n }\n const lead = arrayNew[0][key] as number;\n const last = arrayNew[arrayNew.length - 1][key] as number;\n\n const filteredOld = (arrayOld || []).filter((vol) => {\n const value = vol[key] as number;\n return (lead > last && (value >= lead || value <= last)) || (lead < last && (value <= lead || value >= last)) || lead === last;\n });\n\n const secondaryFilteredOld = secondaryKey\n ? filteredOld.filter((vol) => !arrayNew.some((element) => element[secondaryKey] === vol[secondaryKey]))\n : filteredOld;\n\n const oldData = secondaryFilteredOld.filter((vol) => !arrayNew.some((element) => element[key] === vol[key]));\n const data = arrayNew.concat(oldData);\n\n const direction = order === 'ASC' ? 1 : -1;\n return data.sort((a, b) => {\n const x = a[key] as number;\n const y = b[key] as number;\n if (x > y) {\n return direction;\n }\n if (x < y) {\n return direction * -1;\n }\n return 0;\n });\n};\n","/**\n * Order-independent deep equality check.\n *\n * @remarks\n * Returns `true` when `a` and `b` serialize to the same value after their (nested) object entries are\n * sorted by key, so property order does not affect the result. Intended for cheap \"did this state\n * object change?\" comparisons.\n *\n * Caveats of the JSON-serialization approach: values that JSON drops or coerces (`undefined`,\n * functions, `NaN`, `Date`, `Map`/`Set`) are compared by their serialized form, and array element\n * order is treated as significant (arrays are not reordered in a meaningful way). Use a structural\n * deep-equal library when those cases matter.\n *\n * @param a - First object.\n * @param b - Second object.\n * @returns `true` when the two objects are deeply equal ignoring key order.\n * @example\n * ```ts\n * objectEqual({ a: 1, b: 2 }, { b: 2, a: 1 }); // => true\n * objectEqual({ a: 1 }, { a: 2 }); // => false\n * ```\n */\nexport const objectEqual = (a: object, b: object): boolean => {\n if (Object.is(a, b)) {\n return true;\n }\n const sortDeep = (obj: unknown): unknown => {\n if (typeof obj !== 'object' || !obj) {\n return undefined;\n }\n return Object.entries(obj)\n .sort()\n .map(([entryKey, value]) => [entryKey, typeof value === 'object' ? sortDeep(value) : value]);\n };\n return JSON.stringify(sortDeep(a)) === JSON.stringify(sortDeep(b));\n};\n","type DisableableElement = HTMLElement & { disabled: boolean };\ninterface DisableState {\n count: number;\n original: boolean;\n}\n\nconst disableStates = new WeakMap<DisableableElement, DisableState>();\n\nconst isDisableable = (element: EventTarget | null): element is DisableableElement =>\n element instanceof HTMLElement && 'disabled' in element;\n\nconst getIonicSubmitButtons = (form: HTMLFormElement): DisableableElement[] =>\n Array.from(document.querySelectorAll<HTMLElement>('ion-button[type=\"submit\"]')).filter((button): button is DisableableElement => {\n if (!isDisableable(button)) return false;\n\n const associatedForm = (button as HTMLElement & { form?: HTMLFormElement | string }).form;\n return (\n associatedForm === form ||\n (typeof associatedForm === 'string' && associatedForm === form.id) ||\n (form.id !== '' && button.getAttribute('form') === form.id) ||\n button.closest('form') === form\n );\n });\n\nconst getDisableTargets = (event: Event): DisableableElement[] => {\n const submitter = 'submitter' in event ? (event as SubmitEvent).submitter : null;\n const form = event.target instanceof HTMLFormElement ? event.target : null;\n const targets: DisableableElement[] = [];\n\n if (event.type === 'submit' && form) {\n targets.push(...getIonicSubmitButtons(form));\n }\n\n if (isDisableable(submitter)) {\n const root = submitter.getRootNode();\n const target = root instanceof ShadowRoot ? root.host : submitter;\n if (isDisableable(target)) targets.push(target);\n }\n\n if (targets.length === 0 && isDisableable(event.currentTarget)) targets.push(event.currentTarget);\n if (targets.length === 0 && isDisableable(event.target)) targets.push(event.target);\n return [...new Set(targets)];\n};\n\nconst acquireDisableTarget = (target: DisableableElement): void => {\n const state = disableStates.get(target);\n if (state) {\n state.count += 1;\n return;\n }\n disableStates.set(target, { count: 1, original: target.disabled });\n target.disabled = true;\n};\n\nconst releaseDisableTarget = (target: DisableableElement): void => {\n const state = disableStates.get(target);\n if (!state) return;\n state.count -= 1;\n if (state.count > 0) return;\n target.disabled = state.original;\n disableStates.delete(target);\n};\n\n/**\n * Disable the controls that triggered an event while an async operation runs.\n *\n * @remarks\n * For a click event, the clicked control is disabled. For a submit event, the submitter is\n * disabled and the browser's default form navigation is prevented. Ionic's external\n * `ion-button[form]` uses a hidden native submitter, so buttons associated with the submitted form\n * are resolved through their `form` property and disabled instead. Rejections are swallowed so\n * controls always recover; handle errors inside `work` when the caller needs to react.\n *\n * @param event - The click or submit event that triggered the operation.\n * @param work - The operation result. Promise-like work keeps controls disabled until it settles;\n * void work still shares this entry point and submit prevention without a synthetic async boundary.\n * @returns A Promise for asynchronous work, otherwise void.\n * @example\n * ```html\n * <form #formRef (submit)=\"helper.disableHandler($event, save())\"></form>\n * <ion-button type=\"submit\" [form]=\"formRef\">Save</ion-button>\n * ```\n */\nexport function disableHandler(event: Event, work: void): void;\nexport function disableHandler(event: Event, work: PromiseLike<unknown>): Promise<void>;\nexport function disableHandler(event: Event, work: void | PromiseLike<unknown>): void | Promise<void>;\nexport function disableHandler(event: Event, work: void | PromiseLike<unknown>): void | Promise<void> {\n if (event.type === 'submit') event.preventDefault();\n\n if (work === undefined) return;\n\n const targets = getDisableTargets(event);\n targets.forEach(acquireDisableTarget);\n\n const restore = () => targets.forEach(releaseDisableTarget);\n return new Promise<unknown>((resolve) => resolve(work)).then(restore, restore);\n}\n","import { WritableSignal } from '@angular/core';\n\n/**\n * Toggle the `disabled` flag of a signal-held `ion-infinite-scroll` / `ion-refresher` element.\n *\n * @remarks\n * A tiny pure helper for the common pattern of stashing the completing scroll/refresher element in a\n * signal (e.g. captured from the event) and later enabling/disabling it — for instance disabling\n * infinite scroll once the last page has loaded. A no-op when the signal holds no element.\n *\n * @param completeEvent - a writable signal holding the infinite-scroll / refresher element (or nullish)\n * @param disabled - the value to set on the element's `disabled` property\n * @example\n * ```ts\n * const infinite = signal<HTMLIonInfiniteScrollElement | null>(null);\n * // ...on ionInfinite: infinite.set(ev.target); ...when no more pages:\n * kitChangeEventDisabled(infinite, true);\n * ```\n */\nexport const kitChangeEventDisabled = (\n completeEvent: WritableSignal<HTMLIonInfiniteScrollElement | HTMLIonRefresherElement | null | undefined>,\n disabled: boolean,\n): void => {\n const event = completeEvent();\n if (event) {\n event.disabled = disabled;\n }\n};\n","import { ElementRef } from '@angular/core';\nimport { Observable, startWith } from 'rxjs';\n\n/**\n * Observe an Ionic page's \"is currently entered\" state from its lifecycle DOM events.\n *\n * @remarks\n * Emits `true` on `ionViewDidEnter` and `false` on `ionViewWillEnter` / `ionViewWillLeave`, seeded\n * with `false` via `startWith`. Useful to pause/resume work (timers, video, expensive rendering)\n * while a page is off-screen in Ionic's stack navigation, without wiring the four lifecycle hooks by\n * hand. The listeners are removed when the Observable is unsubscribed.\n *\n * @param el - an `ElementRef` for the page host element (the `ion-page`)\n * @returns an Observable that emits whether the page is currently entered\n * @example\n * ```ts\n * export class FeedPage {\n * readonly #host = inject(ElementRef);\n * readonly isEntered = toSignal(kitCreateDidEnter(this.#host), { initialValue: false });\n * }\n * ```\n */\nexport const kitCreateDidEnter = (el: ElementRef): Observable<boolean> => {\n return new Observable<boolean>((observer) => {\n const willEnter = () => observer.next(false);\n const didEnter = () => observer.next(true);\n const willLeave = () => observer.next(false);\n\n el.nativeElement.addEventListener('ionViewWillEnter', willEnter);\n el.nativeElement.addEventListener('ionViewDidEnter', didEnter);\n el.nativeElement.addEventListener('ionViewWillLeave', willLeave);\n\n return () => {\n el.nativeElement.removeEventListener('ionViewWillEnter', willEnter);\n el.nativeElement.removeEventListener('ionViewDidEnter', didEnter);\n el.nativeElement.removeEventListener('ionViewWillLeave', willLeave);\n };\n }).pipe(startWith(false));\n};\n","import { afterNextRender } from '@angular/core';\nimport type { InputSignal, InputSignalWithTransform, OutputEmitterRef, Signal } from '@angular/core';\n\n/**\n * Component のうち Signal(computed / input / viewChild 等)と `output()` だけを\n * ViewModel から見えるようにする型。`vm` は循環参照になるため除外する。\n *\n * 注意: `new ViewModel(this)` の引数型に直接使うと、vm 依存 computed の推論と循環する。\n * ViewModelStore 側は constructor(host: Component) で受け、`mountViewModel()` により\n * `ViewModelHost<Component, Keys>` へ絞り込むこと(呼び出し点では mapped type を展開しない)。\n */\nexport type ReactiveHost<T> = Pick<\n T,\n {\n [K in Exclude<keyof T, 'vm'>]-?: T[K] extends Signal<unknown> ? K : T[K] extends OutputEmitterRef<any> ? K : never;\n }[Exclude<keyof T, 'vm'>]\n>;\n\n/**\n * ViewModel に公開する Component の Signal と、明示的に許可した非 Signal property。\n */\nexport type ViewModelHost<T, K extends keyof T = never> = ReactiveHost<T> & Pick<T, K>;\n\n/**\n * Component host を ViewModel 用に絞り込み、初回 render 後の mount hook を登録する。\n */\nexport function mountViewModel<T, K extends keyof T = never>(host: T, onMount?: () => void): ViewModelHost<T, K> {\n if (onMount) {\n afterNextRender(onMount);\n }\n return host as ViewModelHost<T, K>;\n}\n\n/**\n * Modal / page に渡す props オブジェクトを、Angular `input()` の InputSignal 形に写す型。\n * `implements ComponentPropsType<Props>` で component 側の input 宣言を揃える。\n */\nexport type ComponentPropsType<T> = {\n [K in keyof T]: InputSignal<T[K]> | InputSignalWithTransform<T[K], any>;\n};\n","/*\n * Public API Surface of @rdlabo/ionic-angular-kit\n */\n\n// Storage: typed wrapper around the platform key/value store.\nexport * from './lib/storage/kit-storage.service';\n// Remember/recall the last entered sign-in email (validated; storage-agnostic helpers).\nexport * from './lib/storage/kit-auth-email-store';\n// Canonical keys (email + theme) for clear-preserving lists.\nexport * from './lib/storage/kit-storage-keys';\n// Clear storage while restoring selected keys (e.g. last sign-in email on logout).\nexport * from './lib/storage/kit-clear-storage';\n\n// Overlay: wrapper around the Ionic Modal / Toast / Alert controllers.\nexport * from './lib/overlay/overlay-config';\nexport * from './lib/overlay/kit-overlay.controller';\nexport * from './lib/overlay/kit-loading.controller';\nexport * from './lib/overlay/kit-reload-alert.controller';\nexport * from './lib/overlay/kit-maintenance.controller';\nexport * from './lib/overlay/kit-auth-failed-alert';\nexport * from './lib/overlay/kit-language-action-sheet';\n\n// Directives.\nexport * from './lib/directives/auth-input.directive';\n\n// Keyboard: native keyboard reposition listeners.\nexport * from './lib/keyboard/kit-keyboard';\n\n// Theme (`@rdlabo/ionic-angular-kit/theme`), Review (`.../review`), Printer (`.../printer`),\n// Offline (`.../offline`) and\n// Firebase auth (`.../auth-firebase`) are separate secondary entry points so their heavy native peers\n// (status-bar / in-app-review+preferences / brotherprint+dom-to-image / firebase) are\n// only pulled in by apps that import those subpaths.\n\n// Auth: functional route guards.\nexport * from './lib/auth/auth-access.service';\nexport * from './lib/auth/auth-guards';\nexport * from './lib/auth/auth-login-exchange';\n\n// HTTP: functional interceptor.\nexport * from './lib/http/kit-http.interceptor';\nexport * from './lib/http/auth-failure';\n\n// Realtime: reconnecting Hibernation WebSocket client infrastructure.\nexport * from './lib/realtime/kit-realtime-connection';\n\n// Utils: framework-agnostic pure helpers.\nexport * from './lib/utils/haptics';\nexport * from './lib/utils/array';\nexport * from './lib/utils/object';\nexport * from './lib/utils/dom';\nexport * from './lib/utils/ionic-scroll-event';\nexport * from './lib/utils/ionic-view-enter';\n\n// Types: shared Component / ViewModel helpers.\nexport * from './lib/types/component';\n","/**\n * Generated bundle index. Do not edit.\n */\n\nexport * from './public-api';\n"],"names":["i1.KitAuthAccessService"],"mappings":";;;;;;;;;;;;;;;;;;;;AAGA;;;;;;;;;;;;;;;;;;;;;AAqBG;MAIU,iBAAiB,CAAA;;IAEnB,MAAM,GAAqB,MAAM,CAAC,OAAO,CAAC,CAAC,MAAM,EAAE;AAE5D;;;;;;;;;;;AAWG;AACH,IAAA,MAAM,GAAG,CAAI,GAAW,EAAE,KAAQ,EAAA;AAChC,QAAA,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,EAAE,KAAK,CAAC;IAC3C;AAEA;;;;;;;;;;AAUG;IACH,MAAM,GAAG,CAAI,GAAW,EAAA;AACtB,QAAA,OAAO,CAAC,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,KAAK,IAAI;IACrD;AAEA;;;;;AAKG;IACH,MAAM,MAAM,CAAC,GAAW,EAAA;QACtB,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,MAAM,CAAC,GAAG,CAAC;IACvC;AAEA;;;;AAIG;AACH,IAAA,MAAM,KAAK,GAAA;QACT,MAAM,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,KAAK,EAAE;IACnC;AAEA;;;;AAIG;AACH,IAAA,MAAM,IAAI,GAAA;QACR,OAAO,CAAC,MAAM,IAAI,CAAC,MAAM,EAAE,IAAI,EAAE;IACnC;8GA7DW,iBAAiB,EAAA,IAAA,EAAA,EAAA,EAAA,MAAA,EAAA,EAAA,CAAA,eAAA,CAAA,UAAA,EAAA,CAAA,CAAA;AAAjB,IAAA,SAAA,IAAA,CAAA,KAAA,GAAA,EAAA,CAAA,qBAAA,CAAA,EAAA,UAAA,EAAA,QAAA,EAAA,OAAA,E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