@rdlabo/ionic-angular-kit 21.6.0 → 21.6.1

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.
@@ -936,6 +936,7 @@ const OFFLINE_REPOSITORY_ATOMIC_MUTATION = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUT
936
936
 
937
937
  /** Current durable storage schema used by both web and native repositories. */
938
938
  const OFFLINE_SCHEMA_VERSION = 2;
939
+ const settledRepositoryOperation = async () => undefined;
939
940
  /** Canonical physical key shared by every repository and replica transaction coordinator. */
940
941
  function canonicalOfflineReplicaRowKey(schema, row) {
941
942
  const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);
@@ -972,9 +973,9 @@ class IonicOfflineRepository {
972
973
  #storage = inject(KitStorageService);
973
974
  #options = inject(OFFLINE_KIT_OPTIONS);
974
975
  #initialization = null;
975
- #writes = Promise.resolve();
976
+ #writes = settledRepositoryOperation();
976
977
  #activeReaders = 0;
977
- #readersIdle = Promise.resolve();
978
+ #readersIdle = settledRepositoryOperation();
978
979
  #resolveReadersIdle = null;
979
980
  #rowIndexBuild = null;
980
981
  initialize() {
@@ -1139,12 +1140,8 @@ class IonicOfflineRepository {
1139
1140
  await this.#ensureRowPartitionsReady();
1140
1141
  await this.#writes;
1141
1142
  this.#beginReaders();
1142
- try {
1143
- return await operation();
1144
- }
1145
- finally {
1146
- this.#endReaders();
1147
- }
1143
+ const read = async () => operation();
1144
+ return read().finally(() => this.#endReaders());
1148
1145
  }
1149
1146
  #beginReaders() {
1150
1147
  if (this.#activeReaders === 0) {
@@ -1159,7 +1156,7 @@ class IonicOfflineRepository {
1159
1156
  if (this.#activeReaders === 0) {
1160
1157
  this.#resolveReadersIdle?.();
1161
1158
  this.#resolveReadersIdle = null;
1162
- this.#readersIdle = Promise.resolve();
1159
+ this.#readersIdle = settledRepositoryOperation();
1163
1160
  }
1164
1161
  }
1165
1162
  async putCommand(command) {
@@ -1314,7 +1311,7 @@ class IonicOfflineRepository {
1314
1311
  targetVersion,
1315
1312
  targetHash,
1316
1313
  });
1317
- try {
1314
+ const commitMigration = async () => {
1318
1315
  const transformedRows = {};
1319
1316
  for (const row of Object.values(rows)) {
1320
1317
  let current = this.#toWebMigrationRow(row);
@@ -1358,8 +1355,8 @@ class IonicOfflineRepository {
1358
1355
  replicaSchemaHash: targetHash,
1359
1356
  });
1360
1357
  await this.#storage.remove(REPLICA_SCHEMA_MIGRATION_KEY);
1361
- }
1362
- catch (error) {
1358
+ };
1359
+ await commitMigration().catch(async (error) => {
1363
1360
  await this.#recoverReplicaSchemaMigration({
1364
1361
  originalRows,
1365
1362
  fromVersion,
@@ -1368,7 +1365,7 @@ class IonicOfflineRepository {
1368
1365
  targetHash,
1369
1366
  });
1370
1367
  throw error;
1371
- }
1368
+ });
1372
1369
  });
1373
1370
  }
1374
1371
  #toWebMigrationRow(row) {
@@ -1752,6 +1749,7 @@ function compareUtf8Binary(left, right) {
1752
1749
  return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
1753
1750
  }
1754
1751
 
1752
+ const settledMutation = async () => undefined;
1755
1753
  /**
1756
1754
  * Serializes only local replica read/derive/write critical sections. Network
1757
1755
  * transport must stay outside this coordinator so synchronization never holds
@@ -1765,7 +1763,7 @@ class OfflineReplicaMutationCoordinator {
1765
1763
  #repository = inject(OFFLINE_REPOSITORY, { optional: true });
1766
1764
  #projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });
1767
1765
  #options = inject(OFFLINE_KIT_OPTIONS, { optional: true });
1768
- #tail = Promise.resolve();
1766
+ #tail = settledMutation();
1769
1767
  /** Enqueues one local replica critical section behind any in-flight mutation. */
1770
1768
  run(operation) {
1771
1769
  const mutation = this.#tail.then(() => {
@@ -3481,7 +3479,7 @@ class OfflineSyncService {
3481
3479
  }
3482
3480
  }
