@rdlabo/ionic-angular-kit 21.5.5 → 21.5.7

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.
@@ -9,11 +9,12 @@ import { Capacitor } from '@capacitor/core';
9
9
  import { HttpContextToken, HttpResponse } from '@angular/common/http';
10
10
  import { defer, catchError, throwError, tap, from, concatMap, of } from 'rxjs';
11
11
 
12
+ const MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES = 1024;
12
13
  const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
13
14
  const RESERVED_COLUMN_NAMES = new Set([
14
15
  'local_id',
15
16
  '_offline_user_id',
16
- '_offline_group_id',
17
+ '_offline_scope_id',
17
18
  'server_id',
18
19
  '_offline_confirmed_json',
19
20
  '_offline_server_revision_json',
@@ -33,6 +34,7 @@ function defineReplicaEntity() {
33
34
  table: definition.table,
34
35
  sourceKey: definition.sourceKey,
35
36
  scope: definition.scope,
37
+ identity: definition.identity,
36
38
  fields: definition.fields,
37
39
  });
38
40
  };
@@ -78,13 +80,99 @@ function nullable(column) {
78
80
  function serverId() {
79
81
  return { kind: 'serverId' };
80
82
  }
83
+ /** Declares an ordered composite natural key without changing the immutable local UUID. */
84
+ function naturalKey(sourceKeys) {
85
+ return { kind: 'naturalKey', sourceKeys };
86
+ }
81
87
  /** Rejects a remote identity on a local-only projection before it reaches platform storage. */
82
88
  function assertOfflineReplicaServerId(schema, value) {
83
- const hasServerId = schema.fields.some((field) => field.policy === 'serverId');
84
- if (!hasServerId && value !== null) {
89
+ if (schema.identity.kind !== 'serverId' && value !== null) {
85
90
  throw new Error(`Offline replica source "${schema.sourceKey}" does not define a serverId field.`);
86
91
  }
87
92
  }
93
+ /** Extracts and validates an entity's natural key in declared component order. */
94
+ function offlineNaturalKeyFromValues(schema, values) {
95
+ if (schema.identity.kind !== 'naturalKey')
96
+ return null;
97
+ if (!isPlainObject$1(values)) {
98
+ throw new Error(`Offline replica values for "${schema.sourceKey}" must be a plain object.`);
99
+ }
100
+ return Object.fromEntries(schema.identity.sourceKeys.map((sourceKey) => {
101
+ const value = values[sourceKey];
102
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKey);
103
+ if ((field.storageKind === 'text' && typeof value !== 'string') ||
104
+ (field.storageKind === 'integer' && (typeof value !== 'number' || !Number.isSafeInteger(value) || !Number.isFinite(value)))) {
105
+ throw new Error(`Offline replica naturalKey field "${sourceKey}" has an invalid value.`);
106
+ }
107
+ if (typeof value === 'string')
108
+ assertNaturalKeyText(sourceKey, value);
109
+ return [sourceKey, value];
110
+ }));
111
+ }
112
+ /** Validates a supplied natural key and returns it in schema-declared order. */
113
+ function normalizeOfflineNaturalKey(schema, naturalKey) {
114
+ if (schema.identity.kind !== 'naturalKey') {
115
+ throw new Error(`Offline replica source "${schema.sourceKey}" does not define a naturalKey identity.`);
116
+ }
117
+ if (!isPlainObject$1(naturalKey)) {
118
+ throw new Error(`Offline replica naturalKey for "${schema.sourceKey}" must be a plain object.`);
119
+ }
120
+ const actualKeys = Object.keys(naturalKey);
121
+ if (actualKeys.length !== schema.identity.sourceKeys.length ||
122
+ actualKeys.some((key) => !schema.identity.sourceKeys.includes(key))) {
123
+ throw new Error(`Offline replica naturalKey for "${schema.sourceKey}" must contain exactly its declared fields.`);
124
+ }
125
+ return offlineNaturalKeyFromValues(schema, naturalKey);
126
+ }
127
+ /** Stable, type-tagged identity key used by web uniqueness and pull collapse. */
128
+ function canonicalOfflineRemoteIdentity(schema, identity) {
129
+ if (schema.identity.kind === 'serverId') {
130
+ if (!('serverId' in identity) || 'naturalKey' in identity) {
131
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires serverId identity.`);
132
+ }
133
+ assertPositiveServerId(identity.serverId);
134
+ return `serverId:n:${identity.serverId}`;
135
+ }
136
+ if (schema.identity.kind === 'naturalKey') {
137
+ if (!('naturalKey' in identity) || 'serverId' in identity) {
138
+ throw new Error(`Offline replica source "${schema.sourceKey}" requires naturalKey identity.`);
139
+ }
140
+ const key = normalizeOfflineNaturalKey(schema, identity.naturalKey);
141
+ return `naturalKey:${JSON.stringify(schema.identity.sourceKeys.map((sourceKey) => {
142
+ const value = key[sourceKey];
143
+ return [sourceKey, typeof value === 'number' ? 'n' : 's', value];
144
+ }))}`;
145
+ }
146
+ throw new Error(`Offline replica source "${schema.sourceKey}" is local-only.`);
147
+ }
148
+ /** Enforces one immutable natural identity across optimistic and confirmed row values. */
149
+ function assertOfflineReplicaNaturalKeyBaseline(schema, values, confirmedValues) {
150
+ if (schema.identity.kind !== 'naturalKey' || confirmedValues === null)
151
+ return;
152
+ const current = canonicalOfflineRemoteIdentity(schema, { naturalKey: offlineNaturalKeyFromValues(schema, values) });
153
+ const confirmed = canonicalOfflineRemoteIdentity(schema, {
154
+ naturalKey: offlineNaturalKeyFromValues(schema, confirmedValues),
155
+ });
156
+ if (current !== confirmed) {
157
+ throw new Error(`Offline replica confirmedValues naturalKey must match values for "${schema.sourceKey}".`);
158
+ }
159
+ }
160
+ function assertPositiveServerId(value) {
161
+ if (!Number.isSafeInteger(value) || value <= 0) {
162
+ throw new Error('Offline replica serverId must be a positive integer.');
163
+ }
164
+ }
165
+ function assertNaturalKeyText(sourceKey, value) {
166
+ if (value.includes('\0')) {
167
+ throw new Error(`Offline replica naturalKey field "${sourceKey}" must not contain NUL.`);
168
+ }
169
+ if (/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(value)) {
170
+ throw new Error(`Offline replica naturalKey field "${sourceKey}" must contain well-formed Unicode.`);
171
+ }
172
+ if (new TextEncoder().encode(value).byteLength > MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES) {
173
+ throw new Error(`Offline replica naturalKey field "${sourceKey}" must not exceed ${MAX_OFFLINE_NATURAL_KEY_TEXT_BYTES} UTF-8 bytes.`);
174
+ }
175
+ }
88
176
  /** Excludes a source property from SQLite while retaining it in the select shape. */
89
177
  function ignored(reason) {
90
178
  return { kind: 'ignored', reason };
@@ -96,22 +184,46 @@ function buildOfflineReplicaEntitySchema(definition) {
96
184
  const serverIdCount = sourceKeys.filter((sourceKey) => definition.fields[sourceKey]?.kind === 'serverId').length;
97
185
  if (serverIdCount > 1)
98
186
  throw new Error('Replica entity must define at most one serverId field.');
99
- const hasServerId = serverIdCount === 1;
100
187
  const fields = sourceKeys.map((sourceKey) => {
101
188
  const fieldDef = definition.fields[sourceKey];
102
189
  return materializeFieldDescriptor(sourceKey, fieldDef);
103
190
  });
104
- const createTableSql = buildCreateTableSql(definition.table, definition.scope, fields, hasServerId);
105
- const schemaFingerprintInput = buildSchemaFingerprintInput(definition.table, definition.sourceKey, definition.scope, fields, hasServerId);
191
+ const identity = materializeIdentity(definition.identity, fields);
192
+ const createTableSql = buildCreateTableSql(definition.table, definition.scope, fields, identity);
193
+ const schemaFingerprintInput = buildSchemaFingerprintInput(definition.table, definition.sourceKey, definition.scope, fields, identity);
106
194
  return {
107
195
  tableName: definition.table,
108
196
  sourceKey: definition.sourceKey,
109
197
  scope: definition.scope,
198
+ identity,
110
199
  fields,
111
200
  createTableSql,
112
201
  schemaFingerprintInput,
113
202
  };
114
203
  }
204
+ function materializeIdentity(definition, fields) {
205
+ const serverField = fields.find((field) => field.policy === 'serverId');
206
+ if (definition && serverField)
207
+ throw new Error('Replica entity cannot define both serverId and naturalKey identity.');
208
+ if (serverField)
209
+ return { kind: 'serverId', sourceKeys: [serverField.sourceKey] };
210
+ if (!definition)
211
+ return { kind: 'localOnly', sourceKeys: [] };
212
+ if (definition.sourceKeys.length === 0)
213
+ throw new Error('Replica naturalKey must contain at least one source field.');
214
+ if (new Set(definition.sourceKeys).size !== definition.sourceKeys.length) {
215
+ throw new Error('Replica naturalKey source fields must be unique.');
216
+ }
217
+ for (const sourceKey of definition.sourceKeys) {
218
+ const field = fields.find((candidate) => candidate.sourceKey === sourceKey);
219
+ if (!field)
220
+ throw new Error(`Replica naturalKey field "${sourceKey}" is not defined.`);
221
+ if (field.policy !== 'column' || field.nullable || !['text', 'integer'].includes(field.storageKind ?? '')) {
222
+ throw new Error(`Replica naturalKey field "${sourceKey}" must be a required text or integer column.`);
223
+ }
224
+ }
225
+ return { kind: 'naturalKey', sourceKeys: [...definition.sourceKeys] };
226
+ }
115
227
  function materializeFieldDescriptor(sourceKey, fieldDef) {
116
228
  if (fieldDef.kind === 'ignored') {
117
229
  if (!fieldDef.reason.trim())
@@ -152,12 +264,12 @@ function materializeFieldDescriptor(sourceKey, fieldDef) {
152
264
  ignoredReason: null,
153
265
  };
154
266
  }
155
- function buildCreateTableSql(tableName, scope, fields, hasServerId) {
267
+ function buildCreateTableSql(tableName, scope, fields, identity) {
156
268
  const columnLines = ['local_id TEXT NOT NULL', '_offline_user_id INTEGER NOT NULL'];
157
- if (scope === 'group') {
158
- columnLines.push('_offline_group_id INTEGER NOT NULL');
269
+ if (scope === 'partition') {
270
+ columnLines.push('_offline_scope_id TEXT NOT NULL');
159
271
  }
160
- if (hasServerId) {
272
+ if (identity.kind === 'serverId') {
161
273
  columnLines.push('server_id INTEGER');
162
274
  }
163
275
  columnLines.push('_offline_confirmed_json TEXT', '_offline_server_revision_json TEXT', '_offline_sync_state TEXT NOT NULL', '_offline_fetched_at INTEGER NOT NULL');
@@ -169,13 +281,18 @@ function buildCreateTableSql(tableName, scope, fields, hasServerId) {
169
281
  columnLines.push(`${field.sqliteColumnName} ${field.affinity}${nullability}`);
170
282
  }
171
283
  const statements = [`CREATE TABLE IF NOT EXISTS ${tableName} (\n ${columnLines.join(',\n ')},\n PRIMARY KEY (local_id)\n)`];
172
- if (hasServerId) {
173
- const indexColumns = scope === 'group' ? '_offline_user_id, _offline_group_id, server_id' : '_offline_user_id, server_id';
284
+ if (identity.kind === 'serverId') {
285
+ const indexColumns = scope === 'partition' ? '_offline_user_id, _offline_scope_id, server_id' : '_offline_user_id, server_id';
174
286
  statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_server_id ON ${tableName} (${indexColumns}) WHERE server_id IS NOT NULL`);
175
287
  }
288
+ else if (identity.kind === 'naturalKey') {
289
+ const naturalKeyColumns = identity.sourceKeys.map((sourceKey) => fields.find((field) => field.sourceKey === sourceKey).sqliteColumnName);
290
+ const indexColumns = ['_offline_user_id', ...(scope === 'partition' ? ['_offline_scope_id'] : []), ...naturalKeyColumns].join(', ');
291
+ statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_natural_key ON ${tableName} (${indexColumns})`);
292
+ }
176
293
  return statements;
177
294
  }
178
- function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, hasServerId) {
295
+ function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, identity) {
179
296
  const fieldParts = fields.map((field) => {
180
297
  if (field.policy === 'ignored') {
181
298
  return `${field.sourceKey}:ignored:${field.ignoredReason ?? ''}`;
@@ -189,7 +306,9 @@ function buildSchemaFingerprintInput(tableName, sourceKey, scope, fields, hasSer
189
306
  `table=${tableName}`,
190
307
  `source=${sourceKey}`,
191
308
  `scope=${scope}`,
192
- `hasServerId=${hasServerId ? '1' : '0'}`,
309
+ ...(identity.kind === 'naturalKey'
310
+ ? [`hasServerId=0`, `identity=naturalKey:${identity.sourceKeys.join(',')}`, 'identityCodec=v1']
311
+ : [`hasServerId=${identity.kind === 'serverId' ? '1' : '0'}`]),
193
312
  `fields=${fieldParts.join(';')}`,
194
313
  ].join('|');
195
314
  }
@@ -625,7 +744,7 @@ class IonicOfflineRepository {
625
744
  .filter((row) => {
626
745
  if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
627
746
  return false;
628
- return schema.scope === 'group' ? row.groupId === scope.groupId : true;
747
+ return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
629
748
  })
630
749
  .map((row) => this.#rowForScope(row, schema, scope))
631
750
  .sort((left, right) => left.localId.localeCompare(right.localId));
@@ -640,7 +759,23 @@ class IonicOfflineRepository {
640
759
  const row = Object.values(rows).find((row) => {
641
760
  if (row.sourceKey !== sourceKey || row.userId !== scope.userId || row.serverId !== serverId)
642
761
  return false;
643
- return schema.scope === 'group' ? row.groupId === scope.groupId : true;
762
+ return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
763
+ });
764
+ return row ? this.#rowForScope(row, schema, scope) : null;
765
+ }
766
+ async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
767
+ await this.initialize();
768
+ await this.#writes;
769
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
770
+ const canonical = canonicalOfflineRemoteIdentity(schema, identity);
771
+ const rows = await this.#readRecord(ROWS_KEY);
772
+ const row = Object.values(rows).find((candidate) => {
773
+ if (candidate.sourceKey !== sourceKey || candidate.userId !== scope.userId)
774
+ return false;
775
+ if (schema.scope === 'partition' && candidate.scopeId !== scope.scopeId)
776
+ return false;
777
+ const candidateIdentity = this.#rowRemoteIdentity(schema, candidate);
778
+ return candidateIdentity !== null && canonicalOfflineRemoteIdentity(schema, candidateIdentity) === canonical;
644
779
  });
645
780
  return row ? this.#rowForScope(row, schema, scope) : null;
646
781
  }
@@ -656,7 +791,7 @@ class IonicOfflineRepository {
656
791
  await this.#writes;
657
792
  const commands = await this.#readRecord(OUTBOX_KEY);
658
793
  return Object.values(commands)
659
- .filter((command) => command.userId === scope.userId && command.groupId === scope.groupId)
794
+ .filter((command) => command.userId === scope.userId && command.scopeId === scope.scopeId)
660
795
  .sort(compareOfflineCommands$1);
661
796
  }
662
797
  async getCommandsForUser(userId) {
@@ -701,9 +836,9 @@ class IonicOfflineRepository {
701
836
  await this.#storage.set(METADATA_KEY, { ...metadata, lastUserId: null });
702
837
  }
703
838
  }
704
- async clearGroup(scope) {
839
+ async clearScope(scope) {
705
840
  await this.initialize();
706
- const belongsToGroup = (value) => value.userId === scope.userId && value.groupId === scope.groupId;
841
+ const belongsToGroup = (value) => value.userId === scope.userId && value.scopeId === scope.scopeId;
707
842
  await Promise.all([
708
843
  this.#filterRecord(ROWS_KEY, (value) => {
709
844
  const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
@@ -879,7 +1014,10 @@ class IonicOfflineRepository {
879
1014
  ]);
880
1015
  const identityCheckRows = { ...rows };
881
1016
  for (const row of transaction.putRows ?? []) {
882
- this.#assertUniqueReplicaServerId(identityCheckRows, row);
1017
+ const existing = identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)];
1018
+ if (existing)
1019
+ this.#assertReplicaIdentityAssignment(existing, row);
1020
+ this.#assertUniqueReplicaIdentity(identityCheckRows, row);
883
1021
  identityCheckRows[this.#rowKey(row, row.sourceKey, row.localId)] = row;
884
1022
  }
885
1023
  if (journal)
@@ -888,7 +1026,7 @@ class IonicOfflineRepository {
888
1026
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
889
1027
  rows[this.#rowKey(row, row.sourceKey, row.localId)] = {
890
1028
  ...row,
891
- groupId: schema.scope === 'user' ? 0 : row.groupId,
1029
+ scopeId: schema.scope === 'user' ? '' : row.scopeId,
892
1030
  values: projectOfflineReplicaValues(schema, row.values),
893
1031
  confirmedValues: row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues),
894
1032
  };
@@ -935,17 +1073,17 @@ class IonicOfflineRepository {
935
1073
  }
936
1074
  #rowKey(scope, sourceKey, localId) {
937
1075
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
938
- const partition = schema.scope === 'user' ? 'user' : String(scope.groupId);
1076
+ const partition = schema.scope === 'user' ? 'user' : String(scope.scopeId);
939
1077
  return `${scope.userId}:${partition}:${sourceKey}:${localId}`;
940
1078
  }
941
1079
  #rowForScope(row, schema, scope) {
942
- return schema.scope === 'user' ? { ...row, groupId: scope.groupId } : row;
1080
+ return schema.scope === 'user' ? { ...row, scopeId: scope.scopeId } : row;
943
1081
  }
944
1082
  #cursorKey(scope) {
945
- return `${scope.userId}:${scope.groupId}`;
1083
+ return `${scope.userId}:${scope.scopeId}`;
946
1084
  }
947
1085
  #schemaHasServerId(schema) {
948
- return schema.fields.some((field) => field.policy === 'serverId');
1086
+ return schema.identity.kind === 'serverId';
949
1087
  }
950
1088
  #validateReplicaRow(row) {
951
1089
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
@@ -953,24 +1091,58 @@ class IonicOfflineRepository {
953
1091
  encodeOfflineReplicaValues(schema, row.values);
954
1092
  if (row.confirmedValues !== null)
955
1093
  encodeOfflineReplicaValues(schema, row.confirmedValues);
1094
+ assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
956
1095
  }
957
- #assertUniqueReplicaServerId(rows, incoming) {
958
- if (incoming.serverId === null)
959
- return;
1096
+ #assertUniqueReplicaIdentity(rows, incoming) {
960
1097
  const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1098
+ const identity = this.#rowRemoteIdentity(schema, incoming);
1099
+ if (identity === null)
1100
+ return;
1101
+ const canonical = canonicalOfflineRemoteIdentity(schema, identity);
961
1102
  const incomingKey = this.#rowKey(incoming, incoming.sourceKey, incoming.localId);
962
1103
  const collision = Object.entries(rows).find(([key, row]) => {
963
1104
  if (key === incomingKey)
964
1105
  return false;
965
- if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey || row.serverId !== incoming.serverId) {
1106
+ if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey)
966
1107
  return false;
967
- }
968
- return schema.scope === 'user' || row.groupId === incoming.groupId;
1108
+ if (schema.scope === 'partition' && row.scopeId !== incoming.scopeId)
1109
+ return false;
1110
+ const rowIdentity = this.#rowRemoteIdentity(schema, row);
1111
+ return rowIdentity !== null && canonicalOfflineRemoteIdentity(schema, rowIdentity) === canonical;
969
1112
  });
970
1113
  if (collision) {
971
- throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
1114
+ if (schema.identity.kind === 'serverId') {
1115
+ throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
1116
+ }
1117
+ throw new Error(`Offline replica remote identity is already mapped to localId ${collision[1].localId}.`);
1118
+ }
1119
+ }
1120
+ #assertReplicaIdentityAssignment(existing, incoming) {
1121
+ const schema = this.#resolveReplicaEntitySchema(incoming.sourceKey);
1122
+ if (schema.identity.kind === 'serverId') {
1123
+ if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
1124
+ throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
1125
+ }
1126
+ return;
1127
+ }
1128
+ if (schema.identity.kind === 'naturalKey') {
1129
+ const current = canonicalOfflineRemoteIdentity(schema, {
1130
+ naturalKey: offlineNaturalKeyFromValues(schema, existing.values),
1131
+ });
1132
+ const next = canonicalOfflineRemoteIdentity(schema, {
1133
+ naturalKey: offlineNaturalKeyFromValues(schema, incoming.values),
1134
+ });
1135
+ if (current !== next)
1136
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
972
1137
  }
973
1138
  }
1139
+ #rowRemoteIdentity(schema, row) {
1140
+ if (schema.identity.kind === 'serverId')
1141
+ return row.serverId === null ? null : { serverId: row.serverId };
1142
+ if (schema.identity.kind === 'naturalKey')
1143
+ return { naturalKey: offlineNaturalKeyFromValues(schema, row.values) };
1144
+ return null;
1145
+ }
974
1146
  #resolveReplicaEntitySchema(sourceKey) {
975
1147
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
976
1148
  if (!schema)
@@ -1006,7 +1178,7 @@ class OfflineReplicaPullService {
1006
1178
  this.#assertPullPage(page);
1007
1179
  this.#assertHandshake(page.schemaVersion, page.schemaHash, schemaHash);
1008
1180
  if (page.hasMore && page.nextCursor === cursor) {
1009
- throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.groupId}.`);
1181
+ throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.scopeId}.`);
1010
1182
  }
1011
1183
  const scopeCommands = await this.#repository.getCommands(scope);
1012
1184
  const userCommands = this.#repository.getCommandsForUser ? await this.#repository.getCommandsForUser(scope.userId) : scopeCommands;
@@ -1035,7 +1207,7 @@ class OfflineReplicaPullService {
1035
1207
  }
1036
1208
  const acknowledgedCommand = acknowledged[0];
1037
1209
  const acknowledgedScope = acknowledgedCommand
1038
- ? { userId: acknowledgedCommand.userId, groupId: acknowledgedCommand.groupId }
1210
+ ? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
1039
1211
  : scope;
1040
1212
  const acknowledgedRow = acknowledgedCommand
1041
1213
  ? await this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId)
@@ -1043,9 +1215,13 @@ class OfflineReplicaPullService {
1043
1215
  if (acknowledgedCommand && !acknowledgedRow) {
1044
1216
  throw new Error(`Acknowledged command "${acknowledgedCommand.commandId}" has no local replica row.`);
1045
1217
  }
1046
- const serverRow = await this.#repository.getReplicaRowByServerId(scope, change.sourceKey, change.serverId);
1218
+ const identity = this.#identity(change);
1219
+ const serverRow = await this.#repository.getReplicaRowByRemoteIdentity(scope, change.sourceKey, identity);
1047
1220
  if (acknowledgedRow && serverRow && acknowledgedRow.localId !== serverRow.localId) {
1048
- throw new Error(`Server id ${change.serverId} is already mapped to another local replica row.`);
1221
+ if (identity.serverId !== undefined) {
1222
+ throw new Error(`Server id ${identity.serverId} is already mapped to another local replica row.`);
1223
+ }
1224
+ throw new Error(`Remote identity for "${change.sourceKey}" is already mapped to another local replica row.`);
1049
1225
  }
1050
1226
  const existing = acknowledgedRow ?? serverRow;
1051
1227
  const related = existing
@@ -1075,7 +1251,7 @@ class OfflineReplicaPullService {
1075
1251
  ...scope,
1076
1252
  sourceKey: change.sourceKey,
1077
1253
  localId: crypto.randomUUID(),
1078
- serverId: change.serverId,
1254
+ serverId: identity.serverId ?? null,
1079
1255
  values: confirmedValues,
1080
1256
  confirmedValues,
1081
1257
  serverRevision: change.serverRevision,
@@ -1141,9 +1317,21 @@ class OfflineReplicaPullService {
1141
1317
  if (typeof change['deleted'] !== 'boolean') {
1142
1318
  throw new Error(`${label}.deleted must be a boolean.`);
1143
1319
  }
1144
- const serverId = change['serverId'];
1145
- if (typeof serverId !== 'number' || !Number.isFinite(serverId) || !Number.isSafeInteger(serverId) || serverId <= 0) {
1146
- throw new Error(`${label}.serverId must be a positive integer.`);
1320
+ const schema = this.#entitySchema(change['sourceKey']);
1321
+ if (schema.identity.kind === 'serverId') {
1322
+ const serverId = change['serverId'];
1323
+ if (typeof serverId !== 'number' || !Number.isSafeInteger(serverId) || serverId <= 0) {
1324
+ throw new Error(`${label}.serverId must be a positive integer.`);
1325
+ }
1326
+ if (change['naturalKey'] !== undefined) {
1327
+ throw new Error(`${label}.naturalKey must be omitted for a serverId entity.`);
1328
+ }
1329
+ }
1330
+ try {
1331
+ canonicalOfflineRemoteIdentity(schema, change);
1332
+ }
1333
+ catch (error) {
1334
+ throw new Error(`${label} has invalid remote identity: ${error instanceof Error ? error.message : String(error)}`);
1147
1335
  }
1148
1336
  const revision = change['serverRevision'];
1149
1337
  if (typeof revision !== 'string' && (typeof revision !== 'number' || !Number.isFinite(revision))) {
@@ -1174,14 +1362,26 @@ class OfflineReplicaPullService {
1174
1362
  }
1175
1363
  #validatedValues(schema, change) {
1176
1364
  if (change.values === null) {
1177
- throw new Error(`Offline replica change "${change.sourceKey}"/${change.serverId} is missing values.`);
1365
+ throw new Error(change.serverId === undefined
1366
+ ? `Offline replica change "${change.sourceKey}" is missing values.`
1367
+ : `Offline replica change "${change.sourceKey}"/${change.serverId} is missing values.`);
1368
+ }
1369
+ const values = projectOfflineReplicaValues(schema, change.values);
1370
+ if (schema.identity.kind === 'naturalKey') {
1371
+ const expected = offlineNaturalKeyFromValues(schema, values);
1372
+ const incoming = normalizeOfflineNaturalKey(schema, change.naturalKey);
1373
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: expected }) !==
1374
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: incoming })) {
1375
+ throw new Error(`Offline replica change "${change.sourceKey}" naturalKey does not match values.`);
1376
+ }
1178
1377
  }
1179
- return projectOfflineReplicaValues(schema, change.values);
1378
+ return values;
1180
1379
  }
1181
1380
  #collapseChanges(changes) {
1182
1381
  const collapsed = new Map();
1183
1382
  for (const [ordinal, change] of changes.entries()) {
1184
- const key = `${change.sourceKey}:${change.serverId}`;
1383
+ const schema = this.#entitySchema(change.sourceKey);
1384
+ const key = `${change.sourceKey}:${canonicalOfflineRemoteIdentity(schema, this.#identity(change))}`;
1185
1385
  const previous = collapsed.get(key);
1186
1386
  const acknowledgedCommandIds = [...new Set([...(previous?.acknowledgedCommandIds ?? []), ...(change.acknowledgedCommandIds ?? [])])];
1187
1387
  const acknowledgementOrdinals = { ...(previous?.acknowledgementOrdinals ?? {}) };
@@ -1232,10 +1432,10 @@ class OfflineReplicaPullService {
1232
1432
  }
1233
1433
  const schema = this.#entitySchema(change.sourceKey);
1234
1434
  const confirmedValues = this.#validatedValues(schema, change);
1235
- this.#assertServerIdAssignment(row.serverId, change.serverId);
1435
+ this.#assertIdentityAssignment(schema, row, this.#identity(change));
1236
1436
  putRows.push({
1237
1437
  ...row,
1238
- serverId: change.serverId,
1438
+ serverId: change.serverId ?? null,
1239
1439
  values: following.length > 0 ? following.at(-1).optimisticValue : confirmedValues,
1240
1440
  confirmedValues,
1241
1441
  serverRevision: change.serverRevision,
@@ -1243,9 +1443,21 @@ class OfflineReplicaPullService {
1243
1443
  syncState: following.length > 0 ? (acknowledgementSuperseded ? 'conflict' : 'pending') : 'confirmed',
1244
1444
  });
1245
1445
  }
1246
- #assertServerIdAssignment(current, incoming) {
1247
- if (current !== null && current !== incoming) {
1248
- throw new Error(`Replica serverId is immutable: current=${current}, incoming=${incoming}.`);
1446
+ #identity(change) {
1447
+ return change.serverId !== undefined ? { serverId: change.serverId } : { naturalKey: change.naturalKey };
1448
+ }
1449
+ #assertIdentityAssignment(schema, row, incoming) {
1450
+ if (schema.identity.kind === 'serverId') {
1451
+ const serverId = incoming.serverId;
1452
+ if (row.serverId !== null && row.serverId !== serverId) {
1453
+ throw new Error(`Replica serverId is immutable: current=${row.serverId}, incoming=${serverId}.`);
1454
+ }
1455
+ return;
1456
+ }
1457
+ const current = offlineNaturalKeyFromValues(schema, row.values);
1458
+ if (current !== null &&
1459
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: current }) !== canonicalOfflineRemoteIdentity(schema, incoming)) {
1460
+ throw new Error(`Replica naturalKey is immutable for "${schema.sourceKey}".`);
1249
1461
  }
1250
1462
  }
