@rdlabo/ionic-angular-kit 21.5.8 → 21.5.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.
@@ -1036,12 +1036,33 @@ class IonicOfflineRepository {
1036
1036
  this.#readRecord(CURSORS_KEY),
1037
1037
  ]);
1038
1038
  const identityCheckRows = { ...rows };
1039
+ const releases = new Map();
1040
+ for (const release of transaction.releaseServerIds ?? []) {
1041
+ if (!Number.isSafeInteger(release.serverId) || release.serverId <= 0) {
1042
+ throw new Error(`Offline replica release has invalid serverId ${String(release.serverId)}.`);
1043
+ }
1044
+ const key = this.#rowKey(release, release.sourceKey, release.localId);
1045
+ if (releases.has(key))
1046
+ throw new Error(`Offline replica serverId release is duplicated for ${release.sourceKey}/${release.localId}.`);
1047
+ releases.set(key, release);
1048
+ }
1049
+ const consumedReleases = new Set();
1039
1050
  for (const row of transaction.putRows ?? []) {
1040
- const existing = identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)];
1051
+ const key = this.#rowKey(row, row.sourceKey, row.localId);
1052
+ const existing = identityCheckRows[key];
1053
+ const release = releases.get(key);
1054
+ if (!existing && release) {
1055
+ throw new Error(`Offline replica serverId release requires an existing row for ${row.sourceKey}/${row.localId}.`);
1056
+ }
1041
1057
  if (existing)
1042
- this.#assertReplicaIdentityAssignment(existing, row);
1058
+ this.#assertReplicaIdentityAssignment(existing, row, release);
1059
+ if (release)
1060
+ consumedReleases.add(key);
1043
1061
  this.#assertUniqueReplicaIdentity(identityCheckRows, row);
1044
- identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)] = row;
1062
+ identityCheckRows[key] = row;
1063
+ }
1064
+ if (consumedReleases.size !== releases.size) {
1065
+ throw new Error('Offline replica serverId release must match an existing row in putRows.');
1045
1066
  }
1046
1067
  if (journal)
1047
1068
  await this.#storage.set(REPLICA_TRANSACTION_KEY, transaction);
@@ -1141,9 +1162,18 @@ class IonicOfflineRepository {
1141
1162
  throw new Error(`Offline replica remote identity is already mapped to localId ${collision[1].localId}.`);
1142
1163
  }
1143
1164
  }
1144
- #assertReplicaIdentityAssignment(existing, incoming) {
1165
+ #assertReplicaIdentityAssignment(existing, incoming, release) {
1145
1166
  const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1167
+ if (release && schema.identity.kind !== 'serverId') {
1168
+ throw new Error(`Offline replica serverId release is unsupported for source "${incoming.sourceKey}".`);
1169
+ }
1146
1170
  if (schema.identity.kind === 'serverId') {
1171
+ if (release) {
1172
+ if (existing.serverId !== release.serverId || incoming.serverId !== null) {
1173
+ throw new Error(`Offline replica serverId release must transition current=${existing.serverId} to incoming=null for ${incoming.sourceKey}/${incoming.localId}.`);
1174
+ }
1175
+ return;
1176
+ }
1147
1177
  if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
1148
1178
  throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
1149
1179
  }
