@rdlabo/ionic-angular-kit 21.6.7 → 21.6.9

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.
@@ -7,7 +7,7 @@ import { App } from '@capacitor/app';
7
7
  import { Network } from '@capacitor/network';
8
8
  import { Capacitor } from '@capacitor/core';
9
9
  import { HttpErrorResponse, HttpContextToken, HttpResponse } from '@angular/common/http';
10
- import { defer, from, map as map$1, catchError, throwError, concatMap, materialize, connect, concat, of, ReplaySubject, take, dematerialize, EMPTY, tap } from 'rxjs';
10
+ import { defer, from, map as map$1, catchError, throwError, concatMap, materialize, connect, concat, of, ReplaySubject, take, Observable, dematerialize, EMPTY, tap } from 'rxjs';
11
11
 
12
12
  const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
13
13
  const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
@@ -1751,7 +1751,7 @@ function compareUtf8Binary(left, right) {
1751
1751
 
1752
1752
  const settledMutation = async () => undefined;
1753
1753
  /**
1754
- * Serializes only local replica read/derive/write critical sections. Network
1754
+ * Serializes local replica reads and read/derive/write critical sections. Network
1755
1755
  * transport must stay outside this coordinator so synchronization never holds
1756
1756
  * the local mutation lane while waiting on I/O.
1757
1757
  *
@@ -1766,16 +1766,29 @@ class OfflineReplicaMutationCoordinator {
1766
1766
  #tail = settledMutation();
1767
1767
  /** Enqueues one local replica critical section behind any in-flight mutation. */
1768
1768
  run(operation) {
1769
- const mutation = this.#tail.then(() => {
1769
+ return this.#enqueue(() => {
1770
1770
  if (!this.#repository)
1771
1771
  throw new Error('Offline repository is not configured.');
1772
1772
  const atomicMutation = this.#repository?.[OFFLINE_REPOSITORY_ATOMIC_MUTATION];
1773
1773
  return atomicMutation ? atomicMutation.call(this.#repository, operation) : operation(this.#repository);
1774
1774
  });
1775
- this.#tail = mutation.then(() => undefined, () => undefined);
1776
- return mutation;
1777
1775
  }
1778
- /** Resolves after every currently queued replica mutation has settled. */
1776
+ /**
1777
+ * Enqueues an external local-replica read behind mutations and keeps later
1778
+ * mutations behind that read until it settles.
1779
+ *
1780
+ * Do not invoke this from inside {@link run}; use the repository passed to
1781
+ * that callback for reads owned by an atomic mutation.
1782
+ */
1783
+ runSerializedRead(read) {
1784
+ return this.#enqueue(read);
1785
+ }
1786
+ #enqueue(operation) {
1787
+ const queued = this.#tail.then(operation);
1788
+ this.#tail = queued.then(() => undefined, () => undefined);
1789
+ return queued;
1790
+ }
1791
+ /** Resolves after every currently queued replica read or mutation has settled. */
1779
1792
  async drain() {
1780
1793
  await this.#tail;
1781
1794
  }
