@rdlabo/ionic-angular-kit 21.6.11 → 22.0.0-0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,1337 +1,47 @@
1
1
  # @rdlabo/ionic-angular-kit
2
2
 
3
- A small ergonomic kit for Ionic Angular applications. It provides:
3
+ `@rdlabo/ionic-angular-kit` provides shared application infrastructure for Ionic Angular applications. It keeps product-specific screens, domain policy, and translations in the consuming app.
4
4
 
5
- **Documentation:** [Read the full documentation](https://docs.rdlabo.dev/projects/ionic-angular-kit)
6
-
7
- - **KitStorageService** — a typed, write-loss-safe wrapper around `@ionic/storage-angular`
8
- - **KitOverlayController** — a unified presenter for Ionic Modal, Toast, and Alert
9
- - **Auth guards** — functional guards plus shared `none` / `local` / `remote` runtime access
10
- - **HTTP interceptor** — a fleet-canonical auth + retry + error-hook interceptor
11
- - **KitRealtimeConnection** — foreground/network-aware Hibernation WebSocket reconnect and resync
12
- - **KitAuthInputDirective** — sign-in email remember/prefill + iOS autofill workaround for `ion-input`
13
- - **kitClearStoragePreservingKeys** — `clear()` that restores selected keys (`KIT_LAST_AUTH_EMAIL_KEY`, `KIT_THEME_STORAGE_KEY`, …)
14
-
15
- ---
16
-
17
- ## Install
18
-
19
- ```bash
5
+ ```sh
20
6
  npm install @rdlabo/ionic-angular-kit
21
- # prereleases (np: X.Y.Z-N) are on the npm dist-tag `beta`:
22
- # npm install @rdlabo/ionic-angular-kit@beta
23
- ```
24
-
25
- Kit shares the repo `v*` release line with the other libraries (see root README § Release).
26
-
27
- ### Peer dependencies
28
-
29
- | Package | Version |
30
- | ------------------------------------ | ---------------- |
31
- | `@angular/common` | `^21.0.0` |
32
- | `@angular/core` | `^21.0.0` |
33
- | `@angular/router` | `^21.0.0` |
34
- | `@ionic/angular` | `^8.0.0` |
35
- | `@ionic/storage-angular` | `^4.0.0` |
36
- | `@capacitor/core` | `>=6.0.0 <9.0.0` |
37
- | `@capacitor/app` | `>=6.0.0 <9.0.0` |
38
- | `@capacitor/haptics` | `>=6.0.0 <9.0.0` |
39
- | `@capacitor/keyboard` | `>=6.0.0 <9.0.0` |
40
- | `@capacitor/network` | `>=6.0.0 <9.0.0` |
41
- | `@capacitor/preferences` | `>=6.0.0 <9.0.0` |
42
- | `@capacitor/status-bar` | `>=6.0.0 <9.0.0` |
43
- | `@capacitor-community/in-app-review` | `>=6.0.0 <9.0.0` |
44
- | `@rdlabo/capacitor-brotherprint` | `>=6.0.0 <9.0.0` |
45
- | `dom-to-image-more` | `^3.0.0` |
46
- | `rxjs` | `^7.8.0` |
47
-
48
- Feature-scoped peers are only needed by the features that use them (`status-bar` → `KitThemeController`; `preferences` + `in-app-review` → `kitRequestReview`; `capacitor-brotherprint` + `dom-to-image-more` → the Brother/PNG printer helpers; `pdf-lib` → the PDF printer helper); an app that doesn't use a feature can ignore its unmet-peer warning.
49
-
50
- ---
51
-
52
- ## Features
53
-
54
- ### KitRealtimeConnection
55
-
56
- An abstract Hibernation WebSocket client for application realtime services. Subclasses supply
57
- connection intent and one or more `{ url, protocols }` targets; the kit owns foreground/network
58
- suspension, target-scoped reconnect that preserves healthy sockets, exponential backoff, open and half-open detection, ping/pong,
59
- self-echo annotation, and `reconnected$` resync signaling. Use `kitRealtimeProtocols()` to pass
60
- authentication and the stable `KIT_REALTIME_CLIENT_ID` through WebSocket subprotocols without
61
- putting credentials in the URL.
62
-
63
- Domain event types, authorization, room selection, and REST resync behavior remain in the app.
64
- Offline-capable authenticated clients set `requireRemoteAccess: true` in `realtimeOptions`; sockets then close on
65
- `local` / `none` and reopen only after `KitAuthAccessService` publishes `remote`.
66
-
67
- ---
68
-
69
- ### KitStorageService
70
-
71
- A typed wrapper around `@ionic/storage-angular` that guarantees writes are never silently dropped even when called immediately after service creation.
72
-
73
- **How it works:** `Storage.create()` is awaited exactly once internally (via a private `#ready` promise). Every public method awaits `#ready` before operating, so callers never need a separate init step.
74
-
75
- **Setup** — provide `IonicStorageModule` (or equivalent) alongside the service:
76
-
77
- ```typescript
78
- // app.config.ts
79
- import { IonicStorageModule } from '@ionic/storage-angular';
80
- import { importProvidersFrom } from '@angular/core';
81
-
82
- export const appConfig: ApplicationConfig = {
83
- providers: [importProvidersFrom(IonicStorageModule.withConfig({ name: '__mydb' }))],
84
- };
85
- ```
86
-
87
- **Usage**
88
-
89
- ```typescript
90
- import { KitStorageService } from '@rdlabo/ionic-angular-kit';
91
-
92
- @Injectable({ providedIn: 'root' })
93
- export class TokenService {
94
- readonly #storage = inject(KitStorageService);
95
-
96
- async saveToken(token: string): Promise<void> {
97
- await this.#storage.set('token', token);
98
- }
99
-
100
- async getToken(): Promise<string | null> {
101
- return this.#storage.get<string>('token');
102
- }
103
- }
104
- ```
105
-
106
- **API**
107
-
108
- ```typescript
109
- set<T>(key: string, value: T): Promise<void>
110
- get<T>(key: string): Promise<T | null> // returns null (not undefined) for missing keys
111
- remove(key: string): Promise<void>
112
- clear(): Promise<void>
113
- keys(): Promise<string[]>
114
- ```
115
-
116
- ---
117
-
118
- ### KitOverlayController + provideKitOverlay
119
-
120
- A unified presenter for Ionic Modal, Toast, and Alert that folds create → present → dismiss into a single awaitable call.
121
-
122
- **Convention:** button labels (`close`, `cancel`) are **not hard-coded** in the kit. The consuming application must inject them via `provideKitOverlay`. This keeps the kit independent of `@angular/localize` and lets each app supply translated strings.
123
-
124
- **Setup**
125
-
126
- ```typescript
127
- // app.config.ts
128
- import { provideKitOverlay } from '@rdlabo/ionic-angular-kit';
129
-
130
- export const appConfig: ApplicationConfig = {
131
- providers: [
132
- provideKitOverlay({
133
- labels: {
134
- close: $localize`閉じる`,
135
- cancel: $localize`キャンセル`,
136
- },
137
- }),
138
- ],
139
- };
140
- ```
141
-
142
- **Usage**
143
-
144
- ```typescript
145
- import { KitOverlayController } from '@rdlabo/ionic-angular-kit';
146
-
147
- @Component({ ... })
148
- export class MyPage {
149
- readonly #overlay = inject(KitOverlayController);
150
-
151
- async openDetail(): Promise<void> {
152
- const result = await this.#overlay.presentModal(DetailPage, { item });
153
- // result type is inferred from `declare static modalReturn` on DetailPage
154
- }
155
-
156
- async confirm(): Promise<void> {
157
- const ok = await this.#overlay.alertConfirm({
158
- header: 'Delete',
159
- message: 'Are you sure?',
160
- okText: 'Delete',
161
- });
162
- if (ok) { /* proceed */ }
163
- }
164
-
165
- async notify(message: string): Promise<void> {
166
- await this.#overlay.presentToast({ message });
167
- }
168
- }
169
7
  ```
170
8
 
171
- **API**
172
-
173
- ```typescript
174
- presentModal<C extends ModalOptions['component']>(
175
- component: C,
176
- ...args: ModalPresentArgs<C>, // props inferred from input() fields; options?: KitModalPresentOptions
177
- ): Promise<ModalReturnOf<C> | undefined>
178
- // Props inferred from the component's input() fields (required/optional).
179
- // Return type inferred from `declare static modalReturn: T` on the component (void if absent).
180
-
181
- presentPopover<O>(
182
- component: PopoverOptions['component'],
183
- componentProps?: PopoverOptions['componentProps'],
184
- options?: Omit<PopoverOptions, 'component'|'componentProps'>, // e.g. { event } to anchor it
185
- ): Promise<O | undefined>
186
-
187
- presentToast(options: ToastOptions): Promise<HTMLIonToastElement>
188
- // kit defaults: position='bottom', duration=2000, swipeGesture='vertical'
189
- // A bottom toast with no explicit positionAnchor auto-anchors above a visible bottom <ion-tab-bar>
190
- // (`slot="top"` bars are ignored) so it clears the tabs; keyboard avoidance rides the native keyboard resize.
191
- // caller options spread over the defaults — any field can be overridden
192
-
193
- alertClose(options: { header: string; message: string; subHeader?: string }): Promise<void>
194
-
195
- alertConfirm(options: {
196
- header: string;
197
- message: string;
198
- okText: string;
199
- subHeader?: string;
200
- }): Promise<boolean> // true iff role === 'confirm'
201
- ```
202
-
203
- `watchKeyboard: true` (on `presentModal` options) expands a bottom sheet to full height when the native keyboard appears (iOS/Android only; no-op on web).
204
-
205
- **How `presentModal` decides required vs. optional props.** Props are inferred from the component's `input()` fields, and whether each prop is **required** or **optional** is decided by a single rule: _does the input's type include `undefined`?_ A default value is not "optional" — providing a default removes `undefined` from the input's type, so a defaulted input becomes a **required** prop.
9
+ ## Requirements
206
10
 
207
- | Declaration | Input type | Includes `undefined`? | Prop |
208
- | ------------------------ | ---------------- | --------------------- | ------------------------------------------ |
209
- | `input.required<T>()` | `T` | No | required |
210
- | `input<T>(defaultValue)` | `T` | No | **required** ← a default makes it required |
211
- | `input<T>()` (no arg) | `T \| undefined` | Yes | optional |
11
+ | Package | Supported version |
12
+ | ---------------------------------- | ----------------- |
13
+ | Angular | 21.x |
14
+ | Ionic Angular | 8.x |
15
+ | RxJS | 7.8.x |
16
+ | Capacitor core and feature plugins | 6.x through 8.x |
212
17
 
213
- To make a prop **optional**, drop the default and use a bare `input<T>()` (its type is `T | undefined`), then apply your fallback where you read it (e.g. `this.enabled() ?? true`). If a component has at least one required input, the `componentProps` argument itself becomes mandatory; if it has no required inputs, `componentProps` may be omitted; a component with no `input()` fields at all accepts loose, untyped props.
18
+ Install `@ionic/storage-angular` when using storage. Other peers are feature-scoped: install only the Capacitor, Firebase, printing, or Live Update packages used by your selected entry points.
214
19
 
215
- **Best practice — the modal launcher pattern.** Never call `modalController.create(...)` inline in a component. Instead, each modal/popover page exports a typed launcher next to itself and every call site goes through `KitOverlayController`:
216
-
217
- ```typescript
218
- // detail.page.ts — component declares its return type:
219
- export class DetailPage {
220
- declare static readonly modalReturn: DetailResult;
221
- readonly item = input.required<Item>();
222
- }
223
-
224
- export const launchDetailPage = (overlay: KitOverlayController, props: { item: Item }): Promise<DetailResult | undefined> =>
225
- overlay.presentModal(DetailPage, props, { backdropDismiss: false });
226
- ```
227
-
228
- This centralizes presentation options, keeps component props and dismiss data type-safe, and makes every modal discoverable. A well-disciplined app has **zero** inline `controller.create()` calls.
229
-
230
- ---
231
-
232
- ### Auth guards + provideKitAuth
233
-
234
- Functional `CanActivateFn` guards for a five-state auth model:
235
-
236
- | State | Meaning |
237
- | --------------- | -------------------------------------------------------- |
238
- | `'user'` | Fully authenticated |
239
- | `'confirm'` | Authenticated but email confirmation pending |
240
- | `'required'` | Not authenticated |
241
- | `'anonymous'` | Anonymous login active (can be prompted to register) |
242
- | `'unavailable'` | The authentication authority cannot currently be reached |
243
-
244
- **Convention:** every redirect path is supplied via `provideKitAuth`; the kit does not hard-code any routes.
245
- `authState` and `redirects` are required. The app-specific hooks `onAuthorized`, `onUnauthenticated`, and
246
- `onUnavailable` are optional. An authenticated user is allowed by default; unauthenticated and unavailable states
247
- redirect by default.
248
-
249
- `'required'` is an authoritative signed-out result. It must never be converted into offline access.
250
- `'unavailable'` means the authentication authority could not produce a result. Likewise,
251
- `isUnavailableError` must classify transport failures only; HTTP 401/403 are explicit denials and must return
252
- `false`. `onUnavailable` authorizes the route for local-replica use only—it does not create an HTTP or realtime
253
- credential.
254
-
255
- `KitAuthAccessService` is the authoritative capability state for the rest of the application:
256
-
257
- | Access mode | Local replica / outbox | Authenticated HTTP / realtime / sync |
258
- | ----------- | ---------------------- | ------------------------------------ |
259
- | `none` | blocked | blocked |
260
- | `local` | allowed | blocked |
261
- | `remote` | allowed | allowed |
262
-
263
- Remote activation has two ordered phases. `activate()` installs the remotely verified identity without starting
264
- transport. The guard then publishes `remote`, and only then calls `resume()` to start pull, outbox replay, and
265
- realtime work. Returning plain `true` remains supported for applications that do not need phased activation.
266
- When a protected guard starts a new asynchronous decision, any previously published `remote` capability is
267
- immediately suspended to `none`; it is granted again only after the current lease completes successfully.
268
- Once the authority returns `required` or `confirm`, an existing `local` capability is also suspended before any
269
- anonymous-sign-in fallback runs. Only the `unavailable` path may retain or re-grant verified local access.
270
-
271
- **Setup**
272
-
273
- ```typescript
274
- // app.config.ts
275
- import { provideKitAuth } from '@rdlabo/ionic-angular-kit';
276
-
277
- export const appConfig: ApplicationConfig = {
278
- providers: [
279
- provideKitAuth(() => {
280
- const auth = inject(AuthService);
281
- return {
282
- authState: () => auth.state$, // Observable<KitAuthState>
283
- redirects: {
284
- whenAuthorized: '/home', // kitRequiredUnauthorizedGuard
285
- whenConfirming: '/auth/confirm', // kitRequiredUnauthorizedGuard
286
- whenNotConfirming: '/auth/signin', // kitRequireConfirmingGuard
287
- whenUnauthorized: '/auth', // kitRequireAuthorizedGuard
288
- },
289
- // onAuthorized / onUnauthenticated omitted → defaults (allow / redirect).
290
- // Supply onAuthorized only when 'user' needs extra work. A phased result is preferred when
291
- // activating the offline runtime:
292
- // onAuthorized: async () => {
293
- // const session = await auth.exchangeCredential();
294
- // return {
295
- // activate: (lease) => offline.prepareRemoteSession(
296
- // session.userId, session.scopeIds, session.subject, lease,
297
- // ),
298
- // resume: () => offline.resumeRemoteSession(),
299
- // };
300
- // },
301
- // Supply onUnauthenticated only for a fallback such as anonymous sign-in:
302
- // onUnauthenticated: async () => { await auth.signInAnonymously(); return true; },
303
- // Supply onUnavailable only for a previously verified local replica:
304
- // onUnavailable: async (_state, _error, lease) =>
305
- // (await offline.activateOfflineSession(auth.currentSubject(), lease)) !== null,
306
- // isUnavailableError: (error) => isOfflineFallbackError(error),
307
- // Optionally recover automatically after the authority is reachable again:
308
- // remoteRecovery: {
309
- // availability: () => auth.authorityAvailable$,
310
- // reauthenticate: async () => {
311
- // const session = await auth.tryExchangeCredential();
312
- // return session
313
- // ? {
314
- // activate: (lease) => offline.prepareRemoteSession(
315
- // session.userId, session.scopeIds, session.subject, lease,
316
- // ),
317
- // resume: () => offline.resumeRemoteSession(),
318
- // }
319
- // : false;
320
- // },
321
- // },
322
- };
323
- }),
324
- ],
325
- };
326
- ```
20
+ ## Entry points
327
21
 
328
- ### kitPresentAuthFailedAlert
22
+ | Import | Responsibility |
23
+ | ----------------------------------------- | ------------------------------------------------------------------------------ |
24
+ | `@rdlabo/ionic-angular-kit` | Storage, overlays, guards, HTTP, realtime, directives, keyboard, and utilities |
25
+ | `@rdlabo/ionic-angular-kit/offline` | Scoped local replica, outbox, pull, replay, and request policies |
26
+ | `@rdlabo/ionic-angular-kit/theme` | Persisted light/dark theme and native status bar sync |
27
+ | `@rdlabo/ionic-angular-kit/review` | Throttled native in-app review requests |
28
+ | `@rdlabo/ionic-angular-kit/printer` | DOM-to-PNG, Brother label, and PDF helpers |
29
+ | `@rdlabo/ionic-angular-kit/auth-firebase` | Firebase dependency wiring and authentication flows |
30
+ | `@rdlabo/ionic-angular-kit/live-update` | Capawesome Live Update readiness provider |
329
31
 
330
- The fleet's canonical "sign-in / token exchange failed" alert: an informative alert (header + optional server error as sub-header + detail message) with a single close button that reloads the app so the user restarts cleanly. Text is passed in (no hardcoded i18n); the caller signs the user out around it. A standalone helper (takes `AlertController`) since `location.reload()` is navigation policy the overlay controller does not hold.
331
-
332
- ```typescript
333
- import { kitPresentAuthFailedAlert } from '@rdlabo/ionic-angular-kit';
334
-
335
- const logged = await auth.tokenLogin().catch(async (e) => {
336
- await kitPresentAuthFailedAlert(alertCtrl, {
337
- header: 'ログインできませんでした',
338
- subHeader: e.error.error,
339
- message: e.error.detail,
340
- closeText: '閉じる',
341
- });
342
- await auth.signOut();
343
- return undefined;
344
- });
345
- ```
346
-
347
- **Guards**
348
-
349
- ```typescript
350
- // routes.ts
351
- import { kitRequiredUnauthorizedGuard, kitRequireConfirmingGuard, kitRequireAuthorizedGuard } from '@rdlabo/ionic-angular-kit';
352
-
353
- export const routes: Routes = [
354
- {
355
- path: 'auth',
356
- canActivate: [kitRequiredUnauthorizedGuard],
357
- // Blocks 'user' → redirects whenAuthorized
358
- // Blocks 'confirm' → redirects whenConfirming
359
- // Allows 'required' and 'anonymous'
360
- loadChildren: () => import('./auth/routes'),
361
- },
362
- {
363
- path: 'confirm',
364
- canActivate: [kitRequireConfirmingGuard],
365
- // Allows only 'confirm'
366
- // 'anonymous' → redirects whenAuthorized
367
- // 'required'/'user' → redirects whenNotConfirming
368
- loadComponent: () => import('./confirm/confirm.page'),
369
- },
370
- {
371
- path: 'app',
372
- canActivate: [kitRequireAuthorizedGuard],
373
- // 'user' → calls onAuthorized → proceeds on true, redirects on UrlTree
374
- // 'anonymous' → allowed (anonymous browsing)
375
- // 'required'/'confirm' → calls onUnauthenticated → proceeds on true/UrlTree, redirects whenUnauthorized on false
376
- loadChildren: () => import('./main/routes'),
377
- },
378
- ];
379
- ```
380
-
381
- ---
382
-
383
- ### kitAuthInterceptor + provideKitHttp
384
-
385
- A fleet-canonical HTTP interceptor with:
386
-
387
- - Per-request auth header injection
388
- - Configurable bypass (CDN, S3, external URLs)
389
- - **Safe retry**: only idempotent methods (`GET`/`HEAD`/`OPTIONS`, or a request with an `Idempotency-Key`) are retried, and only on a transient status `[0, 408, 429, 502, 503, 504]`, up to 2 times with a short jittered backoff (honoring `Retry-After`). **Writes are never auto-retried** (no duplicate saves).
390
- - **Offline fast-fail**: when the device is offline the interceptor stops retrying immediately and hands off to `offlineFallback` instead of waiting out the backoff.
391
-
392
- ### Scoped local replica and outbox (`@rdlabo/ionic-angular-kit/offline`)
393
-
394
- The optional `offline` entry point provides a user/partition-scoped local replica, durable outbox, authenticated
395
- session boundary, cursor-based delta pull, aggregate-ordered replay, optimistic updates, retry classification, and a
396
- request-policy interceptor. Synchronized applications provide URL/DTO read policies, optional local-first mutation
397
- policies, a replica puller, and a command executor through `provideOffline(...)`. External-source or HTTP read caches use
398
- `mode: 'readCacheOnly'`; the kit then supplies the empty pull/executor boundary instead of making every product
399
- declare dummy adapters.
400
- Mutations may still call `OfflineSyncService.enqueue` explicitly. A product that must keep ordinary HTTP services
401
- offline-unaware can instead register `mutationPolicies`; a matched `POST` / `PUT` / `PATCH` / `DELETE` is prepared
402
- locally before transport and returns an optimistic response while the Outbox owns remote replay.
403
- Web storage uses Ionic Storage and supports `readCacheOnly` only. `synchronized` fails fast on Web because the current repository has no cross-tab lock; iOS and Android use encrypted `@capacitor-community/sqlite`. Importing either the
404
- primary entry point or `/offline` does not pull the optional native SQLite plugin into web-only applications.
405
-
406
- For cold-start offline route access, `OfflineCoordinatorService.activateOfflineSession()` restores only a manifest
407
- that is bound to a non-null authentication-provider subject. Supplying a currently known subject also rejects a
408
- different user on a shared device. It activates local replica writes and durable outbox enqueue, but remote pull and
409
- command replay remain disabled until online authentication completes the ordered
410
- `prepareRemoteSession(...)` → publish `remote` → `resumeRemoteSession()` transition. `activateSession(...)` is
411
- available as a one-step API for callers that do not enforce shared access mode.
412
- Explicit sign-out must first call `KitAuthAccessService.clear()` and then await `clearActiveSession()`. The first
413
- step immediately invalidates every in-flight auth lease; the second serializes cleanup after local persistence
414
- already in progress and removes the manifest and user replica.
415
-
416
- ```ts
417
- import { createOfflineAuthBridge, isOfflineFallbackError } from '@rdlabo/ionic-angular-kit/offline';
418
-
419
- provideKitAuth(() => ({
420
- authState: () => auth.state$,
421
- ...createOfflineAuthBridge({
422
- exchange: async (ctx) => {
423
- const remote = await auth.exchangeCredential(ctx);
424
- const authSubject = auth.currentSubject();
425
- return remote && authSubject ? { ...remote, authSubject } : false;
426
- },
427
- currentAuthSubject: () => auth.currentSubject(),
428
- isUnavailableError: isOfflineFallbackError,
429
- availability: () => auth.authorityAvailable$,
430
- }),
431
- redirects,
432
- }));
433
- ```
434
-
435
- `createOfflineAuthBridge` owns `exchange` → `prepareRemoteSession` → kit `grantRemote` → `resumeRemoteSession`
436
- ordering via `KitRemoteAccessRecovery`. Product code keeps consent, error UI, and credential mapping inside
437
- `exchange(context)` (`phase: 'authorize' | 'recover'`, optional route state, lease). Return `null`/`false` to decline
438
- without throwing; thrown errors are never swallowed and remain available to the guard's unavailable/denial
439
- classification. The returned identity requires a positive `userId`, non-empty string `scopeIds`, and a non-empty
440
- `authSubject`. A scope may be a numeric database id serialized as a string or a domain UUID such as an organization
441
- or venue id. The bridge compares the subject before
442
- session activation, immediately before the coordinator commits through a composite lease, and around remote resume.
443
- Optional `isIdentityCurrent` can add provider object-identity checks. `onRemoteResumed` receives the identity, phase,
444
- route state, and post-grant lease for safe redirects or other product side effects. Default recovery availability
445
- follows `offline.networkState !== 'offline'`.
446
-
447
- Register `offlineInterceptor` before `kitAuthInterceptor`. In local mode the auth interceptor synthesizes a
448
- transport-unavailable error before generating credentials or touching the network; the outer offline interceptor
449
- may then serve a matched `GET` from the replica. In `none` mode the same request is rejected and no local data is
450
- returned.
451
-
452
- The offline interceptor observes real transport responses to update API reachability. For matched `GET`
453
- requests only, a transport failure with `status=0` may return a local replica response tagged
454
- `X-Offline-Response: local`. A read policy's optional `projectResponse(response, source)` hook receives both remote
455
- and local results, so the remote branch can persist first and both branches can return a body from one composer.
456
- Matched mutation policies return `X-Offline-Response: optimistic` without starting transport. Unmatched writes go to
457
- transport unchanged. Outbox replay requests bypass policy with `OFFLINE_BYPASS` while still using the same auth
458
- interceptor and transport observation. Mutation policy matchers must be mutually exclusive: zero matches use normal
459
- transport, exactly one match runs its `prepare()`, and multiple matches throw `OfflineMutationPolicyConflictError`
460
- before either `prepare()` or transport starts. This fail-fast boundary prevents provider registration order from
461
- silently selecting the wrong replica/outbox mutation.
462
-
463
- ```ts
464
- @Injectable()
465
- class ItemReadPolicy implements OfflineRequestPolicy {
466
- resolve(request: HttpRequest<unknown>): OfflineRequestPlan | null {
467
- if (request.method !== 'GET' || !request.url.endsWith('/items')) return null;
468
- return {
469
- kind: 'read',
470
- readLocal: () => this.items.readResponse(),
471
- projectResponse: async (response, source) => {
472
- if (source === 'remote') await this.items.persist(response.body);
473
- return response.clone({ body: await this.items.compose() });
474
- },
475
- };
476
- }
477
- }
478
-
479
- @Injectable()
480
- class ItemMutationPolicy implements OfflineMutationRequestPolicy {
481
- resolve(request: HttpRequest<unknown>): OfflineMutationRequestPlan | null {
482
- if (request.method !== 'POST' || !request.url.endsWith('/items')) return null;
483
- return {
484
- kind: 'mutation',
485
- prepare: async () => {
486
- const optimistic = await this.items.enqueueCreate(request.body);
487
- return new HttpResponse({ status: 202, body: optimistic });
488
- },
489
- };
490
- }
491
- }
492
-
493
- provideOffline({
494
- // repository/schema/executor/puller options omitted
495
- requestPolicies: [ItemReadPolicy],
496
- mutationPolicies: [ItemMutationPolicy],
497
- });
498
- ```
499
-
500
- Products may make durable mutation saving device-configurable without disabling replica reads. Supply only the
501
- durable preference adapter; Kit owns the concurrency-sensitive transition. It starts admission closed while loading,
502
- gates every `enqueue` / `enqueuePrepared` / `enqueuePreparedBatch`, and routes matched HTTP writes to normal transport
503
- while disabled. Disabling closes admission synchronously, waits for already accepted commits, flushes pending
504
- commands, verifies an empty Outbox, and then persists `false`. A failed transition restores the last successfully
505
- persisted state. Replacement and discard APIs remain available because they resolve existing commands rather than
506
- create additional pending work.
507
-
508
- ```ts
509
- @Injectable({ providedIn: 'root' })
510
- class ProductMutationPersistenceAdapter implements OfflineMutationPersistenceAdapter {
511
- readonly #settings = inject(ProductSettingsService);
512
-
513
- loadEnabled(): Promise<boolean | null> {
514
- return this.#settings.get('offlineMutationPersistence');
515
- }
516
-
517
- saveEnabled(enabled: boolean): Promise<void> {
518
- return this.#settings.set('offlineMutationPersistence', enabled);
519
- }
520
- }
521
-
522
- provideOffline({
523
- // repository/schema/executor/puller options omitted
524
- mutationPersistence: {
525
- adapter: ProductMutationPersistenceAdapter,
526
- defaultEnabled: true,
527
- },
528
- });
529
-
530
- const offline = inject(OfflineCoordinatorService);
531
- await offline.mutationPersistence.setEnabled(false);
532
- ```
533
-
534
- The product owns settings UI, labels, confirmation copy, and the storage key. Omitting `mutationPersistence` keeps
535
- the historical always-enabled behavior. `readCacheOnly` applications do not expose this setting.
536
-
537
- The native offline runtime uses `@capacitor-community/sqlite` on iOS and Android. Install the plugin in the app and
538
- sync native projects:
539
-
540
- ```bash
541
- # Capacitor 8
542
- npm install @capacitor-community/sqlite@^8.1.0
543
- npx cap sync
544
- ```
545
-
546
- Use the plugin major matching the application's Capacitor major (`^6` for Capacitor 6, `^7` for Capacitor 7,
547
- `^8.1.0` for Capacitor 8).
548
-
549
- Add the required `CapacitorSQLite` plugin block to `capacitor.config.ts`. Encryption must be enabled — the kit opens
550
- databases in encrypted mode and relies on the plugin's built-in secure secret storage (`isSecretStored` /
551
- `setEncryptionSecret` in the device keychain / Android keystore):
552
-
553
- ```ts
554
- // capacitor.config.ts
555
- plugins: {
556
- CapacitorSQLite: {
557
- iosDatabaseLocation: 'Library/CapacitorDatabase',
558
- iosIsEncryption: true,
559
- iosKeychainPrefix: '<your-app-prefix>',
560
- androidIsEncryption: true,
561
- },
562
- },
563
- ```
564
-
565
- Follow the [@capacitor-community/sqlite installation guide](https://github.com/capacitor-community/sqlite#installation)
566
- for platform-specific steps and SQLCipher export-compliance notes.
567
-
568
- Android must not back up or transfer the encrypted database independently from its keystore secret. Set
569
- `android:allowBackup="false"`, `android:fullBackupContent="false"`, and
570
- `android:dataExtractionRules="@xml/data_extraction_rules"` on `<application>`. The referenced Android 12+ rules must
571
- exclude at least the `database`, `sharedpref`, `root`, and `external` domains from both `cloud-backup` and
572
- `device-transfer`, as shown in the plugin installation guide.
573
-
574
- Create the community plugin connection in the application, then pass it with a stable `databaseName` and a
575
- `createEncryptionKey` generator to `provideOffline`. Keeping the runtime object application-supplied prevents the optional
576
- native plugin from entering web-only `/offline` bundles. The kit invokes the generator only
577
- when the plugin has no secret yet, then stores the result in the plugin's Keychain / Android keystore. Later opens use
578
- that stored secret without invoking the generator. Never hard-code or derive the key from a user identifier, device
579
- identifier, or access token; generate a cryptographically random value for the first installation.
580
-
581
- ```ts
582
- import { CapacitorSQLite, SQLiteConnection } from '@capacitor-community/sqlite';
583
- import { createRandomOfflineEncryptionKey, provideOffline } from '@rdlabo/ionic-angular-kit/offline';
584
-
585
- provideOffline({
586
- databaseName: 'product-offline',
587
- sqliteConnection: new SQLiteConnection(CapacitorSQLite),
588
- createEncryptionKey: createRandomOfflineEncryptionKey,
589
- // ...product policies, puller, and executor
590
- });
591
- ```
592
-
593
- An explicit user-requested local reset must run before Angular and Kit initialize SQLite. Use the cold-start helpers
594
- instead of reproducing the community plugin's encrypted connection lifecycle in every application. Kit never invokes
595
- reset automatically after a storage error. The product must show destructive confirmation first and owns the marker key.
596
- Only databases that use Kit's same encrypted secret-mode, connection-version-1, read/write lifecycle belong in
597
- `kitCompatibleDatabaseNames`; delete differently configured databases and files in `additionalCleanup`. The marker is
598
- removed only after every database and product cleanup succeeds, so a partial failure is retried on the next cold launch.
599
-
600
- ```ts
601
- // Settings action
602
- await requestOfflineLocalReset({
603
- markerStore: Preferences,
604
- markerKey: 'product:offline:reset',
605
- });
606
-
607
- // main.ts, before bootstrapApplication(...). Report reset failure but always continue startup.
608
- await recoverOfflineLocalReset({
609
- markerStore: Preferences,
610
- markerKey: 'product:offline:reset',
611
- sqliteConnection,
612
- kitCompatibleDatabaseNames: ['product-offline', 'product-offline-media'],
613
- additionalCleanup: removeOfflineMediaFiles,
614
- }).catch((error: unknown) => {
615
- console.error('Offline local reset failed; it will retry on the next launch.', error);
616
- });
617
-
618
- await bootstrapApplication(AppComponent, appConfig);
619
- ```
620
-
621
- Replica identity follows the product database:
622
-
623
- | Identity declaration | SQLite primary key | Row / executor identity |
624
- | ---------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------- |
625
- | `generatedId('integer' \| 'text')` | scope columns + immutable `local_id`; scoped nullable unique `server_id` | `{ kind: 'generated', localId, remoteId }` |
626
- | `naturalKey(['a', 'b'])` | scope columns plus mapped `a`, `b` columns | `{ kind: 'natural', naturalKey: { a, b } }` |
627
- | `identity: localOnly()` | scope columns + immutable `local_id` | `{ kind: 'local', localId }` |
628
-
629
- Natural-key tables contain neither `local_id` nor `server_id`; their scoped key columns are the SQLite composite
630
- `PRIMARY KEY`. Generated remote ids may be positive safe integers or non-empty text ids such as server-generated
631
- UUIDs. A successful create adds `remoteId` without replacing `localId`. Local-only rows cannot enter the Outbox.
632
- All TEXT identity components are opaque and compared byte-for-byte with SQLite's `BINARY` collation. The server
633
- database must use the same binary equality, or the Hono/API converter must return one canonical form before the
634
- value reaches `naturalKey(...)` or `generatedId('text')`. Do not pass case- or accent-insensitive primary keys
635
- through unchanged: values that the server considers equal must first be canonicalized to identical TEXT.
636
-
637
- `OfflineScope.userId` accepts `number | string`. A type-tagged TEXT codec keeps numeric `7` and text `"7"` in
638
- different metadata, manifest, cursor, Outbox, and entity boundaries.
639
-
640
- The write lifecycle is: persist the immutable Outbox command → rematerialize the aggregate from confirmed
641
- base/localOnly values plus remaining FIFO intents → render that optimistic projection → replay in the background →
642
- keep the transported command until pull acknowledges `commandId` → rematerialize again from the new confirmed
643
- baseline. The server remains authoritative; SQLite is the durable local working database, not an HTTP response cache.
644
-
645
- Synchronized mode requires `aggregateIntentProjector`. Kit calls it inside `OfflineReplicaMutationCoordinator` after
646
- enqueue, batch enqueue, replacement, discard, transport success, and pull acknowledgement. The adapter must derive
647
- only from authoritative confirmed values plus the complete remaining intent chain. Do not call it from product code.
648
- Commands persist an immutable payload plus Kit-owned metadata (`baseRevision`, state, footprint keys). Kit updates
649
- only `baseRevision` when a newer server revision is known, and sets it to `null` after a generated remote identity is
650
- released; the product executor always receives the original payload. Optimistic snapshots and companion before/after
651
- images are not durable truth.
652
-
653
- When an API response is assembled from a base replica row plus product-owned local-only view rows, use
654
- `enqueuePrepared()`. Its callback runs inside the shared replica mutation lane, so every read used to derive the
655
- payload happens after earlier enqueue/ACK/pull applies. Kit then rematerializes the aggregate and commits the
656
- Outbox command with that projection in one `transactReplica()` call. Preparation failure, invalid footprint keys,
657
- non-JSON values, or an attempt to mutate commands/cursors leaves durable state unchanged.
658
-
659
- ```ts
660
- await offlineSync.enqueuePrepared(async (repository) => {
661
- const view = await readProductView(repository, scope, row);
662
- return {
663
- request: {
664
- scopeId: scope.scopeId,
665
- aggregateType: 'items',
666
- identity: { kind: 'generated', localId: row.identity.localId },
667
- operation: 'items.rename',
668
- payload: { title },
669
- localOnlyFootprint: [viewKey(scope, view)],
670
- },
671
- };
672
- });
673
- ```
674
-
675
- Product-specific pullers that materialize their own aggregate tables must keep HTTP transport outside
676
- `OfflineReplicaMutationCoordinator.run()` and wrap only the response apply read/derive/write section. This shares the
677
- same short local critical section as enqueue, ACK, discard, and the generic pull service without holding a lock during
678
- network latency.
679
-
680
- For a DB row whose deletion is represented by absence, enqueue the same full row values with
681
- `replicaMutation: 'delete'`. The runtime stores a library-owned durable tombstone: normal `getReplicaRow()` and
682
- `getReplicaRows()` reads stop returning the row immediately, while synchronization retains its immutable generated
683
- or natural identity, confirmed baseline, and Outbox command. A successful tombstone acknowledgement removes the row
684
- physically; retry, authorization failure, and conflict keep it hidden; discarding restores the latest confirmed
685
- baseline unless the server has also deleted it.
686
-
687
- Custom `OfflineRepository` implementations must implement `getReplicaRowIncludingPendingDelete()` before they can
688
- accept `replicaMutation: 'delete'`; the runtime rejects that enqueue otherwise. This is intentional: ordinary product
689
- reads stay hidden, while the library's remote-identity lookup and synchronization path must still resolve the durable
690
- tombstone for replay, lost-ACK reconciliation, conflict handling, and discard.
691
-
692
- ```ts
693
- await offlineSync.enqueue({
694
- scopeId,
695
- aggregateType: 'favorites',
696
- identity: {
697
- kind: 'natural',
698
- naturalKey: { favFrom: favorite.values.favFrom, favTo: favorite.values.favTo },
699
- },
700
- operation: 'favorite.delete',
701
- payload: { favTo: favorite.values.favTo },
702
- baseRevision: favorite.serverRevision,
703
- replicaMutation: 'delete',
704
- });
705
- ```
706
-
707
- The runtime retains pending, rejected, and conflicted commands until synchronization or an explicit user discard;
708
- it never evicts an unconfirmed mutation because of age or storage pressure. To keep a device that remains offline for
709
- months from exhausting SQLite, enqueue applies backpressure at 1,000 commands or 10 MiB per user by default. Products
710
- may lower these limits with `outboxLimits: { maxCommandsPerUser, maxBytesPerUser }`. When a limit is reached, the
711
- existing replica and Outbox remain unchanged and enqueue rejects with `OfflineOutboxCapacityError`, so the UI can ask
712
- the user to reconnect or resolve/discard an attention item.
713
-
714
- Use `generatedId('integer')` for a positive safe-integer `AUTO_INCREMENT` key and `generatedId('text')` for a
715
- server-generated text key. Use `naturalKey([...])` for an existing single or composite natural primary key.
716
- Natural-key components must be required mapped `text()` or `integer()` columns; nullable, ignored, JSON, empty
717
- declarations, duplicates, and mixed generated/natural declarations reject. Text identities reject NUL, malformed
718
- Unicode, and values larger than 1,024 UTF-8 bytes.
719
-
720
- When the application already knows the numeric server id but the first replica pull has not materialized the row,
721
- pass that identity explicitly while adopting the entity. This is required for updates and especially deletes: an
722
- omitted id would otherwise make the executor interpret the row as a not-yet-created local entity.
723
-
724
- ```ts
725
- await offlineSync.enqueue({
726
- scopeId,
727
- aggregateType: 'items',
728
- identity: { kind: 'generated', localId, remoteId: existingApiItem.id },
729
- operation: 'items.delete',
730
- payload: { method: 'DELETE' },
731
- });
732
- ```
32
+ Secondary entry points isolate optional native and SDK dependencies from the core bundle.
733
33
 
734
- The mapping is immutable and unique inside its effective replica scope. Reassigning one generated `localId` to
735
- another `remoteId`, or assigning the same remote identity to another `localId`, rejects before persistence. A
736
- natural-key change is a delete of the old key plus an insert of the new key, never an update of the primary key.
737
- Web storage enforces the same rule transactionally. SQLite uses a scoped partial unique index for generated
738
- `server_id`; natural identity is enforced by the table's scoped composite primary key. If an adopted row has
739
- no confirmed baseline and
740
- its final command is discarded, the local row is removed; the next pull may materialize the authoritative server
741
- row again. A row with a confirmed baseline rolls back to that baseline instead.
34
+ ## Configure only what you use
742
35
 
743
- Each synchronization cycle pulls authoritative server deltas before replaying the outbox. Every page carries the
744
- replica schema version/hash and advances a durable user/partition cursor in the same transaction as its rows. A schema
745
- mismatch, malformed row, or non-advancing cursor rejects synchronization without advancing that cursor. If a remote
746
- revision changed while a local command is pending, the optimistic row remains visible and both row and command move
747
- to `conflict`; the new server value is retained as the confirmed baseline. A remote tombstone follows the same
748
- retention rule: without pending commands it removes the row, while a pending row and its Outbox remain under
749
- `remote_deleted` conflict so the user can resolve or discard them.
36
+ Most features expose a provider whose callbacks keep routes, copy, credentials, and application side effects outside the kit. Start with [Storage and Overlays](./docs/storage-overlays.md), then add authentication, offline, or native features as your app needs them.
750
37
 
751
- Hono payloads may call a generated database key `serverId`, while the database-independent runtime calls it
752
- `remoteId`. Product pullers must use `normalizeOfflineReplicaPullPage(response)` at the HTTP boundary; do not
753
- reimplement `serverId` stripping/injection per application. Natural-key changes pass through unchanged.
38
+ ## Documentation
754
39
 
755
- The command adapter must send `commandId` as the server-side idempotency key. The server persists that key with the
756
- mutation and returns all keys represented by a delta row as `acknowledgedCommandIds`. This correlation is required:
757
- if the server commits a create/update/delete but its HTTP acknowledgement is lost, the next pull reconciles the
758
- server result into the same generated or natural identity, removes the acknowledged Outbox prefix, and rebases later
759
- commands without creating a second local identity.
760
-
761
- Versioned replica schemas lock web and native storage. Web metadata stores
762
- `replicaSchemaVersion` and `replicaSchemaHash`; native stores the same pair in
763
- `offline_replica_schema_metadata`. Bump `version` for every intentional shape change and supply a
764
- complete one-step migration chain. Native runs each step's SQL `statements`; web runs
765
- `migrateWebRow`, which receives only `{ sourceKey, values, confirmedValues }` and may return the same
766
- shape or `null` to delete a row. Identity and sync metadata (`identity`, scope, revision,
767
- `syncState`) stay outside the callback. The bundle fingerprint hashes `version`, entity layouts, and
768
- migration `fromVersion`/`statements` — never function bodies.
769
-
770
- Changing a natural-key component list or its order changes the schema fingerprint and SQLite primary key. For a
771
- released schema, bump `version`; native migration SQL must rebuild the table with the new composite primary key, and
772
- `migrateWebRow` must preserve every natural-key value. Keep the transaction journal and schema-migration recovery
773
- records until the replacement rows, index, and metadata commit together. This natural-key API is currently
774
- unreleased, so adopting it before the first release needs no compatibility helper or legacy-row migration.
775
-
776
- ```typescript
777
- import {
778
- defineOfflineReplicaSchema,
779
- defineReplicaEntity,
780
- generatedId,
781
- integer,
782
- localOnly,
783
- naturalKey,
784
- provideOffline,
785
- text,
786
- } from '@rdlabo/ionic-angular-kit/offline';
787
-
788
- // This is the Hono package's existing `typeof items.$inferSelect` export.
789
- import type { Items as ItemSelect } from '@product/hono/db/schema';
790
-
791
- const itemEntityV2 = defineReplicaEntity<ItemSelect>()({
792
- table: 'items',
793
- sourceKey: 'items',
794
- scope: 'partition',
795
- fields: {
796
- id: generatedId('integer'),
797
- title: text(),
798
- subtitle: text(),
799
- },
800
- });
801
-
802
- // Mirrors a product DB TableScheme whose primary key is (favFrom, favTo).
803
- type FavoriteSelect = {
804
- favFrom: number;
805
- favTo: number;
806
- label: string;
807
- };
808
-
809
- const favoriteEntity = defineReplicaEntity<FavoriteSelect>()({
810
- table: 'favorites',
811
- sourceKey: 'favorites',
812
- scope: 'user',
813
- identity: naturalKey(['favFrom', 'favTo']),
814
- fields: {
815
- favFrom: integer(),
816
- favTo: integer(),
817
- label: text(),
818
- },
819
- });
820
-
821
- const replicaSchema = defineOfflineReplicaSchema({
822
- version: 2,
823
- entities: [itemEntityV2, favoriteEntity],
824
- migrations: [
825
- {
826
- fromVersion: 1,
827
- statements: ['ALTER TABLE items ADD COLUMN subtitle TEXT NOT NULL DEFAULT ""'],
828
- migrateWebRow: (row) => ({
829
- sourceKey: row.sourceKey,
830
- values: { ...row.values, subtitle: '' },
831
- confirmedValues: row.confirmedValues === null ? null : { ...row.confirmedValues, subtitle: '' },
832
- }),
833
- },
834
- ],
835
- });
836
-
837
- provideOffline({
838
- replicaSchema,
839
- replicaPuller: ProductReplicaPuller,
840
- commandExecutor: ProductCommandExecutor,
841
- aggregateIntentProjector: ProductAggregateIntentProjector,
842
- // ...request policies, databaseName, createEncryptionKey
843
- });
844
-
845
- // Stripe or another external system is the source of truth; no Outbox exists.
846
- provideOffline({
847
- mode: 'readCacheOnly',
848
- replicaSchema: readCacheSchema,
849
- requestPolicies: [ReadCacheRequestPolicy],
850
- databaseName: 'product-read-cache',
851
- createEncryptionKey,
852
- });
853
- ```
854
-
855
- Offline replica schema consumers must compile with TypeScript `strictNullChecks: true`. This is part of the standard,
856
- not a compatibility option: without strict null checking, TypeScript cannot distinguish a nullable Hono property
857
- from a required one and the schema lock cannot prove the SQLite mapping.
858
-
859
- The schema definition must import the Hono package's exported `$inferSelect` type and map every key exactly once as
860
- a SQLite column, `generatedId('integer' | 'text')`, or `ignored(reason)`. A remotely replicated entity declares
861
- either one generated-id field or one ordered `naturalKey([...])`; a local-only projection explicitly declares
862
- `identity: localOnly()`.
863
- Nullable Hono columns require `nullable(...)`; non-null columns reject it. Therefore adding,
864
- removing, or changing nullability of a Drizzle column breaks the app build until its replica mapping is updated.
865
- At runtime, `values` contains only the mapped column projection. Identity is a discriminated union: generated rows
866
- carry `localId`/`remoteId`, natural rows carry only `naturalKey`, and local-only rows carry only `localId`. Ignored
867
- server fields are never persisted.
868
-
869
- - **Status classification**: `0`→`onNetworkError` (connected only), `429`→`onRateLimited`, `502/503/504`→`onServerBusy`, `400/422/500`+message→`onServerError`, `401`→`onUnauthorized`, `403`→`onForbidden`. Other statuses (e.g. `404`) are left to the caller.
870
- - **Universal 60s timeout** — every request fails with a synthetic (retryable) `408` if it hangs for 60s. Deliberately generous (catches a dead server without cutting off a large upload / AI generation; `timeout({ each })` resets per emission, so streaming is unaffected). Not configurable — one fleet-wide behavior.
871
- - **Optional `treatAsError(response)`** — reject a 2xx (e.g. `204`/`206`) as an error when a backend uses it to signal a condition. The one genuinely app-specific bit (some apps receive a normal `204`), kept optional so class interceptors with a 2xx-as-error convention can migrate to `provideKitHttp`.
872
-
873
- **Convention:** all app-specific logic (auth headers, error UI) lives in the config factory. The retry policy, bypass evaluation, and error dispatch are fixed in the kit and not overridable per-call.
874
-
875
- **Only `getAuthHeaders` is required.** Every other hook is optional and defaults to a safe no-op (`buildExtraHeaders` → `{}`, `bypass` → `false`, `offlineFallback` → `null`), so a config specifies only the behavior that actually differs from the baseline.
876
-
877
- **Setup**
878
-
879
- ```typescript
880
- // app.config.ts
881
- import { provideHttpClient, withInterceptors } from '@angular/common/http';
882
- import { isIdentityAuthFailure, kitAuthInterceptor, provideKitHttp, KitReloadAlertController } from '@rdlabo/ionic-angular-kit';
883
-
884
- export const appConfig: ApplicationConfig = {
885
- providers: [
886
- provideHttpClient(withInterceptors([kitAuthInterceptor])),
887
- provideKitHttp(() => {
888
- const auth = inject(AuthService);
889
- const reload = inject(KitReloadAlertController);
890
- return {
891
- // Required for the new offline auth boundary. Kept opt-in so existing applications retain
892
- // their current interceptor behavior until they wire KitAuthAccessService.
893
- enforceAuthAccessMode: true,
894
- // Only an explicitly tagged global identity failure may revoke shared access.
895
- // Omission keeps the legacy 401/403 revoke policy for existing applications.
896
- isAuthAccessDenial: (_req, error) => isIdentityAuthFailure(error),
897
- getAuthHeaders: async (req) => ({
898
- Authorization: `Bearer ${await auth.getToken()}`,
899
- }),
900
- // Status-independent: handles both new identity 401 and tagged historical identity 403.
901
- onAuthAccessDenial: () => auth.signOut(),
902
- onUnauthorized: (_req, error) => {
903
- // Feature UX for reauthentication/credential failures may inspect the error here.
904
- },
905
- // Fleet-canonical "network error → offer reload" (see KitReloadAlertController).
906
- onNetworkError: (status) =>
907
- reload.present({
908
- header: 'ネットワークエラー',
909
- message: `通信できませんでした。リフレッシュしますか?(${status})`,
910
- okText: 'リフレッシュ',
911
- }),
912
- // Auto-dismiss the stale alert once connectivity is back.
913
- onResponse: () => void reload.dismiss(),
914
- // buildExtraHeaders / bypass / offlineFallback / onForbidden / onServerError omitted → kit defaults.
915
- };
916
- }),
917
- ],
918
- };
919
- ```
920
-
921
- For an offline replica, use
922
- `withInterceptors([offlineInterceptor, kitAuthInterceptor])` in that order. The credential-exchange
923
- request that must run before `remote` is granted sets `KIT_AUTH_BOOTSTRAP_REQUEST` in its
924
- `HttpContext`, together with the offline entry point's `OFFLINE_BYPASS`:
925
-
926
- ```ts
927
- const context = new HttpContext().set(KIT_AUTH_BOOTSTRAP_REQUEST, true).set(OFFLINE_BYPASS, true);
928
- http.post('/login', body, { context });
929
- ```
930
-
931
- It still receives authentication headers and uses the normal denial/error pipeline; only the
932
- pre-existing `remote` requirement is deferred. The auth interceptor never consults its configured
933
- offline fallback for this request, while `OFFLINE_BYPASS` prevents an outer offline interceptor
934
- from replacing a transport failure with local data. Do not use the broader HTTP `bypass` hook,
935
- because that also skips authentication headers and error handling, and do not globally relax
936
- `enforceAuthAccessMode`.
937
-
938
- **Error dispatch** (after retries, in `catchError`):
939
-
940
- 1. With `enforceAuthAccessMode`, `401` / `403` never consults `offlineFallback`. The matching hook is
941
- notified and the error is rejected. Shared access is revoked only when `isAuthAccessDenial`
942
- returns `true`; omitting it preserves the legacy behavior that revokes on both 401 and 403.
943
- 2. Otherwise, `offlineFallback` non-null → return fallback observable (no further hooks called)
944
- 3. `401` → `onUnauthorized` · `403` → `onForbidden`
945
- 4. `0` (connected) → `onNetworkError` · `429` → `onRateLimited(retryAfter?)` · `502/503/504` → `onServerBusy(status, retryAfter?)`
946
- 5. `400/422/500` with `error.message` → `onServerError`
947
- 6. anything else (`404`, …) → not handled here; the caller decides
948
-
949
- Plus: a `getAuthHeaders` rejection → `onAuthError(request, error)` (the request is never sent).
950
-
951
- The shared `401` body carries `authFailureScope`:
952
-
953
- - `identity`: the Firebase/global identity cannot be established; global session and replica/outbox
954
- invalidation is allowed.
955
- - `reauthentication`: the identity remains valid, but a recent sign-in/step-up is required.
956
- - `credential`: only a feature-owned delegated credential is invalid.
957
-
958
- `getAuthFailureScope(error)` reads this explicit field and returns `null` for untagged legacy
959
- responses. It also accepts an explicitly tagged historical `403` identity failure for products
960
- whose installed clients still require that status; new APIs use `401`.
961
- `isIdentityAuthFailure(error)` is therefore intentionally strict. Put destructive global cleanup in
962
- `onAuthAccessDenial`; it runs for a classified identity failure independently of whether a compatible
963
- server returned 401 or 403. `onUnauthorized` receives the complete `HttpErrorResponse` for status-specific UX.
964
- An untagged `403` remains a resource/scope/business permission failure and never implies global
965
- identity loss. Existing callbacks that accept only the request remain source-compatible, and applications
966
- that omit `isAuthAccessDenial` retain the historical 401/403 revocation behavior.
967
-
968
- Deploy the API contract before enabling the strict client classifier:
969
-
970
- | Combination | Result |
971
- | ---------------------------- | ----------------------------------------------------------------------------------------------------------- |
972
- | Tagged API + legacy client | The extra body fields are ignored and the client's existing status behavior is preserved. |
973
- | Untagged API + strict client | Global identity loss cannot be identified safely, so the client retains local identity state. |
974
- | Tagged API + strict client | Only `identity` with `AUTH_IDENTITY_INVALID` revokes global access; narrower failures remain feature-owned. |
975
-
976
- For products whose installed clients historically require auth failure as `403`, deploy an explicitly
977
- tagged legacy `403` identity response first. The strict classifier accepts it only with the matching
978
- `statusCode`, scope, and `AUTH_IDENTITY_INVALID` code. Do not infer identity from an untagged legacy
979
- 401/403: that would collapse `credential` and `reauthentication` back into destructive global logout.
980
-
981
- **Note (0.0.9):** `onNetworkError` is now narrowed to genuine network failures (status `0`); `502/503/429` moved to `onServerBusy`/`onRateLimited`. Existing configs stay valid — they just fire less often — so adopt the new hooks only if you want to distinguish server-busy / rate-limit from a connection loss.
982
-
983
- ### KitReloadAlertController
984
-
985
- The fleet's canonical "network error → offer to reload" alert, as a stateful controller that unifies the good-UX variant that had drifted across apps:
986
-
987
- - **De-dup** — never stacks; a second `present()` while one is showing is a no-op.
988
- - **Backdrop lock** — `backdropDismiss: false`, so a critical error isn't dismissed by an accidental backdrop tap.
989
- - **Auto-dismiss on reconnect** — `dismiss()` (called from a later successful response) clears a now-stale error alert.
990
- - **Reload on confirm** — the confirm button calls `location.reload()`; cancel uses the configured `labels.cancel`.
991
-
992
- All text is passed in, so the kit stays free of hardcoded i18n. Wire `present` from a network-class error and `dismiss` from a success (interceptor `onResponse`, or a class interceptor's success path).
993
-
994
- ```typescript
995
- import { KitReloadAlertController } from '@rdlabo/ionic-angular-kit';
996
-
997
- const reload = inject(KitReloadAlertController);
998
- await reload.present({
999
- header: 'ネットワークエラー',
1000
- message: `通信できませんでした。リフレッシュしますか?(${status})`,
1001
- okText: 'リフレッシュ',
1002
- });
1003
- // later, on a successful response:
1004
- await reload.dismiss();
1005
- ```
1006
-
1007
- ---
1008
-
1009
- ### KitAuthInputDirective (`kitAuthInput`)
1010
-
1011
- Sign-in / sign-up conveniences on `ion-input`:
1012
-
1013
- - `'email'` — remember + prefill the last well-formed address (and forget when the user clears it)
1014
- - `'email-remember'` — remember on change only (no prefill — use on sign-up)
1015
- - `'autofill'` — iOS autofill propagation only (password fields)
1016
-
1017
- ```html
1018
- <ion-input type="email" autocomplete="email" kitAuthInput="email" [formField]="form.email" />
1019
- ```
1020
-
1021
- ### kitClearStoragePreservingKeys
1022
-
1023
- Fleet apps typically `storage.clear()` on sign-out. Pass keys that must survive (e.g. the last sign-in email):
1024
-
1025
- ```typescript
1026
- import { KIT_LAST_AUTH_EMAIL_KEY, KIT_THEME_STORAGE_KEY, kitClearStoragePreservingKeys } from '@rdlabo/ionic-angular-kit';
1027
-
1028
- await kitSignOut(auth, {
1029
- success: () => kitClearStoragePreservingKeys(this.storage, [KIT_LAST_AUTH_EMAIL_KEY, KIT_THEME_STORAGE_KEY]),
1030
- });
1031
- ```
1032
-
1033
- It snapshots the listed keys, clears the store, then writes non-null values back.
1034
-
1035
- ---
1036
-
1037
- ### kitKeyboardInit
1038
-
1039
- A plain function (no DI — reads the platform from `Capacitor`, so nothing to inject) that registers native keyboard show/hide listeners to reposition an element when the soft keyboard appears — useful for a footer input bar that must stay above the keyboard. A no-op on web (returns `[]`); SSR-safe (the global `document`/`window` are only read inside native callbacks). Three adjustment strategies:
1040
-
1041
- - `transform` — `translateY(-keyboardHeight + safeAreaBottom)` (smooth iOS animation; typical for `ion-footer`)
1042
- - `offset` — sets the `--offset-bottom` custom property
1043
- - `keyboard-offset` — sets the `--padding-bottom` custom property
1044
-
1045
- ```typescript
1046
- import { kitKeyboardInit } from '@rdlabo/ionic-angular-kit';
1047
-
1048
- export class ComposePage {
1049
- readonly #footer = viewChild.required<ElementRef>('footer');
1050
- #handles: PluginListenerHandle[] = [];
1051
-
1052
- async ngAfterViewInit() {
1053
- this.#handles = await kitKeyboardInit(this.#footer(), 'transform');
1054
- }
1055
- ngOnDestroy() {
1056
- this.#handles.forEach((h) => h.remove()); // caller owns the handles
1057
- }
1058
- }
1059
- ```
1060
-
1061
- ---
1062
-
1063
- ### KitThemeController + provideKitTheme
1064
-
1065
- Light/dark theme controller that unifies the theme logic that had drifted across the fleet: it persists the user's choice, follows the OS `prefers-color-scheme` until the user overrides it, toggles the configured palette classes, and syncs the native Android status bar. It also fixes a latent leak in one variant where the system-theme listener stayed registered after a manual toggle — `changeTheme()` always detaches the listener first, so a later OS change can't silently flip an app the user pinned.
1066
-
1067
- Per-app CSS differences are absorbed by config: `darkClasses` are toggled on when dark, `lightClasses` on when light. The kit ships no class names of its own. Subscribe to `themeSubject` (a `BehaviorSubject`) to reflect the current mode in the UI. It is a controller (not a plain function) because the subject and OS-listener are shared state across the app lifetime.
1068
-
1069
- ```typescript
1070
- // app.config.ts
1071
- provideKitTheme({
1072
- storageKey: StorageKeyEnum.theme,
1073
- darkClasses: ['ion-palette-dark', 'a2ui-dark'],
1074
- lightClasses: ['a2ui-light'],
1075
- });
1076
-
1077
- // app.component.ts — apply on boot
1078
- inject(KitThemeController).setDefaultThemeMode();
1079
-
1080
- // settings page — bind a toggle
1081
- const theme = inject(KitThemeController);
1082
- theme.themeSubject.subscribe((mode) => this.isDark.set(mode === 'dark'));
1083
- theme.changeTheme(true); // force dark, stop following the OS
1084
- ```
1085
-
1086
- ---
1087
-
1088
- ### kitRequestReview
1089
-
1090
- A plain function (no DI — `@capacitor/preferences`, `@capacitor-community/in-app-review` and `Capacitor` are all static) that requests the native in-app review dialog, throttled so the user is prompted at most once per window. A no-op on web. The wait/throttle/record sequence was previously copy-pasted verbatim across the fleet; centralizing it means a single place to tune the prompt cadence. The storage key and throttle window are passed as arguments, so the kit ships no config of its own.
1091
-
1092
- ```typescript
1093
- import { kitRequestReview } from '@rdlabo/ionic-angular-kit';
1094
-
1095
- await kitRequestReview({ storageKey: StorageEnum.lastRequestRate, throttleMonths: 3 });
1096
- ```
1097
-
1098
- ---
1099
-
1100
- ### Utilities
1101
-
1102
- Framework-agnostic helpers (no DI required unless noted):
1103
-
1104
- ```typescript
1105
- import { kitImpact, arrayConcatById, objectEqual, disableHandler } from '@rdlabo/ionic-angular-kit';
1106
-
1107
- // Native light haptic (no-op on web).
1108
- await kitImpact();
1109
-
1110
- // Merge a paginated page into an existing list by numeric id, sorted; new items win on duplicates.
1111
- // Optional 5th arg `secondaryKey` drops old items sharing that secondary field with any new item.
1112
- const merged = arrayConcatById(loaded, nextPage, 'id', 'DESC', 'parentId');
1113
-
1114
- // Order-independent deep equality (sorted-entries JSON) for cheap "did this state change?" checks.
1115
- if (!objectEqual(prev, next)) { /* changed */ }
1116
-
1117
- // Disable the clicked button while an async op runs, re-enabling it after (even on error).
1118
- async onSubmit(event: Event) {
1119
- await disableHandler(event, this.save());
1120
- }
1121
- ```
1122
-
1123
- Ionic-event / lifecycle helpers:
1124
-
1125
- ```typescript
1126
- import { kitChangeEventDisabled, kitCreateDidEnter } from '@rdlabo/ionic-angular-kit';
1127
-
1128
- // Toggle a signal-held ion-infinite-scroll / ion-refresher's `disabled` (no-op when empty).
1129
- kitChangeEventDisabled(infiniteScrollSignal, true);
1130
-
1131
- // Observe an Ionic page's "is entered" state from its lifecycle DOM events (true on didEnter).
1132
- readonly isEntered = toSignal(kitCreateDidEnter(inject(ElementRef)), { initialValue: false });
1133
- ```
1134
-
1135
- ---
1136
-
1137
- ### kitPresentLanguageActionSheet
1138
-
1139
- A plain function (the `ActionSheetController` is passed in — nothing injected) that presents a language picker and, on a new selection, reloads the app at that locale's entry point. Unifies the language-switch flow duplicated across apps: it stashes the current path in `sessionStorage` (to restore after reload), records the chosen locale in `localStorage`, and calls `window.location.replace()` with the app-provided URL. Being a navigation helper, it stays standalone rather than part of a controller. All text, the locale list, and the per-locale URL mapping are injected, so the kit stays free of i18n strings.
1140
-
1141
- ```typescript
1142
- import { kitPresentLanguageActionSheet } from '@rdlabo/ionic-angular-kit';
1143
-
1144
- await kitPresentLanguageActionSheet(inject(ActionSheetController), {
1145
- header: $localize`言語設定`,
1146
- locales: [
1147
- { text: 'English', data: 'en-US' },
1148
- { text: '日本語', data: 'ja' },
1149
- ],
1150
- cancelText: $localize`キャンセル`,
1151
- currentLocale: normalizedLocale,
1152
- currentPath: this.#router.url,
1153
- pathnameStorageKey: StorageKeyEnum.pathnameBeforeRedirect,
1154
- buildRedirectUrl: (locale) => location.origin + (localePath[locale.toLowerCase()] ?? '/index.html'),
1155
- enabled: environment.production,
1156
- });
1157
- ```
1158
-
1159
- ---
1160
-
1161
- ### Printer (label image and PDF plumbing)
1162
-
1163
- Pure functions (no DI) that extract the i18n-free core of the fleet's label printing, so a device-quirk, layout, or PDF fix lands in every app at once. The UI orchestration — paper-selection alerts, loading overlays, storage, printer transport, and app-specific copies policy — stays in each app.
1164
-
1165
- - `kitDomToPng(element, { rotate?, scale? })` — render a DOM element to a base64 PNG with the fleet's device fixes (iOS +2px to avoid bottom clipping, none on Android to avoid a black line; retries up to 10×). The caller presents its own loading UI.
1166
- - `kitRotationImage(base64)` — rotate a base64 image 90° via canvas.
1167
- - `kitBuildBrotherPrintSettings({ modelName, printBase64, label, numberOfCopies, halftoneThreshold })` — assemble the canonical `BRLMPrintOptions` (fit-page, centered, best quality, threshold halftone, standard margins, tape size parsed from the label's `W<w>H<h>` code). Merge `{ port, channelInfo }` from the selected channel before calling `BrotherPrint.printImage()`.
1168
- - `kitCalculatePrintLayout({ paper, labelWidthPx, labelHeightPx, copies, measure?, marginMm? })` — calculate row-major positions across as many pages as required. The default outer margin is 5mm.
1169
- - `kitBuildLabelPdf({ imageData, ...layoutOptions })` — embed the PNG artwork at the calculated positions and return PDF bytes. It deliberately does not open a browser tab or call a native printer.
1170
- - `kitPrintPaperSizes` — A4/B5 presets. Callers may pass any other `KitPrintPaper` dimensions without changing the kit.
1171
-
1172
- ```typescript
1173
- import { kitBuildBrotherPrintSettings, kitBuildLabelPdf, kitDomToPng, kitPrintPaperSizes } from '@rdlabo/ionic-angular-kit/printer';
1174
-
1175
- const png = await kitDomToPng(this.preview().nativeElement, { rotate: true });
1176
- const settings = kitBuildBrotherPrintSettings({
1177
- modelName,
1178
- printBase64: png,
1179
- label,
1180
- numberOfCopies: printOptions.printNum,
1181
- halftoneThreshold: printOptions.halftoneThreshold,
1182
- });
1183
- await BrotherPrint.printImage({ ...settings, port: channel.port, channelInfo: channel.channelInfo });
1184
-
1185
- const pdfBytes = await kitBuildLabelPdf({
1186
- imageData: png,
1187
- paper: kitPrintPaperSizes.a4,
1188
- labelWidthPx: 200,
1189
- labelHeightPx: 100,
1190
- copies: 6,
1191
- marginMm: 5,
1192
- });
1193
- ```
1194
-
1195
- ---
1196
-
1197
- ### Firebase auth (`@rdlabo/ionic-angular-kit/auth-firebase`)
1198
-
1199
- A secondary entry point so only apps that use it pull in `firebase` (declared as an optional peer dependency — install `firebase` in the app). It exists to **isolate the Firebase SDK**: `firebase/auth` is initialized in exactly one place — the DI provider — so apps import `KIT_FIREBASE_AUTH` and call these functions, never wiring `firebase/auth` themselves. The kit uses the vanilla modular `firebase/auth` SDK directly (no `@angular/fire`).
1200
-
1201
- **Design principle: the kit performs no UI.** Every function runs the Firebase operation and nothing else; loading overlays, prompts and error alerts are app side effects. The flow functions take the uniform lifecycle hooks `{ before, success, error, finally }` and, rather than throwing, resolve value flows to `null` and boolean flows to `false`, handing the raw error to the `error` hook so the app presents it from its own dictionary. For anything the functions don't express, drop down to `firebase/auth` directly.
1202
-
1203
- ```typescript
1204
- // app.config.ts — Firebase is initialized only here
1205
- provideKitFirebase({ firebaseConfig: environment.firebase }),
1206
- provideKitFirebaseAnalytics(),
1207
- ```
1208
-
1209
- ```typescript
1210
- import { inject, Injectable } from '@angular/core';
1211
- import {
1212
- KIT_FIREBASE_AUTH,
1213
- kitSignIn,
1214
- kitSignOut,
1215
- kitResolveAuthStatus,
1216
- kitReauthWithRetry,
1217
- type User,
1218
- } from '@rdlabo/ionic-angular-kit/auth-firebase';
1219
- import { updatePassword } from 'firebase/auth'; // escape hatch for the reauth mutation
1220
-
1221
- @Injectable({ providedIn: 'root' })
1222
- export class AuthService {
1223
- readonly #auth = inject(KIT_FIREBASE_AUTH);
1224
-
1225
- // Simple flow: hooks carry the app's side effects; errors go to the app's own dictionary.
1226
- signIn(email: string, password: string) {
1227
- return kitSignIn(this.#auth, email, password, {
1228
- error: (e) => this.presentError(e),
1229
- success: () => this.nav.navigateRoot('/'),
1230
- });
1231
- }
1232
-
1233
- // Re-auth: the kit owns only the re-auth + wrong-password-retry mechanic; the app supplies
1234
- // the password prompt and the loading overlay, and catches the thrown (non-wrong-password) error.
1235
- async changePassword(currentEmail: string, newPassword: string) {
1236
- const ok = await kitReauthWithRetry(this.#auth, currentEmail, {
1237
- prompt: (retry) => this.promptPassword(retry),
1238
- mutate: (user) => updatePassword(user, newPassword),
1239
- withLoading: (run) => this.withLoading(run),
1240
- }).catch((e) => (this.presentError(e), false));
1241
- if (ok) this.overlay.alertClose({ header: 'Saved', message: '…' });
1242
- }
1243
-
1244
- // A delayed denial must not sign out a newer Firebase session. Capture the User that owns the
1245
- // request and pass it as expectedUser; the kit checks object identity after `before` completes
1246
- // and immediately before invoking Firebase signOut.
1247
- signOutDeniedSession(expectedUser: User) {
1248
- return kitSignOut(this.#auth, { before: () => this.clearDeniedSessionTransport() }, { expectedUser });
1249
- }
1250
- }
1251
- ```
1252
-
1253
- Surface:
1254
-
1255
- - **DI** — `KIT_FIREBASE_AUTH` (`InjectionToken<Auth>`), `provideKitFirebase({ firebaseConfig })`, `provideKitFirebaseAnalytics()`.
1256
- - **Flow functions** (uniform hooks + no-throw null/false) — `kitSignIn`, `kitSignUp` (create + send verification), `kitSignOut`, `kitSendPasswordReset`, `kitSendEmailVerification`, `kitUnlinkProvider`. `kitSignOut(..., { expectedUser })` prevents an old asynchronous denial from signing out a newer Firebase User object.
1257
- - **Mechanics** — `kitReauthWithRetry` (app injects `prompt` / `withLoading` / `mutate`; boolean result, non-wrong-password errors thrown), `kitResolveAuthStatus` (`'user' | 'confirm' | 'required'` from the user; social counts as verified; `allowWhen` bypass), `kitAuthState`, `kitGetIdToken`.
1258
- - **Error dictionary** — `KIT_DEFAULT_AUTH_TEXT` (importable canonical constant; the kit does not present it — the app renders its own alert).
1259
- - **Social** (`@rdlabo/ionic-angular-kit/auth-firebase/social`, separate nested entry to isolate the Capacitor plugins) — `kitFacebookLogin`, `kitAppleLogin`, `kitFacebookLogout`; options carry the same `{ before, success, error, finally }` hooks (`success` receives the identity payload for a backend call).
1260
-
1261
- ---
1262
-
1263
- ### Live Update (`@rdlabo/ionic-angular-kit/live-update`)
1264
-
1265
- A secondary entry point (so only apps that use it pull in `@capawesome/capacitor-live-update`, declared as an optional peer) for shipping [Capawesome Live Updates](https://capawesome.io/plugins/live-update/) — over-the-air replacement of the Web (Angular/Ionic) layer without a store review.
1266
-
1267
- #### `provideLiveUpdateReadiness()`
1268
-
1269
- Marks the running Live Update bundle **healthy** once the app has actually rendered, so Capawesome does not auto-roll-back a good bundle. It waits for Angular to become stable **and** the first route to finish (`NavigationEnd` + one animation frame) before calling `LiveUpdate.ready()`. This replaces a fixed `readyTimeout` in `capacitor.config.ts` with a signal tied to real readiness. **Native only** — a no-op on web.
1270
-
1271
- ```typescript
1272
- // app.config.ts
1273
- import { provideLiveUpdateReadiness } from '@rdlabo/ionic-angular-kit/live-update';
1274
-
1275
- export const appConfig: ApplicationConfig = {
1276
- providers: [
1277
- provideZonelessChangeDetection(),
1278
- provideLiveUpdateReadiness(),
1279
- // ...
1280
- ],
1281
- };
1282
- ```
1283
-
1284
- #### Release and channel model
1285
-
1286
- Each app's release workflow runs when a `vX.Y.Z` or `vX.Y.Z-N` tag is pushed. The shared `classify-mobile-release` composite action in [`ionic-angular-library/.github/actions`](https://github.com/rdlabo-dev/ionic-angular-library/tree/main/.github/actions) compares the tag with the previous release and selects the delivery path. Patch and prerelease updates within the same `major.minor` line use `publish-live-update`; major and minor updates use Capawesome Cloud Native Builds and App Store Publishing.
1287
-
1288
- Every delivery channel is named **`production-<native-build-number>`**, where the Android `versionCode` and iOS `CURRENT_PROJECT_VERSION` must match. A Live Update replaces only the JS, HTML, and CSS on an existing native binary, so channels are isolated by build number and updates reach only compatible devices. The upload pins `--android-min/max` and `--ios-min/max` to that build number.
1289
-
1290
- - **Same channel: eligible for Live Update**
1291
- Keep the native build number unchanged. This path is for JS, HTML, and CSS changes only, including bug fixes, copy, UI, application logic, and npm dependencies that do not affect native code. Incrementing only the patch version within the same `major.minor` line keeps the channel unchanged, so existing users receive the update without installing a new store build.
1292
- Example: `9.0.0` (build `9000000`) followed by a web-only `9.0.1` update; both use `production-9000000`.
1293
-
1294
- - **New channel: store release required**
1295
- Increment the major or minor version and the native build number. Include changes to `app/android/**`, `app/ios/**`, `capacitor.config.ts` (or `.json`), and Capacitor plugin versions in this release type. The workflow submits iOS builds to TestFlight and Android builds to the Google Play Internal track; promotion to production happens in each store.
1296
- Example: a native update to `9.1.0` (build `9010000`) creates `production-9010000`. Devices still running `9.0.x` remain on `production-9000000` and are unaffected.
1297
-
1298
- The build number encodes the major and minor versions at the front: `floor(buildNumber / 10000) === major * 100 + minor`.
1299
-
1300
- | Version | Build number | Channel |
1301
- | -------- | ------------ | --------------------- |
1302
- | `9.0.x` | `9000000` | `production-9000000` |
1303
- | `9.1.x` | `9010000` | `production-9010000` |
1304
- | `10.2.x` | `10020000` | `production-10020000` |
1305
-
1306
- `classify-mobile-release` fails CI when a patch or prerelease contains native, configuration, or Capacitor dependency changes and requires a major or minor bump instead. For store releases, it verifies that the tag matches the native marketing version, the Android and iOS versions and build numbers agree, the build number increases, and the encoding above is valid. `validate-live-update` remains available for compatibility with existing consumers.
1307
-
1308
- ---
1309
-
1310
- ## Consumer Vitest setup notes
1311
-
1312
- When testing a consumer app that declares `@rdlabo/ionic-angular-kit` as a `file:` symlink dependency, add the following to your `vitest.config.ts`:
1313
-
1314
- ```typescript
1315
- // vitest.config.ts
1316
- export default defineConfig({
1317
- resolve: {
1318
- dedupe: ['@angular/core', '@angular/common', '@angular/router', '@ionic/angular', '@ionic/core', 'rxjs'],
1319
- },
1320
- test: {
1321
- server: {
1322
- deps: {
1323
- inline: [
1324
- /@ionic\/angular/,
1325
- /@ionic\/core/,
1326
- /ionicons/,
1327
- /@rdlabo\/ionic-angular-kit/, // inline the kit itself
1328
- ],
1329
- },
1330
- },
1331
- },
1332
- });
1333
- ```
40
+ - [Storage and Overlays](./docs/storage-overlays.md)
41
+ - [Authentication and HTTP](./docs/auth-http.md)
42
+ - [Offline and Realtime](./docs/offline-realtime.md)
43
+ - [Optional Features](./docs/optional-features.md)
1334
44
 
1335
- - `resolve.dedupe` prevents Angular's `inject()` from throwing `NG0203 (must be called in an injection context)` when the symlinked kit resolves a different copy of `@angular/core`.
1336
- - `server.deps.inline` is required for ESM packages that Vite cannot handle as external CJS.
1337
- - In test configs, provide all required tokens before testing kit-dependent code: `provideKitOverlay(...)`, `provideKitAuth(...)`, `provideKitHttp(...)`.
45
+ <!-- rdlabo-docs-omit -->
46
+ **Full documentation:** [https://docs.rdlabo.dev/projects/ionic-angular-kit](https://docs.rdlabo.dev/projects/ionic-angular-kit)
47
+ <!-- /rdlabo-docs-omit -->