@rdlabo/ionic-angular-kit 21.5.37 → 21.5.39

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.
@@ -1,5 +1,5 @@
1
1
  import * as i0 from '@angular/core';
2
- import { InjectionToken, Injectable, inject, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
2
+ import { InjectionToken, inject, Injectable, signal, computed, ErrorHandler, effect, makeEnvironmentProviders, provideAppInitializer } from '@angular/core';
3
3
  import { KitStorageService } from '@rdlabo/ionic-angular-kit';
4
4
  import { toObservable } from '@angular/core/rxjs-interop';
5
5
  import { map, distinctUntilChanged } from 'rxjs/operators';
@@ -829,6 +829,36 @@ function isPlainObject$1(value) {
829
829
  return prototype === Object.prototype || prototype === null;
830
830
  }
831
831
 
832
+ /** Returns whether the projector rejected replay onto an authoritative pull revision. */
833
+ function isOfflineAggregateIntentConflict(result) {
834
+ return 'kind' in result && result.kind === 'conflict';
835
+ }
836
+ /** Required product adapter for aggregate rematerialization from remaining Outbox intents. */
837
+ const OFFLINE_AGGREGATE_INTENT_PROJECTOR = new InjectionToken('OFFLINE_AGGREGATE_INTENT_PROJECTOR');
838
+ /**
839
+ * Converts a validated aggregate projection into replica put/remove mutations.
840
+ *
841
+ * @param projection - Rematerialized aggregate returned by the product projector.
842
+ * @param baseRow - Current aggregate base row, used when the projection removes it.
843
+ */
844
+ function offlineAggregateIntentMutations(projection, baseRow) {
845
+ const putRows = [];
846
+ const removeRows = [];
847
+ if (projection.baseRow)
848
+ putRows.push(projection.baseRow);
849
+ else if (baseRow) {
850
+ removeRows.push({
851
+ userId: baseRow.userId,
852
+ scopeId: baseRow.scopeId,
853
+ sourceKey: baseRow.sourceKey,
854
+ identity: baseRow.identity,
855
+ });
856
+ }
857
+ putRows.push(...(projection.putLocalOnlyRows ?? []));
858
+ removeRows.push(...(projection.removeLocalOnlyRows ?? []));
859
+ return { putRows, removeRows };
860
+ }
861
+
832
862
  /**
833
863
  * Converts a backend DB identity (`serverId`) to the runtime identity
834
864
  * (`remoteId`) without allowing product pullers to each reimplement the rule.
@@ -855,6 +885,15 @@ const OFFLINE_REPLICA_PULLER = new InjectionToken('OFFLINE_REPLICA_PULLER');
855
885
  /** Optional product adapter for local-only replica projections. */
856
886
  const OFFLINE_REPLICA_PROJECTOR = new InjectionToken('OFFLINE_REPLICA_PROJECTOR');
857
887
 
888
+ const DEFAULT_OFFLINE_COMMAND_HOOKS = {
889
+ entityType: (command) => command.aggregateType,
890
+ };
891
+ /** DI token for optional product-specific synchronization hooks. */
892
+ const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
893
+ providedIn: 'root',
894
+ factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
895
+ });
896
+
858
897
  /** DI token for product-independent offline persistence settings. */
859
898
  const OFFLINE_KIT_OPTIONS = new InjectionToken('OFFLINE_KIT_OPTIONS');
860
899
 
@@ -877,31 +916,8 @@ function offlineCommandLookupIdentity(identity) {
877
916
  return { kind: 'natural', naturalKey: identity.naturalKey };
878
917
  }
879
918
 
880
- /**
881
- * Serializes only local replica read/derive/write critical sections. Network
882
- * transport must stay outside this coordinator so synchronization never holds
883
- * the local mutation lane while waiting on I/O.
884
- */
885
- class OfflineReplicaMutationCoordinator {
886
- #tail = Promise.resolve();
887
- run(operation) {
888
- const mutation = this.#tail.then(operation);
889
- this.#tail = mutation.then(() => undefined, () => undefined);
890
- return mutation;
891
- }
892
- async drain() {
893
- await this.#tail;
894
- }
895
- static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
896
- static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, providedIn: 'root' }); }
897
- }
898
- i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, decorators: [{
899
- type: Injectable,
900
- args: [{ providedIn: 'root' }]
901
- }] });
902
-
903
919
  /** Current durable storage schema used by both web and native repositories. */
904
- const OFFLINE_SCHEMA_VERSION = 1;
920
+ const OFFLINE_SCHEMA_VERSION = 2;
905
921
  /** Canonical physical key shared by every repository and replica transaction coordinator. */
