@rdlabo/ionic-angular-kit 21.6.8 → 21.6.10

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.
@@ -1015,6 +1015,9 @@ class IonicOfflineRepository {
1015
1015
  async getReplicaRows(scope, sourceKey) {
1016
1016
  return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
1017
1017
  }
1018
+ async getReplicaRowsIncludingPendingDelete(scope, sourceKey) {
1019
+ return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey, true));
1020
+ }
1018
1021
  async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
1019
1022
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
1020
1023
  return null;
@@ -1061,14 +1064,14 @@ class IonicOfflineRepository {
1061
1064
  return null;
1062
1065
  return this.#rowForScope(row, schema, scope);
1063
1066
  }
1064
- async #readReplicaRows(scope, sourceKey) {
1067
+ async #readReplicaRows(scope, sourceKey, includePendingDelete = false) {
1065
1068
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
1066
1069
  const rows = await this.#readRowPartition(scope, sourceKey, schema);
1067
1070
  return Object.values(rows)
1068
1071
  .filter((row) => {
1069
1072
  if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
1070
1073
  return false;
1071
- if ((row.visibility ?? 'present') === 'pending_delete')
1074
+ if (!includePendingDelete && (row.visibility ?? 'present') === 'pending_delete')
1072
1075
  return false;
1073
1076
  return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
1074
1077
  })
@@ -1121,6 +1124,7 @@ class IonicOfflineRepository {
1121
1124
  getReplicaRow: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, false),
1122
1125
  getReplicaRowIncludingPendingDelete: (scope, sourceKey, identity) => this.#readReplicaRow(scope, sourceKey, identity, true),
1123
1126
  getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
1127
+ getReplicaRowsIncludingPendingDelete: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey, true),
1124
1128
  getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
1125
1129
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
1126
1130
  return null;
@@ -1242,7 +1246,10 @@ class IonicOfflineRepository {
1242
1246
  }
1243
1247
  async #migrate() {
1244
1248
  const metadata = await this.#storage.get(METADATA_KEY);