1251
1463
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineReplicaPullService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
@@ -1347,7 +1559,7 @@ class OfflineSessionService {
1347
1559
  await this.initialize();
1348
1560
  if (lease && !lease.isCurrent())
1349
1561
  return false;
1350
- const normalizedScopeIds = [...new Set(scopeIds)].sort((a, b) => a - b);
1562
+ const normalizedScopeIds = [...new Set(scopeIds)].sort((a, b) => a.localeCompare(b));
1351
1563
  const previousUserId = await this.#repository.getLastUserId();
1352
1564
  if (lease && !lease.isCurrent())
1353
1565
  return false;
@@ -1364,8 +1576,8 @@ class OfflineSessionService {
1364
1576
  }
1365
1577
  const active = new Set(normalizedScopeIds);
1366
1578
  await Promise.all((previous?.scopeIds ?? [])
1367
- .filter((groupId) => !active.has(groupId))
1368
- .map((groupId) => this.#repository.clearGroup({ userId, groupId })));
1579
+ .filter((scopeId) => !active.has(scopeId))
1580
+ .map((scopeId) => this.#repository.clearScope({ userId, scopeId })));
1369
1581
  if (lease && !lease.isCurrent())
1370
1582
  return false;
1371
1583
  const manifest = {
@@ -1454,7 +1666,7 @@ class OfflineSessionService {
1454
1666
  #sessionFromManifest() {
1455
1667
  const manifest = this.#activeManifest();
1456
1668
  return manifest
1457
- ? { userId: manifest.userId, scopes: manifest.scopeIds.map((groupId) => ({ userId: manifest.userId, groupId })) }
1669
+ ? { userId: manifest.userId, scopes: manifest.scopeIds.map((scopeId) => ({ userId: manifest.userId, scopeId })) }
1458
1670
  : null;
1459
1671
  }
1460
1672
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSessionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
@@ -1609,7 +1821,7 @@ class OfflineSyncService {
1609
1821
  throw new Error('Cannot enqueue an offline command without an authenticated user');
1610
1822
  const userId = session.userId;
1611
1823
  this.#setActiveUser(userId);
1612
- const scope = { userId, groupId: request.groupId };
1824
+ const scope = { userId, scopeId: request.scopeId };
1613
1825
  this.noteScope(scope);
1614
1826
  const aggregateLocalId = request.aggregateLocalId;
1615
1827
  const normalized = await this.#normalizeEnqueueRequest(scope, request);
@@ -1633,12 +1845,34 @@ class OfflineSyncService {
1633
1845
  };
1634
1846
  await this.#assertOutboxCapacity(userId, command);
1635
1847
  const entityType = this.#entityType(command);
1848
+ const schema = this.#entitySchema(entityType);
1636
1849
  const existing = await this.#repository.getReplicaRow(scope, entityType, aggregateLocalId);
1637
1850
  const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
1638
- if (initialServerId !== null) {
1639
- const mapped = await this.#repository.getReplicaRowByServerId(scope, entityType, initialServerId);
1851
+ const naturalKey = offlineNaturalKeyFromValues(schema, optimisticValue);
1852
+ const remoteIdentity = schema.identity.kind === 'serverId'
1853
+ ? initialServerId === null
1854
+ ? null
1855
+ : { serverId: initialServerId }
1856
+ : schema.identity.kind === 'naturalKey'
1857
+ ? { naturalKey: naturalKey }
1858
+ : null;
1859
+ if (schema.identity.kind === 'naturalKey' && request.serverId != null) {
1860
+ throw new Error(`Offline replica source "${entityType}" does not define a serverId field.`);
1861
+ }
1862
+ if (schema.identity.kind === 'naturalKey') {
1863
+ const canonicalValuesKey = canonicalOfflineRemoteIdentity(schema, remoteIdentity);
1864
+ if (existing &&
1865
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: offlineNaturalKeyFromValues(schema, existing.values) }) !== canonicalValuesKey) {
1866
+ throw new Error(`Offline replica naturalKey is immutable and must match optimistic values for "${entityType}".`);
1867
+ }
1868
+ }
1869
+ if (remoteIdentity !== null) {
1870
+ const mapped = await this.#repository.getReplicaRowByRemoteIdentity(scope, entityType, remoteIdentity);
1640
1871
  if (mapped !== null && mapped.localId !== aggregateLocalId) {
1641
- throw new Error(`Offline replica serverId ${String(initialServerId)} is already mapped to localId ${mapped.localId}.`);
1872
+ if (remoteIdentity.serverId !== undefined) {
1873
+ throw new Error(`Offline replica serverId ${String(remoteIdentity.serverId)} is already mapped to localId ${mapped.localId}.`);
1874
+ }
1875
+ throw new Error(`Offline replica remote identity is already mapped to localId ${mapped.localId}.`);
1642
1876
  }
1643
1877
  }
1644
1878
  const optimisticRow = {
@@ -1791,7 +2025,13 @@ class OfflineSyncService {
1791
2025
  throw new Error(`Offline replica row not found: ${sending.aggregateType}/${sending.aggregateLocalId}`);
1792
2026
  let result;
1793
2027
  try {
1794
- result = await this.#executor.execute(sending, { localId: row.localId, serverId: row.serverId });
2028
+ const schema = this.#entitySchema(row.sourceKey);
2029
+ const naturalKey = offlineNaturalKeyFromValues(schema, row.values);
2030
+ result = await this.#executor.execute(sending, {
2031
+ localId: row.localId,
2032
+ serverId: row.serverId,
2033
+ ...(naturalKey !== null ? { naturalKey } : {}),
2034
+ });
1795
2035
  }
1796
2036
  catch (error) {
1797
2037
  if (!this.#isCurrent(generation))
@@ -1838,6 +2078,8 @@ class OfflineSyncService {
1838
2078
  }
1839
2079
  this.#assertServerRevision(result.serverRevision);
1840
2080
  const confirmedValues = result.confirmedValues ?? command.optimisticValue;
2081
+ const schema = this.#entitySchema(current.sourceKey);
2082
+ this.#assertCommandResultIdentity(schema, current, result);
1841
2083
  const serverId = this.#resolvedServerId(current.serverId, result.serverId);
1842
2084
  const row = {
1843
2085
  ...current,
@@ -1858,7 +2100,7 @@ class OfflineSyncService {
1858
2100
  });
1859
2101
  }
1860
2102
  async #rowForCommand(command) {
1861
- const scope = { userId: command.userId, groupId: command.groupId };
2103
+ const scope = { userId: command.userId, scopeId: command.scopeId };
1862
2104
  const entityType = this.#entityType(command);
1863
2105
  return this.#repository.getReplicaRow(scope, entityType, command.aggregateLocalId);
1864
2106
  }
@@ -1870,6 +2112,12 @@ class OfflineSyncService {
1870
2112
  #entityType(command) {
1871
2113
  return this.#hooks.entityType(command);
1872
2114
  }
2115
+ #entitySchema(sourceKey) {
2116
+ const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
2117
+ if (!schema)
2118
+ throw new Error(`Unknown offline replica source key "${sourceKey}".`);
2119
+ return schema;
2120
+ }
1873
2121
  async #discardCommands(discarded) {
1874
2122
  const all = await this.#readKnownCommands();
1875
2123
  const discardedIds = new Set(discarded.map((command) => command.commandId));
@@ -1905,7 +2153,7 @@ class OfflineSyncService {
1905
2153
  const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
1906
2154
  if (!schema)
1907
2155
  throw new Error(`Unknown offline replica source key "${sourceKey}".`);
1908
- const partition = schema.scope === 'user' ? 'user' : `group:${command.groupId}`;
2156
+ const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
1909
2157
  return `${command.userId}:${partition}:${sourceKey}:${command.aggregateLocalId}`;
1910
2158
  }
1911
2159
  #failedCommand(command, error) {
@@ -1951,6 +2199,23 @@ class OfflineSyncService {
1951
2199
  #initialServerId(current, incoming) {
1952
2200
  return incoming === null || incoming === undefined ? current : this.#resolvedServerId(current, incoming);
1953
2201
  }
2202
+ #assertCommandResultIdentity(schema, current, result) {
2203
+ if (schema.identity.kind === 'naturalKey' && result.serverId !== undefined) {
2204
+ throw new Error(`Offline command returned serverId for naturalKey source "${schema.sourceKey}".`);
2205
+ }
2206
+ if (schema.identity.kind !== 'serverId' && result.serverId !== undefined) {
2207
+ throw new Error(`Offline command returned serverId for source "${schema.sourceKey}" without serverId identity.`);
2208
+ }
2209
+ if (schema.identity.kind === 'naturalKey') {
2210
+ const confirmedValues = result.confirmedValues ?? current.values;
2211
+ const currentKey = offlineNaturalKeyFromValues(schema, current.values);
2212
+ const confirmedKey = offlineNaturalKeyFromValues(schema, confirmedValues);
2213
+ if (canonicalOfflineRemoteIdentity(schema, { naturalKey: currentKey }) !==
2214
+ canonicalOfflineRemoteIdentity(schema, { naturalKey: confirmedKey })) {
2215
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
2216
+ }
2217
+ }
2218
+ }
1954
2219
  async #discoverScopes(generation = this.#generation) {
1955
2220
  const session = await this.#context.getSession();
1956
2221
  if (!this.#isCurrent(generation))
@@ -2080,7 +2345,7 @@ class OfflineSyncService {
2080
2345
  return serialized;
2081
2346
  }
2082
2347
  #scopeKey(scope) {
2083
- return `${scope.userId}:${scope.groupId}`;
2348
+ return `${scope.userId}:${scope.scopeId}`;
2084
2349
  }
2085
2350
  static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
2086
2351
  static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, providedIn: 'root' }); }
