@rdlabo/ionic-angular-kit 21.5.33 → 21.5.35

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.
@@ -909,9 +909,13 @@ function canonicalOfflineReplicaRowKey(schema, row) {
909
909
  }
910
910
  /** DI token for the selected platform repository. */
911
911
  const OFFLINE_REPOSITORY = new InjectionToken('OFFLINE_REPOSITORY');
912
- /** Selects encrypted SQLite on native platforms and Ionic Storage on web. */
912
+ /** Returns whether the platform uses the cross-process-safe native repository. */
913
+ function supportsSynchronizedOfflineRepository(platform) {
914
+ return platform === 'ios' || platform === 'android';
915
+ }
916
+ /** Selects encrypted SQLite on native platforms and Ionic Storage elsewhere. */
913
917
  function selectOfflineRepository(platform, webRepository, nativeRepository) {
914
- return platform === 'ios' || platform === 'android' ? nativeRepository : webRepository;
918
+ return supportsSynchronizedOfflineRepository(platform) ? nativeRepository : webRepository;
915
919
  }
916
920
  const METADATA_KEY = 'offline:metadata';
917
921
  const SESSION_MANIFESTS_KEY = 'offline:session:manifests';
@@ -932,6 +936,9 @@ class IonicOfflineRepository {
932
936
  #options = inject(OFFLINE_KIT_OPTIONS);
933
937
  #initialization = null;
934
938
  #writes = Promise.resolve();
939
+ #activeReaders = 0;
940
+ #readersIdle = Promise.resolve();
941
+ #resolveReadersIdle = null;
935
942
  #rowIndexBuild = null;
936
943
  initialize() {
937
944
  if (!this.#initialization) {
@@ -943,18 +950,16 @@ class IonicOfflineRepository {
943
950
  return this.#initialization;
944
951
  }
945
952
  async getLastUserId() {
946
- await this.initialize();
947
- return (await this.#metadata()).lastUserId;
953
+ return this.#withCommittedRead(() => this.#readLastUserId());
948
954
  }
949
955
  async setLastUserId(userId) {
950
956
  await this.initialize();
951
- await this.#storage.set(METADATA_KEY, { ...(await this.#metadata()), lastUserId: userId });
957
+ await this.#enqueueWrite(async () => {
958
+ await this.#storage.set(METADATA_KEY, { ...(await this.#metadata()), lastUserId: userId });
959
+ });
952
960
  }
953
961
  async getSessionManifest(userId) {
954
- await this.initialize();
955
- await this.#writes;
956
- const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
957
- return manifests[canonicalOfflinePrincipalId(userId)] ?? null;
962
+ return this.#withCommittedRead(() => this.#readSessionManifest(userId));
958
963
  }
959
964
  async putSessionManifest(userId, value) {
960
965
  await this.initialize();
@@ -964,26 +969,61 @@ class IonicOfflineRepository {
964
969
  });
965
970
  }
966
971
  async getReplicaRow(scope, sourceKey, identity) {
967
- await this.initialize();
968
- await this.#writes;
969
- const schema = this.#resolveReplicaEntitySchema(sourceKey);
970
- const rows = await this.#readRowPartition(scope, sourceKey, schema);
971
- const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
972
- if (!row || (row.visibility ?? 'present') === 'pending_delete')
973
- return null;
974
- return this.#rowForScope(row, schema, scope);
972
+ return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, false));
975
973
  }
976
974
  async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
977
- await this.initialize();
978
- await this.#writes;
975
+ return this.#withCommittedRead(() => this.#readReplicaRow(scope, sourceKey, identity, true));
976
+ }
977
+ async getReplicaRows(scope, sourceKey) {
978
+ return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
979
+ }
980
+ async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
981
+ if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
982
+ return null;
983
+ return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
984
+ }
985
+ async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
986
+ return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));
987
+ }
988
+ async getReplicaCursor(scope) {
989
+ return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
990
+ }
991
+ async getReconciliationScopes(userId) {
992
+ return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
993
+ }
994
+ async getCommands(scope) {
995
+ return this.#withCommittedRead(() => this.#readCommands(scope));
996
+ }
997
+ async getCommandsForUser(userId) {
998
+ return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
999
+ }
1000
+ async runReadSnapshot(read) {
1001
+ return this.#withCommittedRead(() => read(this.#reader()));
1002
+ }
1003
+ #normalizeCommand(command) {
1004
+ if (command.serverCommitUnknown !== undefined)
1005
+ return command;
1006
+ const legacyAmbiguousFailure = command.attempts >= 2 && ['blocked_auth', 'conflict', 'rejected'].includes(command.state);
1007
+ return command.state === 'sending' || command.state === 'retry_wait' || legacyAmbiguousFailure
1008
+ ? { ...command, serverCommitUnknown: true }
1009
+ : command;
1010
+ }
1011
+ async #readLastUserId() {
1012
+ return (await this.#metadata()).lastUserId;
1013
+ }
1014
+ async #readSessionManifest(userId) {
1015
+ const manifests = await this.#readRecord(SESSION_MANIFESTS_KEY);
1016
+ return manifests[canonicalOfflinePrincipalId(userId)] ?? null;
1017
+ }
1018
+ async #readReplicaRow(scope, sourceKey, identity, includePendingDelete) {
979
1019
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
980
1020
  const rows = await this.#readRowPartition(scope, sourceKey, schema);
981
1021
  const row = this.#findRowByAddress(rows, scope, sourceKey, schema, identity);
982
- return row ? this.#rowForScope(row, schema, scope) : null;
1022
+ if (!row || (!includePendingDelete && (row.visibility ?? 'present') === 'pending_delete'))
1023
+ return null;
1024
+ return this.#rowForScope(row, schema, scope);
983
1025
  }