1245
- if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
1249
+ if (metadata?.schemaVersion === 1) {
1250
+ await this.#migrateCoreSchemaV1();
1251
+ }
1252
+ else if (metadata?.schemaVersion !== undefined && metadata.schemaVersion !== OFFLINE_SCHEMA_VERSION) {
1246
1253
  throw new Error(`Unsupported offline storage schema version ${metadata.schemaVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
1247
1254
  'A lossless core schema migration is required before this database can be opened.');
1248
1255
  }
@@ -1256,6 +1263,24 @@ class IonicOfflineRepository {
1256
1263
  if (interrupted)
1257
1264
  await this.#applyReplicaTransaction(interrupted, false);
1258
1265
  }
1266
+ async #migrateCoreSchemaV1() {
1267
+ const commands = await this.#readRecord(OUTBOX_KEY);
1268
+ const migratedCommands = Object.fromEntries(Object.entries(commands).map(([key, command]) => {
1269
+ const { optimisticValue, optimisticCompanions, payloadHash, ...current } = command;
1270
+ return [
1271
+ key,
1272
+ {
1273
+ ...current,
1274
+ ...(optimisticValue === undefined ? {} : { legacyOptimisticValue: structuredClone(optimisticValue) }),
1275
+ ...(optimisticCompanions === undefined ? {} : { legacyOptimisticCompanions: structuredClone(optimisticCompanions) }),
1276
+ ...(payloadHash === undefined ? {} : { legacyPayloadHash: payloadHash }),
1277
+ },
1278
+ ];
1279
+ }));
1280
+ const metadata = await this.#metadata();
1281
+ await this.#storage.set(OUTBOX_KEY, migratedCommands);
1282
+ await this.#storage.set(METADATA_KEY, { ...metadata, schemaVersion: OFFLINE_SCHEMA_VERSION });
1283
+ }
1259
1284
  async #initializeReplicaSchema(storedVersion, storedHash) {
1260
1285
  const bundle = this.#options.replicaSchema;
1261
1286
  const targetVersion = bundle.version;
@@ -2034,176 +2059,240 @@ class OfflineReplicaPullService {
2034
2059
  requestCursor = page.nextCursor;
2035
2060
  continue;
2036
2061
  }
2037
- const applied = await this.#replicaMutations.run(async (repository) => {
2038
- const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';
2039
- if (currentCursor !== persistedCursor)
2040
- return currentCursor;
2041
- const scopeCommands = await repository.getCommands(scope);
2042
- const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;
2043
- const changes = this.#collapseChanges(page.changes);
2044
- const projection = await this.#projector?.project({
2045
- scope,
2046
- changes,
2047
- });
2048
- this.#assertProjection(scope, projection);
2049
- const putRows = [];
2050
- const removeRows = [];
2051
- const putCommands = new Map();
2052
- const removeCommandIds = new Set();
2053
- const rematerializeAfter = [];
2054
- if (rebaselinePending || page.rebaselineRequired) {
2055
- removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));
2056
- }
2057
- for (const change of changes) {
2058
- const schema = this.#entitySchema(change.sourceKey);
2059
- const commands = schema.scope === 'user' ? userCommands : scopeCommands;
2060
- const acknowledged = (change.acknowledgedCommandIds ?? [])
2061
- .map((commandId) => {
2062
- const command = commands.find((candidate) => candidate.commandId === commandId);
2063
- if (!command)
2064
- return null;
2065
- if (command.sourceKey !== change.sourceKey) {
2066
- throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
2067
- }
2068
- const requested = reconciliationTargetsById.get(commandId);
2069
- if (command.state === 'awaiting_pull') {
2070
- if (!requested) {
2071
- throw new Error(`Acknowledged command "${commandId}" was not requested for reconciliation on this pull page.`);
2072
- }
2073
- const schema = this.#entitySchema(change.sourceKey);
2074
- if (canonicalOfflineRemoteIdentity(schema, requested.identity) !==
2075
- canonicalOfflineRemoteIdentity(schema, this.#identity(change))) {
2076
- throw new Error(`Acknowledged command "${commandId}" does not match the requested remote identity.`);
2077
- }
2078
- }
2079
- return command;
2080
- })
2081
- .filter((command) => command !== null);
2082
- const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));
2083
- if (acknowledgedIdentities.size > 1) {
2084
- throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple replica identities.`);
2085
- }
2086
- const acknowledgedCommand = acknowledged[0];
2087
- const acknowledgedScope = acknowledgedCommand
2088
- ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
2089
- : scope;
2090
- const acknowledgedRow = acknowledgedCommand
2091
- ? await (this.#repository.getReplicaRowIncludingPendingDelete?.(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity) ?? this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.identity))
2092
- : null;
2093
- if (acknowledgedCommand && !acknowledgedRow) {
2094
- throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
2062
+ const applied = await this.#applyAuthoritativeChanges(scope, page.changes, {
2063
+ expectedCursor: persistedCursor,
2064
+ nextCursor: page.nextCursor,
2065
+ rebaseline: rebaselinePending || page.rebaselineRequired === true,
2066
+ reconciliationTargetsById,
2067
+ });
2068
+ if (applied !== page.nextCursor) {
2069
+ persistedCursor = applied;
2070
+ requestCursor = applied;
2071
+ rebaselinePending = false;
2072
+ continue;
2073
+ }
2074
+ persistedCursor = page.nextCursor;
2075
+ requestCursor = page.nextCursor;
2076
+ rebaselinePending = false;
2077
+ if (!page.hasMore)
2078
+ return;
2079
+ }
2080
+ }
2081
+ /**
2082
+ * Applies an already-fetched authoritative server batch through the same
2083
+ * acknowledgement, conflict, and aggregate-rematerialization boundary as pull.
2084
+ */
2085
+ async applyChanges(scope, changes) {
2086
+ const reconciliationTargets = await this.#reconciliationTargets(scope);
2087
+ await this.#applyAuthoritativeChanges(scope, changes, {
2088
+ expectedCursor: null,
2089
+ nextCursor: null,
2090
+ rebaseline: false,
2091
+ reconciliationTargetsById: new Map(reconciliationTargets.map((target) => [target.commandId, target])),
2092
+ });
2093
+ }
2094
+ async #applyAuthoritativeChanges(scope, incomingChanges, options) {
2095
+ return this.#replicaMutations.run(async (repository) => {
2096
+ const currentCursor = (await repository.getReplicaCursor(scope))?.cursor ?? '';
2097
+ if (options.expectedCursor !== null && currentCursor !== options.expectedCursor)
2098
+ return currentCursor;
2099
+ const scopeCommands = await repository.getCommands(scope);
2100
+ const userCommands = repository.getCommandsForUser ? await repository.getCommandsForUser(scope.userId) : scopeCommands;
2101
+ const changes = this.#collapseChanges(typeof incomingChanges === 'function' ? await incomingChanges(repository) : incomingChanges);
2102
+ const existingRows = await this.#preloadRows(repository, scope, changes);
2103
+ const projection = await this.#projector?.project({
2104
+ scope,
2105
+ changes,
2106
+ });
2107
+ this.#assertProjection(scope, projection);
2108
+ const putRows = [];
2109
+ const removeRows = [];
2110
+ const putCommands = new Map();
2111
+ const removeCommandIds = new Set();
2112
+ const rematerializeAfter = [];
2113
+ if (options.rebaseline) {
2114
+ removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));
2115
+ }
2116
+ for (const change of changes) {
2117
+ const schema = this.#entitySchema(change.sourceKey);
2118
+ const commands = schema.scope === 'user' ? userCommands : scopeCommands;
2119
+ const acknowledged = (change.acknowledgedCommandIds ?? [])
2120
+ .map((commandId) => {
2121
+ const command = commands.find((candidate) => candidate.commandId === commandId);
2122
+ if (!command)
2123
+ return null;
2124
+ if (command.sourceKey !== change.sourceKey) {
2125
+ throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
2095
2126
  }
2096
- const identity = this.#identity(change);
2097
- const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
2098
- if (acknowledgedRow &&
2099
- serverRow &&
2100
- !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))) {
2101
- if (identity.remoteId !== undefined) {
2102
- throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);
2127
+ const requested = options.reconciliationTargetsById.get(commandId);
2128
+ if (command.state === 'awaiting_pull') {
2129
+ if (!requested) {
2130
+ throw new Error(`Acknowledged command "${commandId}" was not requested for reconciliation on this pull page.`);
2131
+ }
2132
+ const schema = this.#entitySchema(change.sourceKey);
2133
+ if (canonicalOfflineRemoteIdentity(schema, requested.identity) !==
2134
+ canonicalOfflineRemoteIdentity(schema, this.#identity(change))) {
2135
+ throw new Error(`Acknowledged command "${commandId}" does not match the requested remote identity.`);
2103
2136
  }
2104
- throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
2105
2137
  }
2106
- const existing = acknowledgedRow ?? serverRow;
2107
- const related = existing
2108
- ? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
2109
- : [];
2110
- const hasPending = related.length > 0;
2111
- if (acknowledgedCommand) {
2112
- this.#assertIdentityAssignment(schema, existing, identity);
2113
- this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);
2114
- continue;
2138
+ return command;
2139
+ })
2140
+ .filter((command) => command !== null);
2141
+ const acknowledgedIdentities = new Set(acknowledged.map((command) => canonicalOfflineCommandIdentity(command.identity)));
2142
+ if (acknowledgedIdentities.size > 1) {
2143
+ throw new Error(`Acknowledged commands for "${change.sourceKey}" target multiple replica identities.`);
2144
+ }
2145
+ const acknowledgedCommand = acknowledged[0];
2146
+ const acknowledgedScope = acknowledgedCommand
2147
+ ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
2148
+ : scope;
2149
+ const acknowledgedRow = acknowledgedCommand
2150
+ ? (existingRows.byCommand.get(this.#commandRowKey(change.sourceKey, acknowledgedScope, acknowledgedCommand.identity)) ?? null)
2151
+ : null;
2152
+ if (acknowledgedCommand && !acknowledgedRow) {
2153
+ throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
2154
+ }
2155
+ const identity = this.#identity(change);
2156
+ const serverRow = existingRows.byRemote.get(this.#remoteRowKey(change.sourceKey, scope, identity)) ?? null;
2157
+ if (acknowledgedRow &&
2158
+ serverRow &&
2159
+ !commandIdentityMatchesReplicaRow(schema, acknowledgedRow, commandIdentityFromReplicaIdentity(serverRow.identity))) {
2160
+ if (identity.remoteId !== undefined) {
2161
+ throw new Error(`Server id ${String(identity.remoteId)} is already mapped to another local replica row.`);
2115
2162
  }
2116
- if (change.deleted) {
2117
- if (!existing)
2118
- continue;
2119
- if (!hasPending) {
2120
- removeRows.push({ ...existing, identity: existing.identity });
2121
- continue;
2122
- }
2123
- putRows.push({
2124
- ...existing,
2125
- confirmedValues: null,
2126
- serverRevision: change.serverRevision,
2127
- syncState: 'conflict',
2128
- fetchedAt: Date.now(),
2129
- });
2130
- for (const command of related) {
2131
- putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
2132
- }
2133
- rematerializeAfter.push(related[0]);
2163
+ throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
2164
+ }
2165
+ const existing = acknowledgedRow ?? serverRow;
2166
+ const related = existing
2167
+ ? commands.filter((command) => command.sourceKey === change.sourceKey && commandIdentityMatchesReplicaRow(schema, existing, command.identity))
2168
+ : [];
2169
+ const hasPending = related.length > 0;
2170
+ if (acknowledgedCommand) {
2171
+ this.#assertIdentityAssignment(schema, existing, identity);
2172
+ this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);
2173
+ continue;
2174
+ }
2175
+ if (change.deleted) {
2176
+ if (!existing)
2134
2177
  continue;
2135
- }
2136
- const confirmedValues = this.#validatedValues(schema, change);
2137
- if (!existing) {
2138
- putRows.push({
2139
- ...scope,
2140
- sourceKey: change.sourceKey,
2141
- identity: schema.identity.kind === 'naturalKey'
2142
- ? offlineNaturalReplicaIdentity(schema, confirmedValues)
2143
- : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
2144
- values: confirmedValues,
2145
- confirmedValues,
2146
- serverRevision: change.serverRevision,
2147
- fetchedAt: Date.now(),
2148
- syncState: 'confirmed',
2149
- });
2178
+ if (!hasPending) {
2179
+ removeRows.push({ ...existing, identity: existing.identity });
2150
2180
  continue;
2151
2181
  }
2152
- const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));
2153
- const confirmedRow = {
2182
+ putRows.push({
2154
2183
  ...existing,
2155
- confirmedValues,
2184
+ confirmedValues: null,
2156
2185
  serverRevision: change.serverRevision,
2186
+ syncState: 'conflict',
2157
2187
  fetchedAt: Date.now(),
2158
- values: remaining.length > 0 ? existing.values : confirmedValues,
2159
- syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2160
- };
2161
- putRows.push(confirmedRow);
2162
- if (remaining.length > 0)
2163
- rematerializeAfter.push(remaining[0]);
2164
- for (const command of remaining) {
2165
- putCommands.set(command.commandId, offlineCommandWithBaseRevision(command, change.serverRevision));
2188
+ });
2189
+ for (const command of related) {
2190
+ putCommands.set(command.commandId, { ...command, state: 'conflict', retryAt: null, lastErrorCode: 'remote_deleted' });
2166
2191
  }
2192
+ rematerializeAfter.push(related[0]);
2193
+ continue;
2167
2194
  }
2168
- const confirmedAndProjected = this.#mergeRowMutations([
2169
- { putRows, removeRows },
2170
- { putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
2171
- ]);
2172
- const rematerialized = await this.#rematerializePendingAggregates(scope, userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
2173
- const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
2174
- const removedCommands = [...removeCommandIds]
2175
- .map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
2176
- scopeCommands.find((command) => command.commandId === commandId))
2177
- .filter((command) => command != null);
2178
- await repository.transactReplica({
2179
- putRows: finalRows.putRows,
2180
- removeRows: finalRows.removeRows,
2181
- putCommands: [...putCommands.values()],
2182
- removeCommandIds: [...removeCommandIds],
2183
- putCursors: [{ ...scope, cursor: page.nextCursor }],
2184
- });
2185
- await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));
2186
- return page.nextCursor;
2195
+ const confirmedValues = this.#validatedValues(schema, change);
2196
+ if (!existing) {
2197
+ putRows.push({
2198
+ ...scope,
2199
+ sourceKey: change.sourceKey,
2200
+ identity: schema.identity.kind === 'naturalKey'
2201
+ ? offlineNaturalReplicaIdentity(schema, confirmedValues)
2202
+ : offlineGeneratedReplicaIdentity(crypto.randomUUID(), identity.remoteId ?? null),
2203
+ values: confirmedValues,
2204
+ confirmedValues,
2205
+ serverRevision: change.serverRevision,
2206
+ fetchedAt: Date.now(),
2207
+ syncState: 'confirmed',
2208
+ });
2209
+ continue;
2210
+ }
2211
+ const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));
2212
+ const confirmedRow = {
2213
+ ...existing,
2214
+ confirmedValues,
2215
+ serverRevision: change.serverRevision,
2216
+ fetchedAt: Date.now(),
2217
+ values: remaining.length > 0 ? existing.values : confirmedValues,
2218
+ syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2219
+ };
2220
+ putRows.push(confirmedRow);
2221
+ if (remaining.length > 0)
2222
+ rematerializeAfter.push(remaining[0]);
2223
+ for (const command of remaining) {
2224
+ putCommands.set(command.commandId, offlineCommandWithBaseRevision(command, change.serverRevision));
2225
+ }
2226
+ }
2227
+ const confirmedAndProjected = this.#mergeRowMutations([
2228
+ { putRows, removeRows },
2229
+ { putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
2230
+ ]);
2231
+ const rematerialized = await this.#rematerializePendingAggregates(scope, userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
2232
+ const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
2233
+ const removedCommands = [...removeCommandIds]
2234
+ .map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
2235
+ scopeCommands.find((command) => command.commandId === commandId))
2236
+ .filter((command) => command != null);
2237
+ await repository.transactReplica({
2238
+ putRows: finalRows.putRows,
2239
+ removeRows: finalRows.removeRows,
2240
+ putCommands: [...putCommands.values()],
2241
+ removeCommandIds: [...removeCommandIds],
2242
+ ...(options.nextCursor === null ? {} : { putCursors: [{ ...scope, cursor: options.nextCursor }] }),
2187
2243
  });