@@ -2289,8 +2554,8 @@ function assertOfflineRemoteIdentity(identity) {
2289
2554
  if (!Number.isSafeInteger(identity.userId) || identity.userId <= 0) {
2290
2555
  throw new Error('Offline remote identity userId must be a positive safe integer.');
2291
2556
  }
2292
- if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => !Number.isSafeInteger(scopeId) || scopeId < 0)) {
2293
- throw new Error('Offline remote identity scopeIds must contain only non-negative safe integers.');
2557
+ if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)) {
2558
+ throw new Error('Offline remote identity scopeIds must contain only non-empty strings.');
2294
2559
  }
2295
2560
  if (typeof identity.authSubject !== 'string' || identity.authSubject.length === 0) {
2296
2561
  throw new Error('Offline remote identity authSubject must be a non-empty string.');
@@ -2386,7 +2651,7 @@ const SCHEMA = [
2386
2651
  `CREATE TABLE IF NOT EXISTS offline_sync_commands (
2387
2652
  command_id TEXT PRIMARY KEY,
2388
2653
  user_id INTEGER NOT NULL,
2389
- group_id INTEGER NOT NULL,
2654
+ scope_id TEXT NOT NULL,
2390
2655
  aggregate_type TEXT NOT NULL,
2391
2656
  aggregate_local_id TEXT NOT NULL,
2392
2657
  operation TEXT NOT NULL,
@@ -2401,7 +2666,7 @@ const SCHEMA = [
2401
2666
  last_error_code TEXT
2402
2667
  )`,
2403
2668
  `CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created
2404
- ON offline_sync_commands (user_id, group_id, created_at)`,
2669
+ ON offline_sync_commands (user_id, scope_id, created_at)`,
2405
2670
  `CREATE TABLE IF NOT EXISTS offline_replica_schema_metadata (
2406
2671
  id INTEGER PRIMARY KEY CHECK (id = 1),
2407
2672
  version INTEGER NOT NULL,
@@ -2409,9 +2674,9 @@ const SCHEMA = [
2409
2674
  )`,
2410
2675
  `CREATE TABLE IF NOT EXISTS offline_replica_cursors (
2411
2676
  user_id INTEGER NOT NULL,
2412
- group_id INTEGER NOT NULL,
2677
+ scope_id TEXT NOT NULL,
2413
2678
  cursor TEXT NOT NULL,
2414
- PRIMARY KEY (user_id, group_id)
2679
+ PRIMARY KEY (user_id, scope_id)
2415
2680
  )`,
2416
2681
  ];
2417
2682
  /** Native iOS/Android repository backed by encrypted `@capacitor-community/sqlite`. */
@@ -2446,9 +2711,9 @@ class SqliteOfflineRepository {
2446
2711
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
2447
2712
  const predicates = ['local_id = ?', '_offline_user_id = ?'];
2448
2713
  const values = [localId, scope.userId];
2449
- if (schema.scope === 'group') {
2450
- predicates.push('_offline_group_id = ?');
2451
- values.push(scope.groupId);
2714
+ if (schema.scope === 'partition') {
2715
+ predicates.push('_offline_scope_id = ?');
2716
+ values.push(scope.scopeId);
2452
2717
  }
2453
2718
  const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2454
2719
  const row = rows[0];
@@ -2460,9 +2725,9 @@ class SqliteOfflineRepository {
2460
2725
  const schema = this.#resolveReplicaEntitySchema(sourceKey);
2461
2726
  const predicates = ['_offline_user_id = ?'];
2462
2727
  const values = [scope.userId];
2463
- if (schema.scope === 'group') {
2464
- predicates.push('_offline_group_id = ?');
2465
- values.push(scope.groupId);
2728
+ if (schema.scope === 'partition') {
2729
+ predicates.push('_offline_scope_id = ?');
2730
+ values.push(scope.scopeId);
2466
2731
  }
2467
2732
  const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY local_id ASC`, values);
2468
2733
  return rows.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row));