984
- async getReplicaRows(scope, sourceKey) {
985
- await this.initialize();
986
- await this.#writes;
1026
+ async #readReplicaRows(scope, sourceKey) {
987
1027
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
988
1028
  const rows = await this.#readRowPartition(scope, sourceKey, schema);
989
1029
  return Object.values(rows)
@@ -997,14 +1037,7 @@ class IonicOfflineRepository {
997
1037
  .map((row) => this.#rowForScope(row, schema, scope))
998
1038
  .sort((left, right) => this.#compareReplicaIdentity(schema, left.identity, right.identity));
999
1039
  }
1000
- async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
1001
- if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
1002
- return null;
1003
- return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
1004
- }
1005
- async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
1006
- await this.initialize();
1007
- await this.#writes;
1040
+ async #readReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
1008
1041
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
1009
1042
  const canonical = canonicalOfflineRemoteIdentity(schema, identity);
1010
1043
  const rows = await this.#readRowPartition(scope, sourceKey, schema);
@@ -1018,44 +1051,77 @@ class IonicOfflineRepository {
1018
1051
  });
1019
1052
  return row ? this.#rowForScope(row, schema, scope) : null;
1020
1053
  }
1021
- async getReplicaCursor(scope) {
1022
- await this.initialize();
1023
- await this.#writes;
1054
+ async #readReplicaCursor(scope) {
1024
1055
  const cursors = await this.#readRecord(CURSORS_KEY);
1025
1056
  const cursor = cursors[this.#cursorKey(scope)];
1026
1057
  return cursor === undefined ? null : { ...scope, cursor };
1027
1058
  }
1028
- async getReconciliationScopes(userId) {
1029
- await this.initialize();
1030
- await this.#writes;
1059
+ async #readReconciliationScopes(userId) {
1031
1060
  const scopes = await this.#readRecord(RECONCILIATION_SCOPES_KEY);
1032
1061
  return Object.values(scopes).filter((scope) => scope.userId === userId);
1033
1062
  }
1034
- async getCommands(scope) {
1035
- await this.initialize();
1036
- await this.#writes;
1063
+ async #readCommands(scope) {
1037
1064
  const commands = await this.#readRecord(OUTBOX_KEY);
1038
1065
  return Object.values(commands)
1039
1066
  .filter((command) => command.userId === scope.userId && command.scopeId === scope.scopeId)
1040
1067
  .map((command) => this.#normalizeCommand(command))
1041
1068
  .sort(compareOfflineCommands$1);
1042
1069
  }
1043
- async getCommandsForUser(userId) {
1044
- await this.initialize();
1045
- await this.#writes;
1070
+ async #readCommandsForUser(userId) {
1046
1071
  const commands = await this.#readRecord(OUTBOX_KEY);
1047
1072
  return Object.values(commands)
1048
1073
  .filter((command) => command.userId === userId)
1049
1074
  .map((command) => this.#normalizeCommand(command))
1050
1075
  .sort(compareOfflineCommands$1);
1051
1076
  }
1052
- #normalizeCommand(command) {
1053
- if (command.serverCommitUnknown !== undefined)
1054
- return command;
1055
- const legacyAmbiguousFailure = command.attempts >= 2 && ['blocked_auth', 'conflict', 'rejected'].includes(command.state);
1056
- return command.state === 'sending' || command.state === 'retry_wait' || legacyAmbiguousFailure
1057
- ? { ...command, serverCommitUnknown: true }
1058
- : command;
1077
+ #reader() {
1078
+ return {
1079
+ getLastUserId: () => this.#readLastUserId(),
1080
+ getSessionManifest: (userId) => this.#readSessionManifest(userId),
1081
+ getReplicaRow: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, false),
1082
+ getReplicaRowIncludingPendingDelete: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, true),
1083
+ getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
1084
+ getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
1085
+ if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
1086
+ return null;
1087
+ return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
1088
+ },
1089
+ getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
1090
+ getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
1091
+ getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
1092
+ getCommands: (scope) => this.#readCommands(scope),
1093
+ getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
1094
+ };
1095
+ }
1096
+ async #withCommittedRead(operation) {
1097
+ await this.initialize();
1098
+ // Finish index readiness first (may enqueue a write). Then await the latest write
1099
+ // tail and register the reader synchronously — no await gap for a writer to start.
1100
+ await this.#ensureRowPartitionsReady();
1101
+ await this.#writes;
1102
+ this.#beginReaders();
1103
+ try {
1104
+ return await operation();
1105
+ }
1106
+ finally {
1107
+ this.#endReaders();
1108
+ }
1109
+ }
1110
+ #beginReaders() {
1111
+ if (this.#activeReaders === 0) {
1112
+ this.#readersIdle = new Promise((resolve) => {
1113
+ this.#resolveReadersIdle = resolve;
1114
+ });
1115
+ }
1116
+ this.#activeReaders += 1;
1117
+ }
1118
+ #endReaders() {
1119
+ this.#activeReaders -= 1;
1120
+ if (this.#activeReaders === 0) {
1121
+ this.#resolveReadersIdle?.();
1122
+ this.#resolveReadersIdle = null;
1123
+ this.#readersIdle = Promise.resolve();
1124
+ }
1059
1125
  }
1060
1126
  async putCommand(command) {
1061
1127
  await this.initialize();
@@ -1352,13 +1418,25 @@ class IonicOfflineRepository {
1352
1418
  return cached;
1353
1419
  if (await this.#storage.get(ROW_PARTITION_READY_KEY))
1354
1420
  return {};
1421
+ // Non-mutating fallback under a reader lease (indexes are normally built before the lease).
1422
+ return this.#legacyRowPartition(scope, sourceKey, schema);
1423
+ }
1424
+ async #legacyRowPartition(scope, sourceKey, schema) {
1425
+ const rows = await this.#readRecord(ROWS_KEY);
1426
+ return Object.fromEntries(Object.entries(rows).filter(([, row]) => {
1427
+ if (row.userId !== scope.userId || row.sourceKey !== sourceKey)
1428
+ return false;
1429
+ return schema.scope === 'user' || row.scopeId === scope.scopeId;
1430
+ }));
1431
+ }
1432
+ async #ensureRowPartitionsReady() {
1433
+ if (await this.#storage.get(ROW_PARTITION_READY_KEY))
1434
+ return;
1355
1435
  await this.#buildRowPartitions();
1356
- const built = await this.#storage.get(key);
1357
- return built ?? {};
1358
1436
  }
1359
1437
  #buildRowPartitions() {
1360
1438
  if (!this.#rowIndexBuild) {
1361
- const build = this.#enqueueWrite(async () => {
1439
+ const run = async () => {
1362
1440
  if (await this.#storage.get(ROW_PARTITION_READY_KEY))
1363
1441
  return;
1364
1442
  const rows = await this.#readRecord(ROWS_KEY);
@@ -1372,7 +1450,8 @@ class IonicOfflineRepository {
1372
1450
  }
1373
1451
  await Promise.all([...partitions].map(([key, partition]) => this.#storage.set(key, partition)));
1374
1452
  await this.#storage.set(ROW_PARTITION_READY_KEY, true);
1375
- });
1453
+ };
1454
+ const build = this.#enqueueWrite(run);
1376
1455
  this.#rowIndexBuild = build.finally(() => {
1377
1456
  this.#rowIndexBuild = null;
1378
1457
  });
@@ -1423,7 +1502,11 @@ class IonicOfflineRepository {
1423
1502
  await this.#storage.set(key, mutate(record));
1424
1503
  }
1425
1504
  #enqueueWrite(operation) {
1426
- const write = this.#writes.then(operation);
1505
+ const write = this.#writes.then(async () => {
1506
+ if (this.#activeReaders > 0)
1507
+ await this.#readersIdle;
1508
+ return operation();
1509
+ });
1427
1510
  this.#writes = write.then(() => undefined, () => undefined);
