@rdlabo/ionic-angular-kit 21.5.14 → 21.5.16

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.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
2
+ import { InjectionToken, Injectable, inject, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
3
  import { KitStorageService } from '@rdlabo/ionic-angular-kit';
4
4
  import { toObservable } from '@angular/core/rxjs-interop';
5
5
  import { map, distinctUntilChanged } from 'rxjs/operators';
@@ -870,6 +870,29 @@ function offlineCommandLookupIdentity(identity) {
870
870
  return { kind: 'natural', naturalKey: identity.naturalKey };
871
871
  }
872
872
 
873
+ /**
874
+ * Serializes only local replica read/derive/write critical sections. Network
875
+ * transport must stay outside this coordinator so synchronization never holds
876
+ * the local mutation lane while waiting on I/O.
877
+ */
878
+ class OfflineReplicaMutationCoordinator {
879
+ #tail = Promise.resolve();
880
+ run(operation) {
881
+ const mutation = this.#tail.then(operation);
882
+ this.#tail = mutation.then(() => undefined, () => undefined);
883
+ return mutation;
884
+ }
885
+ async drain() {
886
+ await this.#tail;
887
+ }
888
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
889
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, providedIn: 'root' }); }
890
+ }
891
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, decorators: [{
892
+ type: Injectable,
893
+ args: [{ providedIn: 'root' }]
894
+ }] });
895
+
873
896
  /** Current durable storage schema used by both web and native repositories. */
874
897
  const OFFLINE_SCHEMA_VERSION = 1;
875
898
  /** DI token for the selected platform repository. */