2188
- if (applied !== page.nextCursor) {
2189
- persistedCursor = applied;
2190
- requestCursor = applied;
2191
- rebaselinePending = false;
2192
- continue;
2244
+ await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));
2245
+ return options.nextCursor ?? currentCursor;
2246
+ });
2247
+ }
2248
+ async #preloadRows(repository, scope, changes) {
2249
+ const sourceKeys = [...new Set(changes.map((change) => change.sourceKey))];
2250
+ const partitions = await Promise.all(sourceKeys.map(async (sourceKey) => ({
2251
+ sourceKey,
2252
+ rows: await (repository.getReplicaRowsIncludingPendingDelete?.(scope, sourceKey) ?? repository.getReplicaRows(scope, sourceKey)),
2253
+ })));
2254
+ const byCommand = new Map();
2255
+ const byRemote = new Map();
2256
+ for (const { sourceKey, rows } of partitions) {
2257
+ const schema = this.#entitySchema(sourceKey);
2258
+ for (const row of rows) {
2259
+ if (row.identity.kind !== 'local') {
2260
+ byCommand.set(this.#commandRowKey(sourceKey, row, commandIdentityFromReplicaIdentity(row.identity)), row);
2261
+ }
2262
+ if (row.identity.kind === 'generated' && row.identity.remoteId !== null) {
2263
+ byRemote.set(this.#remoteRowKey(sourceKey, row, { remoteId: row.identity.remoteId }), row);
2264
+ }
2265
+ else if (row.identity.kind === 'natural') {
2266
+ byRemote.set(this.#remoteRowKey(sourceKey, row, { naturalKey: row.identity.naturalKey }), row);
2267
+ }
2193
2268
  }
2194
- persistedCursor = page.nextCursor;
2195
- requestCursor = page.nextCursor;
2196
- rebaselinePending = false;
2197
- if (!page.hasMore)
2198
- return;
2199
2269
  }
2270
+ return { byCommand, byRemote };
2271
+ }
2272
+ #commandRowKey(sourceKey, scope, identity) {
2273
+ const partition = this.#entitySchema(sourceKey).scope === 'user' ? '' : scope.scopeId;
2274
+ return `${sourceKey}:${scope.userId}:${partition}:${canonicalOfflineCommandIdentity(identity)}`;
2275
+ }
2276
+ #remoteRowKey(sourceKey, scope, identity) {
2277
+ const schema = this.#entitySchema(sourceKey);
2278
+ const partition = schema.scope === 'user' ? '' : scope.scopeId;
2279
+ return `${sourceKey}:${scope.userId}:${partition}:${canonicalOfflineRemoteIdentity(schema, identity)}`;
2200
2280
  }
