@rdlabo/ionic-angular-kit 21.5.9 → 21.5.11

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
@@ -391,8 +391,10 @@ A fleet-canonical HTTP interceptor with:
391
391
 
392
392
  The optional `offline` entry point provides a user/partition-scoped local replica, durable outbox, authenticated
393
393
  session boundary, cursor-based delta pull, aggregate-ordered replay, optimistic updates, retry classification, and a
394
- read-only request-policy interceptor. Applications provide URL/DTO read policies, a replica puller, and a command
395
- executor through `provideOffline(...)`.
394
+ read-only request-policy interceptor. Synchronized applications provide URL/DTO read policies, a replica puller, and
395
+ a command executor through `provideOffline(...)`. External-source or HTTP read caches use
396
+ `mode: 'readCacheOnly'`; the kit then supplies the empty pull/executor boundary instead of making every product
397
+ declare dummy adapters.
396
398
  Mutations are queued explicitly with `OfflineSyncService.enqueue`, not through HTTP interceptor policy.
397
399
  Web storage uses Ionic Storage; iOS and Android use encrypted `@capacitor-community/sqlite`. Importing either the
398
400
  primary entry point or `/offline` does not pull the optional native SQLite plugin into web-only applications.
@@ -506,18 +508,24 @@ provideOffline({
506
508
  });