@@ -1488,6 +1511,7 @@ class OfflineReplicaPullService {
1488
1511
  #options = inject(OFFLINE_KIT_OPTIONS);
1489
1512
  #puller = inject(OFFLINE_REPLICA_PULLER);
1490
1513
  #executor = inject(OFFLINE_COMMAND_EXECUTOR);
1514
+ #replicaMutations = inject(OfflineReplicaMutationCoordinator);
1491
1515
  #schemaHash = null;
1492
1516
  async pull(scope) {
1493
1517
  if (this.#options.mode === 'readCacheOnly')
@@ -1506,123 +1530,133 @@ class OfflineReplicaPullService {
1506
1530
  if (page.hasMore && page.nextCursor === cursor) {
1507
1531
  throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.scopeId}.`);
1508
1532
  }
1509
- const scopeCommands = await this.#repository.getCommands(scope);
1510
- const userCommands = this.#repository.getCommandsForUser ? await this.#repository.getCommandsForUser(scope.userId) : scopeCommands;
1511
- const changes = this.#collapseChanges(page.changes);
1512
- const putRows = [];
1513
- const removeRows = [];
1514
- const putCommands = new Map();
1515
- const removeCommandIds = new Set();
1516
- for (const change of changes) {
1517
- const schema = this.#entitySchema(change.sourceKey);
1518
- const commands = schema.scope === 'user' ? userCommands : scopeCommands;
1519
- const acknowledged = (change.acknowledgedCommandIds ?? [])
1520
- .map((commandId) => {
1521
- const command = commands.find((candidate) => candidate.commandId === commandId);
1522
- if (!command)
1523
- return null;
1524
- if (command.sourceKey !== change.sourceKey) {
1525
- throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
1533
+ const applied = await this.#replicaMutations.run(async () => {
1534
+ const currentCursor = (await this.#repository.getReplicaCursor(scope))?.cursor ?? '';
1535
+ if (currentCursor !== cursor)
1536
+ return currentCursor;
1537
+ const scopeCommands = await this.#repository.getCommands(scope);
1538
+ const userCommands = this.#repository.getCommandsForUser ? await this.#repository.getCommandsForUser(scope.userId) : scopeCommands;
1539
+ const changes = this.#collapseChanges(page.changes);
1540
+ const putRows = [];
1541
+ const removeRows = [];
1542
+ const putCommands = new Map();
1543
+ const removeCommandIds = new Set();
1544
+ for (const change of changes) {
1545
+ const schema = this.#entitySchema(change.sourceKey);
1546
+ const commands = schema.scope === 'user' ? userCommands : scopeCommands;
1547
+ const acknowledged = (change.acknowledgedCommandIds ?? [])
1548
+ .map((commandId) => {
1549
+ const command = commands.find((candidate) => candidate.commandId === commandId);
1550
+ if (!command)
1551
+ return null;
1552
+ if (command.sourceKey !== change.sourceKey) {
1553
+ throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
1554
+ }
1555
+ return command;
1556
+ })
1557
+ .filter((command) => command !== null);
1558
+ const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));
1559
+ if (acknowledgedIdentities.size > 1) {
1560
+ throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple replica identities.`);
1526
1561
  }
1527
- return command;
1528
- })
1529
- .filter((command) => command !== null);
1530
- const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));
1531
- if (acknowledgedIdentities.size > 1) {
1532
- throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple replica identities.`);
1533
- }
1534
- const acknowledgedCommand = acknowledged[0];
1535
- const acknowledgedScope = acknowledgedCommand
1536
- ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
1537
- : scope;
1538
- const acknowledgedRow = acknowledgedCommand
1539
- ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity) ?? this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity))
1540
- : null;
1541
- if (acknowledgedCommand && !acknowledgedRow) {
1542
- throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
1543
- }
1544
- const identity = this.#identity(change);
1545
- const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
1546
- if (acknowledgedRow &&
1547
- serverRow &&
1548
- !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))) {
1549
- if (identity.remoteId !== undefined) {
1550
- throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);
1562
+ const acknowledgedCommand = acknowledged[0];
1563
+ const acknowledgedScope = acknowledgedCommand
1564
+ ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
1565
+ : scope;
1566
+ const acknowledgedRow = acknowledgedCommand
1567
+ ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity) ?? this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity))
1568
+ : null;
1569
+ if (acknowledgedCommand && !acknowledgedRow) {
1570
+ throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
1551
1571
  }
1552
- throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
1553
- }
1554
- const existing = acknowledgedRow ?? serverRow;
1555
- const related = existing
1556
- ? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
1557
- : [];
1558
- const hasPending = related.length > 0;
1559
- if (acknowledgedCommand) {
1560
- this.#assertIdentityAssignment(schema, existing, identity);
1561
- this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds);
1562
- continue;
1563
- }
1564
- if (change.deleted) {
1565
- if (!existing)
1572
+ const identity = this.#identity(change);
1573
+ const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
1574
+ if (acknowledgedRow &&
1575
+ serverRow &&
1576
+ !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))) {
1577
+ if (identity.remoteId !== undefined) {
1578
+ throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);
1579
+ }
1580
+ throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
1581
+ }
1582
+ const existing = acknowledgedRow ?? serverRow;
1583
+ const related = existing
1584
+ ? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
1585
+ : [];
1586
+ const hasPending = related.length > 0;
1587
+ if (acknowledgedCommand) {
1588
+ this.#assertIdentityAssignment(schema, existing, identity);
1589
+ this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds);
1566
1590
  continue;
1567
- if (!hasPending) {
1568
- removeRows.push({ ...existing, identity: existing.identity });
1591
+ }
1592
+ if (change.deleted) {
1593
+ if (!existing)
1594
+ continue;
1595
+ if (!hasPending) {
1596
+ removeRows.push({ ...existing, identity: existing.identity });
1597
+ continue;
1598
+ }
1599
+ putRows.push({
1600
+ ...existing,
1601
+ confirmedValues: null,
1602
+ serverRevision: change.serverRevision,
1603
+ syncState: 'conflict',
1604
+ fetchedAt: Date.now(),
1605
+ });
1606
+ for (const command of related) {
1607
+ putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
1608
+ }
1569
1609
  continue;
1570
1610
  }
1571
- putRows.push({
1572
- ...existing,
1573
- confirmedValues: null,
1574
- serverRevision: change.serverRevision,
1575
- syncState: 'conflict',
1576
- fetchedAt: Date.now(),
1577
- });
1578
- for (const command of related) {
1579
- putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
1611
+ const confirmedValues = this.#validatedValues(schema, change);
1612
+ if (!existing) {
1613
+ putRows.push({
1614
+ ...scope,
1615
+ sourceKey: change.sourceKey,
1616
+ identity: schema.identity.kind === 'naturalKey'
1617
+ ? offlineNaturalReplicaIdentity(schema, confirmedValues)
1618
+ : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
1619
+ values: confirmedValues,
1620
+ confirmedValues,
1621
+ serverRevision: change.serverRevision,
1622
+ fetchedAt: Date.now(),
1623
+ syncState: 'confirmed',
1624
+ });
1625
+ continue;
1580
1626
  }
1581
- continue;
1582
- }
1583
- const confirmedValues = this.#validatedValues(schema, change);
1584
- if (!existing) {
1627
+ const conflicted = related.some((command) => command.baseRevision !== change.serverRevision);
1585
1628
  putRows.push({
1586
- ...scope,
1587
- sourceKey: change.sourceKey,
1588
- identity: schema.identity.kind === 'naturalKey'
1589
- ? offlineNaturalReplicaIdentity(schema, confirmedValues)
1590
- : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
1591
- values: confirmedValues,
1629
+ ...existing,
1630
+ values: hasPending ? existing.values : confirmedValues,
1592
1631
  confirmedValues,
1593
1632
  serverRevision: change.serverRevision,
1594
1633
  fetchedAt: Date.now(),
1595
- syncState: 'confirmed',
1634
+ syncState: conflicted ? 'conflict' : hasPending ? 'pending' : 'confirmed',
1596
1635
  });
1597
- continue;
1598
- }
1599
- const conflicted = related.some((command) => command.baseRevision !== change.serverRevision);
1600
- putRows.push({
1601
- ...existing,
1602
- values: hasPending ? existing.values : confirmedValues,
1603
- confirmedValues,
1604
- serverRevision: change.serverRevision,
1605
- fetchedAt: Date.now(),
1606
- syncState: conflicted ? 'conflict' : hasPending ? 'pending' : 'confirmed',
1607
- });
1608
- if (conflicted) {
1609
- for (const command of related) {
1610
- putCommands.set(command.commandId, {
1611
- ...command,
1612
- state: 'conflict',
1613
- retryAt: null,
1614
- lastErrorCode: 'remote_revision',
1615
- });
1636
+ if (conflicted) {
1637
+ for (const command of related) {
1638
+ putCommands.set(command.commandId, {
1639
+ ...command,
1640
+ state: 'conflict',
1641
+ retryAt: null,
1642
+ lastErrorCode: 'remote_revision',
1643
+ });
1644
+ }
1616
1645
  }
1617
1646
  }
1618
- }
1619
- await this.#repository.transactReplica({
1620
- putRows,
1621
- removeRows,
1622
- putCommands: [...putCommands.values()],
1623
- removeCommandIds: [...removeCommandIds],
1624
- putCursors: [{ ...scope, cursor: page.nextCursor }],
1647
+ await this.#repository.transactReplica({
1648
+ putRows,
1649
+ removeRows,
1650
+ putCommands: [...putCommands.values()],
1651
+ removeCommandIds: [...removeCommandIds],
1652
+ putCursors: [{ ...scope, cursor: page.nextCursor }],
1653
+ });
1654
+ return page.nextCursor;
1625
1655
  });
1656
+ if (applied !== page.nextCursor) {
1657
+ cursor = applied;
1658
+ continue;
1659
+ }
1626
1660
  cursor = page.nextCursor;
1627
1661
  if (!page.hasMore)
1628
1662
  return;
@@ -2074,6 +2108,7 @@ class OfflineOutboxCapacityError extends Error {
2074
2108
  }
2075
2109
  const MAX_PARALLEL_AGGREGATES = 3;
2076
2110
  const MAX_BACKOFF_MS = 60 * 60 * 1000;
2111
+ const POST_SEND_PULL_RETRY_MS = 1_000;
2077
2112
  const DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER = 1_000;
2078
2113
  const DEFAULT_MAX_OUTBOX_BYTES_PER_USER = 10 * 1024 * 1024;
2079
2114
  /** Maintains the optimistic local replica and synchronizes its durable outbox. */
@@ -2085,6 +2120,7 @@ class OfflineSyncService {
2085
2120
  #hooks;
2086
2121
  #options;
2087
2122
  #pull;
2123
+ #replicaMutations;
2088
2124
  #errorHandler;
2089
2125
  #commands;
2090
2126
  #knownScopes;
@@ -2093,8 +2129,6 @@ class OfflineSyncService {
2093
2129
  #flushTransitions;
2094
2130
  #generation;
2095
2131
  #sendingTransitions;
2096
- /** Serializes enqueue and acknowledgement projection over the same local replica. */
2097
- #replicaMutationTail;
2098
2132
  #retryTimer;
2099
2133
  #initialized;
2100
2134
  #lastCommandCreatedAt;
@@ -2106,6 +2140,7 @@ class OfflineSyncService {
2106
2140
  this.#hooks = inject(OFFLINE_COMMAND_HOOKS);
2107
2141
  this.#options = inject(OFFLINE_KIT_OPTIONS);
2108
2142
  this.#pull = inject(OfflineReplicaPullService);
2143
+ this.#replicaMutations = inject(OfflineReplicaMutationCoordinator);
2109
2144
  this.#errorHandler = inject(ErrorHandler);
2110
2145
  this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
2111
2146
  this.#knownScopes = new Map();
@@ -2114,8 +2149,6 @@ class OfflineSyncService {
2114
2149
  this.#flushTransitions = new Set();
2115
2150
  this.#generation = 0;
2116
2151
  this.#sendingTransitions = new Set();
2117
- /** Serializes enqueue and acknowledgement projection over the same local replica. */
2118
- this.#replicaMutationTail = Promise.resolve();
2119
2152
  this.#retryTimer = null;
2120
2153
  this.#initialized = false;
2121
2154
  this.#lastCommandCreatedAt = 0;
@@ -2174,7 +2207,7 @@ class OfflineSyncService {
2174
2207
  }
2175
2208
  async resetSession() {
2176
2209
  this.revokeSession();
2177
- await Promise.allSettled([this.#replicaMutationTail, ...this.#flushTransitions]);
2210
+ await Promise.allSettled([this.#replicaMutations.drain(), ...this.#flushTransitions]);
2178
2211
  await this.#waitForSendingTransitions();
2179
2212
  await this.#restoreInterruptedCommands();
2180
2213
  this.#activeUserId = null;
@@ -2190,6 +2223,20 @@ class OfflineSyncService {
2190
2223
  const generation = this.#generation;
2191
2224
  return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
2192
2225
  }
2226
+ /**
2227
+ * Reads, derives, and commits the base optimistic row, product companion
2228
+ * rows, and Outbox command as one serialized replica transaction.
2229
+ */
2230
+ enqueuePrepared(prepare, options = {}) {
2231
+ const generation = this.#generation;
2232
+ return this.#serializeReplicaMutation(async () => {
2233
+ await this.initialize();
2234
+ if (!this.#isCurrent(generation))
2235
+ throw new Error('Offline session changed before prepared enqueue.');
2236
+ const prepared = await prepare(this.#repository);
2237
+ return this.#enqueue(prepared.request, options, generation, prepared.replicaTransaction);
2238
+ });
2239
+ }
2193
2240
  /**
2194
2241
  * Serializes a product-owned replica projection with enqueue and command ACK
2195
2242
  * reconciliation. For read/derive/write cache updates, prefer
@@ -2218,11 +2265,9 @@ class OfflineSyncService {
2218
2265
  });
2219
2266
  }
2220
2267
  #serializeReplicaMutation(operation) {
2221
- const mutation = this.#replicaMutationTail.then(operation);
2222
- this.#replicaMutationTail = mutation.then(() => undefined, () => undefined);
2223
- return mutation;
2268
+ return this.#replicaMutations.run(operation);
2224
2269
  }
2225
- async #enqueue(request, options, generation) {
2270
+ async #enqueue(request, options, generation, replicaTransaction) {
2226
2271
  await this.initialize();
2227
2272
  if (this.#options.mode === 'readCacheOnly') {
2228
2273
  throw new Error('This offline provider is configured as a read-only cache and cannot enqueue commands.');
@@ -2243,7 +2288,7 @@ class OfflineSyncService {
2243
2288
  const optimisticValue = request.optimisticValue;
2244
2289
  const commandId = crypto.randomUUID();
2245
2290
  const sourceKey = this.#hooks.entityType(request);
2246
- const command = {
2291
+ let command = {
2247
2292
  ...scope,
2248
2293
  commandId,
2249
2294
  aggregateType: request.aggregateType,
@@ -2261,7 +2306,6 @@ class OfflineSyncService {
2261
2306
  createdAt: await this.#nextCommandCreatedAt(userId),
2262
2307
  lastErrorCode: null,
2263
2308
  };
2264
- await this.#assertOutboxCapacity(userId, command);
2265
2309
  const entityType = command.sourceKey;
2266
2310
  const schema = this.#entitySchema(entityType);
2267
2311
  if (schema.identity.kind === 'localOnly') {
@@ -2325,15 +2369,77 @@ class OfflineSyncService {
2325
2369
  syncState: 'pending',
2326
2370
  visibility: request.replicaMutation === 'delete' ? 'pending_delete' : 'present',
2327
2371
  };
2372
+ const optimisticCompanions = await this.#prepareOptimisticCompanions(scope, optimisticRow, replicaTransaction);
2373
+ if (replicaTransaction)
2374
+ this.#canonicalJson(replicaTransaction);
2375
+ if (optimisticCompanions.length > 0)
2376
+ command = { ...command, optimisticCompanions };
2377
+ await this.#assertOutboxCapacity(userId, command);
2328
2378
  if (generation !== this.#generation) {
2329
2379
  throw new Error('Offline session changed before the command could be persisted');
2330
2380
  }
2331
- await this.#repository.transactReplica({ putRows: [optimisticRow], putCommands: [command] });
2381
+ await this.#repository.transactReplica({
2382
+ putRows: [optimisticRow, ...(replicaTransaction?.putRows ?? [])],
2383
+ removeRows: replicaTransaction?.removeRows,
2384
+ putCommands: [command],
2385
+ });
2332
2386
  await this.#refreshState();
2333
2387
  if (options.flush !== false && this.#network.connected())
2334
2388
  this.#flushInBackground();
2335
2389
  return commandId;
2336
2390
  }
2391
+ async #prepareOptimisticCompanions(scope, optimisticRow, transaction) {
2392
+ if (!transaction)
2393
+ return [];
2394
+ const runtimeTransaction = transaction;
2395
+ const unsupported = Object.keys(runtimeTransaction).filter((key) => key !== 'putRows' && key !== 'removeRows');
2396
+ if (unsupported.length > 0) {
2397
+ throw new Error(`Prepared offline enqueue cannot mutate ${unsupported.join(', ')}.`);
2398
+ }
2399
+ const putRows = transaction.putRows ?? [];
2400
+ const removeRows = transaction.removeRows ?? [];
2401
+ const baseKey = this.#replicaRowKey(optimisticRow);
2402
+ const seen = new Set([baseKey]);
2403
+ const mutations = [];
2404
+ for (const row of putRows) {
2405
+ this.#assertCompanionScope(scope, row);
2406
+ const key = this.#replicaRowKey(row);
2407
+ if (seen.has(key))
2408
+ throw new Error(`Prepared offline enqueue contains duplicate replica row ${key}.`);
2409
+ seen.add(key);
2410
+ mutations.push({ key: this.#minimalReplicaRowKey(row), after: row });
2411
+ }
2412
+ for (const row of removeRows) {
2413
+ this.#assertCompanionScope(scope, row);
2414
+ const key = this.#replicaRowKey(row);
2415
+ if (seen.has(key))
2416
+ throw new Error(`Prepared offline enqueue contains duplicate replica row ${key}.`);
2417
+ seen.add(key);
2418
+ mutations.push({ key: this.#minimalReplicaRowKey(row), after: null });
2419
+ }
2420
+ return Promise.all(mutations.map(async ({ key, after }) => ({
2421
+ key,
2422
+ before: (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity)) ??
2423
+ (await this.#repository.getReplicaRow(scope, key.sourceKey, key.identity)),
2424
+ after,
2425
+ })));
2426
+ }
2427
+ #assertCompanionScope(scope, key) {
2428
+ if (key.userId !== scope.userId || key.scopeId !== scope.scopeId) {
2429
+ throw new Error('Prepared offline enqueue companion rows must use the command scope.');
2430
+ }
2431
+ }
2432
+ #minimalReplicaRowKey(key) {
2433
+ return {
2434
+ userId: key.userId,
2435
+ scopeId: key.scopeId,
2436
+ sourceKey: key.sourceKey,
2437
+ identity: key.identity,
2438
+ };
2439
+ }
2440
+ #replicaRowKey(key) {
2441
+ return `${canonicalOfflinePrincipalId(key.userId)}:${key.scopeId}:${key.sourceKey}:${canonicalOfflineReplicaIdentity(key.identity)}`;
2442
+ }
2337
2443
  async #assertOutboxCapacity(userId, command) {
2338
2444
  const commands = this.#repository.getCommandsForUser
2339
2445
  ? await this.#repository.getCommandsForUser(userId)
@@ -2354,19 +2460,28 @@ class OfflineSyncService {
2354
2460
  }
2355
2461
  async discard(commandId, options = {}) {
2356
2462
  await this.initialize();
2357
- const command = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
2358
- if (!command)
2359
- return;
2360
2463
  this.#invalidateFlush();
2361
2464
  await this.#waitForSendingTransitions();
2362
- await this.#discardCommands([command]);
2465
+ // A pull may have completed while transport was being cancelled. Re-read
2466
+ // and project the discard inside the same local mutation lane used by
2467
+ // enqueue, ACK, and pull application so an old before-image cannot replace
2468
+ // a newer authoritative row after its cursor has advanced.
2469
+ const command = await this.#replicaMutations.run(async () => {
2470
+ const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
2471
+ if (!current)
2472
+ return null;
2473
+ await this.#discardCommands([current]);
2474
+ return current;
2475
+ });
2476
+ if (!command)
2477
+ return;
2363
2478
  await this.#hooks.onCommandRemoved?.(command);
2364
2479
  await this.#restoreInterruptedCommands();
2365
2480
  await this.#refreshState();
2366
2481
  if (options.flush !== false && this.#network.connected())
2367
2482
  this.#flushInBackground();
2368
2483
  }
2369
- /** Clears a retry backoff selected explicitly by the user and sends the durable command now. */
2484
+ /** Clears a retry backoff/auth block selected explicitly by the user and sends the durable command now. */
2370
2485
  async retryNow(commandId) {
2371
2486
  await this.initialize();
2372
2487
  this.#invalidateFlush();
@@ -2379,8 +2494,8 @@ class OfflineSyncService {
2379
2494
  const current = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
2380
2495
  if (!current)
2381
2496
  return false;
2382
- if (current.state !== 'retry_wait') {
2383
- throw new Error(`Offline command ${commandId} is not waiting for retry.`);
2497
+ if (current.state !== 'retry_wait' && current.state !== 'blocked_auth') {
2498
+ throw new Error(`Offline command ${commandId} is not waiting for retry or reauthentication.`);
2384
2499
  }
2385
2500
  await repository.putCommand({ ...current, state: 'pending', retryAt: null, lastErrorCode: null });
2386
2501
  return true;
@@ -2392,8 +2507,11 @@ class OfflineSyncService {
2392
2507
  await this.initialize();
2393
2508
  this.#invalidateFlush();
2394
2509
  await this.#waitForSendingTransitions();
2395
- const commands = await this.#readKnownCommands();
2396
- await this.#discardCommands(commands);
2510
+ const commands = await this.#replicaMutations.run(async () => {
2511
+ const current = await this.#readKnownCommands();
2512
+ await this.#discardCommands(current);
2513
+ return current;
2514
+ });
2397
2515
  await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command)));
2398
2516
  await this.#refreshState();
2399
2517
  }
@@ -2427,6 +2545,7 @@ class OfflineSyncService {
2427
2545
  return;
2428
2546
  await this.#pull.pull(scope);
2429
2547
  }
2548
+ const dirtyScopes = new Map();
2430
2549
  while (this.#network.connected() && this.#isCurrent(generation)) {
2431
2550
  const groups = this.#eligibleAggregateGroups(await this.#readKnownCommands());
2432
2551
  if (!this.#isCurrent(generation))
@@ -2438,12 +2557,33 @@ class OfflineSyncService {
2438
2557
  while (cursor < groups.length) {
2439
2558
  const group = groups[cursor++];
2440
2559
  if (group && this.#isCurrent(generation))
2441
- await this.#sendAggregate(group, generation);
2560
+ await this.#sendAggregate(group, generation, dirtyScopes);
2442
2561
  }
2443
2562
  });
2444
2563
  await Promise.all(workers);
2445
2564
  }
2565
+ const postPullFailures = [];
2566
+ for (const scope of dirtyScopes.values()) {
2567
+ if (!this.#isCurrent(generation) || !this.#network.connected())
2568
+ break;
2569
+ try {
2570
+ // A command response may contain only the aggregate's base row. Pull
2571
+ // once per dirty scope so sibling-table journal entries are visible
2572
+ // before the completed Outbox state is exposed to product UI.
2573
+ await this.#pull.pull(scope);
2574
+ }
2575
+ catch (error) {
2576
+ postPullFailures.push(error);
2577
+ }
2578
+ }
2446
2579
  await this.#refreshState(generation);
2580
+ if (postPullFailures.length > 0 && this.#isCurrent(generation)) {
2581
+ // The server command is already committed and acknowledged locally, so
2582
+ // never resend it. Retry only the idempotent scope pull and surface the
2583
+ // failure to explicit flush callers/ErrorHandler.
2584
+ this.#scheduleRetry(Date.now() + POST_SEND_PULL_RETRY_MS);
2585
+ throw postPullFailures[0];
2586
+ }
2447
2587
  }
2448
2588
  #eligibleAggregateGroups(commands) {
2449
2589
  const now = Date.now();
@@ -2459,7 +2599,7 @@ class OfflineSyncService {
2459
2599
  return head?.state === 'pending' || (head?.state === 'retry_wait' && (head.retryAt ?? 0) <= now);
2460
2600
  });
2461
2601
  }
2462
- async #sendAggregate(commands, generation) {
2602
+ async #sendAggregate(commands, generation, dirtyScopes) {
2463
2603
  for (const command of commands) {
2464
2604
  if (!this.#isCurrent(generation))
2465
2605
  return;
@@ -2504,6 +2644,10 @@ class OfflineSyncService {
2504
2644
  if (!this.#isCurrent(generation))
2505
2645
  return;
2506
2646
  await this.#completeCommand(commands, sending, result, generation);
2647
+ if (this.#isCurrent(generation)) {
2648
+ const scope = { userId: sending.userId, scopeId: sending.scopeId };
2649
+ dirtyScopes.set(this.#scopeKey(scope), scope);
2650
+ }
2507
2651
  }
2508
2652
  }
2509
2653
  async #normalizeEnqueueRequest(scope, request, commandIdentity) {
@@ -2578,10 +2722,11 @@ class OfflineSyncService {
2578
2722
  syncState: rebased.length > 0 ? 'pending' : 'confirmed',
2579
2723
  visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
2580
2724
  };
2725
+ const companionTransaction = this.#companionTransactionAfterAcknowledgement(rebased);
2581
2726
  if (!this.#isCurrent(generation))
2582
2727
  return;
2583
2728
  await this.#repository.transactReplica({
2584
- putRows: removesReplica && rebased.length === 0 ? undefined : [row],
2729
+ putRows: [...(removesReplica && rebased.length === 0 ? [] : [row]), ...(companionTransaction.putRows ?? [])],
2585
2730
  releaseRemoteIds: result.clearRemoteId === true &&
2586
2731
  current.identity.kind === 'generated' &&
2587
2732
  current.identity.remoteId !== null &&
@@ -2596,7 +2741,7 @@ class OfflineSyncService {
2596
2741
  },
2597
2742
  ]
2598
2743
  : undefined,
2599
- removeRows: removesReplica && rebased.length === 0 ? [current] : undefined,
2744
+ removeRows: [...(removesReplica && rebased.length === 0 ? [current] : []), ...(companionTransaction.removeRows ?? [])],
2600
2745
  putCommands: rebased,
2601
2746
  removeCommandIds: [command.commandId],
2602
2747
  });
@@ -2633,29 +2778,96 @@ class OfflineSyncService {
2633
2778
  affected.set(this.#aggregateKey(command), command);
2634
2779
  const putRows = [];
2635
2780
  const removeRows = [];
2781
+ const companionRows = new Map();
2782
+ const companionRemovals = new Map();
2636
2783
  for (const [key, command] of affected) {
2637
2784
  const row = await this.#rowForCommand(command);
2638
- if (!row)
2639
- continue;
2640
2785
  const remaining = all.filter((item) => !discardedIds.has(item.commandId) && this.#aggregateKey(item) === key);
2641
- if (remaining.length === 0 && row.confirmedValues === null) {
2642
- removeRows.push(row);
2786
+ if (row) {
2787
+ if (remaining.length === 0 && row.confirmedValues === null) {
2788
+ removeRows.push(row);
2789
+ }
2790
+ else {
2791
+ putRows.push({
2792
+ ...row,
2793
+ values: remaining.length > 0 ? remaining.at(-1).optimisticValue : row.confirmedValues,
2794
+ syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2795
+ visibility: remaining.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
2796
+ });
2797
+ }
2643
2798
  }
2644
- else {
2645
- putRows.push({
2646
- ...row,
2647
- values: remaining.length > 0 ? remaining.at(-1).optimisticValue : row.confirmedValues,
2648
- syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2649
- visibility: remaining.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
2650
- });
2799
+ const aggregateCommands = all.filter((item) => this.#aggregateKey(item) === key);
2800
+ const remainingAggregateCommands = aggregateCommands.filter((item) => !discardedIds.has(item.commandId));
2801
+ for (const companion of this.#companionsAfterDiscard(aggregateCommands, remainingAggregateCommands)) {
2802
+ const companionKey = this.#replicaRowKey(companion.key);
2803
+ const hasRemaining = remainingAggregateCommands.some((remainingCommand) => (remainingCommand.optimisticCompanions ?? []).some((candidate) => this.#replicaRowKey(candidate.key) === companionKey));
2804
+ const current = await this.#getCompanionRow(companion.key);
2805
+ const after = hasRemaining
2806
+ ? companion.after && current
2807
+ ? { ...companion.after, confirmedValues: current.confirmedValues }
2808
+ : companion.after
2809
+ : current
2810
+ ? current.confirmedValues === null
2811
+ ? null
2812
+ : {
2813
+ ...current,
2814
+ values: current.confirmedValues,
2815
+ syncState: 'confirmed',
2816
+ visibility: 'present',
2817
+ }
2818
+ : companion.after;
2819
+ if (after) {
2820
+ companionRows.set(companionKey, after);
2821
+ companionRemovals.delete(companionKey);
2822
+ }
2823
+ else {
2824
+ companionRows.delete(companionKey);
2825
+ companionRemovals.set(companionKey, companion.key);
2826
+ }
2651
2827
  }
2652
2828
  }
2653
2829
  await this.#repository.transactReplica({
2654
- putRows,
2655
- removeRows,
2830
+ putRows: [...putRows, ...companionRows.values()],
2831
+ removeRows: [...removeRows, ...companionRemovals.values()],
2656
2832
  removeCommandIds: [...discardedIds],
2657
2833
  });
2658
2834
  }
2835
+ #getCompanionRow(key) {
2836
+ const scope = { userId: key.userId, scopeId: key.scopeId };
2837
+ return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
2838
+ this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
2839
+ }
2840
+ #companionTransactionAfterAcknowledgement(following) {
2841
+ const latest = new Map();
2842
+ for (const command of following) {
2843
+ for (const companion of command.optimisticCompanions ?? []) {
2844
+ latest.set(this.#replicaRowKey(companion.key), companion);
2845
+ }
2846
+ }
2847
+ return {
2848
+ putRows: [...latest.values()].flatMap((companion) => (companion.after ? [companion.after] : [])),
2849
+ removeRows: [...latest.values()].flatMap((companion) => (companion.after ? [] : [companion.key])),
2850
+ };
2851
+ }
2852
+ #companionsAfterDiscard(all, remaining) {
2853
+ const keys = new Map();
2854
+ for (const command of all) {
2855
+ for (const companion of command.optimisticCompanions ?? []) {
2856
+ const key = this.#replicaRowKey(companion.key);
2857
+ const previous = keys.get(key);
2858
+ keys.set(key, previous ? { ...companion, before: previous.before } : companion);
2859
+ }
2860
+ }
2861
+ for (const command of remaining) {
2862
+ for (const companion of command.optimisticCompanions ?? []) {
2863
+ const key = this.#replicaRowKey(companion.key);
2864
+ const original = keys.get(key);
2865
+ keys.set(key, { ...companion, before: original?.before ?? companion.before });
2866
+ }
2867
+ }
2868
+ const remainingKeys = new Set(remaining.flatMap((command) => (command.optimisticCompanions ?? []).map((item) => this.#replicaRowKey(item.key))));
2869
+ return [...keys.entries()].map(([key, companion]) => (remainingKeys.has(key) ? companion : { ...companion, after: companion.before }));
2870
+ }
2659
2871
  #aggregateKey(command) {
2660
2872
  const sourceKey = this.#entityType(command);
2661
2873
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
@@ -3203,6 +3415,7 @@ const SCHEMA = [
3203
3415
  operation TEXT NOT NULL,
3204
3416
  payload_json TEXT NOT NULL,
3205
3417
  optimistic_value_json TEXT NOT NULL,
3418
+ optimistic_companions_json TEXT,
3206
3419
  replica_mutation TEXT NOT NULL DEFAULT 'upsert',
3207
3420
  payload_hash TEXT NOT NULL,
3208
3421
  base_revision_json TEXT,
@@ -3420,6 +3633,10 @@ class SqliteOfflineRepository {
3420
3633
  this.#databaseId = databaseId;
3421
3634
  for (const statement of SCHEMA)
3422
3635
  await this.#execute(databaseId, statement);
3636
+ const commandColumns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
3637
+ if (!commandColumns.some((row) => row['name'] === 'optimistic_companions_json')) {
3638
+ await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_companions_json TEXT');
3639
+ }
3423
3640
  const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
3424
3641
  if (metadata.length === 0) {
3425
3642
  await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
@@ -3538,6 +3755,9 @@ class SqliteOfflineRepository {
3538
3755
  operation: this.#string(row['operation']),
3539
3756
  payload: this.#parse(row['payload_json']),
3540
3757
  optimisticValue: this.#parse(row['optimistic_value_json']),
3758
+ ...(row['optimistic_companions_json'] === null || row['optimistic_companions_json'] === undefined
3759
+ ? {}
3760
+ : { optimisticCompanions: this.#parse(row['optimistic_companions_json']) }),
3541
3761
  replicaMutation: this.#string(row['replica_mutation']),
3542
3762
  payloadHash: this.#string(row['payload_hash']),
3543
3763
  baseRevision: this.#parseNullable(row['base_revision_json']),
@@ -3551,13 +3771,14 @@ class SqliteOfflineRepository {
3551
3771
  #putCommand(databaseId, command) {
3552
3772
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands
3553
3773
  (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json, optimistic_value_json,
3554
- replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
3555
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3774
+ optimistic_companions_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
3775
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3556
3776
  ON CONFLICT(command_id) DO UPDATE SET
3557
3777
  user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
3558
3778
  source_key = excluded.source_key,
3559
3779
  identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
3560
- optimistic_value_json = excluded.optimistic_value_json, replica_mutation = excluded.replica_mutation,
3780
+ optimistic_value_json = excluded.optimistic_value_json, optimistic_companions_json = excluded.optimistic_companions_json,
3781
+ replica_mutation = excluded.replica_mutation,
3561
3782
  payload_hash = excluded.payload_hash,
3562
3783
  base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
3563
3784
  retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
@@ -3570,6 +3791,7 @@ class SqliteOfflineRepository {
3570
3791
  command.operation,
3571
3792
  JSON.stringify(command.payload),
3572
3793
  JSON.stringify(command.optimisticValue),
3794
+ command.optimisticCompanions === undefined ? null : JSON.stringify(command.optimisticCompanions),
3573
3795
  command.replicaMutation ?? 'upsert',
3574
3796
  command.payloadHash,
3575
3797
  this.#stringifyNullable(command.baseRevision),
@@ -4010,5 +4232,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
4010
4232
  * Generated bundle index. Do not edit.
4011
4233
  */
4012
4234
 
4013
- 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, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, 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, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
4235
+ 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, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, 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, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, text };
4014
4236
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map