1428
1511
  return write;
1429
1512
  }
@@ -1614,6 +1697,24 @@ function compareUtf8Binary(left, right) {
1614
1697
  return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
1615
1698
  }
1616
1699
 
1700
+ /**
1701
+ * Pull handshake reported a replica schema version/hash that does not match the local Kit schema.
1702
+ *
1703
+ * Prefer `instanceof` (or {@link OfflineReplicaSchemaMismatchError.code}) over English message text.
1704
+ */
1705
+ class OfflineReplicaSchemaMismatchError extends Error {
1706
+ /** Stable machine-readable discriminator for fatal pull classification (pre- and post-send). */
1707
+ static { this.code = 'OFFLINE_REPLICA_SCHEMA_MISMATCH'; }
1708
+ constructor(clientVersion, clientHash, serverVersion, serverHash) {
1709
+ super(`Offline replica schema mismatch: client=${clientVersion}/${clientHash}, server=${serverVersion}/${serverHash}.`);
1710
+ this.clientVersion = clientVersion;
1711
+ this.clientHash = clientHash;
1712
+ this.serverVersion = serverVersion;
1713
+ this.serverHash = serverHash;
1714
+ this.code = OfflineReplicaSchemaMismatchError.code;
1715
+ this.name = 'OfflineReplicaSchemaMismatchError';
1716
+ }
1717
+ }
1617
1718
  /** Pulls authoritative server deltas into one durable local replica partition. */
1618
1719
  class OfflineReplicaPullService {
1619
1720
  #repository = inject(OFFLINE_REPOSITORY);
@@ -1978,7 +2079,7 @@ class OfflineReplicaPullService {
1978
2079
  }
1979
2080
  #assertHandshake(version, hash, expectedHash) {
1980
2081
  if (version !== this.#options.replicaSchema.version || hash !== expectedHash) {
1981
- throw new Error(`Offline replica schema mismatch: client=${this.#options.replicaSchema.version}/${expectedHash}, server=${version}/${hash}.`);
2082
+ throw new OfflineReplicaSchemaMismatchError(this.#options.replicaSchema.version, expectedHash, version, hash);
1982
2083
  }
1983
2084
  }
1984
2085
  #entitySchema(sourceKey) {
@@ -2374,6 +2475,26 @@ const MAX_BACKOFF_MS = 60 * 60 * 1000;
2374
2475
  const POST_SEND_PULL_RETRY_MS = 1_000;
2375
2476
  const DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER = 1_000;
2376
2477
  const DEFAULT_MAX_OUTBOX_BYTES_PER_USER = 10 * 1024 * 1024;
2478
+ /** Injectable `[0, 1)` source used by equal-jitter retry delay. Defaults to `Math.random`. */
2479
+ const OFFLINE_RETRY_RANDOM = new InjectionToken('OFFLINE_RETRY_RANDOM', {
2480
+ factory: () => Math.random,
2481
+ });
2482
+ /**
2483
+ * Equal-jitter delay in `[⌊cap/2⌋, cap)` for exponential offline command backoff.
2484
+ * Keeps a positive lower bound (half the exponential cap) while still desynchronizing clients.
2485
+ *
2486
+ * @param attempts - Attempt count already recorded on the failed command (`>= 1` after a send claim).
2487
+ * @param random - Unit interval sample in `[0, 1)`.
2488
+ */
2489
+ function offlineRetryDelayMs(attempts, random = Math.random) {
2490
+ const cap = Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, attempts - 1));
2491
+ const unit = random();
2492
+ if (!(unit >= 0 && unit < 1)) {
2493
+ throw new Error('Offline retry random() must return a number in [0, 1).');
2494
+ }
2495
+ const half = cap / 2;
2496
+ return Math.floor(half + unit * half);
2497
+ }
2377
2498
  /** Maintains the optimistic local replica and synchronizes its durable outbox. */
