@rdlabo/ionic-angular-kit 21.4.1 → 21.4.2

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
@@ -346,22 +346,48 @@ requests only, a transport failure with `status=0` may return a local replica re
346
346
  `X-Offline-Response: local`. `POST` and other write methods always go to transport unchanged; outbox replay
347
347
  requests bypass policy with `OFFLINE_BYPASS` while still using the same transport observation.
348
348
 
349
- Native applications install the Insiders package in the application, then pass its `Sqlite` export
350
- and an encryption key loaded from secure device storage to the kit:
349
+ The native offline runtime currently requires Capacitor 8, `@capawesome-team/capacitor-sqlite` 0.3.x, and
350
+ `@capawesome-team/capacitor-secure-preferences` 0.2.x. Configure the private Insiders registry with the license key
351
+ before installing the SQLite and Secure Preferences packages plus the SQLite WASM runtime. Supply the license key
352
+ through a local/CI secret; never commit it to `.npmrc`.
351
353
 
352
354
  ```bash
353
- npm install @capawesome-team/capacitor-sqlite
355
+ npm config set @capawesome-team:registry https://npm.registry.capawesome.io
356
+ npm config set //npm.registry.capawesome.io/:_authToken "$CAPAWESOME_LICENSE_KEY"
357
+ npm install @capawesome-team/capacitor-sqlite@^0.3.0 \
358
+ @capawesome-team/capacitor-secure-preferences@^0.2.0 \
359
+ @sqlite.org/sqlite-wasm
360
+ npx cap sync
354
361
  ```
355
362
 
363
+ Applications on an older Capacitor major must not install those versions; upgrade to Capacitor 8 before enabling
364
+ the standard native offline runtime. After installation, follow both plugins' platform steps. In particular, exclude
365
+ `CAPAWESOME_SECURE_PREFERENCES.xml` from Android 11-and-lower `fullBackupContent` and Android 12+ cloud backup rules,
366
+ so the database key is not restored independently of its device keystore material.
367
+
368
+ Pass the `Sqlite` export and a database key loaded from secure device storage to the kit. Never hard-code or derive
369
+ the database key from a user identifier or access token.
370
+
356
371
  ```ts
372
+ import { SecurePreferences } from '@capawesome-team/capacitor-secure-preferences';
373
+ import { Sqlite } from '@capawesome-team/capacitor-sqlite';
374
+
375
+ const OFFLINE_DATABASE_KEY = 'product-offline-database-key';
376
+
377
+ async function offlineDatabaseKey(): Promise<string> {
378
+ const { value } = await SecurePreferences.get({ key: OFFLINE_DATABASE_KEY });
379
+ if (value) return value;
380
+
381
+ const bytes = crypto.getRandomValues(new Uint8Array(32));
382
+ const generated = Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
383
+ await SecurePreferences.set({ key: OFFLINE_DATABASE_KEY, value: generated });
384
+ return generated;
385
+ }
386
+
357
387
  provideOffline({
358
388
  // ...product policies, puller, and executor
359
389
  sqlitePlugin: Sqlite,
360
- encryptionKey: async () => {
361
- const { value } = await securePreferences.get({ key: 'offline-database-key' });
362
- if (!value) throw new Error('offline-database-key is missing');
363
- return value;
364
- },
390
+ encryptionKey: offlineDatabaseKey,
365
391
  });
366
392
  ```
367
393
 
