@rdlabo/ionic-angular-kit 21.5.3 → 21.5.5

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
@@ -520,6 +520,13 @@ The write lifecycle is: update the replica immediately → append an outbox comm
520
520
  the optimistic value → replay in the background → validate the server revision → store the confirmed value and
521
521
  revision. The server remains authoritative; SQLite is the durable local working database, not an HTTP response cache.
522
522
 
523
+ The runtime retains pending, rejected, and conflicted commands until synchronization or an explicit user discard;
524
+ it never evicts an unconfirmed mutation because of age or storage pressure. To keep a device that remains offline for
525
+ months from exhausting SQLite, enqueue applies backpressure at 1,000 commands or 10 MiB per user by default. Products
526
+ may lower these limits with `outboxLimits: { maxCommandsPerUser, maxBytesPerUser }`. When a limit is reached, the
527
+ existing replica and Outbox remain unchanged and enqueue rejects with `OfflineOutboxCapacityError`, so the UI can ask
528
+ the user to reconnect or resolve/discard an attention item.
529
+
523
530
  `serverId()` supports positive safe integers only. Products must expose an internal numeric primary key for a
524
531
  replicated entity; a human-facing string such as a public code, slip number, or SKU remains an ordinary replicated
525
532
  column. There is intentionally no text-server-id overload.
@@ -566,8 +566,6 @@ const METADATA_KEY = 'offline:metadata';
566
566
  const SESSION_MANIFESTS_KEY = 'offline:session:manifests';
567
567
  const ROWS_KEY = 'offline:replica:rows';
568
568
  const CURSORS_KEY = 'offline:replica:cursors';
569
- const LEGACY_ENTITIES_KEY = 'offline:business_cache:entities';
570
- const LEGACY_QUERIES_KEY = 'offline:business_cache:queries';
571
569
  const OUTBOX_KEY = 'offline:outbox:commands';
572
570
  const REPLICA_TRANSACTION_KEY = 'offline:replica:transaction';
573
571
  const REPLICA_SCHEMA_MIGRATION_KEY = 'offline:replica:schema-migration';