906
922
  function canonicalOfflineReplicaRowKey(schema, row) {
907
923
  const partition = schema.scope === 'user' ? 'user' : String(row.scopeId);
@@ -1732,6 +1748,207 @@ function compareUtf8Binary(left, right) {
1732
1748
  return leftBytes.length < rightBytes.length ? -1 : leftBytes.length > rightBytes.length ? 1 : 0;
1733
1749
  }
1734
1750
 
1751
+ /**
1752
+ * Serializes only local replica read/derive/write critical sections. Network
1753
+ * transport must stay outside this coordinator so synchronization never holds
1754
+ * the local mutation lane while waiting on I/O.
1755
+ *
1756
+ * This coordinator is the sole caller and validator of aggregate rematerialization.
1757
+ * Invoke {@link projectAggregateIntent} only from inside {@link run}; this
1758
+ * method does not acquire the lane itself.
1759
+ */
1760
+ class OfflineReplicaMutationCoordinator {
1761
+ #projector = inject(OFFLINE_AGGREGATE_INTENT_PROJECTOR, { optional: true });
1762
+ #options = inject(OFFLINE_KIT_OPTIONS, { optional: true });
1763
+ #tail = Promise.resolve();
1764
+ /** Enqueues one local replica critical section behind any in-flight mutation. */
1765
+ run(operation) {
1766
+ const mutation = this.#tail.then(operation);
1767
+ this.#tail = mutation.then(() => undefined, () => undefined);
1768
+ return mutation;
1769
+ }
1770
+ /** Resolves after every currently queued replica mutation has settled. */
1771
+ async drain() {
1772
+ await this.#tail;
1773
+ }
1774
+ /**
1775
+ * Calls the product aggregate-intent projector and validates scope, schema,
1776
+ * identity, and footprints. Throws before returning when the projector is
1777
+ * missing or the projection is unsafe to write.
1778
+ *
1779
+ * @param input - Authoritative base row, current localOnly rows, and remaining commands.
1780
+ */
1781
+ projectAggregateIntent(input) {
1782
+ if (!this.#projector) {
1783
+ throw new Error('Offline aggregate intent projector is not configured.');
1784
+ }
1785
+ if (!this.#options) {
1786
+ throw new Error('Offline aggregate intent projector requires replica schema configuration.');
1787
+ }
1788
+ const projection = this.#projector.project(input);
1789
+ if (isOfflineAggregateIntentConflict(projection)) {
1790
+ if (input.trigger !== 'pull' || input.commands.length === 0 || projection.reason.length === 0) {
1791
+ throw new Error('Offline aggregate intent conflict is valid only for pending commands during pull.');
1792
+ }
1793
+ return projection;
1794
+ }
1795
+ this.#assertAggregateIntentProjection(input, projection);
1796
+ return projection;
1797
+ }
1798
+ #assertAggregateIntentProjection(input, projection) {
1799
+ const expected = this.#expectedAggregate(input);
1800
+ const footprint = this.#localOnlyFootprint(input);
1801
+ this.#assertBaseProjection(input, projection, expected);
1802
+ this.#assertLocalOnlyProjection(input, expected.scope, footprint, projection);
1803
+ }
1804
+ #expectedAggregate(input) {
1805
+ const command = input.commands[0] ?? null;
1806
+ const base = input.baseRow;
1807
+ const local = input.localOnlyRows[0] ?? null;
1808
+ const scope = base
1809
+ ? { userId: base.userId, scopeId: base.scopeId }
1810
+ : command
1811
+ ? { userId: command.userId, scopeId: command.scopeId }
1812
+ : local
1813
+ ? { userId: local.userId, scopeId: local.scopeId }
1814
+ : null;
1815
+ return {
1816
+ scope,
1817
+ sourceKey: base?.sourceKey ?? command?.sourceKey ?? null,
1818
+ commandIdentity: command?.identity ?? null,
1819
+ };
1820
+ }
1821
+ #assertBaseProjection(input, projection, expected) {
1822
+ const remaining = input.commands;
1823
+ const base = input.baseRow;
1824
+ if (remaining.length === 0) {
1825
+ if (base?.confirmedValues == null) {
1826
+ if (projection.baseRow !== null) {
1827
+ throw new Error('Offline aggregate intent projector must remove a base row whose confirmedValues are null.');
1828
+ }
1829
+ return;
1830
+ }
1831
+ this.#assertBaseRowIdentity(expected, projection.baseRow, base);
1832
+ if (!sameJson(projection.baseRow.values, base.confirmedValues)) {
1833
+ throw new Error('Offline aggregate intent projector must restore confirmed values when no commands remain.');
1834
+ }
1835
+ if (projection.baseRow.syncState !== 'confirmed' || (projection.baseRow.visibility ?? 'present') !== 'present') {
1836
+ throw new Error('Offline aggregate intent projector must restore a confirmed present base row when no commands remain.');
1837
+ }
1838
+ return;
1839
+ }
1840
+ if (!projection.baseRow) {
1841
+ throw new Error('Offline aggregate intent projector must return a base row while pending commands remain.');
1842
+ }
1843
+ this.#assertBaseRowIdentity(expected, projection.baseRow, base);
1844
+ const last = remaining.at(-1);
1845
+ if (projection.baseRow.syncState !== 'pending') {
1846
+ throw new Error('Offline aggregate intent projector must keep a pending base row while commands remain.');
1847
+ }
1848
+ const expectedVisibility = last.replicaMutation === 'delete' ? 'pending_delete' : 'present';
1849
+ if ((projection.baseRow.visibility ?? 'present') !== expectedVisibility) {
1850
+ throw new Error('Offline aggregate intent projector must match remaining replica visibility.');
1851
+ }
1852
+ }
1853
+ #assertBaseRowIdentity(expected, row, inputBase) {
1854
+ if (!row || !expected.scope || !expected.sourceKey) {
1855
+ throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
1856
+ }
1857
+ const schema = this.#entitySchema(expected.sourceKey);
1858
+ if (schema.identity.kind === 'localOnly') {
1859
+ throw new Error(`Offline aggregate intent projector cannot rematerialize localOnly source "${expected.sourceKey}".`);
1860
+ }
1861
+ if (row.userId !== expected.scope.userId || row.scopeId !== expected.scope.scopeId || row.sourceKey !== expected.sourceKey) {
1862
+ throw new Error('Offline aggregate intent projector base row must use the current scope and source.');
1863
+ }
1864
+ if (inputBase) {
1865
+ if (!sameJson(row.confirmedValues, inputBase.confirmedValues) || row.serverRevision !== inputBase.serverRevision) {
1866
+ throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');
1867
+ }
1868
+ if (canonicalOfflineReplicaIdentity(row.identity) !== canonicalOfflineReplicaIdentity(inputBase.identity)) {
1869
+ throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
1870
+ }
1871
+ return;
1872
+ }
1873
+ if (row.confirmedValues !== null) {
1874
+ throw new Error('Offline aggregate intent projector base row must keep confirmedValues.');
1875
+ }
1876
+ if (!expected.commandIdentity || !commandIdentityMatchesReplicaRow(schema, row, expected.commandIdentity)) {
1877
+ throw new Error('Offline aggregate intent projector base row must keep the aggregate identity.');
1878
+ }
1879
+ }
1880
+ #assertLocalOnlyProjection(input, scope, footprint, projection) {
1881
+ const currentByKey = new Map(input.localOnlyRows.map((row) => [canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row), row]));
1882
+ const putRows = projection.putLocalOnlyRows ?? [];
1883
+ const removeRows = projection.removeLocalOnlyRows ?? [];
1884
+ const seen = new Set();
1885
+ for (const row of putRows) {
1886
+ const key = this.#assertLocalOnlyMutation(scope, footprint, row);
1887
+ if (seen.has(key))
1888
+ throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);
1889
+ const current = currentByKey.get(key);
1890
+ if (!sameJson(row.confirmedValues, current?.confirmedValues ?? null)) {
1891
+ throw new Error('Offline aggregate intent projector localOnly rows must keep confirmedValues.');
1892
+ }
1893
+ seen.add(key);
1894
+ }
1895
+ for (const row of removeRows) {
1896
+ const key = this.#assertLocalOnlyMutation(scope, footprint, row);
1897
+ if (seen.has(key))
1898
+ throw new Error(`Offline aggregate intent projector contains duplicate localOnly row ${key}.`);
1899
+ seen.add(key);
1900
+ }
1901
+ if (seen.size !== footprint.size) {
1902
+ throw new Error('Offline aggregate intent projector must cover every localOnly footprint exactly once.');
1903
+ }
1904
+ }
1905
+ #assertLocalOnlyMutation(scope, footprint, row) {
1906
+ const schema = this.#entitySchema(row.sourceKey);
1907
+ if (schema.identity.kind !== 'localOnly') {
1908
+ throw new Error(`Offline aggregate intent projector may only mutate localOnly source "${row.sourceKey}".`);
1909
+ }
1910
+ if (!scope || row.userId !== scope.userId || row.scopeId !== scope.scopeId || row.identity.kind !== 'local') {
1911
+ throw new Error('Offline aggregate intent projector rows must use the current scope and local identity.');
1912
+ }
1913
+ const key = canonicalOfflineReplicaRowKey(schema, row);
1914
+ if (!footprint.has(key)) {
1915
+ throw new Error(`Offline aggregate intent projector changed undeclared localOnly row ${key}.`);
1916
+ }
1917
+ return key;
1918
+ }
1919
+ #localOnlyFootprint(input) {
1920
+ const keys = new Set();
1921
+ for (const row of input.localOnlyRows) {
1922
+ keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(row.sourceKey), row));
1923
+ }
1924
+ for (const command of input.commands) {
1925
+ for (const key of commandFootprintKeys(command)) {
1926
+ keys.add(canonicalOfflineReplicaRowKey(this.#entitySchema(key.sourceKey), key));
1927
+ }
1928
+ }
1929
+ return keys;
1930
+ }
1931
+ #entitySchema(sourceKey) {
1932
+ const schema = this.#options?.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
1933
+ if (!schema)
1934
+ throw new Error(`Unknown offline replica source key "${sourceKey}".`);
1935
+ return schema;
1936
+ }
1937
+ static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
1938
+ static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, providedIn: 'root' }); }
1939
+ }
1940
+ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaMutationCoordinator, decorators: [{
1941
+ type: Injectable,
1942
+ args: [{ providedIn: 'root' }]
1943
+ }] });
1944
+ /** Declared localOnly keys persisted on one Outbox command. */
1945
+ function commandFootprintKeys(command) {
1946
+ return command.localOnlyFootprint ?? [];
1947
+ }
1948
+ function sameJson(left, right) {
1949
+ return JSON.stringify(left) === JSON.stringify(right);
1950
+ }
1951
+
1735
1952
  /**
1736
1953
  * Pull handshake reported a replica schema version/hash that does not match the local Kit schema.
1737
1954
  *
@@ -1757,24 +1974,32 @@ class OfflineReplicaPullService {
1757
1974
  #puller = inject(OFFLINE_REPLICA_PULLER);
1758
1975
  #projector = inject(OFFLINE_REPLICA_PROJECTOR, { optional: true });
1759
1976
  #executor = inject(OFFLINE_COMMAND_EXECUTOR);
1977
+ #hooks = inject(OFFLINE_COMMAND_HOOKS);
1760
1978
  #replicaMutations = inject(OfflineReplicaMutationCoordinator);
1761
1979
  #schemaHash = null;
1762
1980
  async pull(scope) {
1763
1981
  if (this.#options.mode === 'readCacheOnly')
1764
1982
  return;
1765
- const schemaHash = await (this.#schemaHash ??= sha256OfflineReplicaSchema(this.#options.replicaSchema));
1983
+ const storageSchemaHash = await (this.#schemaHash ??= sha256OfflineReplicaSchema(this.#options.replicaSchema));
1984
+ const wireProtocol = this.#options.wireProtocol ?? {
1985
+ version: this.#options.replicaSchema.version,
1986
+ hash: storageSchemaHash,
1987
+ };
1766
1988
  let persistedCursor = (await this.#repository.getReplicaCursor(scope))?.cursor ?? '';
1767
1989
  let requestCursor = persistedCursor;
1768
1990
  let rebaselinePending = false;
1769
1991
  for (;;) {
1992
+ const reconciliationTargets = await this.#reconciliationTargets(scope);
1993
+ const reconciliationTargetsById = new Map(reconciliationTargets.map((target) => [target.commandId, target]));
1770
1994
  const page = await this.#puller.pull({
1771
1995
  scope,
1772
1996
  cursor: requestCursor,
1773
- schemaVersion: this.#options.replicaSchema.version,
1774
- schemaHash,
1997
+ schemaVersion: wireProtocol.version,
1998
+ schemaHash: wireProtocol.hash,
1999
+ reconciliationTargets,
1775
2000
  });
1776
2001
  this.#assertPullPage(page);
1777
- this.#assertHandshake(page.schemaVersion, page.schemaHash, schemaHash);
2002
+ this.#assertHandshake(page.schemaVersion, page.schemaHash, wireProtocol);
1778
2003
  if (page.hasMore && page.nextCursor === requestCursor) {
1779
2004
  throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.scopeId}.`);
1780
2005
  }
@@ -1805,10 +2030,9 @@ class OfflineReplicaPullService {
1805
2030
  this.#assertProjection(scope, projection);
1806
2031
  const putRows = [];
1807
2032
  const removeRows = [];
1808
- const rebasedPutRows = [];
1809
- const rebasedRemoveRows = [];
1810
2033
  const putCommands = new Map();
1811
2034
  const removeCommandIds = new Set();
2035
+ const rematerializeAfter = [];
1812
2036
  if (rebaselinePending || page.rebaselineRequired) {
1813
2037
  removeRows.push(...(await this.#confirmedRowsForRebaseline(scope, userCommands)));
1814
2038
  }
@@ -1823,6 +2047,17 @@ class OfflineReplicaPullService {
1823
2047
  if (command.sourceKey !== change.sourceKey) {
1824
2048
  throw new Error(`Acknowledged command "${commandId}" does not target "${change.sourceKey}".`);
1825
2049
  }
2050
+ const requested = reconciliationTargetsById.get(commandId);
2051
+ if (command.state === 'awaiting_pull') {
2052
+ if (!requested) {
2053
+ throw new Error(`Acknowledged command "${commandId}" was not requested for reconciliation on this pull page.`);
2054
+ }
2055
+ const schema = this.#entitySchema(change.sourceKey);
2056
+ if (canonicalOfflineRemoteIdentity(schema, requested.identity) !==
2057
+ canonicalOfflineRemoteIdentity(schema, this.#identity(change))) {
2058
+ throw new Error(`Acknowledged command "${commandId}" does not match the requested remote identity.`);
2059
+ }
2060
+ }
1826
2061
  return command;
1827
2062
  })
1828
2063
  .filter((command) => command !== null);
@@ -1857,7 +2092,7 @@ class OfflineReplicaPullService {
1857
2092
  const hasPending = related.length > 0;
1858
2093
  if (acknowledgedCommand) {
1859
2094
  this.#assertIdentityAssignment(schema, existing, identity);
1860
- this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds);
2095
+ this.#applyAcknowledgement(change, existing, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter);
1861
2096
  continue;
1862
2097
  }
1863
2098
  if (change.deleted) {
@@ -1895,50 +2130,32 @@ class OfflineReplicaPullService {
1895
2130
  });
1896
2131
  continue;
1897
2132
  }
1898
- const revisionChanged = related.some((command) => command.baseRevision !== change.serverRevision);
1899
- const rebaseEligible = related.every((command) => (command.state === 'pending' || command.state === 'retry_wait') && command.serverCommitUnknown !== true);
1900
- const rebase = revisionChanged && rebaseEligible
1901
- ? ((await this.#executor.rebasePendingCommands?.(related, confirmedValues, change.serverRevision, await this.#projectedCompanionRows(related, projection))) ?? null)
1902
- : null;
1903
- this.#assertRebasedSteps(related, rebase?.steps ?? null);
1904
- const conflicted = revisionChanged && rebase === null;
1905
- const rebasedCommands = rebase
1906
- ? related.map((command, index) => ({
1907
- ...command,
1908
- baseRevision: change.serverRevision,
1909
- optimisticValue: rebase.steps[index].optimisticValue,
1910
- ...(rebase.steps[index].optimisticCompanions === undefined
1911
- ? {}
1912
- : { optimisticCompanions: rebase.steps[index].optimisticCompanions }),
1913
- }))
1914
- : [];
1915
- for (const command of rebasedCommands)
1916
- putCommands.set(command.commandId, command);
1917
- this.#appendRebasedCompanionRows(rebasedCommands, rebasedPutRows, rebasedRemoveRows);
1918
- putRows.push({
2133
+ const remaining = related.filter((command) => !removeCommandIds.has(command.commandId));
2134
+ const confirmedRow = {
1919
2135
  ...existing,
1920
- values: rebasedCommands.at(-1)?.optimisticValue ?? (hasPending ? existing.values : confirmedValues),
1921
2136
  confirmedValues,
1922
2137
  serverRevision: change.serverRevision,
1923
2138
  fetchedAt: Date.now(),
1924
- syncState: conflicted ? 'conflict' : hasPending ? 'pending' : 'confirmed',
1925
- });
1926
- if (conflicted) {
1927
- for (const command of related) {
1928
- putCommands.set(command.commandId, {
1929
- ...command,
1930
- state: 'conflict',
1931
- retryAt: null,
1932
- lastErrorCode: 'remote_revision',
1933
- });
1934
- }
2139
+ values: remaining.length > 0 ? existing.values : confirmedValues,
2140
+ syncState: remaining.length > 0 ? 'pending' : 'confirmed',
2141
+ };
2142
+ putRows.push(confirmedRow);
2143
+ if (remaining.length > 0)
2144
+ rematerializeAfter.push(remaining[0]);
2145
+ for (const command of remaining) {
2146
+ putCommands.set(command.commandId, this.#executor.withServerRevision(command, change.serverRevision));
1935
2147
  }
1936
2148
  }
1937
- const finalRows = this.#mergeRowMutations([
2149
+ const confirmedAndProjected = this.#mergeRowMutations([
1938
2150
  { putRows, removeRows },
1939
2151
  { putRows: projection?.putRows ?? [], removeRows: projection?.removeRows ?? [] },
1940
- { putRows: rebasedPutRows, removeRows: rebasedRemoveRows },
1941
2152
  ]);
2153
+ const rematerialized = await this.#rematerializePendingAggregates(scope, userCommands, scopeCommands, confirmedAndProjected, putCommands, removeCommandIds, rematerializeAfter);
2154
+ const finalRows = this.#mergeRowMutations([confirmedAndProjected, rematerialized]);
2155
+ const removedCommands = [...removeCommandIds]
2156
+ .map((commandId) => userCommands.find((command) => command.commandId === commandId) ??
2157
+ scopeCommands.find((command) => command.commandId === commandId))
2158
+ .filter((command) => command != null);
1942
2159
  await this.#repository.transactReplica({
1943
2160
  putRows: finalRows.putRows,
1944
2161
  removeRows: finalRows.removeRows,
@@ -1946,6 +2163,7 @@ class OfflineReplicaPullService {
1946
2163
  removeCommandIds: [...removeCommandIds],
1947
2164
  putCursors: [{ ...scope, cursor: page.nextCursor }],
1948
2165
  });
2166
+ await Promise.all(removedCommands.map((command) => this.#hooks.onCommandRemoved?.(command).catch(() => undefined)));
1949
2167
  return page.nextCursor;
1950
2168
  });
1951
2169
  if (applied !== page.nextCursor) {
@@ -1961,8 +2179,36 @@ class OfflineReplicaPullService {
1961
2179
  return;
1962
2180
  }
1963
2181
  }
2182
+ async #reconciliationTargets(scope) {
2183
+ const commands = (await this.#repository.getCommands(scope)).filter((command) => command.state === 'awaiting_pull');
2184
+ const targets = [];
2185
+ for (const command of commands) {
2186
+ const row = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, command.sourceKey, command.identity)) ??
2187
+ (await this.#repository.getReplicaRow(scope, command.sourceKey, command.identity));
2188
+ if (!row)
2189
+ throw new Error(`Awaiting-pull command "${command.commandId}" has no replica row.`);
2190
+ const identity = command.reconciliationIdentity ??
2191
+ (row.identity.kind === 'generated'
2192
+ ? row.identity.remoteId === null
2193
+ ? null
2194
+ : { remoteId: row.identity.remoteId }
2195
+ : row.identity.kind === 'natural'
2196
+ ? { naturalKey: row.identity.naturalKey }
2197
+ : null);
2198
+ if (!identity)
2199
+ throw new Error(`Awaiting-pull command "${command.commandId}" has no remote identity.`);
2200
+ canonicalOfflineRemoteIdentity(this.#entitySchema(command.sourceKey), identity);
2201
+ targets.push({ commandId: command.commandId, operation: command.operation, sourceKey: command.sourceKey, identity });
2202
+ }
2203
+ return targets;
2204
+ }
1964
2205
  async #confirmedRowsForRebaseline(scope, commands) {
1965
- const preserved = new Set(commands.flatMap((command) => (command.optimisticCompanions ?? []).map((companion) => this.#rowKey(companion.key))));
2206
+ const preserved = new Set(commands.flatMap((command) => {
2207
+ const identity = command.identity.kind === 'generated'
2208
+ ? offlineGeneratedReplicaIdentity(command.identity.localId, null)
2209
+ : { kind: 'natural', naturalKey: command.identity.naturalKey };
2210
+ return [this.#rowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#rowKey(key))];
2211
+ }));
1966
2212
  const rows = (await Promise.all(this.#options.replicaSchema.entities.map((entity) => this.#repository.getReplicaRows(scope, entity.sourceKey)))).flat();
1967
2213
  return rows.filter((row) => row.syncState === 'confirmed' && !preserved.has(this.#rowKey(row)));
1968
2214
  }
@@ -2015,57 +2261,118 @@ class OfflineReplicaPullService {
2015
2261
  this.#assertPullChange(change, index);
2016
2262
  }
2017
2263
  }
2018
- #assertRebasedSteps(original, steps) {
2019
- if (steps === null)
2020
- return;
2021
- if (steps.length !== original.length) {
2022
- throw new Error('Rebased offline values must match the aggregate command count.');
2264
+ async #rematerializePendingAggregates(scope, userCommands, scopeCommands, currentRows, putCommands, removeCommandIds, seeds) {
2265
+ const remaining = [...userCommands, ...scopeCommands]
2266
+ .filter((command, index, all) => all.findIndex((candidate) => candidate.commandId === command.commandId) === index)
2267
+ .filter((command) => !removeCommandIds.has(command.commandId))
2268
+ .map((command) => putCommands.get(command.commandId) ?? command);
2269
+ const affected = new Map();
2270
+ for (const command of [...seeds, ...remaining]) {
2271
+ if (removeCommandIds.has(command.commandId) && !remaining.some((item) => this.#aggregateKey(item) === this.#aggregateKey(command))) {
2272
+ affected.set(this.#aggregateKey(command), command);
2273
+ continue;
2274
+ }
2275
+ if (!removeCommandIds.has(command.commandId) || seeds.some((seed) => seed.commandId === command.commandId)) {
2276
+ affected.set(this.#aggregateKey(command), command);
2277
+ }
2023
2278
  }
2024
- for (const [index, step] of steps.entries()) {
2025
- const originalKeys = (original[index]?.optimisticCompanions ?? []).map((item) => this.#rowKey(item.key)).sort();
2026
- const rebasedKeys = (step.optimisticCompanions ?? []).map((item) => this.#rowKey(item.key)).sort();
2027
- if (JSON.stringify(originalKeys) !== JSON.stringify(rebasedKeys)) {
2028
- throw new Error('Rebased offline companions must preserve each command footprint.');
2279
+ const putRows = [];
2280
+ const removeRows = [];
2281
+ const overlay = new Map(currentRows.putRows.map((row) => [this.#rowKey(row), row]));
2282
+ const removed = new Set(currentRows.removeRows.map((row) => this.#rowKey(row)));
2283
+ for (const [key, seed] of affected) {
2284
+ const remainingForAggregate = remaining.filter((command) => this.#aggregateKey(command) === key);
2285
+ const existingConflict = remainingForAggregate.find((command) => command.state === 'conflict');
2286
+ const footprintCommands = [...remainingForAggregate, seed];
2287
+ const baseRow = await this.#overlayBaseRow(seed, overlay, removed);
2288
+ const persistedLocalOnlyRows = await this.#persistedLocalOnlyRows(footprintCommands);
2289
+ const localOnlyRows = await this.#overlayLocalOnlyRows(footprintCommands, overlay, removed);
2290
+ const projection = existingConflict
2291
+ ? { kind: 'conflict', reason: existingConflict.lastErrorCode ?? 'remote_revision' }
2292
+ : this.#replicaMutations.projectAggregateIntent({
2293
+ baseRow,
2294
+ localOnlyRows,
2295
+ commands: remainingForAggregate,
2296
+ trigger: 'pull',
2297
+ incomingRevision: baseRow?.serverRevision ?? undefined,
2298
+ });
2299
+ if (isOfflineAggregateIntentConflict(projection)) {
2300
+ if (!baseRow)
2301
+ throw new Error('Offline aggregate conflict requires an authoritative base row.');
2302
+ putRows.push({ ...baseRow, values: baseRow.values, syncState: 'conflict' });
2303
+ for (const command of remainingForAggregate) {
2304
+ putCommands.set(command.commandId, {
2305
+ ...command,
2306
+ state: 'conflict',
2307
+ retryAt: null,
2308
+ lastErrorCode: projection.reason,
2309
+ });
2310
+ }
2311
+ const incomingByKey = new Map(localOnlyRows.map((row) => [this.#rowKey(row), row]));
2312
+ for (const previous of persistedLocalOnlyRows) {
2313
+ const incoming = incomingByKey.get(this.#rowKey(previous));
2314
+ putRows.push({
2315
+ ...(incoming ?? previous),
2316
+ values: previous.values,
2317
+ confirmedValues: incoming?.confirmedValues ?? null,
2318
+ syncState: 'conflict',
2319
+ visibility: previous.visibility,
2320
+ });
2321
+ }
2322
+ continue;
2029
2323
  }
2324
+ const mutations = offlineAggregateIntentMutations(projection, baseRow);
2325
+ putRows.push(...(mutations.putRows ?? []));
2326
+ removeRows.push(...(mutations.removeRows ?? []));
2030
2327
  }
2328
+ void scope;
2329
+ return { putRows, removeRows };
2031
2330
  }
2032
- #appendRebasedCompanionRows(commands, putRows, removeRows) {
2033
- const latest = new Map();
2331
+ async #overlayBaseRow(command, overlay, removed) {
2332
+ const schema = this.#entitySchema(command.sourceKey);
2333
+ const identity = command.identity.kind === 'generated'
2334
+ ? offlineGeneratedReplicaIdentity(command.identity.localId, null)
2335
+ : { kind: 'natural', naturalKey: command.identity.naturalKey };
2336
+ const canonical = this.#rowKey({ ...command, identity });
2337
+ if (removed.has(canonical))
2338
+ return null;
2339
+ const overlaid = [...overlay.values()].find((row) => row.sourceKey === command.sourceKey && commandIdentityMatchesReplicaRow(schema, row, command.identity));
2340
+ if (overlaid)
2341
+ return overlaid;
2342
+ const commandScope = { userId: command.userId, scopeId: command.scopeId };
2343
+ return (this.#repository.getReplicaRowIncludingPendingDelete?.(commandScope, command.sourceKey, command.identity) ??
2344
+ this.#repository.getReplicaRow(commandScope, command.sourceKey, command.identity));
2345
+ }
2346
+ async #overlayLocalOnlyRows(commands, overlay, removed) {
2347
+ const keys = new Map();
2034
2348
  for (const command of commands) {
2035
- for (const companion of command.optimisticCompanions ?? []) {
2036
- latest.set(this.#rowKey(companion.key), { key: companion.key, after: companion.after });
2037
- }
2349
+ for (const key of commandFootprintKeys(command))
2350
+ keys.set(this.#rowKey(key), key);
2038
2351
  }
2039
- for (const { key, after } of latest.values()) {
2040
- if (after)
2041
- putRows.push(after);
2042
- else
2043
- removeRows.push(key);
2352
+ const rows = [];
2353
+ for (const [canonical, key] of keys) {
2354
+ if (removed.has(canonical))
2355
+ continue;
2356
+ const overlaid = overlay.get(canonical);
2357
+ if (overlaid) {
2358
+ rows.push(overlaid);
2359
+ continue;
2360
+ }
2361
+ const rowScope = { userId: key.userId, scopeId: key.scopeId };
2362
+ const row = (await this.#repository.getReplicaRowIncludingPendingDelete?.(rowScope, key.sourceKey, key.identity)) ??
2363
+ (await this.#repository.getReplicaRow(rowScope, key.sourceKey, key.identity));
2364
+ if (row)
2365
+ rows.push(row);
2044
2366
  }
2367
+ return rows;
2045
2368
  }
2046
- async #currentCompanionRows(commands) {
2047
- const keys = new Map(commands.flatMap((command) => (command.optimisticCompanions ?? []).map((companion) => [this.#rowKey(companion.key), companion.key])));
2048
- const rows = await Promise.all([...keys.values()].map((key) => {
2049
- const companionScope = { userId: key.userId, scopeId: key.scopeId };
2050
- return (this.#repository.getReplicaRowIncludingPendingDelete?.(companionScope, key.sourceKey, key.identity) ??
2051
- this.#repository.getReplicaRow(companionScope, key.sourceKey, key.identity));
2052
- }));
2053
- return rows.filter((row) => row !== null);
2369
+ async #persistedLocalOnlyRows(commands) {
2370
+ return this.#overlayLocalOnlyRows(commands, new Map(), new Set());
2054
2371
  }
2055
- async #projectedCompanionRows(commands, projection) {
2056
- const footprint = new Set(commands.flatMap((command) => (command.optimisticCompanions ?? []).map((companion) => this.#rowKey(companion.key))));
2057
- const rows = new Map((await this.#currentCompanionRows(commands)).map((row) => [this.#rowKey(row), row]));
2058
- for (const row of projection?.removeRows ?? []) {
2059
- const key = this.#rowKey(row);
2060
- if (footprint.has(key))
2061
- rows.delete(key);
2062
- }
2063
- for (const row of projection?.putRows ?? []) {
2064
- const key = this.#rowKey(row);
2065
- if (footprint.has(key))
2066
- rows.set(key, row);
2067
- }
2068
- return [...rows.values()];
2372
+ #aggregateKey(command) {
2373
+ const schema = this.#entitySchema(command.sourceKey);
2374
+ const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
2375
+ return `${command.userId}:${partition}:${command.sourceKey}:${canonicalOfflineCommandIdentity(command.identity)}`;
2069
2376
  }
2070
2377
  #assertPullChange(change, index) {
2071
2378
  const label = `Offline replica pull page changes[${index}]`;
@@ -2112,9 +2419,9 @@ class OfflineReplicaPullService {
2112
2419
  }
2113
2420
  }
2114
2421
  }
2115
- #assertHandshake(version, hash, expectedHash) {
2116
- if (version !== this.#options.replicaSchema.version || hash !== expectedHash) {
2117
- throw new OfflineReplicaSchemaMismatchError(this.#options.replicaSchema.version, expectedHash, version, hash);
2422
+ #assertHandshake(version, hash, expected) {
2423
+ if (version !== expected.version || hash !== expected.hash) {
2424
+ throw new OfflineReplicaSchemaMismatchError(expected.version, expected.hash, version, hash);
2118
2425
  }
2119
2426
  }
2120
2427
  #entitySchema(sourceKey) {
@@ -2160,7 +2467,7 @@ class OfflineReplicaPullService {
2160
2467
  }
2161
2468
  return [...collapsed.values()];
2162
2469
  }
2163
- #applyAcknowledgement(change, row, related, putRows, removeRows, putCommands, removeCommandIds) {
2470
+ #applyAcknowledgement(change, row, related, putRows, removeRows, putCommands, removeCommandIds, rematerializeAfter) {
2164
2471
  const acknowledgedIds = new Set(change.acknowledgedCommandIds ?? []);
2165
2472
  const lastAcknowledgedIndex = related.reduce((last, command, index) => (acknowledgedIds.has(command.commandId) ? index : last), -1);
2166
2473
  if (lastAcknowledgedIndex < 0) {
@@ -2181,31 +2488,22 @@ class OfflineReplicaPullService {
2181
2488
  for (const command of related.slice(0, lastAcknowledgedIndex + 1)) {
2182
2489
  removeCommandIds.add(command.commandId);
2183
2490
  }
2491
+ rematerializeAfter.push(lastAcknowledgedCommand);
2184
2492
  if (change.deleted) {
2185
2493
  if (following.length > 0) {
2494
+ putRows.push({
2495
+ ...row,
2496
+ confirmedValues: null,
2497
+ serverRevision: change.serverRevision,
2498
+ syncState: acknowledgementSuperseded ? 'conflict' : 'pending',
2499
+ visibility: following.at(-1).replicaMutation === 'delete' ? 'pending_delete' : 'present',
2500
+ fetchedAt: Date.now(),
2501
+ });
2186
2502
  if (acknowledgementSuperseded) {
2187
- putRows.push({
2188
- ...row,
2189
- confirmedValues: null,
2190
- serverRevision: change.serverRevision,
2191
- syncState: 'conflict',
2192
- fetchedAt: Date.now(),
2193
- });
2194
2503
  for (const command of following) {
2195
2504
  putCommands.set(command.commandId, { ...command, state: 'conflict', lastErrorCode: 'remote_deleted' });
2196
2505
  }
2197
2506
  }
2198
- else {
2199
- putRows.push({
2200
- ...row,
2201
- values: following.at(-1).optimisticValue,
2202
- confirmedValues: null,
2203
- serverRevision: change.serverRevision,
2204
- syncState: 'pending',
2205
- visibility: following.at(-1).replicaMutation === 'delete' ? 'pending_delete' : 'present',
2206
- fetchedAt: Date.now(),
2207
- });
2208
- }
2209
2507
  }
2210
2508
  else {
2211
2509
  removeRows.push({ ...row, identity: row.identity });
@@ -2218,7 +2516,7 @@ class OfflineReplicaPullService {
2218
2516
  putRows.push({
2219
2517
  ...row,
2220
2518
  identity: row.identity.kind === 'generated' ? { ...row.identity, remoteId: change.remoteId ?? row.identity.remoteId } : row.identity,
2221
- values: following.length > 0 ? following.at(-1).optimisticValue : confirmedValues,
2519
+ values: following.length > 0 ? row.values : confirmedValues,
2222
2520
  confirmedValues,
2223
2521
  serverRevision: change.serverRevision,
2224
2522
  fetchedAt: Date.now(),
@@ -2261,15 +2559,6 @@ function isPlainObject(value) {
2261
2559
  return prototype === Object.prototype || prototype === null;
2262
2560
  }
2263
2561
 
2264
- const DEFAULT_OFFLINE_COMMAND_HOOKS = {
2265
- entityType: (command) => command.aggregateType,
2266
- };
2267
- /** DI token for optional product-specific synchronization hooks. */
2268
- const OFFLINE_COMMAND_HOOKS = new InjectionToken('OFFLINE_COMMAND_HOOKS', {
2269
- providedIn: 'root',
2270
- factory: () => DEFAULT_OFFLINE_COMMAND_HOOKS,
2271
- });
2272
-
2273
2562
  /** transport不能(status=0)だけをlocal replica fallback対象にし、HTTPエラーは隠さない。 */