3483
3481
  #flushInBackground() {
3484
- void this.#beginFlush(false).catch((error) => this.#errorHandler.handleError(error));
3482
+ void this.#beginFlush(false).catch((error) => this.#reportError(error));
3485
3483
  }
3486
3484
  flush() {
3487
3485
  return this.#beginFlush(true);
@@ -3542,17 +3540,18 @@ class OfflineSyncService {
3542
3540
  for (const scope of pullScopes) {
3543
3541
  if (!this.#isCurrent(generation) || !this.#network.connected())
3544
3542
  return;
3545
- try {
3543
+ const pullScope = async () => {
3546
3544
  await this.#pull.pull(scope);
3547
3545
  await this.#markScopeReconciled(scope, generation);
3548
3546
  pulledScopeKeys.add(this.#scopeKey(scope));
3549
- }
3550
- catch (error) {
3551
- prePullFailures.push(error);
3552
- if (this.#isFatalPullFailure(error)) {
3547
+ };
3548
+ const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3549
+ if (pull.status === 'rejected') {
3550
+ prePullFailures.push(pull.error);
3551
+ if (this.#isFatalPullFailure(pull.error)) {
3553
3552
  // Auth/upgrade-driven recovery only: stop remaining scopes immediately.
3554
- fatalPullFailure = fatalPullFailure ?? error;
3555
- await this.#persistFatalPullAttentions(error, scope, pullScopes, generation);
3553
+ fatalPullFailure = fatalPullFailure ?? pull.error;
3554
+ await this.#persistFatalPullAttentions(pull.error, scope, pullScopes, generation);
3556
3555
  break;
3557
3556
  }
3558
3557
  if (this.#pendingPullScopes.has(this.#scopeKey(scope))) {
@@ -3602,20 +3601,20 @@ class OfflineSyncService {
3602
3601
  for (const scope of postPullScopes) {
3603
3602
  if (!this.#isCurrent(generation) || !this.#network.connected())
3604
3603
  break;
3605
- try {
3606
- // A command response may contain only the aggregate's base row. Pull
3607
- // once per dirty scope so sibling-table journal entries are visible
3608
- // before the completed Outbox state is exposed to product UI.
3604
+ // A command response may contain only the aggregate's base row. Pull once per dirty scope so
3605
+ // sibling-table journal entries are visible before completed Outbox state reaches product UI.
3606
+ const pullScope = async () => {
3609
3607
  await this.#pull.pull(scope);
3610
3608
  await this.#markScopeReconciled(scope, generation);
3611
- }
3612
- catch (error) {
3613
- if (this.#isFatalPullFailure(error)) {
3614
- fatalPullFailure = fatalPullFailure ?? error;
3615
- await this.#persistFatalPullAttentions(error, scope, postPullScopes, generation);
3609
+ };
3610
+ const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3611
+ if (pull.status === 'rejected') {
3612
+ if (this.#isFatalPullFailure(pull.error)) {
3613
+ fatalPullFailure = fatalPullFailure ?? pull.error;
3614
+ await this.#persistFatalPullAttentions(pull.error, scope, postPullScopes, generation);
3616
3615
  break;
3617
3616
  }
3618
- postPullFailures.push(error);
3617
+ postPullFailures.push(pull.error);
3619
3618
  }
3620
3619
  }
3621
3620
  }
@@ -3743,16 +3742,16 @@ class OfflineSyncService {
3743
3742
  await this.#refreshState(generation);
3744
3743
  if (!this.#isCurrent(generation))
3745
3744
  return;
3746
- let row;
3747
- try {
3748
- row = await this.#rowForCommand(sending);
3749
- }
3750
- catch (error) {
3745
+ const claimedCommand = sending;
3746
+ const readRow = async () => this.#rowForCommand(claimedCommand);
3747
+ const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
3748
+ if (rowResult.status === 'rejected') {
3751
3749
  if (!this.#isCurrent(generation))
3752
3750
  return;
3753
- await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
3754
- throw error;
3751
+ await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
3752
+ throw rowResult.error;
3755
3753
  }
3754
+ const row = rowResult.row;
3756
3755
  if (!row) {
3757
3756
  const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
3758
3757
  await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
@@ -3763,31 +3762,29 @@ class OfflineSyncService {
3763
3762
  if (!transportCommand)
3764
3763
  return;
3765
3764
  sending = transportCommand;
3766
- let result;
3767
- try {
3768
- result = await this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
3769
- }
3770
- catch (error) {
3765
+ const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
3766
+ const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
3767
+ if (execution.status === 'rejected') {
3771
3768
  if (!this.#isCurrent(generation))
3772
3769
  return;
3773
- const commitUnknown = this.#executor.provesCommandNotCommitted?.(error, sending)
3770
+ const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
3774
3771
  ? false
3775
- : priorCommitUnknown || this.#serverCommitCouldBeUnknown(error);
3776
- await this.#persistFailedCommand(sending, error, generation, row, commitUnknown);
3777
- if (!this.#isClassifiableTransportError(error))
3778
- throw error;
3772
+ : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
3773
+ await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
3774
+ if (!this.#isClassifiableTransportError(execution.error))
3775
+ throw execution.error;
3779
3776
  break;
3780
3777
  }
3778
+ const result = execution.result;
3781
3779
  if (!this.#isCurrent(generation))
3782
3780
  return;
3783
- try {
3784
- await this.#completeCommand(commands, sending, result, generation);
3785
- }
3786
- catch (error) {
3781
+ const completeCommand = async () => this.#completeCommand(commands, sending, result, generation);
3782
+ const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3783
+ if (completion.status === 'rejected') {
3787
3784
  if (!this.#isCurrent(generation))
3788
3785
  return;
3789
- await this.#persistFailedCommand(sending, error, generation, row, true);
3790
- throw error;
3786
+ await this.#persistFailedCommand(sending, completion.error, generation, row, true);
3787
+ throw completion.error;
3791
3788
  }
3792
3789
  if (this.#isCurrent(generation)) {
3793
3790
  const scope = { userId: sending.userId, scopeId: sending.scopeId };
@@ -4033,9 +4030,19 @@ class OfflineSyncService {
4033
4030
  return status === 0 || status === 429 || status >= 500;
4034
4031
  }
4035
4032
  #reportError(error) {
4036
- void Promise.resolve()
4037
- .then(() => this.#errorHandler.handleError(error))
4038
- .catch(() => undefined);
4033
+ queueMicrotask(() => this.#dispatchError(error));
4034
+ }
4035
+ #dispatchError(error) {
4036
+ let result;
4037
+ try {
4038
+ result = this.#errorHandler.handleError(error);
4039
+ }
4040
+ catch {
4041
+ return;
4042
+ }
4043
+ if (result instanceof Promise) {
4044
+ void result.catch(() => undefined);
4045
+ }
4039
4046
  }
4040
4047
  #assertServerRevision(revision) {
4041
4048
  if (typeof revision === 'number' && !Number.isFinite(revision)) {
@@ -4316,6 +4323,7 @@ function compareOfflineCommands(left, right) {
4316
4323
  return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
4317
4324
  }
4318
4325
 
4326
+ const settledTransition = async () => undefined;
4319
4327
  /** Coordinates local persistence, session boundaries, network state, and outbox synchronization. */
4320
4328
  class OfflineCoordinatorService {
4321
4329
  constructor() {
@@ -4326,7 +4334,7 @@ class OfflineCoordinatorService {
4326
4334
  this.#options = inject(OFFLINE_KIT_OPTIONS);
4327
4335
  this.#storageState = signal({ status: 'initializing' }, ...(ngDevMode ? [{ debugName: "#storageState" }] : /* istanbul ignore next */ []));
4328
4336
  this.#transitionRevision = 0;
4329
- this.#transitionTail = Promise.resolve();
4337
+ this.#transitionTail = settledTransition();
4330
4338
  /**
4331
4339
  * Local storage readiness after {@link initialize}.
4332
4340
  *
@@ -4361,10 +4369,8 @@ class OfflineCoordinatorService {
4361
4369
  */
4362
4370
  async initialize() {
4363
4371
  const networkReady = this.#network.initialize();
4364
- try {
4365
- await this.#repository.initialize();
4366
- }
4367
- catch (error) {
4372
+ const initializeRepository = async () => this.#repository.initialize();
4373
+ const repositoryReady = await initializeRepository().then(() => true, async (error) => {
4368
4374
  await networkReady;
4369
4375
  const typed = this.#asStorageUnavailable(error);
4370
4376
  this.#storageState.set({ status: 'unavailable', error: typed });
@@ -4372,8 +4378,10 @@ class OfflineCoordinatorService {
4372
4378
  if (!onUnavailable)
4373
4379
  throw typed;
4374
4380
  await onUnavailable(typed);
4381
+ return false;
4382
+ });
4383
+ if (!repositoryReady)
4375
4384
  return;
4376
- }
4377
4385
  await networkReady;
4378
4386
  this.#storageState.set({ status: 'ready' });
4379
4387
  await this.#session.initialize();
@@ -4385,9 +4393,9 @@ class OfflineCoordinatorService {
4385
4393
  await this.resumeRemoteSession();
4386
4394
  }
4387
4395
  /** Installs a remotely verified identity without starting pull or outbox replay. */
4388
- prepareRemoteSession(userId, scopeIds, authSubject, authLease) {
4396
+ async prepareRemoteSession(userId, scopeIds, authSubject, authLease) {
4389
4397
  if (this.#storageUnavailable())
4390
- return Promise.resolve(true);
4398
+ return true;
4391
4399
  const revision = ++this.#transitionRevision;
4392
4400
  const lease = this.#lease(revision, authLease);
4393
4401
  return this.#enqueueTransition(async () => {
@@ -4407,9 +4415,9 @@ class OfflineCoordinatorService {
4407
4415
  /**
4408
4416
  * Activates a restored identity for local replica/outbox use without enabling transport sync.
4409
4417
  */
4410
- activateOfflineSession(authSubject, authLease) {
4418
+ async activateOfflineSession(authSubject, authLease) {
4411
4419
  if (this.#storageUnavailable())
4412
- return Promise.resolve(null);
4420
+ return null;
4413
4421
  const revision = ++this.#transitionRevision;
4414
4422
  const lease = this.#lease(revision, authLease);
4415
4423
  return this.#enqueueTransition(async () => {
@@ -4422,9 +4430,9 @@ class OfflineCoordinatorService {
4422
4430
  return lease.isCurrent() ? manifest : null;
4423
4431
  });
4424
4432
  }
4425
- clearActiveSession() {
4433
+ async clearActiveSession() {
4426
4434
  if (this.#storageUnavailable())
4427
- return Promise.resolve();
4435
+ return;
4428
4436
  this.#sync.revokeSession();
4429
4437
  this.#session.revokeAccess();
4430
4438
  ++this.#transitionRevision;
@@ -4445,9 +4453,9 @@ class OfflineCoordinatorService {
4445
4453
  await this.#sync.flush();
4446
4454
  return this.#sync.pendingCount() === 0;
4447
4455
  }
4448
- flush() {
4456
+ async flush() {
4449
4457
  if (this.#storageUnavailable())
4450
- return Promise.resolve();
4458
+ return;
4451
4459
  return this.#sync.flush();
4452
4460
  }
4453
4461
  #asStorageUnavailable(error) {
@@ -4742,10 +4750,11 @@ const COMMUNITY_SQLITE = new InjectionToken('COMMUNITY_SQLITE', {
4742
4750
  * The returned lower-case hexadecimal value is suitable for
4743
4751
  * `OfflineKitOptions.createEncryptionKey` and contains no device or user identifiers.
4744
4752
  */
4745
- function createRandomOfflineEncryptionKey() {
4753
+ async function createRandomOfflineEncryptionKey() {
4746
4754
  const bytes = crypto.getRandomValues(new Uint8Array(32));
4747
- return Promise.resolve(Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join(''));
4755
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
4748
4756
  }
4757
+ const settledSqliteOperation = async () => undefined;
4749
4758
  /** Create the standard encrypted `@capacitor-community/sqlite` driver. */
4750
4759
  function createCommunitySqliteDriver(connection) {
4751
4760
  const databases = new Map();
@@ -4850,15 +4859,15 @@ class SqliteOfflineRepository {
4850
4859
  #options = inject(OFFLINE_KIT_OPTIONS);
4851
4860
  #databaseId = null;
4852
4861
  #initialization = null;
4853
- #writes = Promise.resolve();
4862
+ #writes = settledSqliteOperation();
4854
4863
  #activeReaders = 0;
4855
- #readersIdle = Promise.resolve();
4864
+ #readersIdle = settledSqliteOperation();
4856
4865
  #resolveReadersIdle = null;
4857
4866
  #atomicMutationRevision = null;
4858
4867
  #atomicMutationCommitted = false;
4859
- #atomicOperations = Promise.resolve();
4868
+ #atomicOperations = settledSqliteOperation();
4860
4869
  #readSnapshotActive = false;
4861
- #atomicIdle = Promise.resolve();
4870
+ #atomicIdle = settledSqliteOperation();
4862
4871
  #resolveAtomicIdle = null;
4863
4872
  initialize() {
4864
4873
  this.#initialization ??= this.#open();
@@ -4919,12 +4928,8 @@ class SqliteOfflineRepository {
4919
4928
  }
4920
4929
  return this.#transaction(async () => {
4921
4930
  this.#readSnapshotActive = true;
4922
- try {
4923
- return await read(this.#reader());
4924
- }
4925
- finally {
4926
- this.#readSnapshotActive = false;
4927
- }
4931
+ const executeRead = async () => read(this.#reader());
4932
+ return executeRead().finally(() => (this.#readSnapshotActive = false));
4928
4933
  });
4929
4934
  }
4930
4935
  async [OFFLINE_REPOSITORY_ATOMIC_MUTATION](operation) {
@@ -4934,9 +4939,9 @@ class SqliteOfflineRepository {
4934
4939
  throw new Error('Nested offline replica atomic mutations are not supported.');
4935
4940
  }
4936
4941
  this.#beginReaders();
4937
- try {
4942
+ const executeAtomicMutation = async () => {
4938
4943
  const databaseId = await this.#databaseConnection();
4939
- this.#atomicOperations = Promise.resolve();
4944
+ this.#atomicOperations = settledSqliteOperation();
4940
4945
  this.#atomicMutationCommitted = false;
4941
4946
  this.#atomicIdle = new Promise((resolve) => {
4942
4947
  this.#resolveAtomicIdle = resolve;
@@ -4948,14 +4953,14 @@ class SqliteOfflineRepository {
4948
4953
  await this.#queueAtomicOperation(() => this.#atomicTransaction(databaseId, async () => undefined, false));
4949
4954
  }
4950
4955
  return result;
4951
- }
4952
- finally {
4956
+ };
4957
+ return executeAtomicMutation().finally(() => {
4953
4958
  this.#atomicMutationRevision = null;
4954
4959
  this.#endReaders();
4955
4960
  this.#resolveAtomicIdle?.();
4956
4961
  this.#resolveAtomicIdle = null;
4957
- this.#atomicIdle = Promise.resolve();
4958
- }
4962
+ this.#atomicIdle = settledSqliteOperation();
4963
+ });
4959
4964
  }
4960
4965
  async putCommand(command) {
4961
4966
  await this.#queueWrite((databaseId) => this.#putCommand(databaseId, command));
@@ -5070,35 +5075,35 @@ class SqliteOfflineRepository {
5070
5075
  }
5071
5076
  }
5072
5077
  async #open() {
5073
- try {
5074
- if (!this.#sqlite) {
5075
- throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');
5076
- }
5077
- const { databaseId } = await this.#sqlite.open({
5078
- databaseName: this.#options.databaseName,
5079
- createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),
5080
- });
5081
- this.#databaseId = databaseId;
5082
- for (const statement of SCHEMA)
5083
- await this.#execute(databaseId, statement);
5084
- const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
5085
- if (metadata.length === 0) {
5086
- await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
5087
- OFFLINE_SCHEMA_VERSION,
5088
- ]);
5089
- }
5090
- else {
5091
- const storedVersion = this.#number(metadata[0]['schema_version']);
5092
- if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5093
- throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
5094
- 'A lossless core schema migration is required before this database can be opened.');
5095
- }
5096
- }
5097
- await this.#initializeReplicaSchema(databaseId);
5098
- }
5099
- catch (error) {
5078
+ await this.#openDatabase().catch((error) => {
5100
5079
  throw this.#mapInitializationError(error);
5080
+ });
5081
+ }
5082
+ async #openDatabase() {
5083
+ if (!this.#sqlite) {
5084
+ throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');
5085
+ }
5086
+ const { databaseId } = await this.#sqlite.open({
5087
+ databaseName: this.#options.databaseName,
5088
+ createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),
5089
+ });
5090
+ this.#databaseId = databaseId;
5091
+ for (const statement of SCHEMA)
5092
+ await this.#execute(databaseId, statement);
5093
+ const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
5094
+ if (metadata.length === 0) {
5095
+ await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
5096
+ OFFLINE_SCHEMA_VERSION,
5097
+ ]);
5098
+ }
5099
+ else {
5100
+ const storedVersion = this.#number(metadata[0]['schema_version']);
5101
+ if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5102
+ throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
5103
+ 'A lossless core schema migration is required before this database can be opened.');
5104
+ }
5101
5105
  }
5106
+ await this.#initializeReplicaSchema(databaseId);
5102
5107
  }
5103
5108
  async #initializeReplicaSchema(databaseId) {
5104
5109
  const bundle = this.#options.replicaSchema;
@@ -5140,19 +5145,19 @@ class SqliteOfflineRepository {
5140
5145
  #wrapCreateEncryptionKey(createEncryptionKey) {
5141
5146
  if (!createEncryptionKey)
5142
5147
  return undefined;
5143
- return async () => {
5144
- try {
5148
+ return () => {
5149
+ const create = async () => {
5145
5150
  const encryptionKey = await createEncryptionKey();
5146
5151
  if (!encryptionKey) {
5147
5152
  throw new OfflineStorageUnavailableError('encryption_key_unavailable', 'Native offline storage requires a non-empty encryption key on first open');
5148
5153
  }
5149
5154
  return encryptionKey;
5150
- }
5151
- catch (error) {
5155
+ };
5156
+ return create().catch((error) => {
5152
5157
  if (error instanceof OfflineStorageUnavailableError)
5153
5158
  throw error;
5154
5159
  throw new OfflineStorageUnavailableError('encryption_key_unavailable', error instanceof Error ? error.message : 'Offline encryption key is unavailable.', { cause: error });
5155
- }
5160
+ });
5156
5161
  };
5157
5162
  }
5158
5163
  #mapInitializationError(error) {
@@ -5179,15 +5184,21 @@ class SqliteOfflineRepository {
5179
5184
  }
5180
5185
  async #nativeTransaction(databaseId, run) {
5181
5186
  await this.#sqlite.beginTransaction({ databaseId });
5182
- try {
5183
- const result = await run();
5187
+ const execute = async () => run();
5188
+ return execute()
5189
+ .then(async (result) => {
5184
5190
  await this.#sqlite.commitTransaction({ databaseId });
5185
5191
  return result;
5186
- }
5187
- catch (error) {
5188
- await this.#sqlite.rollbackTransaction({ databaseId });
5192
+ })
5193
+ .catch(async (error) => {
5194
+ const rollback = await this.#sqlite.rollbackTransaction({ databaseId }).then(() => ({ status: 'fulfilled' }), (rollbackError) => ({ status: 'rejected', rollbackError }));
5195
+ if (rollback.status === 'rejected') {
5196
+ throw new AggregateError([error, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
5197
+ cause: error,
5198
+ });
5199
+ }
5189
5200
  throw error;
5190
- }
5201
+ });
5191
5202
  }
5192
5203
  async #databaseConnection() {
5193
5204
  await this.initialize();
@@ -5312,16 +5323,12 @@ class SqliteOfflineRepository {
5312
5323
  const reader = this.#reader();
5313
5324
  const atomicTransaction = (run, marksCommit = true) => this.#queueAtomicOperation(() => this.#atomicTransaction(this.#databaseId, run, marksCommit));
5314
5325
  return {
5315
- initialize: () => Promise.resolve(),
5326
+ initialize: settledSqliteOperation,
5316
5327
  ...reader,
5317
5328
  runReadSnapshot: (read) => this.#queueAtomicOperation(() => this.#nativeTransaction(this.#databaseId, async () => {
5318
5329
  this.#readSnapshotActive = true;
5319
- try {
5320
- return await read(reader);
5321
- }
5322
- finally {
5323
- this.#readSnapshotActive = false;
5324
- }
5330
+ const executeRead = async () => read(reader);
5331
+ return executeRead().finally(() => (this.#readSnapshotActive = false));
5325
5332
  })),
5326
5333
  putCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
5327
5334
  replaceCommand: (command) => atomicTransaction((databaseId) => this.#putCommand(databaseId, command)),
@@ -5351,12 +5358,8 @@ class SqliteOfflineRepository {
5351
5358
  }
5352
5359
  await this.#writes;
5353
5360
  this.#beginReaders();
5354
- try {
5355
- return await operation();
5356
- }
5357
- finally {
5358
- this.#endReaders();
5359
- }
5361
+ const read = async () => operation();
5362
+ return read().finally(() => this.#endReaders());
5360
5363
  }
5361
5364
  #beginReaders() {
5362
5365
  if (this.#activeReaders === 0) {
@@ -5371,7 +5374,7 @@ class SqliteOfflineRepository {
5371
5374
  if (this.#activeReaders === 0) {
5372
5375
  this.#resolveReadersIdle?.();
5373
5376
  this.#resolveReadersIdle = null;
5374
- this.#readersIdle = Promise.resolve();
5377
+ this.#readersIdle = settledSqliteOperation();
5375
5378
  }
5376
5379
  }
5377
5380
  async #query(statement, values = []) {