@@ -371,6 +397,42 @@ Immediately before each send, the executor receives the latest `{ localId, serve
371
397
  SQLite; a successful create adds `serverId` without replacing `localId`. Entity projection and outbox
372
398
  append/removal are committed in one local transaction.
373
399
 
400
+ | Identity | SQLite column | Before synchronization | After server acknowledgement |
401
+ | --- | --- | --- | --- |
402
+ | `localId` | `local_id` | client-generated UUID | unchanged UUID |
403
+ | `serverId` | `server_id` | `NULL` for a new entity | positive server `AUTO_INCREMENT` id |
404
+
405
+ The write lifecycle is: update the replica immediately → append an outbox command in the same transaction → render
406
+ the optimistic value → replay in the background → validate the server revision → store the confirmed value and
407
+ revision. The server remains authoritative; SQLite is the durable local working database, not an HTTP response cache.
408
+
409
+ `serverId()` supports positive safe integers only. Products must expose an internal numeric primary key for a
410
+ replicated entity; a human-facing string such as a public code, slip number, or SKU remains an ordinary replicated
411
+ column. There is intentionally no text-server-id overload.
412
+
413
+ When the application already knows the numeric server id but the first replica pull has not materialized the row,
414
+ pass that identity explicitly while adopting the entity. This is required for updates and especially deletes: an
415
+ omitted id would otherwise make the executor interpret the row as a not-yet-created local entity.
416
+
417
+ ```ts
418
+ await offlineSync.enqueue({
419
+ groupId,
420
+ aggregateType: 'items',
421
+ aggregateLocalId: localId,
422
+ serverId: existingApiItem.id,
423
+ operation: 'items.delete',
424
+ payload: { method: 'DELETE' },
425
+ optimisticValue: existingApiItem,
426
+ });
427
+ ```
428
+
429
+ The mapping is immutable and unique inside its effective replica scope. Reassigning one `localId` to another
430
+ `serverId`, or assigning the same `serverId` to another `localId`, rejects before persistence. Web storage enforces
431
+ the same rule transactionally as SQLite's unique indexes: group-scoped entities are unique per user/group/source,
432
+ and user-scoped entities are unique per user/source across groups. If an adopted row has no confirmed baseline and
433
+ its final command is discarded, the local row is removed; the next pull may materialize the authoritative server
434
+ row again. A row with a confirmed baseline rolls back to that baseline instead.
435
+
374
436
  Each synchronization cycle pulls authoritative server deltas before replaying the outbox. Every page carries the
375
437
  replica schema version/hash and advances a durable user/group cursor in the same transaction as its rows. A schema
376
438
  mismatch, malformed row, or non-advancing cursor rejects synchronization without advancing that cursor. If a remote
@@ -440,9 +502,13 @@ provideOffline({
440
502
  });
441
503
  ```
442
504
 
443
- The schema definition must map every `ItemSelect` key exactly once as a SQLite column, `serverId()`, or
444
- `ignored(reason)`, with exactly one `serverId()` per replicated entity. Nullable Hono columns require
445
- `nullable(...)`; non-null columns reject it. Therefore adding,
505
+ Offline replica schema consumers must compile with TypeScript `strictNullChecks: true`. This is part of the standard,
506
+ not a compatibility option: without strict null checking, TypeScript cannot distinguish a nullable Hono property
507
+ from a required one and the schema lock cannot prove the SQLite mapping.
508
+
509
+ The schema definition must import the Hono package's exported `$inferSelect` type and map every key exactly once as
510
+ a SQLite column, `serverId()`, or `ignored(reason)`, with exactly one numeric `serverId()` per replicated entity.
511
+ Nullable Hono columns require `nullable(...)`; non-null columns reject it. Therefore adding,
446
512
  removing, or changing nullability of a Drizzle column breaks the app build until its replica mapping is updated.
447
513
  At runtime, `values` contains only the mapped column projection; `localId` and `serverId` remain dedicated replica
448
514
  fields and ignored server fields are never persisted.
@@ -452,6 +518,8 @@ Encrypted native builds also require the plugin's SQLCipher platform setup: enab
452
518
  CocoaPods, or enable the `SQLCipher` package trait when using Swift Package Manager on iOS. Follow