2274
2563
  function isOfflineFallbackError(error) {
2275
2564
  return typeof error === 'object' && error !== null && error.status === 0;
@@ -2478,6 +2767,28 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2478
2767
  args: [{ providedIn: 'root' }]
2479
2768
  }] });
2480
2769
 
2770
+ /**
2771
+ * Local offline storage could not be opened or migrated without risking data loss.
2772
+ *
2773
+ * Prefer `instanceof` / {@link OfflineStorageUnavailableError.reason} over message text.
2774
+ * The original failure is preserved on {@link Error.cause}. Kit never deletes Outbox or
2775
+ * replica rows in response to this error; recovery is product-owned and explicit.
2776
+ */
2777
+ class OfflineStorageUnavailableError extends Error {
2778
+ /** Stable machine-readable discriminator for storage initialization failures. */
2779
+ static { this.code = 'OFFLINE_STORAGE_UNAVAILABLE'; }
2780
+ constructor(reason, message, options) {
2781
+ super(message, options);
2782
+ this.reason = reason;
2783
+ this.code = OfflineStorageUnavailableError.code;
2784
+ this.name = 'OfflineStorageUnavailableError';
2785
+ }
2786
+ }
2787
+ /** Narrows an unknown failure to {@link OfflineStorageUnavailableError}. */
2788
+ function isOfflineStorageUnavailableError(error) {
2789
+ return error instanceof OfflineStorageUnavailableError;
2790
+ }
2791
+
2481
2792
  /** Raised before persistence when an outbox payload is not losslessly JSON serializable. */