2378
2499
  class OfflineSyncService {
2379
2500
  #network;
@@ -2385,6 +2506,7 @@ class OfflineSyncService {
2385
2506
  #pull;
2386
2507
  #replicaMutations;
2387
2508
  #errorHandler;
2509
+ #retryRandom;
2388
2510
  #commands;
2389
2511
  #knownScopes;
2390
2512
  /** ACKed scopes whose authoritative post-send pull has not completed yet. */
@@ -2412,6 +2534,7 @@ class OfflineSyncService {
2412
2534
  this.#pull = inject(OfflineReplicaPullService);
2413
2535
  this.#replicaMutations = inject(OfflineReplicaMutationCoordinator);
2414
2536
  this.#errorHandler = inject(ErrorHandler);
2537
+ this.#retryRandom = inject(OFFLINE_RETRY_RANDOM);
2415
2538
  this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
2416
2539
  this.#knownScopes = new Map();
2417
2540
  /** ACKed scopes whose authoritative post-send pull has not completed yet. */
@@ -2436,6 +2559,9 @@ class OfflineSyncService {
2436
2559
  const commands = this.#commands();
2437
2560
  if (commands.some((command) => ['blocked_auth', 'rejected', 'conflict'].includes(command.state)))
2438
2561
  return 'attention';
2562
+ // Any non-sending ambiguous commit (including restart-normalized pending+unknown) needs attention.
2563
+ if (commands.some((command) => command.state !== 'sending' && command.serverCommitUnknown === true))
2564
+ return 'attention';
2439
2565
  if (commands.some((command) => command.state === 'sending'))
2440
2566
  return 'syncing';
2441
2567
  return commands.length > 0 ? 'pending' : 'idle';
@@ -2564,6 +2690,44 @@ class OfflineSyncService {
2564
2690
  return this.#enqueue(prepared.request, options, generation, prepared.replicaTransaction, replaced);
2565
2691
  });
2566
2692
  }
2693
+ /**
2694
+ * Atomically rematerializes every unresolved intent for one aggregate.
2695
+ *
2696
+ * This is the conflict-recovery boundary for ordered intent chains: the old
2697
+ * chain remains durable until every replacement has been prepared and the
2698
+ * complete chain can be committed in one replica transaction.
2699
+ */
2700
+ replacePreparedAggregate(commandId, prepare, options = {}) {
2701
+ const generation = this.#generation;
2702
+ return this.#serializeReplicaMutation(async () => {
2703
+ await this.initialize();
2704
+ if (!this.#isCurrent(generation))
2705
+ throw new Error('Offline session changed before prepared aggregate replacement.');
2706
+ const knownCommands = await this.#readKnownCommands();
2707
+ const selected = knownCommands.find((command) => command.commandId === commandId);
2708
+ if (!selected)
2709
+ throw new Error(`Offline command ${commandId} no longer exists.`);
2710
+ const aggregateKey = this.#aggregateKey(selected);
2711
+ const replaced = knownCommands.filter((command) => this.#aggregateKey(command) === aggregateKey);
2712
+ this.#assertDiscardable(replaced);
2713
+ const prepared = await prepare(this.#repository, replaced);
2714
+ if (prepared.length !== replaced.length) {
2715
+ throw new Error('Offline aggregate replacement must preserve the ordered intent count.');
2716
+ }
2717
+ const session = await this.#beginEnqueueSession(generation);
2718
+ const materializations = [];
2719
+ for (const [index, entry] of prepared.entries()) {
2720
+ this.#assertEnqueueScope(session, entry.request.scopeId);
2721
+ materializations.push(await this.#materializeEnqueue(session.userId, entry.request, entry.replicaTransaction, replaced[index]));
2722
+ }
2723
+ const retained = knownCommands.filter((command) => !replaced.some((item) => item.commandId === command.commandId));
2724
+ this.#assertDistinctBatchFootprints(materializations, retained, true);
2725
+ await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), replaced.map((command) => command.commandId), knownCommands);
2726
+ options.assertCurrent?.();
2727
+ await this.#commitMaterializedEnqueues(materializations, generation, options, replaced.map((command) => command.commandId));
2728
+ return materializations.map((item) => item.command.commandId);
2729
+ });
2730
+ }
2567
2731
  /**
2568
2732
  * Serializes a product-owned replica projection with enqueue and command ACK
2569
2733
  * reconciliation. For read/derive/write cache updates, prefer
@@ -2601,7 +2765,7 @@ class OfflineSyncService {
2601
2765
  const currentCommands = await this.#commandsForUser(session.userId);
2602
2766
  const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
2603
2767
  this.#assertDistinctBatchFootprints([materialization], retainedCommands);
2604
- await this.#assertOutboxCapacity(session.userId, [materialization.command], replaced?.commandId, currentCommands);
2768
+ await this.#assertOutboxCapacity(session.userId, [materialization.command], replaced ? [replaced.commandId] : undefined, currentCommands);
2605
2769
  await this.#commitMaterializedEnqueues([materialization], generation, options, replaced ? [replaced.commandId] : undefined);
2606
2770
  return materialization.command.commandId;
2607
2771
  }
@@ -2751,7 +2915,7 @@ class OfflineSyncService {
2751
2915
  command = { ...command, optimisticCompanions };
2752
2916
  return { command, optimisticRow, optimisticCompanions };
2753
2917
  }
2754
- #assertDistinctBatchFootprints(entries, existingCommands) {
2918
+ #assertDistinctBatchFootprints(entries, existingCommands, allowOneAggregate = false) {
2755
2919
  const aggregates = new Set();
2756
2920
  const replicaKeys = new Set();
2757
2921
  const existingFootprints = new Map();
@@ -2762,7 +2926,7 @@ class OfflineSyncService {
2762
2926
  }
2763
2927
  for (const entry of entries) {
2764
2928
  const aggregate = this.#aggregateKey(entry.command);
2765
- if (aggregates.has(aggregate)) {
2929
+ if (aggregates.has(aggregate) && !allowOneAggregate) {
2766
2930
  throw new Error('Prepared offline batch contains overlapping aggregate intents.');
2767
2931
  }
2768
2932
  aggregates.add(aggregate);
@@ -2770,7 +2934,7 @@ class OfflineSyncService {
2770
2934
  this.#replicaRowKey(entry.optimisticRow),
2771
2935
  ...entry.optimisticCompanions.map((companion) => this.#replicaRowKey(companion.key)),
2772
2936
  ]) {
2773
- if (replicaKeys.has(key)) {
2937
+ if (replicaKeys.has(key) && !allowOneAggregate) {
2774
2938
  throw new Error('Prepared offline batch contains overlapping replica footprints.');
2775
2939
  }
2776
2940
  const existingAggregate = existingFootprints.get(key);
@@ -2889,10 +3053,10 @@ class OfflineSyncService {
2889
3053
  #replicaRowKey(key) {
2890
3054
  return canonicalOfflineReplicaRowKey(this.#entitySchema(key.sourceKey), key);
2891
3055
  }
2892
- async #assertOutboxCapacity(userId, newCommands, excludingCommandId, knownCommands) {
3056
+ async #assertOutboxCapacity(userId, newCommands, excludingCommandIds, knownCommands) {
2893
3057
  const currentCommands = knownCommands ?? (await this.#commandsForUser(userId));
2894
- const commands = excludingCommandId
2895
- ? currentCommands.filter((candidate) => candidate.commandId !== excludingCommandId)
3058
+ const commands = excludingCommandIds
3059
+ ? currentCommands.filter((candidate) => !excludingCommandIds.includes(candidate.commandId))
2896
3060
  : currentCommands;
2897
3061
  const maxCommands = this.#options.outboxLimits?.maxCommandsPerUser ?? DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER;
2898
3062
  const maxBytes = this.#options.outboxLimits?.maxBytesPerUser ?? DEFAULT_MAX_OUTBOX_BYTES_PER_USER;
@@ -3037,23 +3201,36 @@ class OfflineSyncService {
3037
3201
  const pullScopes = isPartial
3038
3202
  ? this.#scopesForPartialPull(this.#foregroundScopePolicy, await this.#readKnownCommands())
3039
3203
  : [...this.#knownScopes.values()];
3204
+ const prePullFailures = [];
3205
+ let fatalPullFailure = null;
3206
+ const pulledScopeKeys = new Set();
3040
3207
  for (const scope of pullScopes) {
3041
3208
  if (!this.#isCurrent(generation) || !this.#network.connected())
3042
3209
  return;
3043
3210
  try {
3044
3211
  await this.#pull.pull(scope);
3045
3212
  await this.#markScopeReconciled(scope, generation);
3213
+ pulledScopeKeys.add(this.#scopeKey(scope));
3046
3214
  }
3047
3215
  catch (error) {
3216
+ prePullFailures.push(error);
3217
+ if (this.#isFatalPullFailure(error)) {
3218
+ // Auth/upgrade-driven recovery only: stop remaining scopes immediately.
3219
+ fatalPullFailure = fatalPullFailure ?? error;
3220
+ break;
3221
+ }
3048
3222
  if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {
3049
3223
  this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
3050
3224
  }
3051
- throw error;
3052
3225
  }
3053
3226
  }
3054
3227
  const dirtyScopes = new Map();
3055
- while (this.#network.connected() && this.#isCurrent(generation)) {
3056
- const groups = this.#eligibleAggregateGroups(await this.#readKnownCommands());
3228
+ const sendWorkerFailures = [];
3229
+ while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
3230
+ const groups = this.#eligibleAggregateGroups(await this.#readKnownCommands()).filter((group) => {
3231
+ const head = group[0];
3232
+ return head !== undefined && pulledScopeKeys.has(this.#scopeKey(head));
3233
+ });
3057
3234
  if (!this.#isCurrent(generation))
3058
3235
  return;
3059
3236
  if (groups.length === 0)
@@ -3063,40 +3240,74 @@ class OfflineSyncService {
3063
3240
  while (cursor < groups.length) {
3064
3241
  const group = groups[cursor++];
3065
3242
  if (group && this.#isCurrent(generation))
3066
- await this.#sendAggregate(group, generation, dirtyScopes);
3243
+ await this.#sendAggregate(group, generation, dirtyScopes, pulledScopeKeys);
3067
3244
  }
3068
3245
  });
3069
- await Promise.all(workers);
3246
+ // Drain with allSettled so one rejecting worker cannot skip sibling settlement or post-send pull.
3247
+ const settled = await Promise.allSettled(workers);
3248
+ for (const result of settled) {
3249
+ if (result.status === 'rejected')
3250
+ sendWorkerFailures.push(result.reason);
3251
+ }
3252
+ if (sendWorkerFailures.length > 0)
3253
+ break;
3070
3254
  }
3071
3255
  for (const scope of dirtyScopes.values()) {
3072
3256
  this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
3073
3257
  }
3074
3258
  const postPullFailures = [];
3075
- for (const scope of this.#pendingPullScopes.values()) {
3076
- if (!this.#isCurrent(generation) || !this.#network.connected())
3077
- break;
3078
- try {
3079
- // A command response may contain only the aggregate's base row. Pull
3080
- // once per dirty scope so sibling-table journal entries are visible
3081
- // before the completed Outbox state is exposed to product UI.
3082
- await this.#pull.pull(scope);
3083
- await this.#markScopeReconciled(scope, generation);
3084
- }
3085
- catch (error) {
3086
- postPullFailures.push(error);
3259
+ // Fatal pre-pull skips pending post-pulls; recovery is auth/upgrade-driven, not timer retry.
3260
+ // Fatal post-send pull stops remaining pending scopes the same way (ACK preserved, no resend).
3261
+ if (fatalPullFailure === null) {
3262
+ for (const scope of this.#pendingPullScopes.values()) {
3263
+ if (!this.#isCurrent(generation) || !this.#network.connected())
3264
+ break;
3265
+ try {
3266
+ // A command response may contain only the aggregate's base row. Pull
3267
+ // once per dirty scope so sibling-table journal entries are visible
3268
+ // before the completed Outbox state is exposed to product UI.
3269
+ await this.#pull.pull(scope);
3270
+ await this.#markScopeReconciled(scope, generation);
3271
+ }
3272
+ catch (error) {
3273
+ if (this.#isFatalPullFailure(error)) {
3274
+ fatalPullFailure = fatalPullFailure ?? error;
3275
+ break;
3276
+ }
3277
+ postPullFailures.push(error);
3278
+ }
3087
3279
  }
3088
3280
  }
3089
3281
  await this.#refreshState(generation);
3090
- if (postPullFailures.length > 0 && this.#isCurrent(generation)) {
3091
- // The server command is already committed and acknowledged locally, so
3092
- // never resend it. Retry only the idempotent scope pull and surface the
3093
- // failure to explicit flush callers/ErrorHandler.
3094
- this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
3095
- throw postPullFailures[0];
3282
+ if (fatalPullFailure !== null) {
3283
+ // Auth/upgrade recovery only — never arm the 1s automatic flush retry.
3284
+ // Post-send ACK already removed the command; reconciliation markers remain for later recovery.
3285
+ // Only the owning generation may clear the timer — a stale fatal must not disarm a
3286
+ // newer session's already-armed retry_wait / post-pull retry.
3287
+ if (this.#isCurrent(generation))
3288
+ this.#scheduleRetry(null);
3289
+ throw fatalPullFailure;
3290
+ }
3291
+ const failures = [...prePullFailures, ...sendWorkerFailures, ...postPullFailures];
3292
+ if (failures.length > 0) {
3293
+ // Keep rejecting the flush promise after workers settle even when the session
3294
+ // was revoked mid-flight, so callers and ErrorHandler still observe the failure.
3295
+ if (this.#isCurrent(generation)) {
3296
+ this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
3297
+ }
3298
+ throw failures[0];
3096
3299
  }
3097
3300
  if (this.#isCurrent(generation))
3098
3301
  this.#coldReconciliationRequired = false;
3099
3302
  }
3303
+ #isFatalPullFailure(error) {
3304
+ const status = this.#errorStatus(error);
3305
+ // Pull-protocol HTTP 409 is schema mismatch (distinct from command-send conflict
3306
+ // classification elsewhere in this service). Same classifier for pre-pull and post-send pull.
3307
+ if (status === 401 || status === 403 || status === 409)
3308
+ return true;
3309
+ return error instanceof OfflineReplicaSchemaMismatchError;
3310
+ }
3100
3311
  #setForegroundScopePolicy(foregroundScopeIds) {
3101
3312
  this.#foregroundScopePolicy = foregroundScopeIds !== undefined ? foregroundScopeIds : null;
3102
3313
  }
@@ -3121,7 +3332,7 @@ class OfflineSyncService {
3121
3332
  return head?.state === 'pending' || (head?.state === 'retry_wait' && (head.retryAt ?? 0) <= now);
3122
3333
  });
3123
3334
  }
3124
- async #sendAggregate(commands, generation, dirtyScopes) {
3335
+ async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
3125
3336
  for (const command of commands) {
3126
3337
  if (!this.#isCurrent(generation))
3127
3338
  return;
@@ -3129,6 +3340,10 @@ class OfflineSyncService {
3129
3340
  break;
3130
3341
  if (!['pending', 'retry_wait'].includes(command.state))
3131
3342
  break;
3343
+ // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
3344
+ // belong to scopes that failed pre-pull even when the head was admitted.
3345
+ if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
3346
+ break;
3132
3347
  let sending = await this.#claimSendingCommand(command, generation);
3133
3348
  if (!sending)
3134
3349
  return;
@@ -3430,7 +3645,7 @@ class OfflineSyncService {
3430
3645
  if (status >= 400 && status < 500 && status !== 429) {
3431
3646
  return { ...command, state: 'rejected', lastErrorCode: String(status), serverCommitUnknown };
3432
3647
  }
3433
- const retryAt = Date.now() + Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.max(0, command.attempts - 1));
3648
+ const retryAt = Date.now() + offlineRetryDelayMs(command.attempts, this.#retryRandom);
3434
3649
  return {
3435
3650
  ...command,
3436
3651
  state: 'retry_wait',
@@ -4218,53 +4433,41 @@ class SqliteOfflineRepository {
4218
4433
  #databaseId = null;
4219
4434
  #initialization = null;
4220
4435
  #writes = Promise.resolve();
4436
+ #activeReaders = 0;
4437
+ #readersIdle = Promise.resolve();
4438
+ #resolveReadersIdle = null;
4221
4439
  initialize() {
4222
4440
  this.#initialization ??= this.#open();
4223
4441
  return this.#initialization;
4224
4442
  }
4225
4443
  async getLastUserId() {
4226
- const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');
4227
- const value = this.#stringOrNull(rows[0]?.['last_user_id']);
4228
- return value === null ? null : parseOfflinePrincipalId(value);
4444
+ return this.#withCommittedRead(() => this.#readLastUserId());
4229
4445
  }
4230
4446
  async setLastUserId(userId) {
4231
4447
  await this.#write(`INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, ?)
4232
4448
  ON CONFLICT(id) DO UPDATE SET schema_version = excluded.schema_version, last_user_id = excluded.last_user_id`, [OFFLINE_SCHEMA_VERSION, canonicalOfflinePrincipalId(userId)]);
4233
4449
  }
4234
4450
  async getSessionManifest(userId) {
4235
- const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
4236
- canonicalOfflinePrincipalId(userId),
4237
- ]);
4238
- const row = rows[0];
4239
- return row ? this.#parse(row['value_json']) : null;
4451
+ return this.#withCommittedRead(() => this.#readSessionManifest(userId));
4240
4452
  }
4241
4453
  async putSessionManifest(userId, value) {
4242
4454
  await this.#write(`INSERT INTO offline_session_manifests (user_id, value_json) VALUES (?, ?)
4243
4455
  ON CONFLICT(user_id) DO UPDATE SET value_json = excluded.value_json`, [canonicalOfflinePrincipalId(userId), JSON.stringify(value)]);
4244
4456
  }
4245
4457
  async getReplicaRow(scope, sourceKey, identity) {
4246
- const row = await this.#queryReplicaRow(scope, sourceKey, identity, false);
4247
- return row;
4458
+ return this.#withCommittedRead(async () => {
4459
+ const row = await this.#queryReplicaRow(scope, sourceKey, identity, false);
4460
+ return row;
4461
+ });
4248
4462
  }
4249
4463
  async getReplicaRowIncludingPendingDelete(scope, sourceKey, identity) {
4250
- const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);
4251
- return row;
4464
+ return this.#withCommittedRead(async () => {
4465
+ const row = await this.#queryReplicaRow(scope, sourceKey, identity, true);
4466
+ return row;
4467
+ });
4252
4468
  }
4253
4469
  async getReplicaRows(scope, sourceKey) {
4254
- const schema = this.#resolveReplicaEntitySchema(sourceKey);
4255
- const predicates = ['_offline_user_id = ?'];
4256
- const values = [canonicalOfflinePrincipalId(scope.userId)];
4257
- if (schema.scope === 'partition') {
4258
- predicates.push('_offline_scope_id = ?');
4259
- values.push(scope.scopeId);
4260
- }
4261
- const orderBy = schema.identity.kind === 'naturalKey'
4262
- ? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key).sqliteColumnName).join(', ')
4263
- : 'local_id ASC';
4264
- const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
4265
- return rows
4266
- .filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
4267
- .map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
4470
+ return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
4268
4471
  }
4269
4472
  async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
4270
4473
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
@@ -4272,60 +4475,22 @@ class SqliteOfflineRepository {
4272
4475
  return this.getReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
4273
4476
  }
4274
4477
  async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
4275
- const schema = this.#resolveReplicaEntitySchema(sourceKey);
4276
- canonicalOfflineRemoteIdentity(schema, identity);
4277
- if (schema.identity.kind === 'generated') {
4278
- const predicates = ['server_id = ?', '_offline_user_id = ?'];
4279
- const values = [identity.remoteId, canonicalOfflinePrincipalId(scope.userId)];
4280
- if (schema.scope === 'partition') {
4281
- predicates.push('_offline_scope_id = ?');
4282
- values.push(scope.scopeId);
4283
- }
4284
- const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
4285
- const row = rows[0];
4286
- return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
4287
- }
4288
- const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
4289
- const predicates = ['_offline_user_id = ?'];
4290
- const values = [canonicalOfflinePrincipalId(scope.userId)];
4291
- if (schema.scope === 'partition') {
4292
- predicates.push('_offline_scope_id = ?');
4293
- values.push(scope.scopeId);
4294
- }
4295
- for (const sourceKeyPart of schema.identity.sourceKeys) {
4296
- const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
4297
- predicates.push(`${field.sqliteColumnName} = ?`);
4298
- values.push(naturalKey[sourceKeyPart]);
4299
- }
4300
- const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
4301
- const row = rows[0];
4302
- return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
4478
+ return this.#withCommittedRead(() => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity));
4303
4479
  }
4304
4480
  async getReplicaCursor(scope) {
4305
- const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
4306
- canonicalOfflinePrincipalId(scope.userId),
4307
- scope.scopeId,
4308
- ]);
4309
- const row = rows[0];
4310
- if (!row)
4311
- return null;
4312
- return { ...scope, cursor: this.#string(row['cursor']) };
4481
+ return this.#withCommittedRead(() => this.#readReplicaCursor(scope));
4313
4482
  }
4314
4483
  async getReconciliationScopes(userId) {
4315
- const rows = await this.#query('SELECT scope_id FROM offline_reconciliation_scopes WHERE user_id = ? ORDER BY scope_id', [
4316
- canonicalOfflinePrincipalId(userId),
4317
- ]);
4318
- return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
4484
+ return this.#withCommittedRead(() => this.#readReconciliationScopes(userId));
4319
4485
  }
4320
4486
  async getCommands(scope) {
4321
- const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC', [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
4322
- return rows.map((row) => this.#command(row));
4487
+ return this.#withCommittedRead(() => this.#readCommands(scope));
4323
4488
  }
4324
4489
  async getCommandsForUser(userId) {
4325
- const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [
4326
- canonicalOfflinePrincipalId(userId),
4327
- ]);
4328
- return rows.map((row) => this.#command(row));
4490
+ return this.#withCommittedRead(() => this.#readCommandsForUser(userId));
4491
+ }
4492
+ async runReadSnapshot(read) {
4493
+ return this.#withCommittedRead(() => read(this.#reader()));
4329
4494
  }
4330
4495
  async putCommand(command) {
4331
4496
  await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
@@ -4513,6 +4678,136 @@ class SqliteOfflineRepository {
4513
4678
  throw new Error('Offline SQLite database is not initialized');
4514
4679
  return this.#databaseId;
4515
4680
  }
4681
+ async #readLastUserId() {
4682
+ const rows = await this.#query('SELECT last_user_id FROM offline_metadata WHERE id = 1');
4683
+ const value = this.#stringOrNull(rows[0]?.['last_user_id']);
4684
+ return value === null ? null : parseOfflinePrincipalId(value);
4685
+ }
4686
+ async #readSessionManifest(userId) {
4687
+ const rows = await this.#query('SELECT value_json FROM offline_session_manifests WHERE user_id = ?', [
4688
+ canonicalOfflinePrincipalId(userId),
4689
+ ]);
4690
+ const row = rows[0];
4691
+ return row ? this.#parse(row['value_json']) : null;
4692
+ }
4693
+ async #readReplicaRows(scope, sourceKey) {
4694
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
4695
+ const predicates = ['_offline_user_id = ?'];
4696
+ const values = [canonicalOfflinePrincipalId(scope.userId)];
4697
+ if (schema.scope === 'partition') {
4698
+ predicates.push('_offline_scope_id = ?');
4699
+ values.push(scope.scopeId);
4700
+ }
4701
+ const orderBy = schema.identity.kind === 'naturalKey'
4702
+ ? schema.identity.sourceKeys.map((key) => schema.fields.find((field) => field.sourceKey === key).sqliteColumnName).join(', ')
4703
+ : 'local_id ASC';
4704
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
4705
+ return rows
4706
+ .filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
4707
+ .map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
4708
+ }
4709
+ async #readReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
4710
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
4711
+ canonicalOfflineRemoteIdentity(schema, identity);
4712
+ if (schema.identity.kind === 'generated') {
4713
+ const predicates = ['server_id = ?', '_offline_user_id = ?'];
4714
+ const values = [identity.remoteId, canonicalOfflinePrincipalId(scope.userId)];
4715
+ if (schema.scope === 'partition') {
4716
+ predicates.push('_offline_scope_id = ?');
4717
+ values.push(scope.scopeId);
4718
+ }
4719
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
4720
+ const row = rows[0];
4721
+ return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
4722
+ }
4723
+ const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
4724
+ const predicates = ['_offline_user_id = ?'];
4725
+ const values = [canonicalOfflinePrincipalId(scope.userId)];
4726
+ if (schema.scope === 'partition') {
4727
+ predicates.push('_offline_scope_id = ?');
4728
+ values.push(scope.scopeId);
4729
+ }
4730
+ for (const sourceKeyPart of schema.identity.sourceKeys) {
4731
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
4732
+ predicates.push(`${field.sqliteColumnName} = ?`);
4733
+ values.push(naturalKey[sourceKeyPart]);
4734
+ }
4735
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
4736
+ const row = rows[0];
4737
+ return row ? this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row) : null;
4738
+ }
4739
+ async #readReplicaCursor(scope) {
4740
+ const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
4741
+ canonicalOfflinePrincipalId(scope.userId),
4742
+ scope.scopeId,
4743
+ ]);
4744
+ const row = rows[0];
4745
+ if (!row)
4746
+ return null;
4747
+ return { ...scope, cursor: this.#string(row['cursor']) };
4748
+ }
4749
+ async #readReconciliationScopes(userId) {
4750
+ const rows = await this.#query('SELECT scope_id FROM offline_reconciliation_scopes WHERE user_id = ? ORDER BY scope_id', [
4751
+ canonicalOfflinePrincipalId(userId),
4752
+ ]);
4753
+ return rows.map((row) => ({ userId, scopeId: this.#string(row['scope_id']) }));
4754
+ }
4755
+ async #readCommands(scope) {
4756
+ const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC', [canonicalOfflinePrincipalId(scope.userId), scope.scopeId]);
4757
+ return rows.map((row) => this.#command(row));
4758
+ }
4759
+ async #readCommandsForUser(userId) {
4760
+ const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? ORDER BY created_at ASC, command_id ASC', [
4761
+ canonicalOfflinePrincipalId(userId),
4762
+ ]);
4763
+ return rows.map((row) => this.#command(row));
4764
+ }
4765
+ #reader() {
4766
+ return {
4767
+ getLastUserId: () => this.#readLastUserId(),
4768
+ getSessionManifest: (userId) => this.#readSessionManifest(userId),
4769
+ getReplicaRow: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, false)),
4770
+ getReplicaRowIncludingPendingDelete: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, true)),
4771
+ getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
4772
+ getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
4773
+ if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
4774
+ return null;
4775
+ return this.#readReplicaRowByRemoteIdentity(scope, sourceKey, { remoteId });
4776
+ },
4777
+ getReplicaRowByRemoteIdentity: (scope, sourceKey, identity) => this.#readReplicaRowByRemoteIdentity(scope, sourceKey, identity),
4778
+ getReplicaCursor: (scope) => this.#readReplicaCursor(scope),
4779
+ getReconciliationScopes: (userId) => this.#readReconciliationScopes(userId),
4780
+ getCommands: (scope) => this.#readCommands(scope),
4781
+ getCommandsForUser: (userId) => this.#readCommandsForUser(userId),
4782
+ };
4783
+ }
4784
+ async #withCommittedRead(operation) {
4785
+ await this.initialize();
4786
+ await this.#writes;
4787
+ this.#beginReaders();
4788
+ try {
4789
+ return await operation();
4790
+ }
4791
+ finally {
4792
+ this.#endReaders();
4793
+ }
4794
+ }
4795
+ #beginReaders() {
4796
+ if (this.#activeReaders === 0) {
4797
+ this.#readersIdle = new Promise((resolve) => {
4798
+ this.#resolveReadersIdle = resolve;
4799
+ });
4800
+ }
4801
+ this.#activeReaders += 1;
4802
+ }
4803
+ #endReaders() {
4804
+ this.#activeReaders -= 1;
4805
+ if (this.#activeReaders === 0) {
4806
+ this.#resolveReadersIdle?.();
4807
+ this.#resolveReadersIdle = null;
4808
+ this.#readersIdle = Promise.resolve();
4809
+ }
4810
+ }
4516
4811
  async #query(statement, values = []) {
4517
4812
  return this.#queryDatabase(await this.#databaseConnection(), statement, values);
4518
4813
  }
@@ -4520,12 +4815,18 @@ class SqliteOfflineRepository {
4520
4815
  return this.#queueWrite((databaseId) => this.#execute(databaseId, statement, values));
4521
4816
  }
4522
4817
  #queueWrite(run) {
4523
- const write = this.#writes.then(async () => run(await this.#databaseConnection()));
4818
+ const write = this.#writes.then(async () => {
4819
+ if (this.#activeReaders > 0)
4820
+ await this.#readersIdle;
4821
+ await run(await this.#databaseConnection());
4822
+ });
4524
4823
  this.#writes = write.catch(() => undefined);
4525
4824
  return write;
4526
4825
  }
4527
4826
  #transaction(run) {
4528
4827
  const write = this.#writes.then(async () => {
4828
+ if (this.#activeReaders > 0)
4829
+ await this.#readersIdle;
4529
4830
  const databaseId = await this.#databaseConnection();
4530
4831
  await this.#sqlite.beginTransaction({ databaseId });
4531
4832
  try {
@@ -4971,9 +5272,18 @@ function provideOffline(options) {
4971
5272
  ...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),
4972
5273
  ...(options.mutationPolicies ?? []).flatMap((policy) => provideOfflineMutationRequestPolicy(policy)),
4973
5274
  ...(options.providers ?? []),
4974
- provideAppInitializer(() => inject(OfflineCoordinatorService).initialize()),
5275
+ provideAppInitializer(() => {
5276
+ assertSupportedOfflineMode(Capacitor.getPlatform(), options.mode ?? 'synchronized');
5277
+ return inject(OfflineCoordinatorService).initialize();
5278
+ }),
4975
5279
  ]);
4976
5280
  }
5281
+ /** Prevents unsupported multi-tab Web writes from silently losing Outbox state. */
5282
+ function assertSupportedOfflineMode(platform, mode) {
5283
+ if (!supportsSynchronizedOfflineRepository(platform) && mode === 'synchronized') {
5284
+ throw new Error('Offline synchronized mode is supported only by native repositories. Use readCacheOnly until the selected repository provides cross-context locking.');
5285
+ }
5286
+ }
4977
5287
 
4978
5288
  const LOCAL_FIRST_MUTATION_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']);
4979
5289
  /** Applies product read and local-first mutation policies while observing real API reachability. */
@@ -5095,5 +5405,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
5095
5405
  * Generated bundle index. Do not edit.
5096
5406
  */
5097
5407
 
5098
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
5408
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
5099
5409
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map