@@ -724,24 +722,8 @@ class IonicOfflineRepository {
724
722
  async #migrate() {
725
723
  const metadata = await this.#storage.get(METADATA_KEY);
726
724
  if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
727
- await Promise.all([
728
- this.#storage.remove(SESSION_MANIFESTS_KEY),
729
- this.#storage.remove(ROWS_KEY),
730
- this.#storage.remove(CURSORS_KEY),
731
- this.#storage.remove(LEGACY_ENTITIES_KEY),
732
- this.#storage.remove(LEGACY_QUERIES_KEY),
733
- this.#storage.remove(OUTBOX_KEY),
734
- this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY),
735
- ]);
736
- await this.#storage.set(METADATA_KEY, {
737
- schemaVersion: OFFLINE_SCHEMA_VERSION,
738
- lastUserId: metadata.lastUserId ?? null,
739
- replicaSchemaVersion: null,
740
- replicaSchemaHash: null,
741
- });
742
- await this.#storage.remove(REPLICA_TRANSACTION_KEY);
743
- await this.#initializeReplicaSchema(null, null);
744
- return;
725
+ throw new Error(`Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
726
+ 'A lossless core schema migration is required before this database can be opened.');
745
727
  }
746
728
  const interruptedSchemaMigration = await this.#storage.get(REPLICA_SCHEMA_MIGRATION_KEY);
747
729
  if (interruptedSchemaMigration) {
@@ -1198,12 +1180,19 @@ class OfflineReplicaPullService {
1198
1180
  }
1199
1181
  #collapseChanges(changes) {
1200
1182
  const collapsed = new Map();
1201
- for (const change of changes) {
1183
+ for (const [ordinal, change] of changes.entries()) {
1202
1184
  const key = `${change.sourceKey}:${change.serverId}`;
1203
1185
  const previous = collapsed.get(key);
1186
+ const acknowledgedCommandIds = [...new Set([...(previous?.acknowledgedCommandIds ?? []), ...(change.acknowledgedCommandIds ?? [])])];
1187
+ const acknowledgementOrdinals = { ...(previous?.acknowledgementOrdinals ?? {}) };
1188
+ for (const commandId of change.acknowledgedCommandIds ?? []) {
1189
+ acknowledgementOrdinals[commandId] = ordinal;
1190
+ }
1204
1191
  collapsed.set(key, {
1205
1192
  ...change,
1206
- acknowledgedCommandIds: [...new Set([...(previous?.acknowledgedCommandIds ?? []), ...(change.acknowledgedCommandIds ?? [])])],
1193
+ acknowledgedCommandIds,
1194
+ acknowledgementOrdinals,
1195
+ collapsedOrdinal: ordinal,
1207
1196
  });
1208
1197
  }
1209
1198
  return [...collapsed.values()];
@@ -1217,9 +1206,13 @@ class OfflineReplicaPullService {
1217
1206
  if (related.slice(0, lastAcknowledgedIndex + 1).some((command) => !acknowledgedIds.has(command.commandId))) {
1218
1207
  throw new Error(`Replica acknowledgement skipped an earlier aggregate command.`);
1219
1208
  }
1209
+ const lastAcknowledgedCommand = related[lastAcknowledgedIndex];
1210
+ const acknowledgementSuperseded = (change.acknowledgementOrdinals[lastAcknowledgedCommand.commandId] ?? -1) < change.collapsedOrdinal;
1220
1211
  const following = related
1221
1212
  .slice(lastAcknowledgedIndex + 1)
1222
- .map((command) => this.#executor.withServerRevision(command, change.serverRevision));
1213
+ .map((command) => acknowledgementSuperseded
1214
+ ? { ...command, state: 'conflict', retryAt: null, lastErrorCode: change.deleted ? 'remote_deleted' : 'remote_revision' }
1215
+ : this.#executor.withServerRevision(command, change.serverRevision));
1223
1216
  for (const command of following)
1224
1217
  putCommands.set(command.commandId, command);
1225
1218
  for (const command of related.slice(0, lastAcknowledgedIndex + 1)) {
@@ -1247,7 +1240,7 @@ class OfflineReplicaPullService {
1247
1240
  confirmedValues,
1248
1241
  serverRevision: change.serverRevision,
1249
1242
  fetchedAt: Date.now(),
1250
- syncState: following.length > 0 ? 'pending' : 'confirmed',
1243
+ syncState: following.length > 0 ? (acknowledgementSuperseded ? 'conflict' : 'pending') : 'confirmed',
1251
1244
  });
1252
1245
  }
1253
1246
  #assertServerIdAssignment(current, incoming) {
@@ -1479,8 +1472,22 @@ class OfflinePayloadValidationError extends Error {
1479
1472
  this.name = 'OfflinePayloadValidationError';
1480
1473
  }
1481
1474
  }
1475
+ /** Raised before persistence when retaining another command would exceed the configured durable Outbox capacity. */
1476
+ class OfflineOutboxCapacityError extends Error {
1477
+ constructor(reason, currentCommands, currentBytes) {
1478
+ super(reason === 'command_count'
1479
+ ? 'Offline Outbox command limit reached; synchronize or discard a pending command before continuing'
1480
+ : 'Offline Outbox storage limit reached; synchronize or discard a pending command before continuing');
1481
+ this.reason = reason;
1482
+ this.currentCommands = currentCommands;
1483
+ this.currentBytes = currentBytes;
1484
+ this.name = 'OfflineOutboxCapacityError';
1485
+ }
1486
+ }
1482
1487
  const MAX_PARALLEL_AGGREGATES = 3;
1483
1488
  const MAX_BACKOFF_MS = 60 * 60 * 1000;
1489
+ const DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER = 1_000;
1490
+ const DEFAULT_MAX_OUTBOX_BYTES_PER_USER = 10 * 1024 * 1024;
1484
1491
  /** Maintains the optimistic local replica and synchronizes its durable outbox. */
1485
1492
  class OfflineSyncService {
1486
1493
  #network;
@@ -1624,6 +1631,7 @@ class OfflineSyncService {
1624
1631
  createdAt: await this.#nextCommandCreatedAt(userId),
1625
1632
  lastErrorCode: null,
1626
1633
  };
1634
+ await this.#assertOutboxCapacity(userId, command);
1627
1635
  const entityType = this.#entityType(command);
1628
1636
  const existing = await this.#repository.getReplicaRow(scope, entityType, aggregateLocalId);
1629
1637
  const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
@@ -1653,6 +1661,24 @@ class OfflineSyncService {
1653
1661
  this.#flushInBackground();
1654
1662
  return commandId;
1655
1663
  }
1664
+ async #assertOutboxCapacity(userId, command) {
1665
+ const commands = this.#repository.getCommandsForUser
1666
+ ? await this.#repository.getCommandsForUser(userId)
1667
+ : (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => this.#repository.getCommands(scope)))).flat();
1668
+ const maxCommands = this.#options.outboxLimits?.maxCommandsPerUser ?? DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER;
1669
+ const maxBytes = this.#options.outboxLimits?.maxBytesPerUser ?? DEFAULT_MAX_OUTBOX_BYTES_PER_USER;
1670
+ const currentBytes = this.#serializedOutboxBytes(commands);
1671
+ if (commands.length >= maxCommands) {
1672
+ throw new OfflineOutboxCapacityError('command_count', commands.length, currentBytes);
1673
+ }
1674
+ const nextBytes = currentBytes + this.#serializedOutboxBytes([command]);
1675
+ if (nextBytes > maxBytes) {
1676
+ throw new OfflineOutboxCapacityError('serialized_bytes', commands.length, currentBytes);
1677
+ }
1678
+ }
1679
+ #serializedOutboxBytes(commands) {
1680
+ return new TextEncoder().encode(JSON.stringify(commands)).byteLength;
1681
+ }
1656
1682
  async discard(commandId, options = {}) {
1657
1683
  await this.initialize();
1658
1684
  const command = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
@@ -2541,8 +2567,10 @@ class SqliteOfflineRepository {
2541
2567
  }
2542
2568
  if (!commandColumns.some((column) => column['name'] === 'optimistic_value_json')) {
2543
2569
  await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_value_json TEXT');
2544
- await this.#execute(databaseId, 'UPDATE offline_sync_commands SET optimistic_value_json = payload_json');
2545
2570
  }
2571
+ // Keep this repair outside the ADD-column branch so a process/database
2572
+ // failure after ALTER but before backfill is retried on every open.
2573
+ await this.#execute(databaseId, 'UPDATE offline_sync_commands SET optimistic_value_json = payload_json WHERE optimistic_value_json IS NULL');
2546
2574
  await this.#execute(databaseId, `INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)
2547
2575
  ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version`, [OFFLINE_SCHEMA_VERSION]);
2548
2576
  await this.#initializeReplicaSchema(databaseId);
@@ -2834,6 +2862,7 @@ function provideOffline(options) {
2834
2862
  databaseName: options.databaseName,
2835
2863
  createEncryptionKey: options.createEncryptionKey,
2836
2864
  replicaSchema: options.replicaSchema,
2865
+ outboxLimits: options.outboxLimits,
2837
2866
  },
2838
2867
  },
2839
2868
  {
@@ -2915,5 +2944,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2915
2944
  * Generated bundle index. Do not edit.
2916
2945
  */
2917
2946
 
2918
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaServerId, booleanColumn, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
2947
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaServerId, booleanColumn, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
2919
2948
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map