@rdlabo/ionic-angular-kit 21.5.15 → 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;
@@ -2086,6 +2120,7 @@ class OfflineSyncService {
2086
2120
  #hooks;
2087
2121
  #options;
2088
2122
  #pull;
2123
+ #replicaMutations;
2089
2124
  #errorHandler;
2090
2125
  #commands;
2091
2126
  #knownScopes;
@@ -2094,8 +2129,6 @@ class OfflineSyncService {
2094
2129
  #flushTransitions;
2095
2130
  #generation;
2096
2131
  #sendingTransitions;
2097
- /** Serializes enqueue and acknowledgement projection over the same local replica. */
2098
- #replicaMutationTail;
2099
2132
  #retryTimer;
2100
2133
  #initialized;
2101
2134
  #lastCommandCreatedAt;
@@ -2107,6 +2140,7 @@ class OfflineSyncService {
2107
2140
  this.#hooks = inject(OFFLINE_COMMAND_HOOKS);
2108
2141
  this.#options = inject(OFFLINE_KIT_OPTIONS);
2109
2142
  this.#pull = inject(OfflineReplicaPullService);
2143
+ this.#replicaMutations = inject(OfflineReplicaMutationCoordinator);
2110
2144
  this.#errorHandler = inject(ErrorHandler);
2111
2145
  this.#commands = signal([], ...(ngDevMode ? [{ debugName: "#commands" }] : /* istanbul ignore next */ []));
2112
2146
  this.#knownScopes = new Map();
@@ -2115,8 +2149,6 @@ class OfflineSyncService {
2115
2149
  this.#flushTransitions = new Set();
2116
2150
  this.#generation = 0;
2117
2151
  this.#sendingTransitions = new Set();
2118
- /** Serializes enqueue and acknowledgement projection over the same local replica. */
2119
- this.#replicaMutationTail = Promise.resolve();
2120
2152
  this.#retryTimer = null;
2121
2153
  this.#initialized = false;
2122
2154
  this.#lastCommandCreatedAt = 0;
@@ -2175,7 +2207,7 @@ class OfflineSyncService {
2175
2207
  }
2176
2208
  async resetSession() {
2177
2209
  this.revokeSession();
2178
- await Promise.allSettled([this.#replicaMutationTail, ...this.#flushTransitions]);
2210
+ await Promise.allSettled([this.#replicaMutations.drain(), ...this.#flushTransitions]);
2179
2211
  await this.#waitForSendingTransitions();
2180
2212
  await this.#restoreInterruptedCommands();
2181
2213
  this.#activeUserId = null;
@@ -2191,6 +2223,20 @@ class OfflineSyncService {
2191
2223
  const generation = this.#generation;
2192
2224
  return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
2193
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
+ }
2194
2240
  /**
2195
2241
  * Serializes a product-owned replica projection with enqueue and command ACK
2196
2242
  * reconciliation. For read/derive/write cache updates, prefer
@@ -2219,11 +2265,9 @@ class OfflineSyncService {
2219
2265
  });
2220
2266
  }
2221
2267
  #serializeReplicaMutation(operation) {
2222
- const mutation = this.#replicaMutationTail.then(operation);
2223
- this.#replicaMutationTail = mutation.then(() => undefined, () => undefined);
2224
- return mutation;
2268
+ return this.#replicaMutations.run(operation);
2225
2269
  }
2226
- async #enqueue(request, options, generation) {
2270
+ async #enqueue(request, options, generation, replicaTransaction) {
2227
2271
  await this.initialize();
2228
2272
  if (this.#options.mode === 'readCacheOnly') {
2229
2273
  throw new Error('This offline provider is configured as a read-only cache and cannot enqueue commands.');
@@ -2244,7 +2288,7 @@ class OfflineSyncService {
2244
2288
  const optimisticValue = request.optimisticValue;
2245
2289
  const commandId = crypto.randomUUID();
2246
2290
  const sourceKey = this.#hooks.entityType(request);
2247
- const command = {
2291
+ let command = {
2248
2292
  ...scope,
2249
2293
  commandId,
2250
2294
  aggregateType: request.aggregateType,
@@ -2262,7 +2306,6 @@ class OfflineSyncService {
2262
2306
  createdAt: await this.#nextCommandCreatedAt(userId),
2263
2307
  lastErrorCode: null,
2264
2308
  };
2265
- await this.#assertOutboxCapacity(userId, command);
2266
2309
  const entityType = command.sourceKey;
2267
2310
  const schema = this.#entitySchema(entityType);
2268
2311
  if (schema.identity.kind === 'localOnly') {
@@ -2326,15 +2369,77 @@ class OfflineSyncService {
2326
2369
  syncState: 'pending',
2327
2370
  visibility: request.replicaMutation === 'delete' ? 'pending_delete' : 'present',
2328
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);
2329
2378
  if (generation !== this.#generation) {
2330
2379
  throw new Error('Offline session changed before the command could be persisted');
2331
2380
  }
2332
- 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
+ });
2333
2386
  await this.#refreshState();
2334
2387
  if (options.flush !== false && this.#network.connected())
2335
2388
  this.#flushInBackground();
2336
2389
  return commandId;
2337
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
+ }
2338
2443
  async #assertOutboxCapacity(userId, command) {
2339
2444
  const commands = this.#repository.getCommandsForUser
2340
2445
  ? await this.#repository.getCommandsForUser(userId)
@@ -2355,12 +2460,21 @@ class OfflineSyncService {
2355
2460
  }
2356
2461
  async discard(commandId, options = {}) {
2357
2462
  await this.initialize();
2358
- const command = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
2359
- if (!command)
2360
- return;
2361
2463
  this.#invalidateFlush();
2362
2464
  await this.#waitForSendingTransitions();
2363
- 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;
2364
2478
  await this.#hooks.onCommandRemoved?.(command);
2365
2479
  await this.#restoreInterruptedCommands();
2366
2480
  await this.#refreshState();
@@ -2393,8 +2507,11 @@ class OfflineSyncService {
2393
2507
  await this.initialize();
2394
2508
  this.#invalidateFlush();
2395
2509
  await this.#waitForSendingTransitions();
2396
- const commands = await this.#readKnownCommands();
2397
- 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
+ });
2398
2515
  await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command)));
2399
2516
  await this.#refreshState();
2400
2517
  }
@@ -2605,10 +2722,11 @@ class OfflineSyncService {
2605
2722
  syncState: rebased.length > 0 ? 'pending' : 'confirmed',
2606
2723
  visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
2607
2724
  };
2725
+ const companionTransaction = this.#companionTransactionAfterAcknowledgement(rebased);
2608
2726
  if (!this.#isCurrent(generation))
2609
2727
  return;
2610
2728
  await this.#repository.transactReplica({
2611
- putRows: removesReplica && rebased.length === 0 ? undefined : [row],
2729
+ putRows: [...(removesReplica && rebased.length === 0 ? [] : [row]), ...(companionTransaction.putRows ?? [])],
2612
2730
  releaseRemoteIds: result.clearRemoteId === true &&
2613
2731
  current.identity.kind === 'generated' &&
2614
2732
  current.identity.remoteId !== null &&
@@ -2623,7 +2741,7 @@ class OfflineSyncService {
2623
2741
  },
2624
2742
  ]
2625
2743
  : undefined,
2626
- removeRows: removesReplica && rebased.length === 0 ? [current] : undefined,
2744
+ removeRows: [...(removesReplica && rebased.length === 0 ? [current] : []), ...(companionTransaction.removeRows ?? [])],
2627
2745
  putCommands: rebased,
2628
2746
  removeCommandIds: [command.commandId],
2629
2747
  });
@@ -2660,29 +2778,96 @@ class OfflineSyncService {
2660
2778
  affected.set(this.#aggregateKey(command), command);
2661
2779
  const putRows = [];
2662
2780
  const removeRows = [];
2781
+ const companionRows = new Map();
2782
+ const companionRemovals = new Map();
2663
2783
  for (const [key, command] of affected) {
2664
2784
  const row = await this.#rowForCommand(command);
2665
- if (!row)
2666
- continue;
2667
2785
  const remaining = all.filter((item) => !discardedIds.has(item.commandId) && this.#aggregateKey(item) === key);
2668
- if (remaining.length === 0 && row.confirmedValues === null) {
2669
- 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
+ }
2670
2798
  }
2671
- else {
2672
- putRows.push({
2673
- ...row,
2674
- values: remaining.length > 0 ? remaining.at(-1).optimisticValue : row.confirmedValues,
2675
- syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2676
- visibility: remaining.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
2677
- });
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
+ }
2678
2827
  }
2679
2828
  }
2680
2829
  await this.#repository.transactReplica({
2681
- putRows,
2682
- removeRows,
2830
+ putRows: [...putRows, ...companionRows.values()],
2831
+ removeRows: [...removeRows, ...companionRemovals.values()],
2683
2832
  removeCommandIds: [...discardedIds],
2684
2833
  });
2685
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
+ }
2686
2871
  #aggregateKey(command) {
2687
2872
  const sourceKey = this.#entityType(command);
2688
2873
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
@@ -3230,6 +3415,7 @@ const SCHEMA = [
3230
3415
  operation TEXT NOT NULL,
3231
3416
  payload_json TEXT NOT NULL,
3232
3417
  optimistic_value_json TEXT NOT NULL,
3418
+ optimistic_companions_json TEXT,
3233
3419
  replica_mutation TEXT NOT NULL DEFAULT 'upsert',
3234
3420
  payload_hash TEXT NOT NULL,
3235
3421
  base_revision_json TEXT,
@@ -3447,6 +3633,10 @@ class SqliteOfflineRepository {
3447
3633
  this.#databaseId = databaseId;
3448
3634
  for (const statement of SCHEMA)
3449
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
+ }
3450
3640
  const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
3451
3641
  if (metadata.length === 0) {
3452
3642
  await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
@@ -3565,6 +3755,9 @@ class SqliteOfflineRepository {
3565
3755
  operation: this.#string(row['operation']),
3566
3756
  payload: this.#parse(row['payload_json']),
3567
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']) }),
3568
3761
  replicaMutation: this.#string(row['replica_mutation']),
3569
3762
  payloadHash: this.#string(row['payload_hash']),
3570
3763
  baseRevision: this.#parseNullable(row['base_revision_json']),
@@ -3578,13 +3771,14 @@ class SqliteOfflineRepository {
3578
3771
  #putCommand(databaseId, command) {
3579
3772
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands
3580
3773
  (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json, optimistic_value_json,
3581
- replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
3582
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3774
+ optimistic_companions_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
3775
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
3583
3776
  ON CONFLICT(command_id) DO UPDATE SET
3584
3777
  user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
3585
3778
  source_key = excluded.source_key,
3586
3779
  identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
3587
- 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,
3588
3782
  payload_hash = excluded.payload_hash,
3589
3783
  base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
3590
3784
  retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
@@ -3597,6 +3791,7 @@ class SqliteOfflineRepository {
3597
3791
  command.operation,
3598
3792
  JSON.stringify(command.payload),
3599
3793
  JSON.stringify(command.optimisticValue),
3794
+ command.optimisticCompanions === undefined ? null : JSON.stringify(command.optimisticCompanions),
3600
3795
  command.replicaMutation ?? 'upsert',
3601
3796
  command.payloadHash,
3602
3797
  this.#stringifyNullable(command.baseRevision),
@@ -4037,5 +4232,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
4037
4232
  * Generated bundle index. Do not edit.
4038
4233
  */
4039
4234
 
4040
- 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 };
4041
4236
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map