2482
2793
  class OfflinePayloadValidationError extends Error {
2483
2794
  constructor(message = 'Offline command payload must contain only JSON values') {
@@ -2676,8 +2987,8 @@ class OfflineSyncService {
2676
2987
  return this.#serializeReplicaMutation(() => this.#enqueue(request, options, generation));
2677
2988
  }
2678
2989
  /**
2679
- * Reads, derives, and commits the base optimistic row, product companion
2680
- * rows, and Outbox command as one serialized replica transaction.
2990
+ * Reads, derives, and commits one Outbox command, then rematerializes its
2991
+ * aggregate from confirmed replica values plus remaining FIFO intents.
2681
2992
  */
2682
2993
  enqueuePrepared(prepare, options = {}) {
2683
2994
  const generation = this.#generation;
@@ -2686,7 +2997,7 @@ class OfflineSyncService {
2686
2997
  if (!this.#isCurrent(generation))
2687
2998
  throw new Error('Offline session changed before prepared enqueue.');
2688
2999
  const prepared = await prepare(this.#repository);
2689
- return this.#enqueue(prepared.request, options, generation, prepared.replicaTransaction);
3000
+ return this.#enqueue(prepared.request, options, generation);
2690
3001
  });
2691
3002
  }
2692
3003
  /**
@@ -2729,7 +3040,7 @@ class OfflineSyncService {
2729
3040
  throw new Error('Offline replacement requires the command to be the only pending intent for its aggregate.');
2730
3041
  }
2731
3042
  const prepared = await prepare(this.#repository);
2732
- return this.#enqueue(prepared.request, options, generation, prepared.replicaTransaction, replaced);
3043
+ return this.#enqueue(prepared.request, options, generation, replaced);
2733
3044
  });
2734
3045
  }
2735
3046
  /**
@@ -2760,7 +3071,7 @@ class OfflineSyncService {
2760
3071
  const materializations = [];
2761
3072
  for (const [index, entry] of prepared.entries()) {
2762
3073
  this.#assertEnqueueScope(session, entry.request.scopeId);
2763
- materializations.push(await this.#materializeEnqueue(session.userId, entry.request, entry.replicaTransaction, replaced[index]));
3074
+ materializations.push(await this.#materializeEnqueue(session.userId, entry.request, replaced[index]));
2764
3075
  }
2765
3076
  const retained = knownCommands.filter((command) => !replaced.some((item) => item.commandId === command.commandId));
2766
3077
  this.#assertDistinctBatchFootprints(materializations, retained, true);
@@ -2800,10 +3111,10 @@ class OfflineSyncService {
2800
3111
  #serializeReplicaMutation(operation) {
2801
3112
  return this.#replicaMutations.run(operation);
2802
3113
  }
2803
- async #enqueue(request, options, generation, replicaTransaction, replaced) {
3114
+ async #enqueue(request, options, generation, replaced) {
2804
3115
  const session = await this.#beginEnqueueSession(generation);
2805
3116
  this.#assertEnqueueScope(session, request.scopeId);
2806
- const materialization = await this.#materializeEnqueue(session.userId, request, replicaTransaction, replaced);
3117
+ const materialization = await this.#materializeEnqueue(session.userId, request, replaced);
2807
3118
  const currentCommands = await this.#commandsForUser(session.userId);
2808
3119
  const retainedCommands = replaced ? currentCommands.filter((command) => command.commandId !== replaced.commandId) : currentCommands;
2809
3120
  this.#assertDistinctBatchFootprints([materialization], retainedCommands);
@@ -2823,7 +3134,7 @@ class OfflineSyncService {
2823
3134
  const materializations = [];
2824
3135
  for (const [index, entry] of prepared.entries()) {
2825
3136
  this.#assertEnqueueScope(session, entry.request.scopeId);
2826
- materializations.push(await this.#materializeEnqueue(session.userId, entry.request, entry.replicaTransaction, undefined, firstCreatedAt + index));
3137
+ materializations.push(await this.#materializeEnqueue(session.userId, entry.request, undefined, firstCreatedAt + index));
2827
3138
  }
2828
3139
  this.#assertDistinctBatchFootprints(materializations, currentCommands);
2829
3140
  await this.#assertOutboxCapacity(session.userId, materializations.map((item) => item.command), undefined, currentCommands);
@@ -2852,14 +3163,16 @@ class OfflineSyncService {
2852
3163
  }
2853
3164
  this.noteScope({ userId: session.userId, scopeId });
2854
3165
  }
2855
- async #materializeEnqueue(userId, request, replicaTransaction, replaced, createdAt) {
3166
+ async #materializeEnqueue(userId, request, replaced, createdAt) {
2856
3167
  const scope = { userId, scopeId: request.scopeId };
2857
3168
  this.noteScope(scope);
2858
3169
  const commandIdentity = offlineCommandLookupIdentity(request.identity);
2859
3170
  const normalized = await this.#normalizeEnqueueRequest(scope, request, commandIdentity);
2860
- const optimisticValue = request.optimisticValue;
2861
3171
  const commandId = crypto.randomUUID();
2862
3172
  const sourceKey = this.#hooks.entityType(request);
3173
+ const localOnlyFootprint = this.#normalizedLocalOnlyFootprint(scope, request.localOnlyFootprint);
3174
+ if (replaced)
3175
+ this.#assertReplacementFootprint(replaced, localOnlyFootprint);
2863
3176
  let command = {
2864
3177
  ...scope,
2865
3178
  commandId,
@@ -2868,7 +3181,6 @@ class OfflineSyncService {
2868
3181
  identity: commandIdentity,
2869
3182
  operation: request.operation,
2870
3183
  payload: normalized.payload,
2871
- optimisticValue,
2872
3184
  replicaMutation: request.replicaMutation ?? 'upsert',
2873
3185
  payloadHash: await this.#payloadHash(normalized.payload),
2874
3186
  baseRevision: normalized.baseRevision,
@@ -2878,6 +3190,8 @@ class OfflineSyncService {
2878
3190
  createdAt: replaced?.createdAt ?? createdAt ?? (await this.#nextCommandCreatedAt(userId)),
2879
3191
  lastErrorCode: null,
2880
3192
  };
3193
+ if (localOnlyFootprint.length > 0)
3194
+ command = { ...command, localOnlyFootprint };
2881
3195
  if (replaced &&
2882
3196
  (replaced.userId !== command.userId ||
2883
3197
  replaced.scopeId !== command.scopeId ||
@@ -2904,11 +3218,16 @@ class OfflineSyncService {
2904
3218
  const generatedIdentity = request.identity.kind === 'generated' ? request.identity : null;
2905
3219
  const initialRemoteId = this.#initialRemoteId(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteId);
2906
3220
  this.#assertRemoteIdHint(schema, existing?.identity.kind === 'generated' ? existing.identity.remoteId : null, generatedIdentity?.remoteIdHint);
2907
- const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
3221
+ const naturalKey = schema.identity.kind === 'naturalKey' && request.identity.kind === 'natural'
3222
+ ? request.identity.naturalKey
3223
+ : existing
3224
+ ? offlineNaturalKeyFromValues(schema, existing.values)
3225
+ : null;
2908
3226
  if (schema.identity.kind === 'naturalKey' &&
2909
- canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.kind === 'natural' ? request.identity.naturalKey : {} }) !==
3227
+ request.identity.kind === 'natural' &&
3228
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: request.identity.naturalKey }) !==
2910
3229
  canonicalOfflineRemoteIdentity(schema, { naturalKey: naturalKey })) {
2911
- throw new Error(`Offline command naturalKey must match optimistic values for "${entityType}".`);
3230
+ throw new Error(`Offline command naturalKey must match replica identity for "${entityType}".`);
2912
3231
  }
2913
3232
  const remoteIdentity = schema.identity.kind === 'generated'
2914
3233
  ? initialRemoteId === null
@@ -2923,7 +3242,7 @@ class OfflineSyncService {
2923
3242
  canonicalOfflineRemoteIdentity(schema, {
2924
3243
  naturalKey: existing.identity.kind === 'natural' ? existing.identity.naturalKey : offlineNaturalKeyFromValues(schema, existing.values),
2925
3244
  }) !== canonicalValuesKey) {
2926
- throw new Error(`Offline replica naturalKey is immutable and must match optimistic values for "${entityType}".`);
3245
+ throw new Error(`Offline replica naturalKey is immutable and must match command identity for "${entityType}".`);
2927
3246
  }
2928
3247
  }
2929
3248
  if (remoteIdentity !== null) {
@@ -2935,27 +3254,33 @@ class OfflineSyncService {
2935
3254
  throw new Error(`Offline replica remote identity is already mapped to another row.`);
2936
3255
  }
2937
3256
  }
2938
- const rowIdentity = schema.identity.kind === 'naturalKey'
2939
- ? offlineNaturalReplicaIdentity(schema, optimisticValue)
2940
- : offlineGeneratedReplicaIdentity(generatedIdentity.localId, initialRemoteId);
2941
- const optimisticRow = {
2942
- ...scope,
2943
- sourceKey: entityType,
2944
- identity: rowIdentity,
2945
- values: optimisticValue,
2946
- confirmedValues: existing?.confirmedValues ?? existing?.values ?? null,
2947
- serverRevision: existing?.serverRevision ?? normalized.baseRevision,
2948
- fetchedAt: Date.now(),
2949
- syncState: 'pending',
2950
- visibility: request.replicaMutation === 'delete' ? 'pending_delete' : 'present',
2951
- };
2952
- const preparedCompanions = await this.#prepareOptimisticCompanions(scope, optimisticRow, replicaTransaction);
2953
- const optimisticCompanions = replaced ? this.#replacementCompanions(replaced, preparedCompanions) : preparedCompanions;
2954
- if (replicaTransaction)
2955
- this.#canonicalJson(replicaTransaction);
2956
- if (optimisticCompanions.length > 0)
2957
- command = { ...command, optimisticCompanions };
2958
- return { command, optimisticRow, optimisticCompanions };
3257
+ this.#canonicalJson(normalized.payload);
3258
+ const seedBaseRow = existing
3259
+ ? undefined
3260
+ : request.identity.kind === 'generated'
3261
+ ? {
3262
+ ...scope,
3263
+ sourceKey,
3264
+ identity: { kind: 'generated', localId: request.identity.localId, remoteId: initialRemoteId },
3265
+ values: {},
3266
+ confirmedValues: null,
3267
+ serverRevision: null,
3268
+ fetchedAt: Date.now(),
3269
+ syncState: 'pending',
3270
+ }
3271
+ : request.identity.kind === 'natural'
3272
+ ? {
3273
+ ...scope,
3274
+ sourceKey,
3275
+ identity: { kind: 'natural', naturalKey: request.identity.naturalKey },
3276
+ values: { ...request.identity.naturalKey },
3277
+ confirmedValues: null,
3278
+ serverRevision: null,
3279
+ fetchedAt: Date.now(),
3280
+ syncState: 'pending',
3281
+ }
3282
+ : null;
3283
+ return { command, seedBaseRow };
2959
3284
  }
2960
3285
  #assertDistinctBatchFootprints(entries, existingCommands, allowOneAggregate = false) {
2961
3286
  const aggregates = new Set();
@@ -2972,10 +3297,7 @@ class OfflineSyncService {
2972
3297
  throw new Error('Prepared offline batch contains overlapping aggregate intents.');
2973
3298
  }
2974
3299
  aggregates.add(aggregate);
2975
- for (const key of [
2976
- this.#replicaRowKey(entry.optimisticRow),
2977
- ...entry.optimisticCompanions.map((companion) => this.#replicaRowKey(companion.key)),
2978
- ]) {
3300
+ for (const key of this.#commandFootprintKeys(entry.command)) {
2979
3301
  if (replicaKeys.has(key) && !allowOneAggregate) {
2980
3302
  throw new Error('Prepared offline batch contains overlapping replica footprints.');
2981
3303
  }
@@ -2991,21 +3313,28 @@ class OfflineSyncService {
2991
3313
  const identity = command.identity.kind === 'generated'
2992
3314
  ? offlineGeneratedReplicaIdentity(command.identity.localId, null)
2993
3315
  : { kind: 'natural', naturalKey: command.identity.naturalKey };
2994
- return [
2995
- this.#replicaRowKey({ ...command, identity }),
2996
- ...(command.optimisticCompanions ?? []).map((companion) => this.#replicaRowKey(companion.key)),
2997
- ];
3316
+ return [this.#replicaRowKey({ ...command, identity }), ...commandFootprintKeys(command).map((key) => this.#replicaRowKey(key))];
2998
3317
  }
2999
3318
  async #commitMaterializedEnqueues(entries, generation, options, removeCommandIds) {
3000
3319
  if (generation !== this.#generation) {
3001
3320
  throw new Error('Offline session changed before the command could be persisted');
3002
3321
  }
3322
+ const known = await this.#readKnownCommands();
3323
+ const remaining = [
3324
+ ...known.filter((command) => !(removeCommandIds ?? []).includes(command.commandId)),
3325
+ ...entries.map((entry) => entry.command),
3326
+ ].sort(compareOfflineCommands);
3327
+ const affected = new Map();
3328
+ const seeds = new Map();
3329
+ for (const entry of entries) {
3330
+ affected.set(this.#aggregateKey(entry.command), entry.command);
3331
+ if (entry.seedBaseRow !== undefined)
3332
+ seeds.set(this.#aggregateKey(entry.command), entry.seedBaseRow);
3333
+ }
3334
+ const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining, seeds);
3003
3335
  await this.#repository.transactReplica({
3004
- putRows: entries.flatMap((entry) => [
3005
- entry.optimisticRow,
3006
- ...entry.optimisticCompanions.flatMap((companion) => (companion.after ? [companion.after] : [])),
3007
- ]),
3008
- removeRows: entries.flatMap((entry) => entry.optimisticCompanions.flatMap((companion) => (companion.after ? [] : [companion.key]))),
3336
+ putRows: rematerialized.putRows,
3337
+ removeRows: rematerialized.removeRows,
3009
3338
  putCommands: entries.map((entry) => entry.command),
3010
3339
  removeCommandIds,
3011
3340
  });
@@ -3013,76 +3342,36 @@ class OfflineSyncService {
3013
3342
  if (options.flush !== false && this.#network.connected())
3014
3343
  this.#flushInBackground();
3015
3344
  }
3016
- async #prepareOptimisticCompanions(scope, optimisticRow, transaction) {
3017
- if (!transaction)
3345
+ #normalizedLocalOnlyFootprint(scope, footprint) {
3346
+ if (!footprint || footprint.length === 0)
3018
3347
  return [];
3019
- const runtimeTransaction = transaction;
3020
- const unsupported = Object.keys(runtimeTransaction).filter((key) => key !== 'putRows' && key !== 'removeRows');
3021
- if (unsupported.length > 0) {
3022
- throw new Error(`Prepared offline enqueue cannot mutate ${unsupported.join(', ')}.`);
3023
- }
3024
- const putRows = transaction.putRows ?? [];
3025
- const removeRows = transaction.removeRows ?? [];
3026
- const baseKey = this.#replicaRowKey(optimisticRow);
3027
- const seen = new Set([baseKey]);
3028
- const mutations = [];
3029
- for (const row of putRows) {
3030
- this.#assertCompanionScope(scope, row);
3031
- const key = this.#replicaRowKey(row);
3032
- if (seen.has(key))
3033
- throw new Error(`Prepared offline enqueue contains duplicate replica row ${key}.`);
3034
- seen.add(key);
3035
- mutations.push({ key: this.#minimalReplicaRowKey(row), after: row });
3036
- }
3037
- for (const row of removeRows) {
3038
- this.#assertCompanionScope(scope, row);
3039
- const key = this.#replicaRowKey(row);
3040
- if (seen.has(key))
3041
- throw new Error(`Prepared offline enqueue contains duplicate replica row ${key}.`);
3042
- seen.add(key);
3043
- mutations.push({ key: this.#minimalReplicaRowKey(row), after: null });
3044
- }
3045
- return Promise.all(mutations.map(async ({ key, after }) => {
3046
- const before = (await this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity)) ??
3047
- (await this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
3048
- return { key, before, after: this.#optimisticCompanionAfter(after, before) };
3049
- }));
3348
+ const seen = new Set();
3349
+ return footprint.map((key) => {
3350
+ this.#assertLocalOnlyFootprintKey(scope, key);
3351
+ const canonical = this.#replicaRowKey(key);
3352
+ if (seen.has(canonical))
3353
+ throw new Error(`Prepared offline enqueue contains duplicate replica row ${canonical}.`);
3354
+ seen.add(canonical);
3355
+ return this.#minimalReplicaRowKey(key);
3356
+ });
3050
3357
  }
3051
- #assertCompanionScope(scope, key) {
3358
+ #assertLocalOnlyFootprintKey(scope, key) {
3052
3359
  if (key.userId !== scope.userId || key.scopeId !== scope.scopeId) {
3053
- throw new Error('Prepared offline enqueue companion rows must use the command scope.');
3360
+ throw new Error('Prepared offline enqueue localOnly footprint must use the command scope.');
3054
3361
  }
3055
- }
3056
- #replacementCompanions(replaced, optimisticCompanions) {
3057
- const previousByKey = new Map((replaced.optimisticCompanions ?? []).map((companion) => [this.#replicaRowKey(companion.key), companion]));
3058
- const previousKeys = new Set(previousByKey.keys());
3059
- const replacementKeys = new Set(optimisticCompanions.map((companion) => this.#replicaRowKey(companion.key)));
3060
- if (previousKeys.size !== replacementKeys.size || [...previousKeys].some((key) => !replacementKeys.has(key))) {
3061
- throw new Error('Offline replacement must preserve the optimistic companion footprint.');
3362
+ if (this.#entitySchema(key.sourceKey).identity.kind !== 'localOnly') {
3363
+ throw new Error(`Prepared offline enqueue footprint may only declare localOnly source "${key.sourceKey}".`);
3364
+ }
3365
+ if (key.identity.kind !== 'local') {
3366
+ throw new Error('Prepared offline enqueue footprint must use local identity.');
3062
3367
  }
3063
- return optimisticCompanions.map((companion) => {
3064
- const previousBefore = previousByKey.get(this.#replicaRowKey(companion.key)).before;
3065
- const before = this.#replacementCompanionBefore(companion.before, previousBefore);
3066
- return { ...companion, before, after: this.#optimisticCompanionAfter(companion.after, before) };
3067
- });
3068
- }
3069
- #replacementCompanionBefore(current, historical) {
3070
- const confirmedValues = current ? current.confirmedValues : (historical?.confirmedValues ?? null);
3071
- if (confirmedValues === null)
3072
- return null;
3073
- const source = current ?? historical;
3074
- return {
3075
- ...source,
3076
- values: confirmedValues,
3077
- confirmedValues,
3078
- syncState: 'confirmed',
3079
- visibility: 'present',
3080
- };
3081
3368
  }
3082
- #optimisticCompanionAfter(after, before) {
3083
- if (!after)
3084
- return null;
3085
- return { ...after, confirmedValues: before?.confirmedValues ?? null };
3369
+ #assertReplacementFootprint(replaced, next) {
3370
+ const previous = new Set(commandFootprintKeys(replaced).map((key) => this.#replicaRowKey(key)));
3371
+ const incoming = new Set(next.map((key) => this.#replicaRowKey(key)));
3372
+ if (previous.size !== incoming.size || [...previous].some((key) => !incoming.has(key))) {
3373
+ throw new Error('Offline replacement must preserve the localOnly footprint.');
3374
+ }
3086
3375
  }
3087
3376
  #minimalReplicaRowKey(key) {
3088
3377
  return {
@@ -3182,7 +3471,7 @@ class OfflineSyncService {
3182
3471
  await Promise.all(commands.map((command) => this.#hooks.onCommandRemoved?.(command).catch((error) => this.#reportError(error))));
3183
3472
  }
3184
3473
  #assertDiscardable(commands) {
3185
- const ambiguous = commands.filter((command) => command.state === 'sending' || command.serverCommitUnknown === true);
3474
+ const ambiguous = commands.filter((command) => command.state === 'sending' || command.state === 'awaiting_pull' || command.serverCommitUnknown === true);
3186
3475
  if (ambiguous.length > 0) {
3187
3476
  throw new OfflineCommandInFlightError(ambiguous.map((command) => command.commandId));
3188
3477
  }
@@ -3270,14 +3559,14 @@ class OfflineSyncService {
3270
3559
  const dirtyScopes = new Map();
3271
3560
  const sendWorkerFailures = [];
3272
3561
  while (this.#network.connected() && this.#isCurrent(generation) && fatalPullFailure === null) {
3273
- const groups = this.#eligibleAggregateGroups(await this.#readKnownCommands()).filter((group) => {
3274
- const head = group[0];
3275
- return head !== undefined && pulledScopeKeys.has(this.#scopeKey(head));
3276
- });
3562
+ const known = await this.#readKnownCommands();
3563
+ const groups = this.#eligibleAggregateGroups(known).filter((group) => group.some((command) => (command.state === 'pending' || command.state === 'retry_wait') &&
3564
+ pulledScopeKeys.has(this.#scopeKey({ userId: command.userId, scopeId: command.scopeId }))));
3277
3565
  if (!this.#isCurrent(generation))
3278
3566
  return;
3279
3567
  if (groups.length === 0)
3280
3568
  break;
3569
+ const pendingBefore = known.filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
3281
3570
  let cursor = 0;
3282
3571
  const workers = Array.from({ length: Math.min(MAX_PARALLEL_AGGREGATES, groups.length) }, async () => {
3283
3572
  while (cursor < groups.length) {
@@ -3294,6 +3583,9 @@ class OfflineSyncService {
3294
3583
  }
3295
3584
  if (sendWorkerFailures.length > 0)
3296
3585
  break;
3586
+ const pendingAfter = (await this.#readKnownCommands()).filter((command) => command.state === 'pending' || command.state === 'retry_wait').length;
3587
+ if (pendingAfter >= pendingBefore)
3588
+ break;
3297
3589
  }
3298
3590
  for (const scope of dirtyScopes.values()) {
3299
3591
  this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
@@ -3344,6 +3636,14 @@ class OfflineSyncService {
3344
3636
  }
3345
3637
  if (this.#isCurrent(generation))
3346
3638
  this.#coldReconciliationRequired = false;
3639
+ if (this.#isCurrent(generation)) {
3640
+ for (const command of await this.#readKnownCommands()) {
3641
+ if (command.state !== 'awaiting_pull')
3642
+ continue;
3643
+ const scope = { userId: command.userId, scopeId: command.scopeId };
3644
+ this.#pendingPullScopes.set(this.#scopeKey(scope), scope);
3645
+ }
3646
+ }
3347
3647
  }
3348
3648
  #isFatalPullFailure(error) {
3349
3649
  const status = this.#errorStatus(error);
@@ -3417,15 +3717,14 @@ class OfflineSyncService {
3417
3717
  group.push(command);
3418
3718
  groups.set(key, group);
3419
3719
  }
3420
- return [...groups.values()].filter((group) => {
3421
- const head = group[0];
3422
- return head?.state === 'pending' || (head?.state === 'retry_wait' && (head.retryAt ?? 0) <= now);
3423
- });
3720
+ return [...groups.values()].filter((group) => group.some((command) => command.state === 'pending' || (command.state === 'retry_wait' && (command.retryAt ?? 0) <= now)));
3424
3721
  }
3425
3722
  async #sendAggregate(commands, generation, dirtyScopes, pulledScopeKeys) {
3426
3723
  for (const command of commands) {
3427
3724
  if (!this.#isCurrent(generation))
3428
3725
  return;
3726
+ if (command.state === 'awaiting_pull')
3727
+ continue;
3429
3728
  if (command.state === 'retry_wait' && (command.retryAt ?? 0) > Date.now())
3430
3729
  break;
3431
3730
  if (!['pending', 'retry_wait'].includes(command.state))
@@ -3489,7 +3788,6 @@ class OfflineSyncService {
3489
3788
  throw error;
3490
3789
  }
3491
3790
  if (this.#isCurrent(generation)) {
3492
- await this.#hooks.onCommandRemoved?.(sending).catch((error) => this.#reportError(error));
3493
3791
  const scope = { userId: sending.userId, scopeId: sending.scopeId };
3494
3792
  dirtyScopes.set(this.#scopeKey(scope), scope);
3495
3793
  }
@@ -3501,7 +3799,23 @@ class OfflineSyncService {
3501
3799
  const sourceKey = this.#hooks.entityType(request);
3502
3800
  const row = await this.#getReplicaRowForSync(scope, sourceKey, commandIdentity);
3503
3801
  if (row?.serverRevision != null && row.serverRevision !== baseRevision) {
3504
- const rebased = this.#executor.withServerRevision({ ...scope, ...request, sourceKey, identity: commandIdentity, payload, baseRevision }, row.serverRevision);
3802
+ const rebased = this.#executor.withServerRevision({
3803
+ ...scope,
3804
+ commandId: '',
3805
+ aggregateType: request.aggregateType,
3806
+ sourceKey,
3807
+ identity: commandIdentity,
3808
+ operation: request.operation,
3809
+ payload,
3810
+ replicaMutation: request.replicaMutation ?? 'upsert',
3811
+ payloadHash: '',
3812
+ baseRevision,
3813
+ state: 'pending',
3814
+ attempts: 0,
3815
+ retryAt: null,
3816
+ createdAt: 0,
3817
+ lastErrorCode: null,
3818
+ }, row.serverRevision);
3505
3819
  baseRevision = row.serverRevision;
3506
3820
  payload = rebased.payload;
3507
3821
  }
@@ -3517,9 +3831,6 @@ class OfflineSyncService {
3517
3831
  if (result.clearRemoteId === true && result.serverRevision !== undefined) {
3518
3832
  throw new Error('Offline command cannot return serverRevision and clearRemoteId together.');
3519
3833
  }
3520
- // An enqueue may have completed while transport was in flight. Re-read the
3521
- // aggregate immediately before the atomic acknowledgement transaction so a
3522
- // delete ACK cannot remove a row that has already been re-added locally.
3523
3834
  const latestCommands = (await this.#readKnownCommands()).filter((candidate) => this.#aggregateKey(candidate) === this.#aggregateKey(command));
3524
3835
  const latestIndex = latestCommands.findIndex((candidate) => candidate.commandId === command.commandId);
3525
3836
  if (latestIndex < 0)
@@ -3536,7 +3847,6 @@ class OfflineSyncService {
3536
3847
  : revision === undefined
3537
3848
  ? following
3538
3849
  : following.map((item) => this.#executor.withServerRevision(item, revision));
3539
- latestCommands.splice(latestIndex + 1, rebased.length, ...rebased);
3540
3850
  const current = await this.#rowForCommand(command);
3541
3851
  if (!this.#isCurrent(generation))
3542
3852
  return;
@@ -3548,14 +3858,27 @@ class OfflineSyncService {
3548
3858
  if (result.clearRemoteId === true && !removesReplica) {
3549
3859
  throw new Error('Offline command can clear remoteId only for a confirmed replica removal.');
3550
3860
  }
3551
- const confirmedValues = removesReplica ? null : (result.confirmedValues ?? command.optimisticValue);
3552
3861
  const schema = this.#entitySchema(current.sourceKey);
3553
3862
  this.#assertCommandResultIdentity(schema, current, result);
3554
3863
  const resolvedRemoteId = this.#resolvedRemoteId(current, result);
3555
- const row = {
3864
+ const reconciliationIdentity = current.identity.kind === 'generated'
3865
+ ? resolvedRemoteId === null
3866
+ ? undefined
3867
+ : { remoteId: resolvedRemoteId }
3868
+ : current.identity.kind === 'natural'
3869
+ ? { naturalKey: current.identity.naturalKey }
3870
+ : undefined;
3871
+ const awaitingPull = {
3872
+ ...command,
3873
+ state: 'awaiting_pull',
3874
+ retryAt: null,
3875
+ lastErrorCode: null,
3876
+ serverCommitUnknown: false,
3877
+ ...(reconciliationIdentity ? { reconciliationIdentity } : {}),
3878
+ };
3879
+ latestCommands.splice(latestIndex, 1 + rebased.length, awaitingPull, ...rebased);
3880
+ const identityUpdatedBase = {
3556
3881
  ...current,
3557
- values: rebased.length > 0 ? current.values : confirmedValues,
3558
- confirmedValues,
3559
3882
  identity: current.identity.kind === 'generated'
3560
3883
  ? {
3561
3884
  ...current.identity,
@@ -3564,18 +3887,13 @@ class OfflineSyncService {
3564
3887
  : current.identity,
3565
3888
  serverRevision: result.clearRemoteId === true ? null : (revision ?? current.serverRevision),
3566
3889
  fetchedAt: Date.now(),
3567
- syncState: rebased.length > 0 ? 'pending' : 'confirmed',
3568
- visibility: rebased.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
3569
3890
  };
3570
- const companionTransaction = this.#companionTransactionAfterAcknowledgement(rebased);
3891
+ const rematerialized = await this.#rematerializeAggregate(awaitingPull, latestCommands, identityUpdatedBase);
3571
3892
  if (!this.#isCurrent(generation))
3572
3893
  return;
3573
3894
  await this.#repository.transactReplica({
3574
- putRows: [...(removesReplica && rebased.length === 0 ? [] : [row]), ...(companionTransaction.putRows ?? [])],
3575
- releaseRemoteIds: result.clearRemoteId === true &&
3576
- current.identity.kind === 'generated' &&
3577
- current.identity.remoteId !== null &&
3578
- !(removesReplica && rebased.length === 0)
3895
+ putRows: rematerialized.putRows,
3896
+ releaseRemoteIds: result.clearRemoteId === true && current.identity.kind === 'generated' && current.identity.remoteId !== null
3579
3897
  ? [
3580
3898
  {
3581
3899
  userId: current.userId,
@@ -3586,9 +3904,8 @@ class OfflineSyncService {
3586
3904
  },
3587
3905
  ]
3588
3906
  : undefined,
3589
- removeRows: [...(removesReplica && rebased.length === 0 ? [current] : []), ...(companionTransaction.removeRows ?? [])],
3590
- putCommands: rebased,
3591
- removeCommandIds: [command.commandId],
3907
+ removeRows: rematerialized.removeRows,
3908
+ putCommands: [awaitingPull, ...rebased],
3592
3909
  putReconciliationScopes: [{ userId: command.userId, scopeId: command.scopeId }],
3593
3910
  });
3594
3911
  const scope = { userId: command.userId, scopeId: command.scopeId };
@@ -3624,97 +3941,53 @@ class OfflineSyncService {
3624
3941
  const affected = new Map();
3625
3942
  for (const command of discarded)
3626
3943
  affected.set(this.#aggregateKey(command), command);
3627
- const putRows = [];
3628
- const removeRows = [];
3629
- const companionRows = new Map();
3630
- const companionRemovals = new Map();
3631
- for (const [key, command] of affected) {
3632
- const row = await this.#rowForCommand(command);
3633
- const remaining = all.filter((item) => !discardedIds.has(item.commandId) && this.#aggregateKey(item) === key);
3634
- if (row) {
3635
- if (remaining.length === 0 && row.confirmedValues === null) {
3636
- removeRows.push(row);
3637
- }
3638
- else {
3639
- putRows.push({
3640
- ...row,
3641
- values: remaining.length > 0 ? remaining.at(-1).optimisticValue : row.confirmedValues,
3642
- syncState: remaining.length > 0 ? 'pending' : 'confirmed',
3643
- visibility: remaining.at(-1)?.replicaMutation === 'delete' ? 'pending_delete' : 'present',
3644
- });
3645
- }
3646
- }
3647
- const aggregateCommands = all.filter((item) => this.#aggregateKey(item) === key);
3648
- const remainingAggregateCommands = aggregateCommands.filter((item) => !discardedIds.has(item.commandId));
3649
- for (const companion of this.#companionsAfterDiscard(aggregateCommands, remainingAggregateCommands)) {
3650
- const companionKey = this.#replicaRowKey(companion.key);
3651
- const hasRemaining = remainingAggregateCommands.some((remainingCommand) => (remainingCommand.optimisticCompanions ?? []).some((candidate) => this.#replicaRowKey(candidate.key) === companionKey));
3652
- const current = await this.#getCompanionRow(companion.key);
3653
- const after = hasRemaining
3654
- ? companion.after && current
3655
- ? { ...companion.after, confirmedValues: current.confirmedValues }
3656
- : companion.after
3657
- : current
3658
- ? current.confirmedValues === null
3659
- ? null
3660
- : {
3661
- ...current,
3662
- values: current.confirmedValues,
3663
- syncState: 'confirmed',
3664
- visibility: 'present',
3665
- }
3666
- : companion.after;
3667
- if (after) {
3668
- companionRows.set(companionKey, after);
3669
- companionRemovals.delete(companionKey);
3670
- }
3671
- else {
3672
- companionRows.delete(companionKey);
3673
- companionRemovals.set(companionKey, companion.key);
3674
- }
3675
- }
3676
- }
3944
+ const remaining = all.filter((item) => !discardedIds.has(item.commandId));
3945
+ const rematerialized = await this.#rematerializeAffectedAggregates(affected, remaining);
3677
3946
  await this.#repository.transactReplica({
3678
- putRows: [...putRows, ...companionRows.values()],
3679
- removeRows: [...removeRows, ...companionRemovals.values()],
3947
+ putRows: rematerialized.putRows,
3948
+ removeRows: rematerialized.removeRows,
3680
3949
  removeCommandIds: [...discardedIds],
3681
3950
  });
3682
3951
  }
3683
- #getCompanionRow(key) {
3684
- const scope = { userId: key.userId, scopeId: key.scopeId };
3685
- return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
3686
- this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
3952
+ async #rematerializeAffectedAggregates(affected, remaining, seeds = new Map()) {
3953
+ const putRows = [];
3954
+ const removeRows = [];
3955
+ for (const [key, command] of affected) {
3956
+ const remainingForAggregate = remaining.filter((item) => this.#aggregateKey(item) === key);
3957
+ const footprintCommands = [...remainingForAggregate, ...[...affected.values()].filter((item) => this.#aggregateKey(item) === key)];
3958
+ const rematerialized = await this.#rematerializeAggregate(command, remainingForAggregate, seeds.has(key) ? seeds.get(key) : undefined, footprintCommands);
3959
+ putRows.push(...(rematerialized.putRows ?? []));
3960
+ removeRows.push(...(rematerialized.removeRows ?? []));
3961
+ }
3962
+ return { putRows, removeRows };
3687
3963
  }
3688
- #companionTransactionAfterAcknowledgement(following) {
3689
- const latest = new Map();
3690
- for (const command of following) {
3691
- for (const companion of command.optimisticCompanions ?? []) {
3692
- latest.set(this.#replicaRowKey(companion.key), companion);
3693
- }
3964
+ async #rematerializeAggregate(command, remaining, baseRow = undefined, footprintCommands = remaining) {
3965
+ const current = baseRow === undefined ? await this.#rowForCommand(command) : baseRow;
3966
+ const projection = this.#replicaMutations.projectAggregateIntent({
3967
+ baseRow: current,
3968
+ localOnlyRows: await this.#localOnlyRowsForCommands(footprintCommands),
3969
+ commands: remaining,
3970
+ trigger: 'local',
3971
+ });
3972
+ if (isOfflineAggregateIntentConflict(projection)) {
3973
+ throw new Error('Offline aggregate intent projector cannot return conflict outside pull reconciliation.');
3694
3974
  }
3695
- return {
3696
- putRows: [...latest.values()].flatMap((companion) => (companion.after ? [companion.after] : [])),
3697
- removeRows: [...latest.values()].flatMap((companion) => (companion.after ? [] : [companion.key])),
3698
- };
3975
+ return offlineAggregateIntentMutations(projection, current);
3699
3976
  }
3700
- #companionsAfterDiscard(all, remaining) {
3977
+ async #localOnlyRowsForCommands(commands) {
3701
3978
  const keys = new Map();
3702
- for (const command of all) {
3703
- for (const companion of command.optimisticCompanions ?? []) {
3704
- const key = this.#replicaRowKey(companion.key);
3705
- const previous = keys.get(key);
3706
- keys.set(key, previous ? { ...companion, before: previous.before } : companion);
3707
- }
3708
- }
3709
- for (const command of remaining) {
3710
- for (const companion of command.optimisticCompanions ?? []) {
3711
- const key = this.#replicaRowKey(companion.key);
3712
- const original = keys.get(key);
3713
- keys.set(key, { ...companion, before: original?.before ?? companion.before });
3979
+ for (const command of commands) {
3980
+ for (const key of commandFootprintKeys(command)) {
3981
+ keys.set(this.#replicaRowKey(key), key);
3714
3982
  }
3715
3983
  }
3716
- const remainingKeys = new Set(remaining.flatMap((command) => (command.optimisticCompanions ?? []).map((item) => this.#replicaRowKey(item.key))));
3717
- return [...keys.entries()].map(([key, companion]) => (remainingKeys.has(key) ? companion : { ...companion, after: companion.before }));
3984
+ const rows = await Promise.all([...keys.values()].map((key) => this.#getLocalOnlyRow(key)));
3985
+ return rows.filter((row) => row !== null);
3986
+ }
3987
+ #getLocalOnlyRow(key) {
3988
+ const scope = { userId: key.userId, scopeId: key.scopeId };
3989
+ return (this.#repository.getReplicaRowIncludingPendingDelete?.(scope, key.sourceKey, key.identity) ??
3990
+ this.#repository.getReplicaRow(scope, key.sourceKey, key.identity));
3718
3991
  }
3719
3992
  #aggregateKey(command) {
3720
3993
  const sourceKey = this.#entityType(command);
@@ -3830,10 +4103,9 @@ class OfflineSyncService {
3830
4103
  if (schema.identity.kind !== 'generated' && result.remoteId !== undefined) {
3831
4104
  throw new Error(`Offline command returned generated remote id for source "${schema.sourceKey}" without generated identity.`);
3832
4105
  }
3833
- if (schema.identity.kind === 'naturalKey') {
3834
- const confirmedValues = result.confirmedValues ?? current.values;
4106
+ if (schema.identity.kind === 'naturalKey' && result.confirmedValues !== undefined) {
3835
4107
  const currentKey = current.identity.kind === 'natural' ? current.identity.naturalKey : offlineNaturalKeyFromValues(schema, current.values);
3836
- const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
4108
+ const confirmedKey = offlineNaturalKeyFromValues(schema, result.confirmedValues);
3837
4109
  if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
3838
4110
  canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
3839
4111
  throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
@@ -4084,8 +4356,22 @@ class OfflineCoordinatorService {
4084
4356
  this.#network = inject(OfflineNetworkService);
4085
4357
  this.#sync = inject(OfflineSyncService);
4086
4358
  this.#session = inject(OfflineSessionService);
4359
+ this.#options = inject(OFFLINE_KIT_OPTIONS);
4360
+ this.#storageState = signal({ status: 'initializing' }, ...(ngDevMode ? [{ debugName: "#storageState" }] : /* istanbul ignore next */ []));
4087
4361
  this.#transitionRevision = 0;
4088
4362
  this.#transitionTail = Promise.resolve();
4363
+ /**
4364
+ * Local storage readiness after {@link initialize}.
4365
+ *
4366
+ * When `unavailable`, the product opted into online-only startup; replica/outbox APIs must not be used.
4367
+ */
4368
+ this.storageState = this.#storageState.asReadonly();
4369
+ /**
4370
+ * Product-policy guard: `true` only when encrypted local storage finished initialization successfully.
4371
+ *
4372
+ * Use this (or {@link storageState}) to disable offline mutations and replica reads when storage is unavailable.
4373
+ */
4374
+ this.isStorageReady = computed(() => this.#storageState().status === 'ready', ...(ngDevMode ? [{ debugName: "isStorageReady" }] : /* istanbul ignore next */ []));
4089
4375
  this.networkState = this.#network.state;
4090
4376
  this.syncState = this.#sync.syncState;
4091
4377
  this.pendingCount = this.#sync.pendingCount;
@@ -4095,10 +4381,34 @@ class OfflineCoordinatorService {
4095
4381
  #network;
4096
4382
  #sync;
4097
4383
  #session;
4384
+ #options;
4385
+ #storageState;
4098
4386
  #transitionRevision;
4099
4387
  #transitionTail;
4388
+ /**
4389
+ * Opens local storage, then session and sync.
4390
+ *
4391
+ * Repository failure without {@link OfflineKitOptions.onStorageUnavailable} throws
4392
+ * {@link OfflineStorageUnavailableError}. When the callback is present and settles, this method
4393
+ * resolves with {@link storageState} `unavailable` and skips session/sync initialization.
4394
+ */
4100
4395
  async initialize() {
4101
- await Promise.all([this.#repository.initialize(), this.#network.initialize()]);
4396
+ const networkReady = this.#network.initialize();
4397
+ try {
4398
+ await this.#repository.initialize();
4399
+ }
4400
+ catch (error) {
4401
+ await networkReady;
4402
+ const typed = this.#asStorageUnavailable(error);
4403
+ this.#storageState.set({ status: 'unavailable', error: typed });
4404
+ const onUnavailable = this.#options.onStorageUnavailable;
4405
+ if (!onUnavailable)
4406
+ throw typed;
4407
+ await onUnavailable(typed);
4408
+ return;
4409
+ }
4410
+ await networkReady;
4411
+ this.#storageState.set({ status: 'ready' });
4102
4412
  await this.#session.initialize();
4103
4413
  await this.#sync.initialize();
4104
4414
  }
@@ -4109,6 +4419,8 @@ class OfflineCoordinatorService {
4109
4419
  }
4110
4420
  /** Installs a remotely verified identity without starting pull or outbox replay. */
4111
4421
  prepareRemoteSession(userId, scopeIds, authSubject, authLease) {
4422
+ if (this.#storageUnavailable())
4423
+ return Promise.resolve(true);
4112
4424
  const revision = ++this.#transitionRevision;
4113
4425
  const lease = this.#lease(revision, authLease);
4114
4426
  return this.#enqueueTransition(async () => {
@@ -4121,12 +4433,16 @@ class OfflineCoordinatorService {
4121
4433
  }
4122
4434
  /** Starts pull and outbox replay after the caller has published remote access. */
4123
4435
  async resumeRemoteSession(options) {
4436
+ if (this.#storageUnavailable())
4437
+ return;
4124
4438
  await this.#sync.refreshSession(options?.foregroundScopeIds);
4125
4439
  }
4126
4440
  /**
4127
4441
  * Activates a restored identity for local replica/outbox use without enabling transport sync.
4128
4442
  */
4129
4443
  activateOfflineSession(authSubject, authLease) {
4444
+ if (this.#storageUnavailable())
4445
+ return Promise.resolve(null);
4130
4446
  const revision = ++this.#transitionRevision;
4131
4447
  const lease = this.#lease(revision, authLease);
4132
4448
  return this.#enqueueTransition(async () => {
@@ -4140,6 +4456,8 @@ class OfflineCoordinatorService {
4140
4456
  });
4141
4457
  }
4142
4458
  clearActiveSession() {
4459
+ if (this.#storageUnavailable())
4460
+ return Promise.resolve();
4143
4461
  this.#sync.revokeSession();
4144
4462
  this.#session.revokeAccess();
4145
4463
  ++this.#transitionRevision;
@@ -4149,6 +4467,8 @@ class OfflineCoordinatorService {
4149
4467
  });
4150
4468
  }
4151
4469
  async prepareLogout(action) {
4470
+ if (this.#storageUnavailable())
4471
+ return action !== 'cancel';
4152
4472
  if (action === 'cancel')
4153
4473
  return false;
4154
4474
  if (action === 'discard') {
@@ -4159,8 +4479,21 @@ class OfflineCoordinatorService {
4159
4479
  return this.#sync.pendingCount() === 0;
4160
4480
  }
4161
4481
  flush() {
4482
+ if (this.#storageUnavailable())
4483
+ return Promise.resolve();
4162
4484
  return this.#sync.flush();
4163
4485
  }
4486
+ #asStorageUnavailable(error) {
4487
+ if (error instanceof OfflineStorageUnavailableError)
4488
+ return error;
4489
+ const message = error instanceof Error ? error.message : 'Offline storage is unavailable.';
4490
+ return new OfflineStorageUnavailableError('storage_unavailable', message || 'Offline storage is unavailable.', {
4491
+ cause: error,
4492
+ });
4493
+ }
4494
+ #storageUnavailable() {
4495
+ return this.#storageState().status === 'unavailable';
4496
+ }
4164
4497
  #lease(revision, authLease) {
4165
4498
  return { isCurrent: () => revision === this.#transitionRevision && (authLease?.isCurrent() ?? true) };
4166
4499
  }
@@ -4506,8 +4839,7 @@ const SCHEMA = [
4506
4839
  identity_json TEXT NOT NULL,
4507
4840
  operation TEXT NOT NULL,
4508
4841
  payload_json TEXT NOT NULL,
4509
- optimistic_value_json TEXT NOT NULL,
4510
- optimistic_companions_json TEXT,
4842
+ local_only_footprint_json TEXT,
4511
4843
  replica_mutation TEXT NOT NULL DEFAULT 'upsert',
4512
4844
  payload_hash TEXT NOT NULL,
4513
4845
  base_revision_json TEXT,
@@ -4516,7 +4848,8 @@ const SCHEMA = [
4516
4848
  retry_at INTEGER,
4517
4849
  created_at INTEGER NOT NULL,
4518
4850
  last_error_code TEXT,
4519
- server_commit_unknown INTEGER NOT NULL DEFAULT 0
4851
+ server_commit_unknown INTEGER NOT NULL DEFAULT 0,
4852
+ reconciliation_identity_json TEXT
4520
4853
  )`,
4521
4854
  `CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created
4522
4855
  ON offline_sync_commands (user_id, scope_id, created_at)`,
@@ -4732,39 +5065,35 @@ class SqliteOfflineRepository {
4732
5065
  });
4733
5066
  }
4734
5067
  async #open() {
4735
- if (!this.#sqlite)
4736
- throw new Error('Native offline storage requires a community SQLite connection');
4737
- const { databaseId } = await this.#sqlite.open({
4738
- databaseName: this.#options.databaseName,
4739
- createEncryptionKey: this.#options.createEncryptionKey,
4740
- });
4741
- this.#databaseId = databaseId;
4742
- for (const statement of SCHEMA)
4743
- await this.#execute(databaseId, statement);
4744
- const commandColumns = await this.#queryDatabase(databaseId, 'PRAGMA table_info(offline_sync_commands)');
4745
- if (!commandColumns.some((row) => row['name'] === 'optimistic_companions_json')) {
4746
- await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN optimistic_companions_json TEXT');
4747
- }
4748
- if (!commandColumns.some((row) => row['name'] === 'server_commit_unknown')) {
4749
- await this.#execute(databaseId, 'ALTER TABLE offline_sync_commands ADD COLUMN server_commit_unknown INTEGER NOT NULL DEFAULT 0');
4750
- await this.#execute(databaseId, `UPDATE offline_sync_commands SET server_commit_unknown = 1
4751
- WHERE state IN ('sending', 'retry_wait')
4752
- OR (attempts >= 2 AND state IN ('blocked_auth', 'conflict', 'rejected'))`);
4753
- }
4754
- const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
4755
- if (metadata.length === 0) {
4756
- await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
4757
- OFFLINE_SCHEMA_VERSION,
4758
- ]);
4759
- }
4760
- else {
4761
- const storedVersion = this.#number(metadata[0]['schema_version']);
4762
- if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
4763
- throw new Error(`Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
4764
- 'A lossless core schema migration is required before this database can be opened.');
5068
+ try {
5069
+ if (!this.#sqlite) {
5070
+ throw new OfflineStorageUnavailableError('storage_unavailable', 'Native offline storage requires a community SQLite connection');
4765
5071
  }
5072
+ const { databaseId } = await this.#sqlite.open({
5073
+ databaseName: this.#options.databaseName,
5074
+ createEncryptionKey: this.#wrapCreateEncryptionKey(this.#options.createEncryptionKey),
5075
+ });
5076
+ this.#databaseId = databaseId;
5077
+ for (const statement of SCHEMA)
5078
+ await this.#execute(databaseId, statement);
5079
+ const metadata = await this.#queryDatabase(databaseId, 'SELECT schema_version FROM offline_metadata WHERE id = 1');
5080
+ if (metadata.length === 0) {
5081
+ await this.#execute(databaseId, 'INSERT INTO offline_metadata (id, schema_version, last_user_id) VALUES (1, ?, NULL)', [
5082
+ OFFLINE_SCHEMA_VERSION,
5083
+ ]);
5084
+ }
5085
+ else {
5086
+ const storedVersion = this.#number(metadata[0]['schema_version']);
5087
+ if (storedVersion !== OFFLINE_SCHEMA_VERSION) {
5088
+ throw new OfflineStorageUnavailableError('core_schema_incompatible', `Unsupported offline storage schema version ${storedVersion}; expected ${OFFLINE_SCHEMA_VERSION}. ` +
5089
+ 'A lossless core schema migration is required before this database can be opened.');
5090
+ }
5091
+ }
5092
+ await this.#initializeReplicaSchema(databaseId);
5093
+ }
5094
+ catch (error) {
5095
+ throw this.#mapInitializationError(error);
4766
5096
  }
4767
- await this.#initializeReplicaSchema(databaseId);
4768
5097
  }
4769
5098
  async #initializeReplicaSchema(databaseId) {
4770
5099
  const bundle = this.#options.replicaSchema;
@@ -4784,16 +5113,16 @@ class SqliteOfflineRepository {
4784
5113
  return;
4785
5114
  }
4786
5115
  if (storedVersion === targetVersion) {
4787
- throw new Error(`Offline replica schema hash mismatch at version ${targetVersion}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`);
5116
+ throw new OfflineStorageUnavailableError('replica_schema_mismatch', `Offline replica schema hash mismatch at version ${targetVersion}. Reinstall the application or bump replicaSchema.version after intentional schema changes.`);
4788
5117
  }
4789
5118
  if (storedVersion > targetVersion) {
4790
- throw new Error(`Offline replica schema version ${storedVersion} is newer than application version ${targetVersion}. Upgrade the application before opening this database.`);
5119
+ throw new OfflineStorageUnavailableError('replica_schema_mismatch', `Offline replica schema version ${storedVersion} is newer than application version ${targetVersion}. Upgrade the application before opening this database.`);
4791
5120
  }
4792
5121
  await this.#nativeTransaction(databaseId, async () => {
4793
5122
  for (let version = storedVersion; version < targetVersion; version++) {
4794
5123
  const migration = bundle.migrations.find((candidate) => candidate.fromVersion === version);
4795
5124
  if (!migration) {
4796
- throw new Error(`Missing offline replica schema migration from version ${version} to ${version + 1}.`);
5125
+ throw new OfflineStorageUnavailableError('migration_missing', `Missing offline replica schema migration from version ${version} to ${version + 1}.`);
4797
5126
  }
4798
5127
  for (const statement of migration.statements) {
4799
5128
  await this.#execute(databaseId, statement);
@@ -4803,6 +5132,35 @@ class SqliteOfflineRepository {
4803
5132
  await this.#upsertReplicaSchemaMetadata(databaseId, targetVersion, targetHash);
4804
5133
  });
4805
5134
  }
5135
+ #wrapCreateEncryptionKey(createEncryptionKey) {
5136
+ if (!createEncryptionKey)
5137
+ return undefined;
5138
+ return async () => {
5139
+ try {
5140
+ const encryptionKey = await createEncryptionKey();
5141
+ if (!encryptionKey) {
5142
+ throw new OfflineStorageUnavailableError('encryption_key_unavailable', 'Native offline storage requires a non-empty encryption key on first open');
5143
+ }
5144
+ return encryptionKey;
5145
+ }
5146
+ catch (error) {
5147
+ if (error instanceof OfflineStorageUnavailableError)
5148
+ throw error;
5149
+ throw new OfflineStorageUnavailableError('encryption_key_unavailable', error instanceof Error ? error.message : 'Offline encryption key is unavailable.', { cause: error });
5150
+ }
5151
+ };
5152
+ }
5153
+ #mapInitializationError(error) {
5154
+ if (error instanceof OfflineStorageUnavailableError)
5155
+ return error;
5156
+ const message = error instanceof Error ? error.message : 'Offline storage is unavailable.';
5157
+ if (message.includes('non-empty encryption key on first open')) {
5158
+ return new OfflineStorageUnavailableError('encryption_key_unavailable', message, { cause: error });
5159
+ }
5160
+ return new OfflineStorageUnavailableError('storage_unavailable', message || 'Offline storage is unavailable.', {
5161
+ cause: error,
5162
+ });
5163
+ }
4806
5164
  async #executeReplicaCreateStatements(databaseId, bundle) {
4807
5165
  for (const entity of bundle.entities) {
4808
5166
  for (const statement of entity.createTableSql) {
@@ -5021,10 +5379,9 @@ class SqliteOfflineRepository {
5021
5379
  identity: parseOfflineCommandIdentity(this.#parse(row['identity_json'])),
5022
5380
  operation: this.#string(row['operation']),
5023
5381
  payload: this.#parse(row['payload_json']),
5024
- optimisticValue: this.#parse(row['optimistic_value_json']),
5025
- ...(row['optimistic_companions_json'] === null || row['optimistic_companions_json'] === undefined
5382
+ ...(row['local_only_footprint_json'] === null || row['local_only_footprint_json'] === undefined
5026
5383
  ? {}
5027
- : { optimisticCompanions: this.#parse(row['optimistic_companions_json']) }),
5384
+ : { localOnlyFootprint: this.#parse(row['local_only_footprint_json']) }),
5028
5385
  replicaMutation: this.#string(row['replica_mutation']),
5029
5386
  payloadHash: this.#string(row['payload_hash']),
5030
5387
  baseRevision: this.#parseNullable(row['base_revision_json']),
@@ -5034,24 +5391,28 @@ class SqliteOfflineRepository {
5034
5391
  createdAt: this.#number(row['created_at']),
5035
5392
  lastErrorCode: this.#stringOrNull(row['last_error_code']),
5036
5393
  serverCommitUnknown: this.#numberOrNull(row['server_commit_unknown']) === 1,
5394
+ ...(row['reconciliation_identity_json'] === null || row['reconciliation_identity_json'] === undefined
5395
+ ? {}
5396
+ : { reconciliationIdentity: this.#parse(row['reconciliation_identity_json']) }),
5037
5397
  };
5038
5398
  }
5039
5399
  #putCommand(databaseId, command) {
5040
5400
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands
5041
- (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json, optimistic_value_json,
5042
- optimistic_companions_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
5043
- server_commit_unknown)
5401
+ (command_id, user_id, scope_id, aggregate_type, source_key, identity_json, operation, payload_json,
5402
+ local_only_footprint_json, replica_mutation, payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code,
5403
+ server_commit_unknown, reconciliation_identity_json)
5044
5404
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
5045
5405
  ON CONFLICT(command_id) DO UPDATE SET
5046
5406
  user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
5047
5407
  source_key = excluded.source_key,
5048
5408
  identity_json = excluded.identity_json, operation = excluded.operation, payload_json = excluded.payload_json,
5049
- optimistic_value_json = excluded.optimistic_value_json, optimistic_companions_json = excluded.optimistic_companions_json,
5409
+ local_only_footprint_json = excluded.local_only_footprint_json,
5050
5410
  replica_mutation = excluded.replica_mutation,
5051
5411
  payload_hash = excluded.payload_hash,
5052
5412
  base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
5053
5413
  retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code,
5054
- server_commit_unknown = excluded.server_commit_unknown`, [
5414
+ server_commit_unknown = excluded.server_commit_unknown,
5415
+ reconciliation_identity_json = excluded.reconciliation_identity_json`, [
5055
5416
  command.commandId,
5056
5417
  canonicalOfflinePrincipalId(command.userId),
5057
5418
  command.scopeId,
@@ -5060,8 +5421,7 @@ class SqliteOfflineRepository {
5060
5421
  serializeOfflineCommandIdentity(command.identity),
5061
5422
  command.operation,
5062
5423
  JSON.stringify(command.payload),
5063
- JSON.stringify(command.optimisticValue),
5064
- command.optimisticCompanions === undefined ? null : JSON.stringify(command.optimisticCompanions),
5424
+ command.localOnlyFootprint === undefined ? null : JSON.stringify(command.localOnlyFootprint),
5065
5425
  command.replicaMutation ?? 'upsert',
5066
5426
  command.payloadHash,
5067
5427
  this.#stringifyNullable(command.baseRevision),
@@ -5071,6 +5431,7 @@ class SqliteOfflineRepository {
5071
5431
  command.createdAt,
5072
5432
  command.lastErrorCode,
5073
5433
  command.serverCommitUnknown === true ? 1 : 0,
5434
+ command.reconciliationIdentity === undefined ? null : JSON.stringify(command.reconciliationIdentity),
5074
5435
  ]);
5075
5436
  }
5076
5437
  async #queryReplicaRow(scope, sourceKey, identity, includePendingDelete) {
@@ -5405,6 +5766,9 @@ const READ_CACHE_ONLY_REPLICA_PULLER = {
5405
5766
  * Web uses Ionic Storage. Native iOS/Android uses encrypted `@capacitor-community/sqlite`. The application owns
5406
5767
  * URL/DTO policy and command execution; the kit owns persistence, ordering, retries, and session
5407
5768
  * isolation.
5769
+ *
5770
+ * Optional {@link OfflineKitOptions.onStorageUnavailable} opts into online-only startup when
5771
+ * local storage cannot be opened; without it, the app initializer still throws.
5408
5772
  */
5409
5773
  function provideOffline(options) {
5410
5774
  const synchronized = options.mode !== 'readCacheOnly';
@@ -5417,7 +5781,9 @@ function provideOffline(options) {
5417
5781
  databaseName: options.databaseName,
5418
5782
  createEncryptionKey: options.createEncryptionKey,
5419
5783
  replicaSchema: options.replicaSchema,
5784
+ wireProtocol: options.wireProtocol,
5420
5785
  outboxLimits: options.outboxLimits,
5786
+ onStorageUnavailable: options.onStorageUnavailable,
5421
5787
  },
5422
5788
  },
5423
5789
  {
@@ -5439,6 +5805,9 @@ function provideOffline(options) {
5439
5805
  ...(options.replicaProjector
5440
5806
  ? [options.replicaProjector, { provide: OFFLINE_REPLICA_PROJECTOR, useExisting: options.replicaProjector }]
5441
5807
  : []),
5808
+ ...(synchronized && 'aggregateIntentProjector' in options && options.aggregateIntentProjector
5809
+ ? [options.aggregateIntentProjector, { provide: OFFLINE_AGGREGATE_INTENT_PROJECTOR, useExisting: options.aggregateIntentProjector }]
5810
+ : []),
5442
5811
  ...options.requestPolicies.flatMap((policy) => provideOfflineRequestPolicy(policy)),
5443
5812
  ...(options.mutationPolicies ?? []).flatMap((policy) => provideOfflineMutationRequestPolicy(policy)),
5444
5813
  ...(options.providers ?? []),
@@ -5575,5 +5944,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
5575
5944
  * Generated bundle index. Do not edit.
5576
5945
  */
5577
5946
 
5578
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, 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_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineLocalId, assertOfflineReplicaGeneratedRemoteId, assertOfflineReplicaNaturalKeyBaseline, assertSupportedOfflineMode, booleanColumn, canonicalOfflineCommandIdentity, canonicalOfflinePrincipalId, canonicalOfflineRemoteIdentity, canonicalOfflineReplicaIdentity, canonicalOfflineReplicaRowKey, commandIdentityFromReplicaIdentity, commandIdentityMatchesReplicaRow, createCommunitySqliteDriver, createOfflineAuthBridge, createRandomOfflineEncryptionKey, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, generatedId, ignored, integer, isOfflineFallbackError, json, localOnly, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
5947
+ 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_HEADER, OFFLINE_RETRY_RANDOM, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCommandInFlightError, OfflineCoordinatorService, OfflineMutationPolicyConflictError, OfflineMutationProtocolError, OfflineMutationRequestPolicyRegistry, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaMutationCoordinator, OfflineReplicaPullService, OfflineReplicaSchemaMismatchError, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, 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, naturalKey, normalizeOfflineNaturalKey, normalizeOfflineReplicaPullPage, nullable, offlineAggregateIntentMutations, offlineCommandLookupIdentity, offlineCommandTargetFromReplicaRow, offlineGeneratedReplicaIdentity, offlineInterceptor, offlineNaturalKeyFromValues, offlineNaturalReplicaIdentity, offlineReplicaRemoteIdentity, offlineRetryDelayMs, offlineSessionManifestAllows, parseOfflineCommandIdentity, parseOfflineMutationEnvelope, parseOfflinePrincipalId, projectOfflineReplicaValues, provideOffline, provideOfflineMutationRequestPolicy, provideOfflineRequestPolicy, real, replicaAddressFromIdentity, requirePositiveOfflineInteger, selectOfflineRepository, serializeOfflineCommandIdentity, sha256OfflineReplicaSchema, supportsSynchronizedOfflineRepository, text };
5579
5948
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map