507
509
  ```
508
510
 
509
- Every SQLite entity uses an immutable client-generated UUID as `localId`; the outbox references only
510
- `aggregateLocalId`. Remote identity is declared per entity:
511
+ Replica identity follows the product database:
511
512
 
512
- | Remote identity | SQLite representation | Executor target |
513
- | ------------------------------- | --------------------------------------------- | ----------------------------------------- |
514
- | `serverId()` | nullable `server_id` | `{ localId, serverId }` |
515
- | `naturalKey(['a', 'b'])` | mapped `a`/`b` columns; no `server_id` column | `{ localId, serverId: null, naturalKey }` |
516
- | no remote identity (local-only) | mapped values only | `{ localId, serverId: null }` |
513
+ | Identity declaration | SQLite primary key | Row / executor identity |
514
+ | ---------------------------------- | ------------------------------------------------------------------------ | ------------------------------------------- |
515
+ | `generatedId('integer' \| 'text')` | scope columns + immutable `local_id`; scoped nullable unique `server_id` | `{ kind: 'generated', localId, remoteId }` |
516
+ | `naturalKey(['a', 'b'])` | scope columns plus mapped `a`, `b` columns | `{ kind: 'natural', naturalKey: { a, b } }` |
517
+ | `identity: localOnly()` | scope columns + immutable `local_id` | `{ kind: 'local', localId }` |
517
518
 
518
- A successful numeric create adds `serverId` without replacing `localId`. A natural key is derived from current
519
- mapped values in declaration order; it is not duplicated as hidden row metadata. Entity projection and outbox
520
- append/removal are committed in one local transaction.
519
+ Natural-key tables contain neither `local_id` nor `server_id`; their scoped key columns are the SQLite composite
520
+ `PRIMARY KEY`. Generated remote ids may be positive safe integers or non-empty text ids such as server-generated
521
+ UUIDs. A successful create adds `remoteId` without replacing `localId`. Local-only rows cannot enter the Outbox.
522
+ All TEXT identity components are opaque and compared byte-for-byte with SQLite's `BINARY` collation. The server
523
+ database must use the same binary equality, or the Hono/API converter must return one canonical form before the
524
+ value reaches `naturalKey(...)` or `generatedId('text')`. Do not pass case- or accent-insensitive primary keys
525
+ through unchanged: values that the server considers equal must first be canonicalized to identical TEXT.
526
+
527
+ `OfflineScope.userId` accepts `number | string`. A type-tagged TEXT codec keeps numeric `7` and text `"7"` in
528
+ different metadata, manifest, cursor, Outbox, and entity boundaries.
521
529
 
522
530
  The write lifecycle is: update the replica immediately → append an outbox command in the same transaction → render
523
531
  the optimistic value → replay in the background → validate the server revision → store the confirmed value and
@@ -525,8 +533,8 @@ revision. The server remains authoritative; SQLite is the durable local working
525
533
 
526
534
  For a DB row whose deletion is represented by absence, enqueue the same full row values with
527
535
  `replicaMutation: 'delete'`. The runtime stores a library-owned durable tombstone: normal `getReplicaRow()` and
528
- `getReplicaRows()` reads stop returning the row immediately, while synchronization retains its immutable `localId`,
529
- remote identity, confirmed baseline, and Outbox command. A successful tombstone acknowledgement removes the row
536
+ `getReplicaRows()` reads stop returning the row immediately, while synchronization retains its immutable generated
537
+ or natural identity, confirmed baseline, and Outbox command. A successful tombstone acknowledgement removes the row
530
538
  physically; retry, authorization failure, and conflict keep it hidden; discarding restores the latest confirmed
531
539
  baseline unless the server has also deleted it.
532
540
 
@@ -539,7 +547,10 @@ tombstone for replay, lost-ACK reconciliation, conflict handling, and discard.
539
547
  await offlineSync.enqueue({
540
548
  scopeId,
541
549
  aggregateType: 'favorites',
542
- aggregateLocalId: favorite.localId,
550
+ identity: {
551
+ kind: 'natural',
552
+ naturalKey: { favFrom: favorite.values.favFrom, favTo: favorite.values.favTo },
553
+ },
543
554
  operation: 'favorite.delete',
544
555
  payload: { favTo: favorite.values.favTo },
545
556
  optimisticValue: favorite.values,
@@ -555,10 +566,11 @@ may lower these limits with `outboxLimits: { maxCommandsPerUser, maxBytesPerUser
555
566
  existing replica and Outbox remain unchanged and enqueue rejects with `OfflineOutboxCapacityError`, so the UI can ask
556
567
  the user to reconnect or resolve/discard an attention item.
557
568
 
558
- Use `serverId()` for a positive safe-integer `AUTO_INCREMENT` key. Use `naturalKey([...])` when the product table's
559
- remote identity is an existing composite primary key. Natural-key components must be required mapped `text()` or
560
- `integer()` columns; nullable, ignored, JSON, empty declarations, duplicates, and mixed `serverId()`/`naturalKey()`
561
- declarations reject. Text components reject NUL, malformed Unicode, and values larger than 1,024 UTF-8 bytes.
569
+ Use `generatedId('integer')` for a positive safe-integer `AUTO_INCREMENT` key and `generatedId('text')` for a
570
+ server-generated text key. Use `naturalKey([...])` for an existing single or composite natural primary key.
571
+ Natural-key components must be required mapped `text()` or `integer()` columns; nullable, ignored, JSON, empty
572
+ declarations, duplicates, and mixed generated/natural declarations reject. Text identities reject NUL, malformed
573
+ Unicode, and values larger than 1,024 UTF-8 bytes.
562
574
 
563
575
  When the application already knows the numeric server id but the first replica pull has not materialized the row,
564
576
  pass that identity explicitly while adopting the entity. This is required for updates and especially deletes: an
@@ -568,19 +580,18 @@ omitted id would otherwise make the executor interpret the row as a not-yet-crea
568
580
  await offlineSync.enqueue({
569
581
  scopeId,
570
582
  aggregateType: 'items',
571
- aggregateLocalId: localId,
572
- serverId: existingApiItem.id,
583
+ identity: { kind: 'generated', localId, remoteId: existingApiItem.id },
573
584
  operation: 'items.delete',
574
585
  payload: { method: 'DELETE' },
575
586
  optimisticValue: existingApiItem,
576
587
  });
577
588
  ```
578
589
 
579
- The mapping is immutable and unique inside its effective replica scope. Reassigning one `localId` to another
580
- `serverId` or natural key, or assigning the same remote identity to another `localId`, rejects before persistence.
581
- Web storage enforces the rule transactionally. SQLite uses a scoped partial unique index for `server_id` and a
582
- scoped composite unique index over the natural-key columns: partition-scoped entities are unique per
583
- user/partition/source, and user-scoped entities are unique per user/source across partitions. If an adopted row has
590
+ The mapping is immutable and unique inside its effective replica scope. Reassigning one generated `localId` to
591
+ another `remoteId`, or assigning the same remote identity to another `localId`, rejects before persistence. A
592
+ natural-key change is a delete of the old key plus an insert of the new key, never an update of the primary key.
593
+ Web storage enforces the same rule transactionally. SQLite uses a scoped partial unique index for generated
594
+ `server_id`; natural identity is enforced by the table's scoped composite primary key. If an adopted row has
584
595
  no confirmed baseline and
585
596
  its final command is discarded, the local row is removed; the next pull may materialize the authoritative server
586
597
  row again. A row with a confirmed baseline rolls back to that baseline instead.
@@ -593,23 +604,27 @@ to `conflict`; the new server value is retained as the confirmed baseline. A rem
593
604
  retention rule: without pending commands it removes the row, while a pending row and its Outbox remain under
594
605
  `remote_deleted` conflict so the user can resolve or discard them.
595
606
 
607
+ Hono payloads may call a generated database key `serverId`, while the database-independent runtime calls it
608
+ `remoteId`. Product pullers must use `normalizeOfflineReplicaPullPage(response)` at the HTTP boundary; do not
609
+ reimplement `serverId` stripping/injection per application. Natural-key changes pass through unchanged.
610
+
596
611
  The command adapter must send `commandId` as the server-side idempotency key. The server persists that key with the
597
612
  mutation and returns all keys represented by a delta row as `acknowledgedCommandIds`. This correlation is required:
598
613
  if the server commits a create/update/delete but its HTTP acknowledgement is lost, the next pull reconciles the
599
- server result into the original `localId`, removes the acknowledged outbox prefix, and rebases later commands without
600
- creating a second local identity.
614
+ server result into the same generated or natural identity, removes the acknowledged Outbox prefix, and rebases later
615
+ commands without creating a second local identity.
601
616
 
602
617
  Versioned replica schemas lock web and native storage. Web metadata stores
603
618
  `replicaSchemaVersion` and `replicaSchemaHash`; native stores the same pair in
604
619
  `offline_replica_schema_metadata`. Bump `version` for every intentional shape change and supply a
605
620
  complete one-step migration chain. Native runs each step's SQL `statements`; web runs
606
621
  `migrateWebRow`, which receives only `{ sourceKey, values, confirmedValues }` and may return the same
607
- shape or `null` to delete a row. Identity and sync metadata (`localId`, `serverId`, scope, revision,
622
+ shape or `null` to delete a row. Identity and sync metadata (`identity`, scope, revision,
608
623
  `syncState`) stay outside the callback. The bundle fingerprint hashes `version`, entity layouts, and
609
624
  migration `fromVersion`/`statements` — never function bodies.
610
625
 
611
- Changing a natural-key component list or its order changes the schema fingerprint and SQLite unique index. For a
612
- released schema, bump `version`; native migration SQL must `DROP INDEX` and recreate the scoped composite index, and
626
+ Changing a natural-key component list or its order changes the schema fingerprint and SQLite primary key. For a
627
+ released schema, bump `version`; native migration SQL must rebuild the table with the new composite primary key, and
613
628
  `migrateWebRow` must preserve every natural-key value. Keep the transaction journal and schema-migration recovery
614
629
  records until the replacement rows, index, and metadata commit together. This natural-key API is currently
615
630
  unreleased, so adopting it before the first release needs no compatibility helper or legacy-row migration.
@@ -618,10 +633,11 @@ unreleased, so adopting it before the first release needs no compatibility helpe
618
633
  import {
619
634
  defineOfflineReplicaSchema,
620
635
  defineReplicaEntity,
636
+ generatedId,
621
637
  integer,
638
+ localOnly,
622
639
  naturalKey,
623
640
  provideOffline,
624
- serverId,
625
641
  text,
626
642
  } from '@rdlabo/ionic-angular-kit/offline';
627
643
 
@@ -633,7 +649,7 @@ const itemEntityV2 = defineReplicaEntity<ItemSelect>()({
633
649
  sourceKey: 'items',
634
650
  scope: 'partition',
635
651
  fields: {
636
- id: serverId(),
652
+ id: generatedId('integer'),
637
653
  title: text(),
638
654
  subtitle: text(),
639
655
  },
@@ -680,6 +696,15 @@ provideOffline({
680
696
  commandExecutor: ProductCommandExecutor,
681
697
  // ...request policies, databaseName, createEncryptionKey
682
698
  });
699
+
700
+ // Stripe or another external system is the source of truth; no Outbox exists.
701
+ provideOffline({
702
+ mode: 'readCacheOnly',
703
+ replicaSchema: readCacheSchema,
704
+ requestPolicies: [ReadCacheRequestPolicy],
705
+ databaseName: 'product-read-cache',
706
+ createEncryptionKey,
707
+ });
683
708
  ```
684
709
 
685
710
  Offline replica schema consumers must compile with TypeScript `strictNullChecks: true`. This is part of the standard,
@@ -687,12 +712,14 @@ not a compatibility option: without strict null checking, TypeScript cannot dist
687
712
  from a required one and the schema lock cannot prove the SQLite mapping.
688
713
 
689
714
  The schema definition must import the Hono package's exported `$inferSelect` type and map every key exactly once as
690
- a SQLite column, `serverId()`, or `ignored(reason)`. A remotely replicated entity declares either one numeric
691
- `serverId()` or one ordered `naturalKey([...])`; a local-only projection declares neither.
715
+ a SQLite column, `generatedId('integer' | 'text')`, or `ignored(reason)`. A remotely replicated entity declares
716
+ either one generated-id field or one ordered `naturalKey([...])`; a local-only projection explicitly declares
717
+ `identity: localOnly()`.
692
718
  Nullable Hono columns require `nullable(...)`; non-null columns reject it. Therefore adding,
693
719
  removing, or changing nullability of a Drizzle column breaks the app build until its replica mapping is updated.
694
- At runtime, `values` contains only the mapped column projection; `localId` and numeric `serverId` remain dedicated
695
- replica fields, natural identity is always derived from `values`, and ignored server fields are never persisted.
720
+ At runtime, `values` contains only the mapped column projection. Identity is a discriminated union: generated rows
721
+ carry `localId`/`remoteId`, natural rows carry only `naturalKey`, and local-only rows carry only `localId`. Ignored
722
+ server fields are never persisted.
696
723
 
697
724
  - **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.
698
725
  - **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.