@@ -2569,6 +2582,9 @@ class OfflineNetworkService {
2569
2582
  constructor() {
2570
2583
  this.#osConnected = signal(null, ...(ngDevMode ? [{ debugName: "#osConnected" }] : /* istanbul ignore next */ []));
2571
2584
  this.#apiReachable = signal(null, ...(ngDevMode ? [{ debugName: "#apiReachable" }] : /* istanbul ignore next */ []));
2585
+ this.#appActive = signal(true, ...(ngDevMode ? [{ debugName: "#appActive" }] : /* istanbul ignore next */ []));
2586
+ this.#lifecycleRevision = signal(0, ...(ngDevMode ? [{ debugName: "#lifecycleRevision" }] : /* istanbul ignore next */ []));
2587
+ this.#networkRevision = 0;
2572
2588
  this.#listeners = [];
2573
2589
  this.#initialized = false;
2574
2590
  this.state = computed(() => {
@@ -2579,23 +2595,43 @@ class OfflineNetworkService {
2579
2595
  return 'unverified';
2580
2596
  }, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
2581
2597
  this.connected = computed(() => this.state() !== 'offline', ...(ngDevMode ? [{ debugName: "connected" }] : /* istanbul ignore next */ []));
2598
+ /** Whether Capacitor currently permits foreground transport work. */
2599
+ this.appActive = this.#appActive.asReadonly();
2600
+ /** Changes on every foreground/background transition, even when connectivity is unchanged. */
2601
+ this.lifecycleRevision = this.#lifecycleRevision.asReadonly();
2582
2602
  }
2583
2603
  #osConnected;
2584
2604
  #apiReachable;
2605
+ #appActive;
2606
+ #lifecycleRevision;
2607
+ #networkRevision;
2585
2608
  #listeners;
2586
2609
  #initialized;
2587
2610
  async initialize() {
2588
2611
  if (this.#initialized)
2589
2612
  return;
2590
2613
  this.#initialized = true;
2591
- this.#osConnected.set((await Network.getStatus()).connected);
2592
- this.#listeners.push(await Network.addListener('networkStatusChange', ({ connected }) => {
2593
- this.#osConnected.set(connected);
2594
- this.#apiReachable.set(connected ? null : false);
2595
- }), await App.addListener('appStateChange', ({ isActive }) => {
2596
- if (isActive)
2597
- void this.#refreshOsStatus();
2598
- }));
2614
+ const [networkListener, appListener] = await Promise.all([
2615
+ Network.addListener('networkStatusChange', ({ connected }) => {
2616
+ this.#networkRevision += 1;
2617
+ this.#osConnected.set(connected);
2618
+ this.#apiReachable.set(connected ? null : false);
2619
+ }),
2620
+ App.addListener('appStateChange', ({ isActive }) => {
2621
+ this.#lifecycleRevision.update((revision) => revision + 1);
2622
+ this.#appActive.set(isActive);
2623
+ if (isActive)
2624
+ void this.#refreshOsStatus();
2625
+ }),
2626
+ ]);
2627
+ this.#listeners.push(networkListener, appListener);
2628
+ const networkRevision = this.#networkRevision;
2629
+ const lifecycleRevision = this.#lifecycleRevision();
2630
+ const [network, app] = await Promise.all([Network.getStatus(), App.getState()]);
2631
+ if (this.#networkRevision === networkRevision)
2632
+ this.#osConnected.set(network.connected);
2633
+ if (this.#lifecycleRevision() === lifecycleRevision)
2634
+ this.#appActive.set(app.isActive);
2599
2635
  }
2600
2636
  markApiSuccess() {
2601
2637
  this.#apiReachable.set(true);
@@ -2604,7 +2640,10 @@ class OfflineNetworkService {
2604
2640
  this.#apiReachable.set(false);
2605
2641
  }
2606
2642
  async #refreshOsStatus() {
2607
- this.#osConnected.set((await Network.getStatus()).connected);
2643
+ const revision = this.#networkRevision;
2644
+ const status = await Network.getStatus();
2645
+ if (this.#networkRevision === revision)
2646
+ this.#osConnected.set(status.connected);
2608
2647
  }
2609
2648
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
2610
2649
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, providedIn: 'root' }); }
@@ -2739,6 +2778,8 @@ class OfflineSyncService {
2739
2778
  #pendingPullScopes;
2740
2779
  #activeUserId;
2741
2780
  #flushPromise;
2781
+ #flushLifecycleRevision;
2782
+ #resumeAfterFlush;
2742
2783
  #partialFlushInFlight;
2743
2784
  #chainedFullFlush;
2744
2785
  #flushTransitions;
@@ -2769,6 +2810,8 @@ class OfflineSyncService {
2769
2810
  this.#pendingPullScopes = new Map();
2770
2811
  this.#activeUserId = null;
2771
2812
  this.#flushPromise = null;
2813
+ this.#flushLifecycleRevision = 0;
2814
+ this.#resumeAfterFlush = false;
2772
2815
  this.#partialFlushInFlight = false;
2773
2816
  this.#chainedFullFlush = null;
2774
2817
  this.#flushTransitions = new Set();
@@ -2800,11 +2843,12 @@ class OfflineSyncService {
2800
2843
  }, ...(ngDevMode ? [{ debugName: "syncState" }] : /* istanbul ignore next */ []));
2801
2844
  effect(() => {
2802
2845
  const connected = this.#network.connected();
2846
+ const appActive = this.#appActive();
2803
2847
  // The network transition may be observed after an explicit flush has already
2804
2848
  // persisted a fatal pull attention. Do not let that stale transition restart
2805
2849
  // the intentionally stopped loop; auth/session refresh remains able to retry.
2806
2850
  const hasFatalPullAttention = untracked(() => this.#pullAttentions().length > 0);
2807
- if (this.#initialized && connected && !hasFatalPullAttention)
2851
+ if (this.#initialized && connected && appActive && !hasFatalPullAttention)
2808
2852
  this.#flushInBackground();
2809
2853
  });
2810
2854
  }
@@ -2812,7 +2856,7 @@ class OfflineSyncService {
2812
2856
  const generation = this.#generation;
2813
2857
  if (!(await this.#restoreCurrentGeneration(generation)))
2814
2858
  return;
2815
- if (options.flush !== false && this.#network.connected())
2859
+ if (options.flush !== false && this.#canSynchronize())
2816
2860
  this.#flushInBackground();
2817
2861
  }
2818
2862
  #ensureInitialized() {
@@ -2854,7 +2898,7 @@ class OfflineSyncService {
2854
2898
  await this.#discoverScopes();
2855
2899
  await this.#restoreInterruptedCommands();
2856
2900
  await this.#refreshState();
2857
- if (this.#network.connected())
2901
+ if (this.#canSynchronize())
2858
2902
  this.#flushInBackground();
2859
2903
  }
2860
2904
  /** Restores local outbox visibility without enabling pull or replay transport. */
@@ -3245,7 +3289,7 @@ class OfflineSyncService {
3245
3289
  removeCommandIds,
3246
3290
  });
3247
3291
  await this.#refreshState().catch((error) => this.#reportError(error));
3248
- if (options.flush !== false && this.#network.connected())
3292
+ if (options.flush !== false && this.#canSynchronize())
3249
3293
  this.#flushInBackground();
3250
3294
  }
3251
3295
  #normalizedLocalOnlyFootprint(scope, footprint) {
@@ -3336,7 +3380,7 @@ class OfflineSyncService {
3336
3380
  await this.#restoreInterruptedCommands();
3337
3381
  await this.#refreshState();
3338
3382
  await this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error));
3339
- if (options.flush !== false && this.#network.connected())
3383
+ if (options.flush !== false && this.#canSynchronize())
3340
3384
  this.#flushInBackground();
3341
3385
  }
3342
3386
  /** Clears a retry backoff/auth block selected explicitly by the user and sends the durable command now. */
@@ -3365,7 +3409,7 @@ class OfflineSyncService {
3365
3409
  });
3366
3410
  return true;
3367
3411
  });
3368
- if (retried && this.#network.connected())
3412
+ if (retried && this.#canSynchronize())
3369
3413
  await this.flush();
3370
3414
  }
3371
3415
  async discardAllPending() {
@@ -3401,8 +3445,12 @@ class OfflineSyncService {
3401
3445
  return this.#beginFlush(true);
3402
3446
  }
3403
3447
  #beginFlush(explicitFull) {
3448
+ const lifecycleRevision = this.#lifecycleRevision();
3404
3449
  const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
3405
3450
  if (this.#flushPromise) {
3451
+ if (lifecycleRevision !== this.#flushLifecycleRevision && this.#canSynchronize()) {
3452
+ this.#resumeAfterFlush = true;
3453
+ }
3406
3454
  if (explicitFull && this.#partialFlushInFlight) {
3407
3455
  if (!this.#chainedFullFlush) {
3408
3456
  const generation = this.#generation;
@@ -3431,7 +3479,13 @@ class OfflineSyncService {
3431
3479
  this.#flushPromise = null;
3432
3480
  this.#partialFlushInFlight = false;
3433
3481
  }
3482
+ const resumeAfterFlush = this.#resumeAfterFlush;
3483
+ this.#resumeAfterFlush = false;
3484
+ if (resumeAfterFlush && this.#canSynchronize()) {
3485
+ queueMicrotask(() => this.#flushInBackground());
3486
+ }
3434
3487
  });
3488
+ this.#flushLifecycleRevision = lifecycleRevision;
3435
3489
  this.#flushPromise = promise;
3436
3490
  this.#partialFlushInFlight = isPartial;
3437
3491
  this.#flushTransitions.add(promise);
@@ -3440,7 +3494,7 @@ class OfflineSyncService {
3440
3494
  async #runFlush(generation, explicitFull) {
3441
3495
  if (!this.#isCurrent(generation))
3442
3496
  return;
3443
- if (!this.#network.connected()) {
3497
+ if (!this.#canSynchronize()) {
3444
3498
  await this.#refreshState(generation);
3445
3499
  return;
3446
3500
  }
@@ -3454,8 +3508,9 @@ class OfflineSyncService {
3454
3508
  let fatalPullFailure = null;
3455
3509
  const pulledScopeKeys = new Set();
3456
3510
  for (const scope of pullScopes) {
3457
- if (!this.#isCurrent(generation) || !this.#network.connected())
3511
+ if (!this.#isCurrent(generation) || !this.#canSynchronize())
3458
3512
  return;
3513
+ const pullLifecycleRevision = this.#lifecycleRevision();
3459
3514
  const pullScope = async () => {
3460
3515
  await this.#pull.pull(scope);
3461
3516
  await this.#markScopeReconciled(scope, generation);
@@ -3463,6 +3518,8 @@ class OfflineSyncService {
3463
3518
  };
3464
3519
  const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3465
3520
  if (pull.status === 'rejected') {
3521
+ if (this.#isInterruptedTransportFailure(pull.error, pullLifecycleRevision))
3522
+ return;
3466
3523
  prePullFailures.push(pull.error);
3467
3524
  if (this.#isFatalPullFailure(pull.error)) {
3468
3525
  // Auth/upgrade-driven recovery only: stop remaining scopes immediately.
@@ -3477,7 +3534,7 @@ class OfflineSyncService {
3477
3534
  }
3478
3535
  const dirtyScopes = new Map();
3479
3536
  const sendWorkerFailures = [];
3480
- while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
3537
+ while (this.#canSynchronize() && this.#isCurrent(generation) && fatalPullFailure === null) {
3481
3538
  const known = await this.#readKnownCommands();
3482
3539
  const groups = this.#eligibleAggregateGroups(known).filter((group) => group.some((command) => (command.state === 'pending' || command.state === 'retry_wait') &&
3483
3540
  pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))));
@@ -3488,7 +3545,7 @@ class OfflineSyncService {
3488
3545
  const pendingBefore = known.filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
3489
3546
  let cursor = 0;
3490
3547
  const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {
3491
- while (cursor < groups.length) {
3548
+ while (cursor < groups.length && this.#canSynchronize()) {
3492
3549
  const group = groups[cursor++];
3493
3550
  if (group && this.#isCurrent(generation))
3494
3551
  await this.#sendAggregate(group, generation, dirtyScopes, pulledScopeKeys);
@@ -3515,8 +3572,9 @@ class OfflineSyncService {
3515
3572
  if (fatalPullFailure === null) {
3516
3573
  const postPullScopes = [...this.#pendingPullScopes.values()];
3517
3574
  for (const scope of postPullScopes) {
3518
- if (!this.#isCurrent(generation) || !this.#network.connected())
3575
+ if (!this.#isCurrent(generation) || !this.#canSynchronize())
3519
3576
  break;
3577
+ const pullLifecycleRevision = this.#lifecycleRevision();
3520
3578
  // A command response may contain only the aggregate's base row. Pull once per dirty scope so
3521
3579
  // sibling-table journal entries are visible before completed Outbox state reaches product UI.
3522
3580
  const pullScope = async () => {
@@ -3525,6 +3583,8 @@ class OfflineSyncService {
3525
3583
  };
3526
3584
  const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3527
3585
  if (pull.status === 'rejected') {
3586
+ if (this.#isInterruptedTransportFailure(pull.error, pullLifecycleRevision))
3587
+ return;
3528
3588
  if (this.#isFatalPullFailure(pull.error)) {
3529
3589
  fatalPullFailure = fatalPullFailure ?? pull.error;
3530
3590
  await this.#persistFatalPullAttentions(pull.error, scope, postPullScopes, generation);
@@ -3570,6 +3630,21 @@ class OfflineSyncService {
3570
3630
  return true;
3571
3631
  return error instanceof OfflineReplicaSchemaMismatchError;
3572
3632
  }
3633
+ #isInterruptedTransportFailure(error, lifecycleRevision) {
3634
+ if (this.#lifecycleRevision() === lifecycleRevision)
3635
+ return false;
3636
+ const status = this.#errorStatus(error);
3637
+ return status === 0 || status === 408;
3638
+ }
3639
+ #canSynchronize() {
3640
+ return this.#appActive() && this.#network.connected();
3641
+ }
3642
+ #appActive() {
3643
+ return this.#network.appActive?.() ?? true;
3644
+ }
3645
+ #lifecycleRevision() {
3646
+ return this.#network.lifecycleRevision?.() ?? 0;
3647
+ }
3573
3648
  #pullAttentionReason(error) {
3574
3649
  if (error instanceof OfflineReplicaSchemaMismatchError)
3575
3650
  return 'schema_upgrade_required';
@@ -4110,7 +4185,7 @@ class OfflineSyncService {
4110
4185
  return;
4111
4186
  this.#retryTimer = setTimeout(() => {
4112
4187
  this.#retryTimer = null;
4113
- if (this.#network.connected())
4188
+ if (this.#canSynchronize())
4114
4189
  this.#flushInBackground();
4115
4190
  }, Math.max(0, retryAt - Date.now()));
4116
4191
  }
@@ -4119,6 +4194,7 @@ class OfflineSyncService {
4119
4194
  this.#flushPromise = null;
4120
4195
  this.#partialFlushInFlight = false;
4121
4196
  this.#chainedFullFlush = null;
4197
+ this.#resumeAfterFlush = false;
4122
4198
  this.#scheduleRetry(null);
4123
4199
  }
4124
4200
  #isCurrent(generation) {
@@ -5137,27 +5213,106 @@ async function createRandomOfflineEncryptionKey() {
5137
5213
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
5138
5214
  }
5139
5215
  const settledSqliteOperation = async () => undefined;
5140
- /** Create the standard encrypted `@capacitor-community/sqlite` driver. */
5216
+ const communitySqliteDrivers = new WeakMap();
5217
+ function sqliteErrorMessage(error) {
5218
+ if (error instanceof Error)
5219
+ return error.message;
5220
+ if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {
5221
+ return error.message;
5222
+ }
5223
+ return String(error);
5224
+ }
5225
+ function normalizeCommunitySqliteDatabaseName(database) {
5226
+ return database.endsWith('.db') ? database.slice(0, -3) : database;
5227
+ }
5228
+ function isExistingCommunitySqliteConnectionError(error, database) {
5229
+ const databaseName = normalizeCommunitySqliteDatabaseName(database);
5230
+ return sqliteErrorMessage(error).includes(`Connection ${databaseName} already exists`);
5231
+ }
5232
+ function settleCommunitySqliteCreation(creation) {
5233
+ return creation.then((database) => ({ ok: true, database }), (error) => ({ ok: false, error }));
5234
+ }
5235
+ async function createReloadSafeCommunitySqliteDatabase(connection, databaseName) {
5236
+ const create = () => connection.createConnection(databaseName, COMMUNITY_SQLITE_ENCRYPTED, COMMUNITY_SQLITE_MODE, COMMUNITY_SQLITE_VERSION, COMMUNITY_SQLITE_READONLY);
5237
+ const creation = await settleCommunitySqliteCreation(create());
5238
+ if (creation.ok)
5239
+ return creation.database;
5240
+ if (!isExistingCommunitySqliteConnectionError(creation.error, databaseName) || !connection.closeConnection) {
5241
+ throw creation.error;
5242
+ }
5243
+ await connection.closeConnection(databaseName, COMMUNITY_SQLITE_READONLY);
5244
+ return create();
5245
+ }
5246
+ /**
5247
+ * Create the canonical encrypted `@capacitor-community/sqlite` driver for a connection owner.
5248
+ *
5249
+ * The supplied connection is the identity and exclusive owner of its native plugin connections. Repeated
5250
+ * calls with the same object return the same driver so normal concurrent access cannot be mistaken for a
5251
+ * WebView-reload orphan. Consumers must route database access through this driver and must not close or
5252
+ * replace the connection while the driver is active. A real WebView reload creates a new JavaScript owner,
5253
+ * allowing the driver to close the native connection orphaned by the previous owner and recreate it.
5254
+ */
5141
5255
  function createCommunitySqliteDriver(connection) {
5256
+ const currentDriver = communitySqliteDrivers.get(connection);
5257
+ if (currentDriver)
5258
+ return currentDriver;
5142
5259
  const databases = new Map();
5260
+ const openings = new Map();
5261
+ let secretInitialization = null;
5143
5262
  const database = (databaseId) => {
5144
- const value = databases.get(databaseId);
5263
+ const value = databases.get(normalizeCommunitySqliteDatabaseName(databaseId));
5145
5264
  if (!value)
5146
5265
  throw new Error(`Offline SQLite database "${databaseId}" is not open`);
5147
5266
  return value;
5148
5267
  };
5149
- return {
5150
- async open({ databaseName, createEncryptionKey }) {
5268
+ const ensureSecret = (createEncryptionKey) => {
5269
+ if (secretInitialization)
5270
+ return secretInitialization;
5271
+ const initialization = (async () => {
5151
5272
  const stored = await connection.isSecretStored();
5152
- if (!stored.result) {
5153
- const encryptionKey = await createEncryptionKey?.();
5154
- if (!encryptionKey)
5155
- throw new Error('Native offline storage requires a non-empty encryption key on first open');
5156
- await connection.setEncryptionSecret(encryptionKey);
5157
- }
5158
- const value = await connection.createConnection(databaseName, COMMUNITY_SQLITE_ENCRYPTED, COMMUNITY_SQLITE_MODE, COMMUNITY_SQLITE_VERSION, COMMUNITY_SQLITE_READONLY);
5273
+ if (stored.result)
5274
+ return;
5275
+ const encryptionKey = await createEncryptionKey?.();
5276
+ if (!encryptionKey)
5277
+ throw new Error('Native offline storage requires a non-empty encryption key on first open');
5278
+ await connection.setEncryptionSecret(encryptionKey);
5279
+ })();
5280
+ secretInitialization = initialization;
5281
+ return initialization.then(undefined, (error) => {
5282
+ if (secretInitialization === initialization)
5283
+ secretInitialization = null;
5284
+ throw error;
5285
+ });
5286
+ };
5287
+ const openDatabase = async (databaseName, createEncryptionKey) => {
5288
+ const databaseKey = normalizeCommunitySqliteDatabaseName(databaseName);
5289
+ const opened = databases.get(databaseKey);
5290
+ if (opened)
5291
+ return opened;
5292
+ const currentOpening = openings.get(databaseKey);
5293
+ if (currentOpening)
5294
+ return currentOpening;
5295
+ const opening = (async () => {
5296
+ await ensureSecret(createEncryptionKey);
5297
+ const value = await createReloadSafeCommunitySqliteDatabase(connection, databaseName);
5159
5298
  await value.open();
5160
- databases.set(databaseName, value);
5299
+ databases.set(databaseKey, value);
5300
+ return value;
5301
+ })();
5302
+ openings.set(databaseKey, opening);
5303
+ return opening.then((value) => {
5304
+ if (openings.get(databaseKey) === opening)
5305
+ openings.delete(databaseKey);
5306
+ return value;
5307
+ }, (error) => {
5308
+ if (openings.get(databaseKey) === opening)
5309
+ openings.delete(databaseKey);
5310
+ throw error;
5311
+ });
5312
+ };
5313
+ const driver = {
5314
+ async open({ databaseName, createEncryptionKey }) {
5315
+ await openDatabase(databaseName, createEncryptionKey);
5161
5316
  return { databaseId: databaseName };
5162
5317
  },
5163
5318
  async execute({ databaseId, statement, values = [] }) {
@@ -5177,6 +5332,8 @@ function createCommunitySqliteDriver(connection) {
5177
5332
  await database(databaseId).rollbackTransaction();
5178
5333
  },
5179
5334
  };
5335
+ communitySqliteDrivers.set(connection, driver);
5336
+ return driver;
5180
5337
  }
5181
5338
  const SCHEMA = [
5182
5339
  `CREATE TABLE IF NOT EXISTS offline_metadata (
@@ -6310,7 +6467,7 @@ const offlineInterceptor = (request, next) => {
6310
6467
  if (!plan)
6311
6468
  return transport();
6312
6469
  if (plan.readStrategy === 'local-first') {
6313
- return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler));
6470
+ return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
6314
6471
  }
6315
6472
  return readNetworkFirst(request, plan, transport, fallback);
6316
6473
  }
@@ -6340,16 +6497,36 @@ function readNetworkFirst(request, plan, transport, fallback) {
6340
6497
  * `firstValueFrom` and `take(1)` cancel in-flight transport and suppress
6341
6498
  * further emissions.
6342
6499
  */
6343
- function readLocalFirst(request, plan, transport, fallback, errorHandler) {
6344
- return defer(transport).pipe(materialize(), connect((bufferedTransport$) => resolveLocalAttempt(plan, errorHandler).pipe(concatMap((localResponse) => localResponse
6500
+ function readLocalFirst(request, plan, transport, fallback, errorHandler, replicaMutations) {
6501
+ return defer(transport).pipe(materialize(), connect((bufferedTransport$) => resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((localResponse) => localResponse
6345
6502
  ? concat(of(localResponse), drainRemoteAfterLocal(bufferedTransport$, plan))
6346
6503
  : drainRemoteNetworkFirst(bufferedTransport$, request, plan, fallback))), { connector: () => new ReplaySubject() }));
6347
6504
  }
6348
- function resolveLocalAttempt(plan, errorHandler) {
6349
- return defer(() => from(plan.readLocal()).pipe(catchError((localError) => {
6505
+ function resolveLocalAttempt(plan, errorHandler, replicaMutations) {
6506
+ return serializedLocalRead(plan, replicaMutations).pipe(catchError((localError) => {
6350
6507
  errorHandler.handleError(localError);
6351
6508
  return of(null);
6352
- }))).pipe(concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler) : of(null))), take(1));
6509
+ }), concatMap((local) => (local ? tryProjectLocal(local, plan, errorHandler) : of(null))), take(1));
6510
+ }
6511
+ /** Skips a queued local read when its HTTP subscriber leaves before the lane opens. */
6512
+ function serializedLocalRead(plan, replicaMutations) {
6513
+ return new Observable((subscriber) => {
6514
+ let cancelled = false;
6515
+ void replicaMutations
6516
+ .runSerializedRead(async () => (cancelled ? null : plan.readLocal()))
6517
+ .then((response) => {
6518
+ if (cancelled)
6519
+ return;
6520
+ subscriber.next(response);
6521
+ subscriber.complete();
6522
+ }, (error) => {
6523
+ if (!cancelled)
6524
+ subscriber.error(error);
6525
+ });
6526
+ return () => {
6527
+ cancelled = true;
6528
+ };
6529
+ });
6353
6530
  }
6354
6531
  function tryProjectLocal(cached, plan, errorHandler) {
6355
6532
  return emitTaggedLocalResponse(cached, plan).pipe(catchError((error) => {
@@ -6393,13 +6570,14 @@ function observeTransport(source, network) {
6393
6570
  class OfflineRequestFallbackService {
6394
6571
  #registry = inject(OfflineRequestPolicyRegistry);
6395
6572
  #errorHandler = inject(ErrorHandler);
6573
+ #replicaMutations = inject(OfflineReplicaMutationCoordinator);
6396
6574
  handle(request, error, resolvedPlan) {
6397
6575
  if (request.context.get(OFFLINE_BYPASS) || request.method !== 'GET' || !isOfflineFallbackError(error))
6398
6576
  return null;
6399
6577
  const plan = resolvedPlan ?? this.#registry.resolve(request);
6400
6578
  if (!plan || plan.kind !== 'read')
6401
6579
  return null;
6402
- return defer(() => from(plan.readLocal())).pipe(catchError((localError) => {
6580
+ return serializedLocalRead(plan, this.#replicaMutations).pipe(catchError((localError) => {
6403
6581
  this.#errorHandler.handleError(localError);
6404
6582
  return throwError(() => error);
6405
6583
  }), concatMap((cached) => cached ? of(cached.clone({ headers: cached.headers.set(OFFLINE_RESPONSE_HEADER, 'local') })) : throwError(() => error)));