@@ -1769,7 +1799,8 @@ class OfflineSyncService {
1769
1799
  #flushTransitions;
1770
1800
  #generation;
1771
1801
  #sendingTransitions;
1772
- #enqueueTail;
1802
+ /** Serializes enqueue and acknowledgement projection over the same local replica. */
1803
+ #replicaMutationTail;
1773
1804
  #retryTimer;
1774
1805
  #initialized;
1775
1806
  #lastCommandCreatedAt;
@@ -1789,7 +1820,8 @@ class OfflineSyncService {
1789
1820
  this.#flushTransitions = new Set();
1790
1821
  this.#generation = 0;
1791
1822
  this.#sendingTransitions = new Set();
1792
- this.#enqueueTail = Promise.resolve();
1823
+ /** Serializes enqueue and acknowledgement projection over the same local replica. */
1824
+ this.#replicaMutationTail = Promise.resolve();
1793
1825
  this.#retryTimer = null;
1794
1826
  this.#initialized = false;
1795
1827
  this.#lastCommandCreatedAt = 0;
@@ -1848,7 +1880,7 @@ class OfflineSyncService {
1848
1880
  }
1849
1881
  async resetSession() {
1850
1882
  this.revokeSession();
1851
- await Promise.allSettled([this.#enqueueTail, ...this.#flushTransitions]);
1883
+ await Promise.allSettled([this.#replicaMutationTail, ...this.#flushTransitions]);
1852
1884
  await this.#waitForSendingTransitions();
1853
1885
  await this.#restoreInterruptedCommands();
1854
1886
  this.#activeUserId = null;
@@ -1862,9 +1894,39 @@ class OfflineSyncService {
1862
1894
  }
1863
1895
  enqueue(request, options = {}) {
1864
1896
  const generation = this.#generation;
1865
- const enqueue = this.#enqueueTail.then(() => this.#enqueue(request, options, generation));
1866
- this.#enqueueTail = enqueue.then(() => undefined, () => undefined);
1867
- return enqueue;
1897
+ return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
1898
+ }
1899
+ /**
1900
+ * Serializes a product-owned replica projection with enqueue and command ACK
1901
+ * reconciliation. For read/derive/write cache updates, prefer
1902
+ * `runSerializedReplicaMutation` so the read is serialized as well.
1903
+ */
1904
+ async transactReplica(transaction) {
1905
+ await this.runSerializedReplicaMutation(async (repository) => {
1906
+ await repository.transactReplica(transaction);
1907
+ });
1908
+ }
1909
+ /**
1910
+ * Runs a product cache's replica read/derive/write sequence atomically with
1911
+ * enqueue and ACK projection. Use this for any repository reads that inform
1912
+ * a later transaction; `transactReplica` alone only serializes the write.
1913
+ */
1914
+ runSerializedReplicaMutation(operation) {
1915
+ const generation = this.#generation;
1916
+ return this.#serializeReplicaMutation(async () => {
1917
+ await this.initialize();
1918
+ if (!this.#isCurrent(generation))
1919
+ throw new Error('Offline session changed before serialized replica mutation.');
1920
+ const result = await operation(this.#repository);
1921
+ if (this.#isCurrent(generation))
1922
+ await this.#refreshState(generation);
1923
+ return result;
1924
+ });
1925
+ }
1926
+ #serializeReplicaMutation(operation) {
1927
+ const mutation = this.#replicaMutationTail.then(operation);
1928
+ this.#replicaMutationTail = mutation.then(() => undefined, () => undefined);
1929
+ return mutation;
1868
1930
  }
1869
1931
  async #enqueue(request, options, generation) {
1870
1932
  await this.initialize();
@@ -1904,6 +1966,7 @@ class OfflineSyncService {
1904
1966
  }
1905
1967
  const existing = await this.#getReplicaRowForSync(scope, entityType, aggregateLocalId);
1906
1968
  const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
1969
+ this.#assertServerIdHint(existing?.serverId ?? null, request.serverIdHint);
1907
1970
  const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
1908
1971
  const remoteIdentity = schema.identity.kind === 'serverId'
1909
1972
  ? initialServerId === null
@@ -1912,7 +1975,7 @@ class OfflineSyncService {
1912
1975
  : schema.identity.kind === 'naturalKey'
1913
1976
  ? { naturalKey: naturalKey }
1914
1977
  : null;
1915
- if (schema.identity.kind === 'naturalKey' && request.serverId != null) {
1978
+ if (schema.identity.kind === 'naturalKey' && (request.serverId != null || request.serverIdHint != null)) {
1916
1979
  throw new Error(`Offline replica source "${entityType}" does not define a serverId field.`);
1917
1980
  }
1918
1981
  if (schema.identity.kind === 'naturalKey') {
@@ -2056,10 +2119,9 @@ class OfflineSyncService {
2056
2119
  });
2057
2120
  }
2058
2121
  async #sendAggregate(commands, generation) {
2059
- for (let index = 0; index < commands.length; index++) {
2122
+ for (const command of commands) {
2060
2123
  if (!this.#isCurrent(generation))
2061
2124
  return;
2062
- const command = commands[index];
2063
2125
  if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
2064
2126
  break;
2065
2127
  if (!['pending', 'retry_wait'].includes(command.state))
@@ -2106,7 +2168,7 @@ class OfflineSyncService {
2106
2168
  }
2107
2169
  if (!this.#isCurrent(generation))
2108
2170
  return;
2109
- await this.#completeCommand(commands, index, sending, result, generation);
2171
+ await this.#completeCommand(commands, sending, result, generation);
2110
2172
  }
2111
2173
  }
2112
2174
  async #normalizeEnqueueRequest(scope, request) {
@@ -2121,12 +2183,36 @@ class OfflineSyncService {
2121
2183
  }
2122
2184
  return { payload, baseRevision };
2123
2185
  }
2124
- async #completeCommand(commands, index, command, result, generation) {
2186
+ async #completeCommand(commands, command, result, generation) {
2187
+ return this.#serializeReplicaMutation(() => this.#completeCommandLocked(commands, command, result, generation));
2188
+ }
2189
+ async #completeCommandLocked(commands, command, result, generation) {
2190
+ if (result.clearServerId === true && result.serverId !== undefined) {
2191
+ throw new Error('Offline command cannot return serverId and clearServerId together.');
2192
+ }
2193
+ if (result.clearServerId === true && result.serverRevision !== undefined) {
2194
+ throw new Error('Offline command cannot return serverRevision and clearServerId together.');
2195
+ }
2196
+ // An enqueue may have completed while transport was in flight. Re-read the
2197
+ // aggregate immediately before the atomic acknowledgement transaction so a
2198
+ // delete ACK cannot remove a row that has already been re-added locally.
2199
+ const latestCommands = (await this.#readKnownCommands()).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
2200
+ const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);
2201
+ if (latestIndex < 0)
2202
+ return;
2125
2203
  const revision = result.serverRevision;
2126
- const following = commands.slice(index + 1);
2127
- const rebased = revision === undefined ? following : following.map((item) => this.#executor.withServerRevision(item, revision));
2128
- for (let offset = 0; offset < rebased.length; offset++)
2129
- commands[index + 1 + offset] = rebased[offset];
2204
+ const following = latestCommands.slice(latestIndex + 1);
2205
+ const rebased = result.clearServerId === true
2206
+ ? following.map((item) => {
2207
+ if (!this.#executor.withoutServerRevision) {
2208
+ throw new Error('Offline command executor must implement withoutServerRevision to recreate a deleted serverId row.');
2209
+ }
2210
+ return this.#executor.withoutServerRevision(item);
2211
+ })
2212
+ : revision === undefined
2213
+ ? following
2214
+ : following.map((item) => this.#executor.withServerRevision(item, revision));
2215
+ latestCommands.splice(latestIndex + 1, rebased.length, ...rebased);
2130
2216
  const current = await this.#rowForCommand(command);
2131
2217
  if (!this.#isCurrent(generation))
2132
2218
  return;
@@ -2135,16 +2221,23 @@ class OfflineSyncService {
2135
2221
  }
2136
2222
  this.#assertServerRevision(result.serverRevision);
2137
2223
  const removesReplica = result.removeReplica === true || command.replicaMutation === 'delete';
2224
+ if (result.clearServerId === true && !removesReplica) {
2225
+ throw new Error('Offline command can clear serverId only for a confirmed replica removal.');
2226
+ }
2138
2227
  const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
2139
2228
  const schema = this.#entitySchema(current.sourceKey);
2140
2229
  this.#assertCommandResultIdentity(schema, current, result);
2141
- const serverId = this.#resolvedServerId(current.serverId, result.serverId);
2230
+ const serverId = result.clearServerId === true ? null : this.#resolvedServerId(current.serverId, result.serverId);
2142
2231
  const row = {
2143
2232
  ...current,
2144
- values: rebased.length > 0 ? rebased.at(-1).optimisticValue : confirmedValues,
2233
+ // The row may have received a local-only patch (for example, a UI
2234
+ // projection was integrated) while this command was in flight. Keep the
2235
+ // current durable optimistic state instead of restoring the stale
2236
+ // command snapshot when later commands remain queued.
2237
+ values: rebased.length > 0 ? current.values : confirmedValues,
2145
2238
  confirmedValues,
2146
2239
  serverId,
2147
- serverRevision: revision ?? current.serverRevision,
2240
+ serverRevision: result.clearServerId === true ? null : (revision ?? current.serverRevision),
2148
2241
  fetchedAt: Date.now(),
2149
2242
  syncState: rebased.length > 0 ? 'pending' : 'confirmed',
2150
2243
  visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
@@ -2153,10 +2246,22 @@ class OfflineSyncService {
2153
2246
  return;
2154
2247
  await this.#repository.transactReplica({
2155
2248
  putRows: removesReplica && rebased.length === 0 ? undefined : [row],
2249
+ releaseServerIds: result.clearServerId === true && current.serverId !== null && !(removesReplica && rebased.length === 0)
2250
+ ? [
2251
+ {
2252
+ userId: current.userId,
2253
+ scopeId: current.scopeId,
2254
+ sourceKey: current.sourceKey,
2255
+ localId: current.localId,
2256
+ serverId: current.serverId,
2257
+ },
2258
+ ]
2259
+ : undefined,
2156
2260
  removeRows: removesReplica && rebased.length === 0 ? [current] : undefined,
2157
2261
  putCommands: rebased,
2158
2262
  removeCommandIds: [command.commandId],
2159
2263
  });
2264
+ commands.splice(0, commands.length, ...latestCommands);
2160
2265
  }
2161
2266
  async #rowForCommand(command) {
2162
2267
  const scope = { userId: command.userId, scopeId: command.scopeId };
@@ -2263,7 +2368,20 @@ class OfflineSyncService {
2263
2368
  #initialServerId(current, incoming) {
2264
2369
  return incoming === null || incoming === undefined ? current : this.#resolvedServerId(current, incoming);
2265
2370
  }
2371
+ #assertServerIdHint(current, hint) {
2372
+ if (hint === null || hint === undefined)
2373
+ return;
2374
+ if (!Number.isSafeInteger(hint) || hint <= 0) {
2375
+ throw new Error(`Offline command returned invalid serverId hint ${String(hint)}.`);
2376
+ }
2377
+ if (current !== null && current !== hint) {
2378
+ throw new Error(`Offline replica serverId hint does not match current=${current}: incoming=${hint}.`);
2379
+ }
2380
+ }
2266
2381
  #assertCommandResultIdentity(schema, current, result) {
2382
+ if (result.clearServerId === true && schema.identity.kind !== 'serverId') {
2383
+ throw new Error(`Offline command cannot clear serverId for source "${schema.sourceKey}".`);
2384
+ }
2267
2385
  if (schema.identity.kind === 'naturalKey' && result.serverId !== undefined) {
2268
2386
  throw new Error(`Offline command returned serverId for naturalKey source "${schema.sourceKey}".`);
2269
2387
  }
@@ -2905,8 +3023,27 @@ class SqliteOfflineRepository {
2905
3023
  }
2906
3024
  async transactReplica(transaction) {
2907
3025
  await this.#transaction(async (databaseId) => {
2908
- for (const row of transaction.putRows ?? [])
2909
- await this.#putReplicaRow(databaseId, row);
3026
+ const releases = new Map();
3027
+ for (const release of transaction.releaseServerIds ?? []) {
3028
+ if (!Number.isSafeInteger(release.serverId) || release.serverId <= 0) {
3029
+ throw new Error(`Offline replica release has invalid serverId ${String(release.serverId)}.`);
3030
+ }
3031
+ const key = this.#replicaRowKey(release);
3032
+ if (releases.has(key))
3033
+ throw new Error(`Offline replica serverId release is duplicated for ${release.sourceKey}/${release.localId}.`);
3034
+ releases.set(key, release);
3035
+ }
3036
+ const consumedReleases = new Set();
3037
+ for (const row of transaction.putRows ?? []) {
3038
+ const key = this.#replicaRowKey(row);
3039
+ const release = releases.get(key);
3040
+ await this.#putReplicaRow(databaseId, row, release);
3041
+ if (release)
3042
+ consumedReleases.add(key);
3043
+ }
3044
+ if (consumedReleases.size !== releases.size) {
3045
+ throw new Error('Offline replica serverId release must match an existing row in putRows.');
3046
+ }
2910
3047
  for (const row of transaction.removeRows ?? [])
2911
3048
  await this.#removeReplicaRow(databaseId, row);
2912
3049
  for (const command of transaction.putCommands ?? [])
@@ -3094,7 +3231,7 @@ class SqliteOfflineRepository {
3094
3231
  command.lastErrorCode,
3095
3232
  ]);
3096
3233
  }
3097
- async #putReplicaRow(databaseId, row) {
3234
+ async #putReplicaRow(databaseId, row, release) {
3098
3235
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
3099
3236
  assertOfflineReplicaServerId(schema, row.serverId);
3100
3237
  const encoded = encodeOfflineReplicaValues(schema, row.values);
@@ -3102,8 +3239,11 @@ class SqliteOfflineRepository {
3102
3239
  encodeOfflineReplicaValues(schema, row.confirmedValues);
3103
3240
  assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
3104
3241
  const existing = await this.getReplicaRowIncludingPendingDelete(row, row.sourceKey, row.localId);
3242
+ if (!existing && release) {
3243
+ throw new Error(`Offline replica serverId release requires an existing row for ${row.sourceKey}/${row.localId}.`);
3244
+ }
3105
3245
  if (existing)
3106
- this.#assertReplicaIdentityAssignment(schema, existing, row);
3246
+ this.#assertReplicaIdentityAssignment(schema, existing, row, release);
3107
3247
  const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
3108
3248
  const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
3109
3249
  const values = [
@@ -3186,8 +3326,21 @@ class SqliteOfflineRepository {
3186
3326
  #schemaHasServerId(schema) {
3187
3327
  return schema.identity.kind === 'serverId';
3188
3328
  }
3189
- #assertReplicaIdentityAssignment(schema, existing, incoming) {
3329
+ #replicaRowKey(row) {
3330
+ const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
3331
+ return `${row.userId}:${schema.scope === 'user' ? 'user' : row.scopeId}:${row.sourceKey}:${row.localId}`;
3332
+ }
3333
+ #assertReplicaIdentityAssignment(schema, existing, incoming, release) {
3334
+ if (release && schema.identity.kind !== 'serverId') {
3335
+ throw new Error(`Offline replica serverId release is unsupported for source "${incoming.sourceKey}".`);
3336
+ }
3190
3337
  if (schema.identity.kind === 'serverId') {
3338
+ if (release) {
3339
+ if (existing.serverId !== release.serverId || incoming.serverId !== null) {
3340
+ throw new Error(`Offline replica serverId release must transition current=${existing.serverId} to incoming=null for ${incoming.sourceKey}/${incoming.localId}.`);
3341
+ }
3342
+ return;
3343
+ }
3191
3344
  if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
3192
3345
  throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
3193
3346
  }