@rdlabo/ionic-angular-kit 22.0.0-beta.pr97.shac93e32c6e176 → 22.0.0-beta.pr98.sha5e7e3312b58f

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, filter, NEVER, race, take, Observable, dematerialize, EMPTY, tap } from 'rxjs';
10
+ import { defer, from, map as map$1, concatMap, EMPTY, of, catchError, throwError, materialize, connect, concat, ReplaySubject, filter, NEVER, race, take, Observable, dematerialize, 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_]*$/;
@@ -933,6 +933,33 @@ function offlineCommandLookupIdentity(identity) {
933
933
  * This symbol is intentionally not re-exported from the package entry point.
934
934
  */
935
935
  const OFFLINE_REPOSITORY_ATOMIC_MUTATION = Symbol('OFFLINE_REPOSITORY_ATOMIC_MUTATION');
936
+ /** Internal typed boundary for a local write that is safe to recompute once from a fresh snapshot. */
937
+ class OfflineReplicaTransientWriteError extends Error {
938
+ constructor(reason, message, options) {
939
+ super(message, options);
940
+ this.reason = reason;
941
+ this.name = 'OfflineReplicaTransientWriteError';
942
+ }
943
+ }
944
+ function normalizeOfflineReplicaTransientWriteError(error) {
945
+ if (error instanceof OfflineReplicaTransientWriteError)
946
+ return error;
947
+ const code = typeof error === 'object' && error !== null && typeof error.code === 'string'
948
+ ? error.code.toUpperCase()
949
+ : '';
950
+ const message = error instanceof Error ? error.message : typeof error === 'string' ? error : '';
951
+ const normalizedMessage = message.toUpperCase();
952
+ if (code.includes('SQLITE_BUSY') || normalizedMessage.includes('SQLITE_BUSY')) {
953
+ return new OfflineReplicaTransientWriteError('sqlite_busy', message || 'SQLite is busy.', { cause: error });
954
+ }
955
+ if (code.includes('SQLITE_LOCKED') ||
956
+ normalizedMessage.includes('SQLITE_LOCKED') ||
957
+ message.includes('database is locked') ||
958
+ message.includes('database table is locked')) {
959
+ return new OfflineReplicaTransientWriteError('sqlite_locked', message || 'SQLite database is locked.', { cause: error });
960
+ }
961
+ return error;
962
+ }
936
963
 
937
964
  /** Current durable storage schema used by both web and native repositories. */
938
965
  const OFFLINE_SCHEMA_VERSION = 2;
@@ -2824,6 +2851,15 @@ class OfflinePayloadValidationError extends Error {
2824
2851
  this.name = 'OfflinePayloadValidationError';
2825
2852
  }
2826
2853
  }
2854
+ /** A foreground durable-command send reached a terminal server-side state. */
2855
+ class OfflineImmediateCommandRejectedError extends Error {
2856
+ constructor(state, code) {
2857
+ super(`Immediate offline command delivery ended in ${state}${code ? ` (${code})` : ''}.`);
2858
+ this.state = state;
2859
+ this.code = code;
2860
+ this.name = 'OfflineImmediateCommandRejectedError';
2861
+ }
2862
+ }
2827
2863
  /** Raised before persistence when retaining another command would exceed the configured durable Outbox capacity. */