@@ -2473,9 +2738,33 @@ class SqliteOfflineRepository {
2473
2738
  return null;
2474
2739
  const predicates = ['server_id = ?', '_offline_user_id = ?'];
2475
2740
  const values = [serverId, scope.userId];
2476
- if (schema.scope === 'group') {
2477
- predicates.push('_offline_group_id = ?');
2478
- values.push(scope.groupId);
2741
+ if (schema.scope === 'partition') {
2742
+ predicates.push('_offline_scope_id = ?');
2743
+ values.push(scope.scopeId);
2744
+ }
2745
+ const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2746
+ const row = rows[0];
2747
+ if (!row)
2748
+ return null;
2749
+ return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
2750
+ }
2751
+ async getReplicaRowByRemoteIdentity(scope, sourceKey, identity) {
2752
+ const schema = this.#resolveReplicaEntitySchema(sourceKey);
2753
+ canonicalOfflineRemoteIdentity(schema, identity);
2754
+ if (schema.identity.kind === 'serverId') {
2755
+ return this.getReplicaRowByServerId(scope, sourceKey, identity.serverId);
2756
+ }
2757
+ const naturalKey = normalizeOfflineNaturalKey(schema, identity.naturalKey);
2758
+ const predicates = ['_offline_user_id = ?'];
2759
+ const values = [scope.userId];
2760
+ if (schema.scope === 'partition') {
2761
+ predicates.push('_offline_scope_id = ?');
2762
+ values.push(scope.scopeId);
2763
+ }
2764
+ for (const sourceKeyPart of schema.identity.sourceKeys) {
2765
+ const field = schema.fields.find((candidate) => candidate.sourceKey === sourceKeyPart);
2766
+ predicates.push(`${field.sqliteColumnName} = ?`);
2767
+ values.push(naturalKey[sourceKeyPart]);
2479
2768
  }
2480
2769
  const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2481
2770
  const row = rows[0];
@@ -2484,9 +2773,9 @@ class SqliteOfflineRepository {
2484
2773
  return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
2485
2774
  }
2486
2775
  async getReplicaCursor(scope) {
2487
- const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND group_id = ?', [
2776
+ const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
2488
2777
  scope.userId,
2489
- scope.groupId,
2778
+ scope.scopeId,
2490
2779
  ]);
2491
2780
  const row = rows[0];
2492
2781
  if (!row)
@@ -2494,7 +2783,7 @@ class SqliteOfflineRepository {
2494
2783
  return { ...scope, cursor: this.#string(row['cursor']) };
2495
2784
  }
2496
2785
  async getCommands(scope) {
2497
- const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND group_id = ? ORDER BY created_at ASC, command_id ASC', [scope.userId, scope.groupId]);
2786
+ const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND scope_id = ? ORDER BY created_at ASC, command_id ASC', [scope.userId, scope.scopeId]);
2498
2787
  return rows.map((row) => this.#command(row));
2499
2788
  }
2500
2789
  async getCommandsForUser(userId) {
@@ -2523,15 +2812,15 @@ class SqliteOfflineRepository {
2523
2812
  await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [userId]);
2524
2813
  });
2525
2814
  }
2526
- async clearGroup(scope) {
2815
+ async clearScope(scope) {
2527
2816
  await this.#transaction(async (database) => {
2528
- const values = [scope.userId, scope.groupId];
2529
- await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ? AND group_id = ?', values);
2530
- await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND group_id = ?', values);
2817
+ const values = [scope.userId, scope.scopeId];
2818
+ await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ? AND scope_id = ?', values);
2819
+ await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
2531
2820
  for (const entity of this.#options.replicaSchema.entities) {
2532
- if (entity.scope !== 'group')
2821
+ if (entity.scope !== 'partition')
2533
2822
  continue;
2534
- await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_group_id = ?`, values);
2823
+ await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);
2535
2824
  }
2536
2825
  });
2537
2826
  }
@@ -2671,7 +2960,7 @@ class SqliteOfflineRepository {
2671
2960
  return {
2672
2961
  commandId: this.#string(row['command_id']),
2673
2962
  userId: this.#number(row['user_id']),
2674
- groupId: this.#number(row['group_id']),
2963
+ scopeId: this.#string(row['scope_id']),
2675
2964
  aggregateType: this.#string(row['aggregate_type']),
2676
2965
  aggregateLocalId: this.#string(row['aggregate_local_id']),
2677
2966
  operation: this.#string(row['operation']),
@@ -2688,18 +2977,18 @@ class SqliteOfflineRepository {
2688
2977
  }
2689
2978
  #putCommand(databaseId, command) {
2690
2979
  return this.#execute(databaseId, `INSERT INTO offline_sync_commands
2691
- (command_id, user_id, group_id, aggregate_type, aggregate_local_id, operation, payload_json, optimistic_value_json,
2980
+ (command_id, user_id, scope_id, aggregate_type, aggregate_local_id, operation, payload_json, optimistic_value_json,
2692
2981
  payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
2693
2982
  VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2694
2983
  ON CONFLICT(command_id) DO UPDATE SET
2695
- user_id = excluded.user_id, group_id = excluded.group_id, aggregate_type = excluded.aggregate_type,
2984
+ user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
2696
2985
  aggregate_local_id = excluded.aggregate_local_id, operation = excluded.operation, payload_json = excluded.payload_json,
2697
2986
  optimistic_value_json = excluded.optimistic_value_json, payload_hash = excluded.payload_hash,
2698
2987
  base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
2699
2988
  retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
2700
2989
  command.commandId,
2701
2990
  command.userId,
2702
- command.groupId,
2991
+ command.scopeId,
2703
2992
  command.aggregateType,
2704
2993
  command.aggregateLocalId,
2705
2994
  command.operation,
@@ -2714,16 +3003,22 @@ class SqliteOfflineRepository {
2714
3003
  command.lastErrorCode,
2715
3004
  ]);
2716
3005
  }
2717
- #putReplicaRow(databaseId, row) {
3006
+ async #putReplicaRow(databaseId, row) {
2718
3007
  const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
2719
3008
  assertOfflineReplicaServerId(schema, row.serverId);
2720
3009
  const encoded = encodeOfflineReplicaValues(schema, row.values);
3010
+ if (row.confirmedValues !== null)
3011
+ encodeOfflineReplicaValues(schema, row.confirmedValues);
3012
+ assertOfflineReplicaNaturalKeyBaseline(schema, row.values, row.confirmedValues);
3013
+ const existing = await this.getReplicaRow(row, row.sourceKey, row.localId);
3014
+ if (existing)
3015
+ this.#assertReplicaIdentityAssignment(schema, existing, row);
2721
3016
  const confirmedValues = row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues);
2722
3017
  const { sql, domainColumns } = this.#buildReplicaUpsertStatement(schema);
2723
3018
  const values = [
2724
3019
  row.localId,
2725
3020
  row.userId,
2726
- ...(schema.scope === 'group' ? [row.groupId] : []),
3021
+ ...(schema.scope === 'partition' ? [row.scopeId] : []),
2727
3022
  ...(this.#schemaHasServerId(schema) ? [row.serverId] : []),
2728
3023
  confirmedValues === null ? null : JSON.stringify(confirmedValues),
2729
3024
  row.serverRevision == null ? null : JSON.stringify(row.serverRevision),
@@ -2731,28 +3026,28 @@ class SqliteOfflineRepository {
2731
3026
  row.fetchedAt,
2732
3027
  ...domainColumns.map((column) => encoded[column] ?? null),
2733
3028
  ];
2734
- return this.#execute(databaseId, sql, values);
3029
+ await this.#execute(databaseId, sql, values);
2735
3030
  }
2736
3031
  #removeReplicaRow(databaseId, key) {
2737
3032
  const schema = this.#resolveReplicaEntitySchema(key.sourceKey);
2738
3033
  const predicates = ['local_id = ?', '_offline_user_id = ?'];
2739
3034
  const values = [key.localId, key.userId];
2740
- if (schema.scope === 'group') {
2741
- predicates.push('_offline_group_id = ?');
2742
- values.push(key.groupId);
3035
+ if (schema.scope === 'partition') {
3036
+ predicates.push('_offline_scope_id = ?');
3037
+ values.push(key.scopeId);
2743
3038
  }
2744
3039
  return this.#execute(databaseId, `DELETE FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
2745
3040
  }
2746
3041
  #putReplicaCursor(databaseId, cursor) {
2747
- return this.#execute(databaseId, `INSERT INTO offline_replica_cursors (user_id, group_id, cursor) VALUES (?, ?, ?)
2748
- ON CONFLICT(user_id, group_id) DO UPDATE SET cursor = excluded.cursor`, [cursor.userId, cursor.groupId, cursor.cursor]);
3042
+ return this.#execute(databaseId, `INSERT INTO offline_replica_cursors (user_id, scope_id, cursor) VALUES (?, ?, ?)
3043
+ ON CONFLICT(user_id, scope_id) DO UPDATE SET cursor = excluded.cursor`, [cursor.userId, cursor.scopeId, cursor.cursor]);
2749
3044
  }
2750
3045
  #buildReplicaUpsertStatement(schema) {
2751
3046
  const insertColumns = ['local_id', '_offline_user_id'];
2752
3047
  const updateSets = ['_offline_user_id = excluded._offline_user_id'];
2753
- if (schema.scope === 'group') {
2754
- insertColumns.push('_offline_group_id');
2755
- updateSets.push('_offline_group_id = excluded._offline_group_id');
3048
+ if (schema.scope === 'partition') {
3049
+ insertColumns.push('_offline_scope_id');
3050
+ updateSets.push('_offline_scope_id = excluded._offline_scope_id');
2756
3051
  }
2757
3052
  if (this.#schemaHasServerId(schema)) {
2758
3053
  insertColumns.push('server_id');
@@ -2796,7 +3091,25 @@ class SqliteOfflineRepository {
2796
3091
  return schema;
2797
3092
  }
2798
3093
  #schemaHasServerId(schema) {
2799
- return schema.fields.some((field) => field.policy === 'serverId');
3094
+ return schema.identity.kind === 'serverId';
3095
+ }
3096
+ #assertReplicaIdentityAssignment(schema, existing, incoming) {
3097
+ if (schema.identity.kind === 'serverId') {
3098
+ if (existing.serverId !== null && existing.serverId !== incoming.serverId) {
3099
+ throw new Error(`Offline replica serverId is immutable: current=${existing.serverId}, incoming=${String(incoming.serverId)}.`);
3100
+ }
3101
+ return;
3102
+ }
3103
+ if (schema.identity.kind === 'naturalKey') {
3104
+ const current = canonicalOfflineRemoteIdentity(schema, {
3105
+ naturalKey: offlineNaturalKeyFromValues(schema, existing.values),
3106
+ });
3107
+ const next = canonicalOfflineRemoteIdentity(schema, {
3108
+ naturalKey: offlineNaturalKeyFromValues(schema, incoming.values),
3109
+ });
3110
+ if (current !== next)
3111
+ throw new Error(`Offline replica naturalKey is immutable for "${schema.sourceKey}".`);
3112
+ }
2800
3113
  }
2801
3114
  async #execute(databaseId, statement, values = []) {
2802
3115
  await this.#sqlite.execute({ databaseId, statement, values });
@@ -2944,5 +3257,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
2944
3257
  * Generated bundle index. Do not edit.
2945
3258
  */
2946
3259
 
2947
- export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaServerId, booleanColumn, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, nullable, offlineInterceptor, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
3260
+ export { COMMUNITY_SQLITE, DEFAULT_OFFLINE_COMMAND_HOOKS, IonicOfflineRepository, OFFLINE_BYPASS, OFFLINE_COMMAND_EXECUTOR, OFFLINE_COMMAND_HOOKS, OFFLINE_KIT_OPTIONS, OFFLINE_REPLICA_PULLER, OFFLINE_REPOSITORY, OFFLINE_REQUEST_POLICIES, OFFLINE_RESPONSE_HEADER, OFFLINE_SCHEMA_VERSION, OFFLINE_SYNC_CONTEXT, OfflineCoordinatorService, OfflineNetworkService, OfflineOutboxCapacityError, OfflinePayloadValidationError, OfflineReplicaPullService, OfflineRequestFallbackService, OfflineRequestPolicyRegistry, OfflineSessionService, OfflineSyncService, SqliteOfflineRepository, assertOfflineReplicaNaturalKeyBaseline, assertOfflineReplicaServerId, booleanColumn, canonicalOfflineRemoteIdentity, createCommunitySqliteDriver, createOfflineAuthBridge, datetime, decodeOfflineReplicaValues, defineOfflineReplicaSchema, defineReplicaEntity, encodeOfflineReplicaValues, ignored, integer, isOfflineFallbackError, json, naturalKey, normalizeOfflineNaturalKey, nullable, offlineInterceptor, offlineNaturalKeyFromValues, projectOfflineReplicaValues, provideOffline, provideOfflineRequestPolicy, real, selectOfflineRepository, serverId, sha256OfflineReplicaSchema, text };
2948
3261
  //# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map