453
519
  the [Capawesome SQLite installation guide](https://capawesome.io/docs/plugins/sqlite/#installation)
454
520
  for the exact native configuration and export-compliance notes.
521
+ Also follow the [Capawesome Secure Preferences installation guide](https://capawesome.io/docs/plugins/secure-preferences/#installation),
522
+ including its Android backup exclusion rules.
455
523
 
456
524
  - **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.
457
525
  - **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.
@@ -880,13 +880,18 @@ class IonicOfflineRepository {
880
880
  await this.#assertReplicaSchemaLocked();
881
881
  for (const row of transaction.putRows ?? [])
882
882
  this.#validateReplicaRow(row);
883
- if (journal)
884
- await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);
885
883
  const [rows, commands, cursors] = await Promise.all([
886
884
  this.#readRecord(ROWS_KEY),
887
885
  this.#readRecord(OUTBOX_KEY),
888
886
  this.#readRecord(CURSORS_KEY),
889
887
  ]);
888
+ const identityCheckRows = { ...rows };
889
+ for (const row of transaction.putRows ?? []) {
890
+ this.#assertUniqueReplicaServerId(identityCheckRows, row);
891
+ identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)] = row;
892
+ }
893
+ if (journal)
894
+ await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);
890
895
  for (const row of transaction.putRows ?? []) {
891
896
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
892
897
  rows[this.#rowKey(row, row.sourceKey, row.localId)] = {
@@ -956,6 +961,23 @@ class IonicOfflineRepository {
956
961
  if (row.confirmedValues !== null)
957
962
  encodeOfflineReplicaValues(schema, row.confirmedValues);
958
963
  }
964
+ #assertUniqueReplicaServerId(rows, incoming) {
965
+ if (incoming.serverId === null)
966
+ return;
967
+ const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
968
+ const incomingKey = this.#rowKey(incoming, incoming.sourceKey, incoming.localId);
969
+ const collision = Object.entries(rows).find(([key, row]) => {
970
+ if (key === incomingKey)
971
+ return false;
972
+ if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey || row.serverId !== incoming.serverId) {
973
+ return false;
974
+ }
975
+ return schema.scope === 'user' || row.groupId === incoming.groupId;
976
+ });
977
+ if (collision) {
978
+ throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
979
+ }
980
+ }
959
981
  #resolveReplicaEntitySchema(sourceKey) {
960
982
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
961
983
  if (!schema)
@@ -1506,11 +1528,18 @@ class OfflineSyncService {
1506
1528
  };
1507
1529
  const entityType = this.#entityType(command);
1508
1530
  const existing = await this.#repository.getReplicaRow(scope, entityType, aggregateLocalId);
1531
+ const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
1532
+ if (initialServerId !== null) {
1533
+ const mapped = await this.#repository.getReplicaRowByServerId(scope, entityType, initialServerId);
1534
+ if (mapped !== null && mapped.localId !== aggregateLocalId) {
1535
+ throw new Error(`Offline replica serverId ${String(initialServerId)} is already mapped to localId ${mapped.localId}.`);
1536
+ }
1537
+ }
1509
1538
  const optimisticRow = {
1510
1539
  ...scope,
1511
1540
  sourceKey: entityType,
1512
1541
  localId: aggregateLocalId,
1513
- serverId: existing?.serverId ?? null,
1542
+ serverId: initialServerId,
1514
1543
  values: optimisticValue,
1515
1544
  confirmedValues: existing?.confirmedValues ?? existing?.values ?? null,
1516
1545
  serverRevision: existing?.serverRevision ?? normalized.baseRevision,
@@ -1725,7 +1754,7 @@ class OfflineSyncService {
1725
1754
  if (!row)
1726
1755
  continue;
1727
1756
  const remaining = all.filter((item) => !discardedIds.has(item.commandId) && this.#aggregateKey(item) === key);
1728
- if (remaining.length === 0 && row.confirmedValues === null && row.serverId === null) {
1757
+ if (remaining.length === 0 && row.confirmedValues === null) {
1729
1758
  removeRows.push(row);
1730
1759
  }
1731
1760
  else {
@@ -1790,6 +1819,9 @@ class OfflineSyncService {
1790
1819
  }
1791
1820
  return incoming;
1792
1821
  }
1822
+ #initialServerId(current, incoming) {
1823
+ return incoming === null || incoming === undefined ? current : this.#resolvedServerId(current, incoming);
1824
+ }
1793
1825
  async #discoverScopes(generation = this.#generation) {
1794
1826
  const session = await this.#context.getSession();
1795
1827
  if (!this.#isCurrent(generation))