2828
2864
  class OfflineOutboxCapacityError extends Error {
2829
2865
  constructor(reason, currentCommands, currentBytes) {
@@ -2896,6 +2932,7 @@ class OfflineSyncService {
2896
2932
  #flushTransitions;
2897
2933
  #generation;
2898
2934
  #sendingTransitions;
2935
+ #commandSendTransitions;
2899
2936
  #retryTimer;
2900
2937
  /** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
2901
2938
  #foregroundScopePolicy;
@@ -2930,6 +2967,7 @@ class OfflineSyncService {
2930
2967
  this.#flushTransitions = new Set();
2931
2968
  this.#generation = 0;
2932
2969
  this.#sendingTransitions = new Set();
2970
+ this.#commandSendTransitions = new Map();
2933
2971
  this.#retryTimer = null;
2934
2972
  /** When non-null, automatic flushes pull only foreground scopes plus Outbox scopes. */
2935
2973
  this.#foregroundScopePolicy = null;
@@ -3235,7 +3273,10 @@ class OfflineSyncService {
3235
3273
  this.noteScope(scope);
3236
3274
  const commandIdentity = offlineCommandLookupIdentity(request.identity);
3237
3275
  const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity, repository);
3238
- const commandId = crypto.randomUUID();
3276
+ const commandId = request.commandId ?? crypto.randomUUID();
3277
+ if (typeof commandId !== 'string' || commandId.length === 0 || commandId.length > 255) {
3278
+ throw new Error('Offline command id must contain between 1 and 255 characters.');
3279
+ }
3239
3280
  const sourceKey = this.#hooks.entityType(request);
3240
3281
  const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);
3241
3282
  if (replaced)
@@ -3351,6 +3392,7 @@ class OfflineSyncService {
3351
3392
  #assertDistinctBatchFootprints(entries, existingCommands, allowOneAggregate = false) {
3352
3393
  const aggregates = new Set();
3353
3394
  const replicaKeys = new Set();
3395
+ const commandIds = new Set(existingCommands.map((command) => command.commandId));
3354
3396
  const existingFootprints = new Map();
3355
3397
  for (const command of existingCommands) {
3356
3398
  const aggregate = this.#aggregateKey(command);
@@ -3358,6 +3400,10 @@ class OfflineSyncService {
3358
3400
  existingFootprints.set(key, aggregate);
3359
3401
  }
3360
3402
  for (const entry of entries) {
3403
+ if (commandIds.has(entry.command.commandId)) {
3404
+ throw new Error(`Offline command id ${entry.command.commandId} is already in use.`);
3405
+ }
3406
+ commandIds.add(entry.command.commandId);
3361
3407
  const aggregate = this.#aggregateKey(entry.command);
3362
3408
  if (aggregates.has(aggregate) && !allowOneAggregate) {
3363
3409
  throw new Error('Prepared offline batch contains overlapping aggregate intents.');
@@ -3555,11 +3601,137 @@ class OfflineSyncService {
3555
3601
  const generation = this.#generation;
3556
3602
  return this.#flushAfterInitialization(generation);
3557
3603
  }
3604
+ /**
3605
+ * Sends one newly-created generated aggregate immediately after its durable
3606
+ * enqueue, without waiting for a pre-send pull.
3607
+ *
3608
+ * This fast path is deliberately narrow: the command must still be pending,
3609
+ * have no remote id or confirmed baseline, and be the first intent for its
3610
+ * aggregate. Existing aggregates continue through {@link flush}, where the
3611
+ * pre-pull conflict barrier remains mandatory. Authoritative pull
3612
+ * reconciliation is scheduled in the background after the local transport
3613
+ * acknowledgement has been committed.
3614
+ *
3615
+ * @returns The generated remote id when transport completed locally, or
3616
+ * `null` when transport is unavailable or did not produce a confirmed id.
3617
+ */
3618
+ async sendGeneratedCommandNow(commandId, locator) {
3619
+ const generation = this.#generation;
3620
+ if (!(await this.#restoreCurrentGeneration(generation)))
3621
+ return null;
3622
+ const userId = this.#activeUserId;
3623
+ if (userId === null)
3624
+ return null;
3625
+ return this.#beginGeneratedCommandSend(commandId, locator, generation, userId);
3626
+ }
3558
3627
  async #flushAfterInitialization(generation) {
3559
3628
  if (!(await this.#restoreCurrentGeneration(generation)))
3560
3629
  return;
3561
3630
  return this.#beginFlush(true);
3562
3631
  }
3632
+ #beginGeneratedCommandSend(commandId, locator, generation, userId) {
3633
+ const result = this.#runGeneratedCommandSend(commandId, locator, generation, userId);
3634
+ let requiresReconciliation = false;
3635
+ const transition = result
3636
+ .then((remoteId) => {
3637
+ requiresReconciliation = remoteId !== null;
3638
+ }, () => undefined)
3639
+ .finally(() => {
3640
+ this.#flushTransitions.delete(transition);
3641
+ if (requiresReconciliation && this.#canSynchronize() && this.#isCurrentUser(generation, userId)) {
3642
+ // A normal flush may already be in its post-pull phase. Ensure the
3643
+ // newly acknowledged command receives a later reconciliation pass.
3644
+ if (this.#flushPromise)
3645
+ this.#resumeAfterFlush = true;
3646
+ queueMicrotask(() => this.#flushInBackground());
3647
+ }
3648
+ });
3649
+ this.#flushTransitions.add(transition);
3650
+ return result;
3651
+ }
3652
+ async #runGeneratedCommandSend(commandId, locator, generation, userId) {
3653
+ if (!this.#isCurrentUser(generation, userId))
3654
+ return null;
3655
+ if (!this.#canSynchronize()) {
3656
+ await this.#refreshState(generation);
3657
+ return null;
3658
+ }
3659
+ if (this.#pullAttentions().length > 0)
3660
+ return null;
3661
+ if (!(await this.#discoverScopes(generation)))
3662
+ return null;
3663
+ if (!this.#isCurrentUser(generation, userId))
3664
+ return null;
3665
+ const known = await this.#readKnownCommands();
3666
+ if (!this.#isCurrentUser(generation, userId))
3667
+ return null;
3668
+ const command = known.find((candidate) => candidate.commandId === commandId);
3669
+ if (!command)
3670
+ return this.#generatedRemoteId(locator, userId, generation);
3671
+ if (command.userId !== userId)
3672
+ return null;
3673
+ if (command.scopeId !== locator.scopeId ||
3674
+ command.sourceKey !== locator.sourceKey ||
3675
+ command.identity.kind !== 'generated' ||
3676
+ command.identity.localId !== locator.localId) {
3677
+ throw new Error('Immediate generated command locator does not match the durable command.');
3678
+ }
3679
+ if (command.state === 'awaiting_pull') {
3680
+ return this.#commandReconciliationRemoteId(command) ?? this.#generatedRemoteId(locator, userId, generation);
3681
+ }
3682
+ if (command.state !== 'pending')
3683
+ return null;
3684
+ const aggregate = known.filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
3685
+ if (aggregate[0]?.commandId !== command.commandId) {
3686
+ throw new Error('Immediate generated command delivery requires the first aggregate intent.');
3687
+ }
3688
+ const row = await this.#rowForCommand(command);
3689
+ if (!row ||
3690
+ row.identity.kind !== 'generated' ||
3691
+ row.identity.remoteId !== null ||
3692
+ row.confirmedValues !== null ||
3693
+ command.identity.kind !== 'generated' ||
3694
+ command.baseRevision !== null ||
3695
+ command.replicaMutation === 'delete') {
3696
+ throw new Error('Immediate generated command delivery requires a new unconfirmed aggregate.');
3697
+ }
3698
+ const scope = { userId: command.userId, scopeId: command.scopeId };
3699
+ const scopeKey = this.#scopeKey(scope);
3700
+ if (!this.#knownScopes.has(scopeKey))
3701
+ return null;
3702
+ const dirtyScopes = new Map();
3703
+ await this.#sendAggregate([command], generation, dirtyScopes, new Set([scopeKey]));
3704
+ if (!this.#isCurrentUser(generation, userId))
3705
+ return null;
3706
+ for (const dirtyScope of dirtyScopes.values()) {
3707
+ this.#pendingPullScopes.set(this.#scopeKey(dirtyScope), dirtyScope);
3708
+ }
3709
+ await this.#refreshState(generation);
3710
+ if (!this.#isCurrentUser(generation, userId))
3711
+ return null;
3712
+ const completed = (await this.#readKnownCommands()).find((candidate) => candidate.commandId === commandId);
3713
+ if (!this.#isCurrentUser(generation, userId))
3714
+ return null;
3715
+ if (completed && ['blocked_auth', 'rejected', 'conflict'].includes(completed.state)) {
3716
+ throw new OfflineImmediateCommandRejectedError(completed.state, completed.lastErrorCode);
3717
+ }
3718
+ return completed
3719
+ ? (this.#commandReconciliationRemoteId(completed) ?? this.#generatedRemoteId(locator, userId, generation))
3720
+ : this.#generatedRemoteId(locator, userId, generation);
3721
+ }
3722
+ async #generatedRemoteId(locator, userId, generation) {
3723
+ if (!this.#isCurrentUser(generation, userId))
3724
+ return null;
3725
+ const row = await this.#repository.getReplicaRow({ userId, scopeId: locator.scopeId }, locator.sourceKey, {
3726
+ kind: 'generated',
3727
+ localId: locator.localId,
3728
+ });
3729
+ return this.#isCurrentUser(generation, userId) && row?.identity.kind === 'generated' ? row.identity.remoteId : null;
3730
+ }
3731
+ #commandReconciliationRemoteId(command) {
3732
+ const identity = command.reconciliationIdentity;
3733
+ return identity && 'remoteId' in identity ? (identity.remoteId ?? null) : null;
3734
+ }
3563
3735
  #beginFlush(explicitFull) {
3564
3736
  const lifecycleRevision = this.#lifecycleRevision();
3565
3737
  const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
@@ -3829,75 +4001,94 @@ class OfflineSyncService {
3829
4001
  }
3830
4002
  async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
3831
4003
  for (const command of commands) {
3832
- if (!this.#isCurrent(generation))
3833
- return;
3834
- if (command.state === 'awaiting_pull')
3835
- continue;
3836
- if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
3837
- break;
3838
- if (!['pending', 'retry_wait'].includes(command.state))
3839
- break;
3840
- // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
3841
- // belong to scopes that failed pre-pull even when the head was admitted.
3842
- if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
4004
+ if (!(await this.#sendCommandOnce(commands, command, generation, dirtyScopes, pulledScopeKeys)))
3843
4005
  break;
3844
- let sending = await this.#claimSendingCommand(command, generation);
3845
- if (!sending)
3846
- return;
4006
+ }
4007
+ }
4008
+ #sendCommandOnce(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys) {
4009
+ const transitionKey = this.#commandSendKey(command, generation);
4010
+ const active = this.#commandSendTransitions.get(transitionKey);
4011
+ if (active)
4012
+ return active;
4013
+ const transition = this.#sendCommand(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys).finally(() => {
4014
+ if (this.#commandSendTransitions.get(transitionKey) === transition) {
4015
+ this.#commandSendTransitions.delete(transitionKey);
4016
+ }
4017
+ });
4018
+ this.#commandSendTransitions.set(transitionKey, transition);
4019
+ return transition;
4020
+ }
4021
+ #commandSendKey(command, generation) {
4022
+ return JSON.stringify([generation, canonicalOfflinePrincipalId(command.userId), command.commandId]);
4023
+ }
4024
+ async #sendCommand(aggregateCommands, command, generation, dirtyScopes, pulledScopeKeys) {
4025
+ if (!this.#isCurrent(generation))
4026
+ return false;
4027
+ if (command.state === 'awaiting_pull')
4028
+ return true;
4029
+ if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
4030
+ return false;
4031
+ if (!['pending', 'retry_wait'].includes(command.state))
4032
+ return false;
4033
+ // User-scoped aggregates ignore scopeId in the FIFO key, so later commands may
4034
+ // belong to scopes that failed pre-pull even when the head was admitted.
4035
+ if (!pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId })))
4036
+ return false;
4037
+ let sending = await this.#claimSendingCommand(command, generation);
4038
+ if (!sending || !this.#isCurrent(generation))
4039
+ return false;
4040
+ await this.#refreshState(generation);
4041
+ if (!this.#isCurrent(generation))
4042
+ return false;
4043
+ const claimedCommand = sending;
4044
+ const readRow = async () => this.#rowForCommand(claimedCommand);
4045
+ const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
4046
+ if (rowResult.status === 'rejected') {
3847
4047
  if (!this.#isCurrent(generation))
3848
- return;
3849
- await this.#refreshState(generation);
4048
+ return false;
4049
+ await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
4050
+ throw rowResult.error;
4051
+ }
4052
+ const row = rowResult.row;
4053
+ if (!row) {
4054
+ const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
4055
+ await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
4056
+ throw error;
4057
+ }
4058
+ const priorCommitUnknown = sending.serverCommitUnknown === true;
4059
+ const transportCommand = await this.#markTransportStarted(sending, generation);
4060
+ if (!transportCommand)
4061
+ return false;
4062
+ sending = transportCommand;
4063
+ const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
4064
+ const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
4065
+ if (execution.status === 'rejected') {
3850
4066
  if (!this.#isCurrent(generation))
3851
- return;
3852
- const claimedCommand = sending;
3853
- const readRow = async () => this.#rowForCommand(claimedCommand);
3854
- const rowResult = await readRow().then((row) => ({ status: 'fulfilled', row }), (error) => ({ status: 'rejected', error }));
3855
- if (rowResult.status === 'rejected') {
3856
- if (!this.#isCurrent(generation))
3857
- return;
3858
- await this.#persistFailedCommand(sending, rowResult.error, generation, null, sending.serverCommitUnknown === true);
3859
- throw rowResult.error;
3860
- }
3861
- const row = rowResult.row;
3862
- if (!row) {
3863
- const error = new Error(`Offline replica row not found: ${sending.aggregateType}/${canonicalOfflineCommandIdentity(sending.identity)}`);
3864
- await this.#persistFailedCommand(sending, error, generation, null, sending.serverCommitUnknown === true);
3865
- throw error;
3866
- }
3867
- const priorCommitUnknown = sending.serverCommitUnknown === true;
3868
- const transportCommand = await this.#markTransportStarted(sending, generation);
3869
- if (!transportCommand)
3870
- return;
3871
- sending = transportCommand;
3872
- const executeCommand = async () => this.#executor.execute(sending, offlineCommandTargetFromReplicaRow(row));
3873
- const execution = await executeCommand().then((result) => ({ status: 'fulfilled', result }), (error) => ({ status: 'rejected', error }));
3874
- if (execution.status === 'rejected') {
3875
- if (!this.#isCurrent(generation))
3876
- return;
3877
- const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
3878
- ? false
3879
- : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
3880
- await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
3881
- if (!this.#isClassifiableTransportError(execution.error))
3882
- throw execution.error;
3883
- break;
3884
- }
3885
- const result = execution.result;
4067
+ return false;
4068
+ const commitUnknown = this.#executor.provesCommandNotCommitted?.(execution.error, sending)
4069
+ ? false
4070
+ : priorCommitUnknown || this.#serverCommitCouldBeUnknown(execution.error);
4071
+ await this.#persistFailedCommand(sending, execution.error, generation, row, commitUnknown);
4072
+ if (!this.#isClassifiableTransportError(execution.error))
4073
+ throw execution.error;
4074
+ return false;
4075
+ }
4076
+ const result = execution.result;
4077
+ if (!this.#isCurrent(generation))
4078
+ return false;
4079
+ const completeCommand = async () => this.#completeCommandWithRetry(aggregateCommands, sending, result, generation);
4080
+ const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
4081
+ if (completion.status === 'rejected') {
3886
4082
  if (!this.#isCurrent(generation))
3887
- return;
3888
- const completeCommand = async () => this.#completeCommand(commands, sending, result, generation);
3889
- const completion = await completeCommand().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3890
- if (completion.status === 'rejected') {
3891
- if (!this.#isCurrent(generation))
3892
- return;
3893
- await this.#persistFailedCommand(sending, completion.error, generation, row, true);
3894
- throw completion.error;
3895
- }
3896
- if (this.#isCurrent(generation)) {
3897
- const scope = { userId: sending.userId, scopeId: sending.scopeId };
3898
- dirtyScopes.set(this.#scopeKey(scope), scope);
3899
- }
4083
+ return false;
4084
+ await this.#persistFailedCommand(sending, completion.error, generation, row, true);
4085
+ throw completion.error;
3900
4086
  }
4087
+ if (this.#isCurrent(generation)) {
4088
+ const scope = { userId: sending.userId, scopeId: sending.scopeId };
4089
+ dirtyScopes.set(this.#scopeKey(scope), scope);
4090
+ }
4091
+ return true;
3901
4092
  }
3902
4093
  async #normalizeEnqueueRequest(scope, request, commandIdentity, repository) {
3903
4094
  let baseRevision = request.baseRevision ?? null;
@@ -3911,6 +4102,18 @@ class OfflineSyncService {
3911
4102
  async #completeCommand(commands, command, result, generation) {
3912
4103
  return this.#serializeReplicaMutation((repository) => this.#completeCommandLocked(commands, command, result, generation, repository));
3913
4104
  }
4105
+ async #completeCommandWithRetry(commands, command, result, generation) {
4106
+ return this.#completeCommand(commands, command, result, generation).catch(async (firstError) => {
4107
+ if (!isRetryableLocalCompletionError(firstError))
4108
+ throw firstError;
4109
+ const retry = await this.#completeCommand(commands, command, result, generation).then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
4110
+ if (retry.status === 'fulfilled')
4111
+ return;
4112
+ if (!isRetryableLocalCompletionError(retry.error))
4113
+ throw retry.error;
4114
+ throw new OfflineLocalCompletionError(retry.error, firstError);
4115
+ });
4116
+ }
3914
4117
  async #completeCommandLocked(commands, command, result, generation, repository) {
3915
4118
  if (result.clearRemoteId === true && result.remoteId !== undefined) {
3916
4119
  throw new Error('Offline command cannot return remoteId and clearRemoteId together.');
@@ -4093,7 +4296,7 @@ class OfflineSyncService {
4093
4296
  ...command,
4094
4297
  state: 'retry_wait',
4095
4298
  retryAt,
4096
- lastErrorCode: status > 0 ? String(status) : 'network',
4299
+ lastErrorCode: error instanceof OfflineLocalCompletionError ? 'local_completion' : status > 0 ? String(status) : 'network',
4097
4300
  serverCommitUnknown,
4098
4301
  };
4099
4302
  }
@@ -4315,6 +4518,9 @@ class OfflineSyncService {
4315
4518
  #isCurrent(generation) {
4316
4519
  return generation === this.#generation;
4317
4520
  }
4521
+ #isCurrentUser(generation, userId) {
4522
+ return this.#isCurrent(generation) && this.#activeUserId === userId;
4523
+ }
4318
4524
  async #restoreInterruptedCommands() {
4319
4525
  const commands = await this.#readKnownCommands();
4320
4526
  await Promise.all(commands
@@ -4396,7 +4602,7 @@ class OfflineSyncService {
4396
4602
  this.#pendingPullScopes.delete(this.#scopeKey(scope));
4397
4603
  }
4398
4604
  async #waitForSendingTransitions() {
4399
- await Promise.allSettled([...this.#sendingTransitions]);
4605
+ await Promise.allSettled([...this.#sendingTransitions, ...this.#commandSendTransitions.values()]);
4400
4606
  }
4401
4607
  #canonicalJson(value) {
4402
4608
  if (Array.isArray(value))
@@ -4432,6 +4638,17 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "22.1.3", ngImpor
4432
4638
  function compareOfflineCommands(left, right) {
4433
4639
  return left.createdAt - right.createdAt || (left.commandId < right.commandId ? -1 : left.commandId > right.commandId ? 1 : 0);
4434
4640
  }
4641
+ class OfflineLocalCompletionError extends AggregateError {
4642
+ constructor(retryError, firstError) {
4643
+ super([firstError, retryError], 'Offline command reached the server but local acknowledgement could not be persisted.', {
4644
+ cause: retryError,
4645
+ });
4646
+ this.name = 'OfflineLocalCompletionError';
4647
+ }
4648
+ }
4649
+ function isRetryableLocalCompletionError(error) {
4650
+ return error instanceof OfflineReplicaTransientWriteError;
4651
+ }
4435
4652
 
4436
4653
  /** Raised when disabling requires pending commands to be synchronized while transport is offline. */
4437
4654
  class OfflineMutationPersistenceRequiresOnlineError extends Error {
@@ -4826,6 +5043,7 @@ class OfflineCoordinatorService {
4826
5043
  ...(ngDevMode ? [{ debugName: "isStorageReady" }] : /* istanbul ignore next */ []));
4827
5044
  this.networkState = this.#network.state;
4828
5045
  this.syncState = this.#sync.syncState;
5046
+ this.pendingCommands = this.#sync.pendingCommands;
4829
5047
  this.pendingCount = this.#sync.pendingCount;
4830
5048
  this.conflicts = this.#sync.conflicts;
4831
5049
  /** Device-local control for accepting new durable Outbox mutations. */
@@ -5391,6 +5609,9 @@ const offlineInterceptor = (request, next) => {
5391
5609
  const plan = registry.resolve(request);
5392
5610
  if (!plan)
5393
5611
  return transport();
5612
+ if (plan.readStrategy === 'local-only') {
5613
+ return readLocalOnly(plan, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5614
+ }
5394
5615
  if (plan.readStrategy === 'local-first') {
5395
5616
  return readLocalFirst(request, plan, transport, fallback, inject(ErrorHandler), inject(OfflineReplicaMutationCoordinator));
5396
5617
  }
@@ -5409,6 +5630,10 @@ const offlineInterceptor = (request, next) => {
5409
5630
  }
5410
5631
  return transport();
5411
5632
  };
5633
+ /** Resolves a provisional/local identity without starting remote transport. */
5634
+ function readLocalOnly(plan, errorHandler, replicaMutations) {
5635
+ return resolveLocalAttempt(plan, errorHandler, replicaMutations).pipe(concatMap((response) => (response ? of(response) : EMPTY)));
5636
+ }
5412
5637
  function readNetworkFirst(request, plan, transport, fallback, replicaMutations) {
5413
5638
  return defer(transport).pipe(catchError((error) => fallback.handle(request, error, plan) ?? throwError(() => error)), concatMap((event) => projectReadResponse(event, plan, replicaMutations)));
5414
5639
  }
@@ -5490,7 +5715,10 @@ function projectReadResponse(event, plan, replicaMutations) {
5490
5715
  if (!(event instanceof HttpResponse) || !plan.projectResponse)
5491
5716
  return of(event);
5492
5717
  const source = event.headers.get(OFFLINE_RESPONSE_HEADER) === 'local' ? 'local' : 'remote';
5493
- return from(replicaMutations.runSerializedRead(() => plan.projectResponse(event, source))).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
5718
+ const projection = plan.serializeResponseProjection
5719
+ ? replicaMutations.runSerializedRead(() => plan.projectResponse(event, source))
5720
+ : plan.projectResponse(event, source);
5721
+ return from(projection).pipe(map$1((response) => source === 'local' ? response.clone({ headers: response.headers.set(OFFLINE_RESPONSE_HEADER, 'local') }) : response));
5494
5722
  }
5495
5723
  function observeTransport(source, network) {
5496
5724
  return source.pipe(tap({
@@ -6126,7 +6354,9 @@ class SqliteOfflineRepository {
6126
6354
  ON CONFLICT(id) DO UPDATE SET version = excluded.version, schema_hash = excluded.schema_hash`, [version, schemaHash]);
6127
6355
  }
6128
6356
  async #nativeTransaction(databaseId, run) {
6129
- await this.#sqlite.beginTransaction({ databaseId });
6357
+ await this.#sqlite.beginTransaction({ databaseId }).catch((error) => {
6358
+ throw normalizeOfflineReplicaTransientWriteError(error);
6359
+ });
6130
6360
  const execute = async () => run();
6131
6361
  return execute()
6132
6362
  .then(async (result) => {
@@ -6134,13 +6364,14 @@ class SqliteOfflineRepository {
6134
6364
  return result;
6135
6365
  })
6136
6366
  .catch(async (error) => {
6367
+ const normalizedError = normalizeOfflineReplicaTransientWriteError(error);
6137
6368
  const rollback = await this.#sqlite.rollbackTransaction({ databaseId }).then(() => ({ status: 'fulfilled' }), (rollbackError) => ({ status: 'rejected', rollbackError }));
6138
6369
  if (rollback.status === 'rejected') {
6139
- throw new AggregateError([error, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
6140
- cause: error,
6370
+ throw new AggregateError([normalizedError, rollback.rollbackError], 'Offline SQLite transaction and rollback both failed.', {
6371
+ cause: normalizedError,
6141
6372
  });
6142
6373
  }
6143
- throw error;
6374
+ throw normalizedError;
6144
6375
  });
6145
6376
  }
6146
6377
  async #databaseConnection() {
@@ -6363,7 +6594,7 @@ class SqliteOfflineRepository {
6363
6594
  await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = schema_version WHERE id = 1');
6364
6595
  const actual = await this.#dataVersion(databaseId);
6365
6596
  if (actual !== expected) {
6366
- throw new Error('Offline replica changed through another SQLite connection; retry the operation from fresh state.');
6597
+ throw new OfflineReplicaTransientWriteError('concurrent_revision', 'Offline replica changed through another SQLite connection; retry the operation from fresh state.');
6367
6598
  }
6368
6599
  return run(databaseId);
6369
6600
  });
@@ -6974,5 +7205,5 @@ function assertSupportedOfflineMode(platform, mode) {
6974
7205
  * Generated bundle index. Do not edit.
6975
7206
  */
6976
7207
 
6977
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_COMPLETE_HEADER, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPersistenceDisabledError, OfflineMutationPersistencePendingError, OfflineMutationPersistenceRequiresOnlineError, OfflineMutationPersistenceService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineRouteInitializerService, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, migrateOfflineDatabaseEncryption, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReadEmission, offlineReadSource, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, provideRouteScopedOffline, real, recoverOfflineLocalReset, replicaAddressFromIdentity, requestOfflineLocalReset, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, shouldCommitOfflineCollection, supportsSynchronizedOfflineRepository, text };
7208
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_AGGREGATE_INTENT_PROJECTOR, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_MUTATION_REQUEST_POLICIES, OFFLINE_REPLICA_PROJECTOR, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_COMPLETE_HEADER, OFFLINE_RESPONSE_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineImmediateCommandRejectedError, OfflineMutationPersistenceDisabledError, OfflineMutationPersistencePendingError, OfflineMutationPersistenceRequiresOnlineError, OfflineMutationPersistenceService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineRouteInitializerService, OfflineSessionService, OfflineStorageUnavailableError, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandFootprintKeys, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineAggregateIntentConflict, isOfflineFallbackError, isOfflineStorageUnavailableError, json, localOnly, migrateOfflineDatabaseEncryption, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineCommandWithBaseRevision, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReadEmission, offlineReadSource, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, provideRouteScopedOffline, real, recoverOfflineLocalReset, replicaAddressFromIdentity, requestOfflineLocalReset, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, shouldCommitOfflineCollection, supportsSynchronizedOfflineRepository, text };
6978
7209
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map