2201
2281
  async #reconciliationTargets(scope) {
2202
2282
  const commands = (await this.#repository.getCommands(scope)).filter((command) => command.state === 'awaiting_pull');
2283
+ const rowsByCommand = new Map();
2284
+ await Promise.all([...new Set(commands.map((command) => command.sourceKey))].map(async (sourceKey) => {
2285
+ const rows = await (this.#repository.getReplicaRowsIncludingPendingDelete?.(scope, sourceKey) ??
2286
+ this.#repository.getReplicaRows(scope, sourceKey));
2287
+ for (const row of rows) {
2288
+ if (row.identity.kind !== 'local') {
2289
+ rowsByCommand.set(this.#commandRowKey(sourceKey, row, commandIdentityFromReplicaIdentity(row.identity)), row);
2290
+ }
2291
+ }
2292
+ }));
2203
2293
  const targets = [];
2204
2294
  for (const command of commands) {
2205
- const row = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, command.sourceKey, command.identity)) ??
2206
- (await this.#repository.getReplicaRow(scope, command.sourceKey, command.identity));
2295
+ const row = rowsByCommand.get(this.#commandRowKey(command.sourceKey, command, command.identity));
2207
2296
  if (!row)
2208
2297
  throw new Error(`Awaiting-pull command "${command.commandId}" has no replica row.`);
2209
2298
  const identity = command.reconciliationIdentity ??
@@ -2582,6 +2671,9 @@ class OfflineNetworkService {
2582
2671
  constructor() {
2583
2672
  this.#osConnected = signal(null, ...(ngDevMode ? [{ debugName: "#osConnected" }] : /* istanbul ignore next */ []));
2584
2673
  this.#apiReachable = signal(null, ...(ngDevMode ? [{ debugName: "#apiReachable" }] : /* istanbul ignore next */ []));
2674
+ this.#appActive = signal(true, ...(ngDevMode ? [{ debugName: "#appActive" }] : /* istanbul ignore next */ []));
2675
+ this.#lifecycleRevision = signal(0, ...(ngDevMode ? [{ debugName: "#lifecycleRevision" }] : /* istanbul ignore next */ []));
2676
+ this.#networkRevision = 0;
2585
2677
  this.#listeners = [];
2586
2678
  this.#initialized = false;
2587
2679
  this.state = computed(() => {
@@ -2592,23 +2684,43 @@ class OfflineNetworkService {
2592
2684
  return 'unverified';
2593
2685
  }, ...(ngDevMode ? [{ debugName: "state" }] : /* istanbul ignore next */ []));
2594
2686
  this.connected = computed(() => this.state() !== 'offline', ...(ngDevMode ? [{ debugName: "connected" }] : /* istanbul ignore next */ []));
2687
+ /** Whether Capacitor currently permits foreground transport work. */
2688
+ this.appActive = this.#appActive.asReadonly();
2689
+ /** Changes on every foreground/background transition, even when connectivity is unchanged. */
2690
+ this.lifecycleRevision = this.#lifecycleRevision.asReadonly();
2595
2691
  }
2596
2692
  #osConnected;
2597
2693
  #apiReachable;
2694
+ #appActive;
2695
+ #lifecycleRevision;
2696
+ #networkRevision;
2598
2697
  #listeners;
2599
2698
  #initialized;
2600
2699
  async initialize() {
2601
2700
  if (this.#initialized)
2602
2701
  return;
2603
2702
  this.#initialized = true;
2604
- this.#osConnected.set((await Network.getStatus()).connected);
2605
- this.#listeners.push(await Network.addListener('networkStatusChange', ({ connected }) => {
2606
- this.#osConnected.set(connected);
2607
- this.#apiReachable.set(connected ? null : false);
2608
- }), await App.addListener('appStateChange', ({ isActive }) => {
2609
- if (isActive)
2610
- void this.#refreshOsStatus();
2611
- }));
2703
+ const [networkListener, appListener] = await Promise.all([
2704
+ this.addNetworkStatusListener(({ connected }) => {
2705
+ this.#networkRevision += 1;
2706
+ this.#osConnected.set(connected);
2707
+ this.#apiReachable.set(connected ? null : false);
2708
+ }),
2709
+ this.addAppStateListener(({ isActive }) => {
2710
+ this.#lifecycleRevision.update((revision) => revision + 1);
2711
+ this.#appActive.set(isActive);
2712
+ if (isActive)
2713
+ void this.#refreshOsStatus();
2714
+ }),
2715
+ ]);
2716
+ this.#listeners.push(networkListener, appListener);
2717
+ const networkRevision = this.#networkRevision;
2718
+ const lifecycleRevision = this.#lifecycleRevision();
2719
+ const [network, app] = await Promise.all([this.getNetworkStatus(), this.getAppState()]);
2720
+ if (this.#networkRevision === networkRevision)
2721
+ this.#osConnected.set(network.connected);
2722
+ if (this.#lifecycleRevision() === lifecycleRevision)
2723
+ this.#appActive.set(app.isActive);
2612
2724
  }
2613
2725
  markApiSuccess() {
2614
2726
  this.#apiReachable.set(true);
@@ -2616,8 +2728,27 @@ class OfflineNetworkService {
2616
2728
  markApiFailure() {
2617
2729
  this.#apiReachable.set(false);
2618
2730
  }
2731
+ /** Factory seam for Capacitor app-state discovery and deterministic tests. */
2732
+ getAppState() {
2733
+ return App.getState();
2734
+ }
2735
+ /** Factory seam for Capacitor app-state listeners and deterministic tests. */
2736
+ addAppStateListener(listener) {
2737
+ return App.addListener('appStateChange', listener);
2738
+ }
2739
+ /** Factory seam for Capacitor network discovery and deterministic tests. */
2740
+ getNetworkStatus() {
2741
+ return Network.getStatus();
2742
+ }
2743
+ /** Factory seam for Capacitor network listeners and deterministic tests. */
2744
+ addNetworkStatusListener(listener) {
2745
+ return Network.addListener('networkStatusChange', listener);
2746
+ }
2619
2747
  async #refreshOsStatus() {
2620
- this.#osConnected.set((await Network.getStatus()).connected);
2748
+ const revision = this.#networkRevision;
2749
+ const status = await this.getNetworkStatus();
2750
+ if (this.#networkRevision === revision)
2751
+ this.#osConnected.set(status.connected);
2621
2752
  }
2622
2753
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
2623
2754
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineNetworkService, providedIn: 'root' }); }
@@ -2752,6 +2883,8 @@ class OfflineSyncService {
2752
2883
  #pendingPullScopes;
2753
2884
  #activeUserId;
2754
2885
  #flushPromise;
2886
+ #flushLifecycleRevision;
2887
+ #resumeAfterFlush;
2755
2888
  #partialFlushInFlight;
2756
2889
  #chainedFullFlush;
2757
2890
  #flushTransitions;
@@ -2782,6 +2915,8 @@ class OfflineSyncService {
2782
2915
  this.#pendingPullScopes = new Map();
2783
2916
  this.#activeUserId = null;
2784
2917
  this.#flushPromise = null;
2918
+ this.#flushLifecycleRevision = 0;
2919
+ this.#resumeAfterFlush = false;
2785
2920
  this.#partialFlushInFlight = false;
2786
2921
  this.#chainedFullFlush = null;
2787
2922
  this.#flushTransitions = new Set();
@@ -2813,11 +2948,12 @@ class OfflineSyncService {
2813
2948
  }, ...(ngDevMode ? [{ debugName: "syncState" }] : /* istanbul ignore next */ []));
2814
2949
  effect(() => {
2815
2950
  const connected = this.#network.connected();
2951
+ const appActive = this.#appActive();
2816
2952
  // The network transition may be observed after an explicit flush has already
2817
2953
  // persisted a fatal pull attention. Do not let that stale transition restart
2818
2954
  // the intentionally stopped loop; auth/session refresh remains able to retry.
2819
2955
  const hasFatalPullAttention = untracked(() => this.#pullAttentions().length > 0);
2820
- if (this.#initialized && connected && !hasFatalPullAttention)
2956
+ if (this.#initialized && connected && appActive && !hasFatalPullAttention)
2821
2957
  this.#flushInBackground();
2822
2958
  });
2823
2959
  }
@@ -2825,7 +2961,7 @@ class OfflineSyncService {
2825
2961
  const generation = this.#generation;
2826
2962
  if (!(await this.#restoreCurrentGeneration(generation)))
2827
2963
  return;
2828
- if (options.flush !== false && this.#network.connected())
2964
+ if (options.flush !== false && this.#canSynchronize())
2829
2965
  this.#flushInBackground();
2830
2966
  }
2831
2967
  #ensureInitialized() {
@@ -2867,7 +3003,7 @@ class OfflineSyncService {
2867
3003
  await this.#discoverScopes();
2868
3004
  await this.#restoreInterruptedCommands();
2869
3005
  await this.#refreshState();
2870
- if (this.#network.connected())
3006
+ if (this.#canSynchronize())
2871
3007
  this.#flushInBackground();
2872
3008
  }
2873
3009
  /** Restores local outbox visibility without enabling pull or replay transport. */
@@ -3258,7 +3394,7 @@ class OfflineSyncService {
3258
3394
  removeCommandIds,
3259
3395
  });
3260
3396
  await this.#refreshState().catch((error) => this.#reportError(error));
3261
- if (options.flush !== false && this.#network.connected())
3397
+ if (options.flush !== false && this.#canSynchronize())
3262
3398
  this.#flushInBackground();
3263
3399
  }
3264
3400
  #normalizedLocalOnlyFootprint(scope, footprint) {
@@ -3349,7 +3485,7 @@ class OfflineSyncService {
3349
3485
  await this.#restoreInterruptedCommands();
3350
3486
  await this.#refreshState();
3351
3487
  await this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error));
3352
- if (options.flush !== false && this.#network.connected())
3488
+ if (options.flush !== false && this.#canSynchronize())
3353
3489
  this.#flushInBackground();
3354
3490
  }
3355
3491
  /** Clears a retry backoff/auth block selected explicitly by the user and sends the durable command now. */
@@ -3378,7 +3514,7 @@ class OfflineSyncService {
3378
3514
  });
3379
3515
  return true;
3380
3516
  });
3381
- if (retried && this.#network.connected())
3517
+ if (retried && this.#canSynchronize())
3382
3518
  await this.flush();
3383
3519
  }
3384
3520
  async discardAllPending() {
@@ -3414,8 +3550,12 @@ class OfflineSyncService {
3414
3550
  return this.#beginFlush(true);
3415
3551
  }
3416
3552
  #beginFlush(explicitFull) {
3553
+ const lifecycleRevision = this.#lifecycleRevision();
3417
3554
  const isPartial = !explicitFull && this.#foregroundScopePolicy !== null;
3418
3555
  if (this.#flushPromise) {
3556
+ if (lifecycleRevision !== this.#flushLifecycleRevision && this.#canSynchronize()) {
3557
+ this.#resumeAfterFlush = true;
3558
+ }
3419
3559
  if (explicitFull && this.#partialFlushInFlight) {
3420
3560
  if (!this.#chainedFullFlush) {
3421
3561
  const generation = this.#generation;
@@ -3444,7 +3584,13 @@ class OfflineSyncService {
3444
3584
  this.#flushPromise = null;
3445
3585
  this.#partialFlushInFlight = false;
3446
3586
  }
3587
+ const resumeAfterFlush = this.#resumeAfterFlush;
3588
+ this.#resumeAfterFlush = false;
3589
+ if (resumeAfterFlush && this.#canSynchronize()) {
3590
+ queueMicrotask(() => this.#flushInBackground());
3591
+ }
3447
3592
  });
3593
+ this.#flushLifecycleRevision = lifecycleRevision;
3448
3594
  this.#flushPromise = promise;
3449
3595
  this.#partialFlushInFlight = isPartial;
3450
3596
  this.#flushTransitions.add(promise);
@@ -3453,7 +3599,7 @@ class OfflineSyncService {
3453
3599
  async #runFlush(generation, explicitFull) {
3454
3600
  if (!this.#isCurrent(generation))
3455
3601
  return;
3456
- if (!this.#network.connected()) {
3602
+ if (!this.#canSynchronize()) {
3457
3603
  await this.#refreshState(generation);
3458
3604
  return;
3459
3605
  }
@@ -3467,8 +3613,9 @@ class OfflineSyncService {
3467
3613
  let fatalPullFailure = null;
3468
3614
  const pulledScopeKeys = new Set();
3469
3615
  for (const scope of pullScopes) {
3470
- if (!this.#isCurrent(generation) || !this.#network.connected())
3616
+ if (!this.#isCurrent(generation) || !this.#canSynchronize())
3471
3617
  return;
3618
+ const pullLifecycleRevision = this.#lifecycleRevision();
3472
3619
  const pullScope = async () => {
3473
3620
  await this.#pull.pull(scope);
3474
3621
  await this.#markScopeReconciled(scope, generation);
@@ -3476,6 +3623,8 @@ class OfflineSyncService {
3476
3623
  };
3477
3624
  const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3478
3625
  if (pull.status === 'rejected') {
3626
+ if (this.#isInterruptedTransportFailure(pull.error, pullLifecycleRevision))
3627
+ return;
3479
3628
  prePullFailures.push(pull.error);
3480
3629
  if (this.#isFatalPullFailure(pull.error)) {
3481
3630
  // Auth/upgrade-driven recovery only: stop remaining scopes immediately.
@@ -3490,7 +3639,7 @@ class OfflineSyncService {
3490
3639
  }
3491
3640
  const dirtyScopes = new Map();
3492
3641
  const sendWorkerFailures = [];
3493
- while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
3642
+ while (this.#canSynchronize() && this.#isCurrent(generation) && fatalPullFailure === null) {
3494
3643
  const known = await this.#readKnownCommands();
3495
3644
  const groups = this.#eligibleAggregateGroups(known).filter((group) => group.some((command) => (command.state === 'pending' || command.state === 'retry_wait') &&
3496
3645
  pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))));
@@ -3501,7 +3650,7 @@ class OfflineSyncService {
3501
3650
  const pendingBefore = known.filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
3502
3651
  let cursor = 0;
3503
3652
  const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {
3504
- while (cursor < groups.length) {
3653
+ while (cursor < groups.length && this.#canSynchronize()) {
3505
3654
  const group = groups[cursor++];
3506
3655
  if (group && this.#isCurrent(generation))
3507
3656
  await this.#sendAggregate(group, generation, dirtyScopes, pulledScopeKeys);
@@ -3528,8 +3677,9 @@ class OfflineSyncService {
3528
3677
  if (fatalPullFailure === null) {
3529
3678
  const postPullScopes = [...this.#pendingPullScopes.values()];
3530
3679
  for (const scope of postPullScopes) {
3531
- if (!this.#isCurrent(generation) || !this.#network.connected())
3680
+ if (!this.#isCurrent(generation) || !this.#canSynchronize())
3532
3681
  break;
3682
+ const pullLifecycleRevision = this.#lifecycleRevision();
3533
3683
  // A command response may contain only the aggregate's base row. Pull once per dirty scope so
3534
3684
  // sibling-table journal entries are visible before completed Outbox state reaches product UI.
3535
3685
  const pullScope = async () => {
@@ -3538,6 +3688,8 @@ class OfflineSyncService {
3538
3688
  };
3539
3689
  const pull = await pullScope().then(() => ({ status: 'fulfilled' }), (error) => ({ status: 'rejected', error }));
3540
3690
  if (pull.status === 'rejected') {
3691
+ if (this.#isInterruptedTransportFailure(pull.error, pullLifecycleRevision))
3692
+ return;
3541
3693
  if (this.#isFatalPullFailure(pull.error)) {
3542
3694
  fatalPullFailure = fatalPullFailure ?? pull.error;
3543
3695
  await this.#persistFatalPullAttentions(pull.error, scope, postPullScopes, generation);
@@ -3583,6 +3735,21 @@ class OfflineSyncService {
3583
3735
  return true;
3584
3736
  return error instanceof OfflineReplicaSchemaMismatchError;
3585
3737
  }
3738
+ #isInterruptedTransportFailure(error, lifecycleRevision) {
3739
+ if (this.#lifecycleRevision() === lifecycleRevision)
3740
+ return false;
3741
+ const status = this.#errorStatus(error);
3742
+ return status === 0 || status === 408;
3743
+ }
3744
+ #canSynchronize() {
3745
+ return this.#appActive() && this.#network.connected();
3746
+ }
3747
+ #appActive() {
3748
+ return this.#network.appActive?.() ?? true;
3749
+ }
3750
+ #lifecycleRevision() {
3751
+ return this.#network.lifecycleRevision?.() ?? 0;
3752
+ }
3586
3753
  #pullAttentionReason(error) {
3587
3754
  if (error instanceof OfflineReplicaSchemaMismatchError)
3588
3755
  return 'schema_upgrade_required';
@@ -4123,7 +4290,7 @@ class OfflineSyncService {
4123
4290
  return;
4124
4291
  this.#retryTimer = setTimeout(() => {
4125
4292
  this.#retryTimer = null;
4126
- if (this.#network.connected())
4293
+ if (this.#canSynchronize())
4127
4294
  this.#flushInBackground();
4128
4295
  }, Math.max(0, retryAt - Date.now()));
4129
4296
  }
@@ -4132,6 +4299,7 @@ class OfflineSyncService {
4132
4299
  this.#flushPromise = null;
4133
4300
  this.#partialFlushInFlight = false;
4134
4301
  this.#chainedFullFlush = null;
4302
+ this.#resumeAfterFlush = false;
4135
4303
  this.#scheduleRetry(null);
4136
4304
  }
4137
4305
  #isCurrent(generation) {
@@ -5150,27 +5318,106 @@ async function createRandomOfflineEncryptionKey() {
5150
5318
  return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');
5151
5319
  }
5152
5320
  const settledSqliteOperation = async () => undefined;
5153
- /** Create the standard encrypted `@capacitor-community/sqlite` driver. */
5321
+ const communitySqliteDrivers = new WeakMap();
5322
+ function sqliteErrorMessage(error) {
5323
+ if (error instanceof Error)
5324
+ return error.message;
5325
+ if (typeof error === 'object' && error !== null && 'message' in error && typeof error.message === 'string') {
5326
+ return error.message;
5327
+ }
5328
+ return String(error);
5329
+ }
5330
+ function normalizeCommunitySqliteDatabaseName(database) {
5331
+ return database.endsWith('.db') ? database.slice(0, -3) : database;
5332
+ }
5333
+ function isExistingCommunitySqliteConnectionError(error, database) {
5334
+ const databaseName = normalizeCommunitySqliteDatabaseName(database);
5335
+ return sqliteErrorMessage(error).includes(`Connection ${databaseName} already exists`);
5336
+ }
5337
+ function settleCommunitySqliteCreation(creation) {
5338
+ return creation.then((database) => ({ ok: true, database }), (error) => ({ ok: false, error }));
5339
+ }
5340
+ async function createReloadSafeCommunitySqliteDatabase(connection, databaseName) {
5341
+ const create = () => connection.createConnection(databaseName, COMMUNITY_SQLITE_ENCRYPTED, COMMUNITY_SQLITE_MODE, COMMUNITY_SQLITE_VERSION, COMMUNITY_SQLITE_READONLY);
5342
+ const creation = await settleCommunitySqliteCreation(create());
5343
+ if (creation.ok)
5344
+ return creation.database;
5345
+ if (!isExistingCommunitySqliteConnectionError(creation.error, databaseName) || !connection.closeConnection) {
5346
+ throw creation.error;
5347
+ }
5348
+ await connection.closeConnection(databaseName, COMMUNITY_SQLITE_READONLY);
5349
+ return create();
5350
+ }
5351
+ /**
5352
+ * Create the canonical encrypted `@capacitor-community/sqlite` driver for a connection owner.
5353
+ *
5354
+ * The supplied connection is the identity and exclusive owner of its native plugin connections. Repeated
5355
+ * calls with the same object return the same driver so normal concurrent access cannot be mistaken for a
5356
+ * WebView-reload orphan. Consumers must route database access through this driver and must not close or
5357
+ * replace the connection while the driver is active. A real WebView reload creates a new JavaScript owner,
5358
+ * allowing the driver to close the native connection orphaned by the previous owner and recreate it.
5359
+ */
5154
5360
  function createCommunitySqliteDriver(connection) {
5361
+ const currentDriver = communitySqliteDrivers.get(connection);
5362
+ if (currentDriver)
5363
+ return currentDriver;
5155
5364
  const databases = new Map();
5365
+ const openings = new Map();
5366
+ let secretInitialization = null;
5156
5367
  const database = (databaseId) => {
5157
- const value = databases.get(databaseId);
5368
+ const value = databases.get(normalizeCommunitySqliteDatabaseName(databaseId));
5158
5369
  if (!value)
5159
5370
  throw new Error(`Offline SQLite database "${databaseId}" is not open`);
5160
5371
  return value;
5161
5372
  };
5162
- return {
5163
- async open({ databaseName, createEncryptionKey }) {
5373
+ const ensureSecret = (createEncryptionKey) => {
5374
+ if (secretInitialization)
5375
+ return secretInitialization;
5376
+ const initialization = (async () => {
5164
5377
  const stored = await connection.isSecretStored();
5165
- if (!stored.result) {
5166
- const encryptionKey = await createEncryptionKey?.();
5167
- if (!encryptionKey)
5168
- throw new Error('Native offline storage requires a non-empty encryption key on first open');
5169
- await connection.setEncryptionSecret(encryptionKey);
5170
- }
5171
- const value = await connection.createConnection(databaseName, COMMUNITY_SQLITE_ENCRYPTED, COMMUNITY_SQLITE_MODE, COMMUNITY_SQLITE_VERSION, COMMUNITY_SQLITE_READONLY);
5378
+ if (stored.result)
5379
+ return;
5380
+ const encryptionKey = await createEncryptionKey?.();
5381
+ if (!encryptionKey)
5382
+ throw new Error('Native offline storage requires a non-empty encryption key on first open');
5383
+ await connection.setEncryptionSecret(encryptionKey);
5384
+ })();
5385
+ secretInitialization = initialization;
5386
+ return initialization.then(undefined, (error) => {
5387
+ if (secretInitialization === initialization)
5388
+ secretInitialization = null;
5389
+ throw error;
5390
+ });
5391
+ };
5392
+ const openDatabase = async (databaseName, createEncryptionKey) => {
5393
+ const databaseKey = normalizeCommunitySqliteDatabaseName(databaseName);
5394
+ const opened = databases.get(databaseKey);
5395
+ if (opened)
5396
+ return opened;
5397
+ const currentOpening = openings.get(databaseKey);
5398
+ if (currentOpening)
5399
+ return currentOpening;
5400
+ const opening = (async () => {
5401
+ await ensureSecret(createEncryptionKey);
5402
+ const value = await createReloadSafeCommunitySqliteDatabase(connection, databaseName);
5172
5403
  await value.open();
5173
- databases.set(databaseName, value);
5404
+ databases.set(databaseKey, value);
5405
+ return value;
5406
+ })();
5407
+ openings.set(databaseKey, opening);
5408
+ return opening.then((value) => {
5409
+ if (openings.get(databaseKey) === opening)
5410
+ openings.delete(databaseKey);
5411
+ return value;
5412
+ }, (error) => {
5413
+ if (openings.get(databaseKey) === opening)
5414
+ openings.delete(databaseKey);
5415
+ throw error;
5416
+ });
5417
+ };
5418
+ const driver = {
5419
+ async open({ databaseName, createEncryptionKey }) {
5420
+ await openDatabase(databaseName, createEncryptionKey);
5174
5421
  return { databaseId: databaseName };
5175
5422
  },
5176
5423
  async execute({ databaseId, statement, values = [] }) {
@@ -5190,6 +5437,8 @@ function createCommunitySqliteDriver(connection) {
5190
5437
  await database(databaseId).rollbackTransaction();
5191
5438
  },
5192
5439
  };
5440
+ communitySqliteDrivers.set(connection, driver);
5441
+ return driver;
5193
5442
  }
5194
5443
  const SCHEMA = [
5195
5444
  `CREATE TABLE IF NOT EXISTS offline_metadata (
@@ -5210,6 +5459,9 @@ const SCHEMA = [
5210
5459
  identity_json TEXT NOT NULL,
5211
5460
  operation TEXT NOT NULL,
5212
5461
  payload_json TEXT NOT NULL,
5462
+ optimistic_value_json TEXT NOT NULL DEFAULT 'null',
5463
+ optimistic_companions_json TEXT,
5464
+ legacy_optimistic_value_json TEXT,
5213
5465
  local_only_footprint_json TEXT,
5214
5466
  replica_mutation TEXT NOT NULL DEFAULT 'upsert',
5215
5467
  payload_hash TEXT NOT NULL,
@@ -5297,6 +5549,9 @@ class SqliteOfflineRepository {
5297
5549
  async getReplicaRows(scope, sourceKey) {
5298
5550
  return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey));
5299
5551
  }
5552
+ async getReplicaRowsIncludingPendingDelete(scope, sourceKey) {
5553
+ return this.#withCommittedRead(() => this.#readReplicaRows(scope, sourceKey, true));
5554
+ }
5300
5555
  async getReplicaRowByRemoteId(scope, sourceKey, remoteId) {
5301
5556
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
5302
5557
  return null;
@@ -5434,10 +5689,26 @@ class SqliteOfflineRepository {
5434
5689
  releases.set(key, release);
5435
5690
  }
5436
5691
  const consumedReleases = new Set();
5692
+ const existingRows = new Map();
5693
+ const partitions = new Map();
5694
+ for (const row of transaction.putRows ?? []) {
5695
+ const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
5696
+ const partitionScopeId = schema.scope === 'partition' ? row.scopeId : '';
5697
+ partitions.set(`${canonicalOfflinePrincipalId(row.userId)}:${partitionScopeId}:${row.sourceKey}`, {
5698
+ scope: row,
5699
+ sourceKey: row.sourceKey,
5700
+ });
5701
+ }
5702
+ await Promise.all([...partitions.values()].map(async ({ scope, sourceKey }) => {
5703
+ for (const row of await this.#readReplicaRows(scope, sourceKey, true)) {
5704
+ existingRows.set(this.#replicaRowKey(row), row);
5705
+ }
5706
+ }));
5437
5707
  for (const row of transaction.putRows ?? []) {
5438
5708
  const key = this.#replicaRowKey(row);
5439
5709
  const release = releases.get(key);
5440
- await this.#putReplicaRow(databaseId, row, release);
5710
+ await this.#putReplicaRow(databaseId, row, release, existingRows.get(key) ?? null);
5711
+ existingRows.set(key, row);
5441
5712
  if (release)
5442
5713
  consumedReleases.add(key);
5443
5714
  }
@@ -5493,13 +5764,35 @@ class SqliteOfflineRepository {
5493
5764
  }
5494
5765
  else {
5495
5766
  const storedVersion = this.#number(metadata[0]['schema_version']);
5496
- if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5767
+ if (storedVersion === 1) {
5768
+ await this.#migrateCoreSchemaV1(databaseId);
5769
+ }
5770
+ else if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5497
5771
  throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
5498
5772
  'A lossless core schema migration is required before this database can be opened.');
5499
5773
  }
5500
5774
  }
5501
5775
  await this.#initializeReplicaSchema(databaseId);
5502
5776
  }
5777
+ async #migrateCoreSchemaV1(databaseId) {
5778
+ const columns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
5779
+ const names = new Set(columns.map((row) => this.#string(row['name'])));
5780
+ await this.#nativeTransaction(databaseId, async () => {
5781
+ if (!names.has('legacy_optimistic_value_json')) {
5782
+ await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN legacy_optimistic_value_json TEXT');
5783
+ }
5784
+ if (!names.has('local_only_footprint_json')) {
5785
+ await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN local_only_footprint_json TEXT');
5786
+ }
5787
+ if (!names.has('reconciliation_identity_json')) {
5788
+ await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN reconciliation_identity_json TEXT');
5789
+ }
5790
+ if (names.has('optimistic_value_json')) {
5791
+ await this.#execute(databaseId, 'UPDATE offline_sync_commands SET legacy_optimistic_value_json = optimistic_value_json WHERE legacy_optimistic_value_json IS NULL');
5792
+ }
5793
+ await this.#execute(databaseId, 'UPDATE offline_metadata SET schema_version = ? WHERE id = 1', [OFFLINE_SCHEMA_VERSION]);
5794
+ });
5795
+ }
5503
5796
  async #initializeReplicaSchema(databaseId) {
5504
5797
  const bundle = this.#options.replicaSchema;
5505
5798
  const targetVersion = bundle.version;
@@ -5613,7 +5906,7 @@ class SqliteOfflineRepository {
5613
5906
  const row = rows[0];
5614
5907
  return row ? this.#parse(row['value_json']) : null;
5615
5908
  }
5616
- async #readReplicaRows(scope, sourceKey) {
5909
+ async #readReplicaRows(scope, sourceKey, includePendingDelete = false) {
5617
5910
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
5618
5911
  const predicates = ['_offline_user_id = ?'];
5619
5912
  const values = [canonicalOfflinePrincipalId(scope.userId)];
@@ -5626,7 +5919,7 @@ class SqliteOfflineRepository {
5626
5919
  : 'local_id ASC';
5627
5920
  const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY ${orderBy}`, values);
5628
5921
  return rows
5629
- .filter((row) => (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
5922
+ .filter((row) => includePendingDelete || (row['_offline_visibility'] ?? 'present') !== 'pending_delete')
5630
5923
  .map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row));
5631
5924
  }
5632
5925
  async #readReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
@@ -5702,6 +5995,7 @@ class SqliteOfflineRepository {
5702
5995
  getReplicaRow: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, false)),
5703
5996
  getReplicaRowIncludingPendingDelete: async (scope, sourceKey, identity) => (await this.#queryReplicaRow(scope, sourceKey, identity, true)),
5704
5997
  getReplicaRows: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey),
5998
+ getReplicaRowsIncludingPendingDelete: (scope, sourceKey) => this.#readReplicaRows(scope, sourceKey, true),
5705
5999
  getReplicaRowByRemoteId: async (scope, sourceKey, remoteId) => {
5706
6000
  if (this.#resolveReplicaEntitySchema(sourceKey).identity.kind !== 'generated')
5707
6001
  return null;
@@ -5841,6 +6135,15 @@ class SqliteOfflineRepository {
5841
6135
  identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),
5842
6136
  operation: this.#string(row['operation']),
5843
6137
  payload: this.#parse(row['payload_json']),
6138
+ ...(row['legacy_optimistic_value_json'] === null || row['legacy_optimistic_value_json'] === undefined
6139
+ ? {}
6140
+ : { legacyOptimisticValue: this.#parse(row['legacy_optimistic_value_json']) }),
6141
+ ...(row['optimistic_companions_json'] === null || row['optimistic_companions_json'] === undefined
6142
+ ? {}
6143
+ : { legacyOptimisticCompanions: this.#parse(row['optimistic_companions_json']) }),
6144
+ ...(row['payload_hash'] === null || row['payload_hash'] === undefined || row['payload_hash'] === ''
6145
+ ? {}
6146
+ : { legacyPayloadHash: this.#string(row['payload_hash']) }),
5844
6147
  ...(row['local_only_footprint_json'] === null || row['local_only_footprint_json'] === undefined
5845
6148
  ? {}
5846
6149
  : { localOnlyFootprint: this.#parse(row['local_only_footprint_json']) }),
@@ -5860,13 +6163,16 @@ class SqliteOfflineRepository {
5860
6163
  #putCommand(databaseId, command) {
5861
6164
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands
5862
6165
  (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json,
5863
- local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
6166
+ optimistic_value_json, optimistic_companions_json, legacy_optimistic_value_json, local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
5864
6167
  server_commit_unknown, reconciliation_identity_json)
5865
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
6168
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5866
6169
  ON CONFLICT(command_id) DO UPDATE SET
5867
6170
  user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
5868
6171
  source_key = excluded.source_key,
5869
6172
  identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
6173
+ optimistic_value_json = excluded.optimistic_value_json,
6174
+ optimistic_companions_json = excluded.optimistic_companions_json,
6175
+ legacy_optimistic_value_json = excluded.legacy_optimistic_value_json,
5870
6176
  local_only_footprint_json = excluded.local_only_footprint_json,
5871
6177
  replica_mutation = excluded.replica_mutation,
5872
6178
  payload_hash = excluded.payload_hash,
@@ -5882,9 +6188,12 @@ class SqliteOfflineRepository {
5882
6188
  serializeOfflineCommandIdentity(command.identity),
5883
6189
  command.operation,
5884
6190
  JSON.stringify(command.payload),
6191
+ JSON.stringify(command.legacyOptimisticValue ?? null),
6192
+ command.legacyOptimisticCompanions === undefined ? null : JSON.stringify(command.legacyOptimisticCompanions),
6193
+ command.legacyOptimisticValue === undefined ? null : JSON.stringify(command.legacyOptimisticValue),
5885
6194
  command.localOnlyFootprint === undefined ? null : JSON.stringify(command.localOnlyFootprint),
5886
6195
  command.replicaMutation ?? 'upsert',
5887
- '',
6196
+ command.legacyPayloadHash ?? '',
5888
6197
  this.#stringifyNullable(command.baseRevision),
5889
6198
  command.state,
5890
6199
  command.attempts,
@@ -5925,7 +6234,7 @@ class SqliteOfflineRepository {
5925
6234
  return null;
5926
6235
  return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, row);
5927
6236
  }
5928
- async #putReplicaRow(databaseId, row, release) {
6237
+ async #putReplicaRow(databaseId, row, release, existing) {
5929
6238
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
5930
6239
  if (row.identity.kind === 'generated') {
5931
6240
  assertOfflineReplicaGeneratedRemoteId(schema, row.identity.remoteId);
@@ -5944,7 +6253,6 @@ class SqliteOfflineRepository {
5944
6253
  if (row.confirmedValues !== null)
5945
6254
  encodeOfflineReplicaValues(schema, row.confirmedValues);
5946
6255
  assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
5947
- const existing = await this.#queryReplicaRow(row, row.sourceKey, replicaAddressFromIdentity(row.identity), true);
5948
6256
  if (!existing && release) {
5949
6257
  throw new Error(`Offline replica remoteId release requires an existing row for ${row.sourceKey}/${canonicalOfflineReplicaIdentity(row.identity)}.`);
5950
6258
  }