@rdlabo/ionic-angular-kit 21.5.4 → 21.5.6
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.
package/README.md
CHANGED
|
@@ -291,7 +291,7 @@ export const appConfig: ApplicationConfig = {
|
|
|
291
291
|
// const session = await auth.exchangeCredential();
|
|
292
292
|
// return {
|
|
293
293
|
// activate: (lease) => offline.prepareRemoteSession(
|
|
294
|
-
// session.userId, session.
|
|
294
|
+
// session.userId, session.scopeIds, session.subject, lease,
|
|
295
295
|
// ),
|
|
296
296
|
// resume: () => offline.resumeRemoteSession(),
|
|
297
297
|
// };
|
|
@@ -310,7 +310,7 @@ export const appConfig: ApplicationConfig = {
|
|
|
310
310
|
// return session
|
|
311
311
|
// ? {
|
|
312
312
|
// activate: (lease) => offline.prepareRemoteSession(
|
|
313
|
-
// session.userId, session.
|
|
313
|
+
// session.userId, session.scopeIds, session.subject, lease,
|
|
314
314
|
// ),
|
|
315
315
|
// resume: () => offline.resumeRemoteSession(),
|
|
316
316
|
// }
|
|
@@ -389,7 +389,7 @@ A fleet-canonical HTTP interceptor with:
|
|
|
389
389
|
|
|
390
390
|
### Scoped local replica and outbox (`@rdlabo/ionic-angular-kit/offline`)
|
|
391
391
|
|
|
392
|
-
The optional `offline` entry point provides a user/
|
|
392
|
+
The optional `offline` entry point provides a user/partition-scoped local replica, durable outbox, authenticated
|
|
393
393
|
session boundary, cursor-based delta pull, aggregate-ordered replay, optimistic updates, retry classification, and a
|
|
394
394
|
read-only request-policy interceptor. Applications provide URL/DTO read policies, a replica puller, and a command
|
|
395
395
|
executor through `provideOffline(...)`.
|
|
@@ -401,8 +401,8 @@ For cold-start offline route access, `OfflineCoordinatorService.activateOfflineS
|
|
|
401
401
|
that is bound to a non-null authentication-provider subject. Supplying a currently known subject also rejects a
|
|
402
402
|
different user on a shared device. It activates local replica writes and durable outbox enqueue, but remote pull and
|
|
403
403
|
command replay remain disabled until online authentication completes the ordered
|
|
404
|
-
`prepareRemoteSession(...)` → publish `remote` → `resumeRemoteSession()` transition. `activateSession(...)`
|
|
405
|
-
available as a
|
|
404
|
+
`prepareRemoteSession(...)` → publish `remote` → `resumeRemoteSession()` transition. `activateSession(...)` is
|
|
405
|
+
available as a one-step API for callers that do not enforce shared access mode.
|
|
406
406
|
Explicit sign-out must first call `KitAuthAccessService.clear()` and then await `clearActiveSession()`. The first
|
|
407
407
|
step immediately invalidates every in-flight auth lease; the second serializes cleanup after local persistence
|
|
408
408
|
already in progress and removes the manifest and user replica.
|
|
@@ -430,8 +430,9 @@ provideKitAuth(() => ({
|
|
|
430
430
|
ordering via `KitRemoteAccessRecovery`. Product code keeps consent, error UI, and credential mapping inside
|
|
431
431
|
`exchange(context)` (`phase: 'authorize' | 'recover'`, optional route state, lease). Return `null`/`false` to decline
|
|
432
432
|
without throwing; thrown errors are never swallowed and remain available to the guard's unavailable/denial
|
|
433
|
-
classification. The returned identity requires a positive `userId`, non-
|
|
434
|
-
|
|
433
|
+
classification. The returned identity requires a positive `userId`, non-empty string `scopeIds`, and a non-empty
|
|
434
|
+
`authSubject`. A scope may be a numeric database id serialized as a string or a domain UUID such as an organization
|
|
435
|
+
or venue id. The bridge compares the subject before
|
|
435
436
|
session activation, immediately before the coordinator commits through a composite lease, and around remote resume.
|
|
436
437
|
Optional `isIdentityCurrent` can add provider object-identity checks. `onRemoteResumed` receives the identity, phase,
|
|
437
438
|
route state, and post-grant lease for safe redirects or other product side effects. Default recovery availability
|
|
@@ -520,6 +521,13 @@ The write lifecycle is: update the replica immediately → append an outbox comm
|
|
|
520
521
|
the optimistic value → replay in the background → validate the server revision → store the confirmed value and
|
|
521
522
|
revision. The server remains authoritative; SQLite is the durable local working database, not an HTTP response cache.
|
|
522
523
|
|
|
524
|
+
The runtime retains pending, rejected, and conflicted commands until synchronization or an explicit user discard;
|
|
525
|
+
it never evicts an unconfirmed mutation because of age or storage pressure. To keep a device that remains offline for
|
|
526
|
+
months from exhausting SQLite, enqueue applies backpressure at 1,000 commands or 10 MiB per user by default. Products
|
|
527
|
+
may lower these limits with `outboxLimits: { maxCommandsPerUser, maxBytesPerUser }`. When a limit is reached, the
|
|
528
|
+
existing replica and Outbox remain unchanged and enqueue rejects with `OfflineOutboxCapacityError`, so the UI can ask
|
|
529
|
+
the user to reconnect or resolve/discard an attention item.
|
|
530
|
+
|
|
523
531
|
`serverId()` supports positive safe integers only. Products must expose an internal numeric primary key for a
|
|
524
532
|
replicated entity; a human-facing string such as a public code, slip number, or SKU remains an ordinary replicated
|
|
525
533
|
column. There is intentionally no text-server-id overload.
|
|
@@ -530,7 +538,7 @@ omitted id would otherwise make the executor interpret the row as a not-yet-crea
|
|
|
530
538
|
|
|
531
539
|
```ts
|
|
532
540
|
await offlineSync.enqueue({
|
|
533
|
-
|
|
541
|
+
scopeId,
|
|
534
542
|
aggregateType: 'items',
|
|
535
543
|
aggregateLocalId: localId,
|
|
536
544
|
serverId: existingApiItem.id,
|
|
@@ -542,13 +550,14 @@ await offlineSync.enqueue({
|
|
|
542
550
|
|
|
543
551
|
The mapping is immutable and unique inside its effective replica scope. Reassigning one `localId` to another
|
|
544
552
|
`serverId`, or assigning the same `serverId` to another `localId`, rejects before persistence. Web storage enforces
|
|
545
|
-
the same rule transactionally as SQLite's unique indexes:
|
|
546
|
-
and user-scoped entities are unique per user/source across
|
|
553
|
+
the same rule transactionally as SQLite's unique indexes: partition-scoped entities are unique per
|
|
554
|
+
user/partition/source, and user-scoped entities are unique per user/source across partitions. If an adopted row has
|
|
555
|
+
no confirmed baseline and
|
|
547
556
|
its final command is discarded, the local row is removed; the next pull may materialize the authoritative server
|
|
548
557
|
row again. A row with a confirmed baseline rolls back to that baseline instead.
|
|
549
558
|
|
|
550
559
|
Each synchronization cycle pulls authoritative server deltas before replaying the outbox. Every page carries the
|
|
551
|
-
replica schema version/hash and advances a durable user/
|
|
560
|
+
replica schema version/hash and advances a durable user/partition cursor in the same transaction as its rows. A schema
|
|
552
561
|
mismatch, malformed row, or non-advancing cursor rejects synchronization without advancing that cursor. If a remote
|
|
553
562
|
revision changed while a local command is pending, the optimistic row remains visible and both row and command move
|
|
554
563
|
to `conflict`; the new server value is retained as the confirmed baseline.
|
|
@@ -577,7 +586,7 @@ import type { Items as ItemSelect } from '@product/hono/db/schema';
|
|
|
577
586
|
const itemEntityV2 = defineReplicaEntity<ItemSelect>()({
|
|
578
587
|
table: 'items',
|
|
579
588
|
sourceKey: 'items',
|
|
580
|
-
scope: '
|
|
589
|
+
scope: 'partition',
|
|
581
590
|
fields: {
|
|
582
591
|
id: serverId(),
|
|
583
592
|
title: text(),
|
|
@@ -13,7 +13,7 @@ const IDENTIFIER_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
|
13
13
|
const RESERVED_COLUMN_NAMES = new Set([
|
|
14
14
|
'local_id',
|
|
15
15
|
'_offline_user_id',
|
|
16
|
-
'
|
|
16
|
+
'_offline_scope_id',
|
|
17
17
|
'server_id',
|
|
18
18
|
'_offline_confirmed_json',
|
|
19
19
|
'_offline_server_revision_json',
|
|
@@ -154,8 +154,8 @@ function materializeFieldDescriptor(sourceKey, fieldDef) {
|
|
|
154
154
|
}
|
|
155
155
|
function buildCreateTableSql(tableName, scope, fields, hasServerId) {
|
|
156
156
|
const columnLines = ['local_id TEXT NOT NULL', '_offline_user_id INTEGER NOT NULL'];
|
|
157
|
-
if (scope === '
|
|
158
|
-
columnLines.push('
|
|
157
|
+
if (scope === 'partition') {
|
|
158
|
+
columnLines.push('_offline_scope_id TEXT NOT NULL');
|
|
159
159
|
}
|
|
160
160
|
if (hasServerId) {
|
|
161
161
|
columnLines.push('server_id INTEGER');
|
|
@@ -170,7 +170,7 @@ function buildCreateTableSql(tableName, scope, fields, hasServerId) {
|
|
|
170
170
|
}
|
|
171
171
|
const statements = [`CREATE TABLE IF NOT EXISTS ${tableName} (\n ${columnLines.join(',\n ')},\n PRIMARY KEY (local_id)\n)`];
|
|
172
172
|
if (hasServerId) {
|
|
173
|
-
const indexColumns = scope === '
|
|
173
|
+
const indexColumns = scope === 'partition' ? '_offline_user_id, _offline_scope_id, server_id' : '_offline_user_id, server_id';
|
|
174
174
|
statements.push(`CREATE UNIQUE INDEX IF NOT EXISTS uq_${tableName}_server_id ON ${tableName} (${indexColumns}) WHERE server_id IS NOT NULL`);
|
|
175
175
|
}
|
|
176
176
|
return statements;
|
|
@@ -625,7 +625,7 @@ class IonicOfflineRepository {
|
|
|
625
625
|
.filter((row) => {
|
|
626
626
|
if (row.sourceKey !== sourceKey || row.userId !== scope.userId)
|
|
627
627
|
return false;
|
|
628
|
-
return schema.scope === '
|
|
628
|
+
return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
|
|
629
629
|
})
|
|
630
630
|
.map((row) => this.#rowForScope(row, schema, scope))
|
|
631
631
|
.sort((left, right) => left.localId.localeCompare(right.localId));
|
|
@@ -640,7 +640,7 @@ class IonicOfflineRepository {
|
|
|
640
640
|
const row = Object.values(rows).find((row) => {
|
|
641
641
|
if (row.sourceKey !== sourceKey || row.userId !== scope.userId || row.serverId !== serverId)
|
|
642
642
|
return false;
|
|
643
|
-
return schema.scope === '
|
|
643
|
+
return schema.scope === 'partition' ? row.scopeId === scope.scopeId : true;
|
|
644
644
|
});
|
|
645
645
|
return row ? this.#rowForScope(row, schema, scope) : null;
|
|
646
646
|
}
|
|
@@ -656,7 +656,7 @@ class IonicOfflineRepository {
|
|
|
656
656
|
await this.#writes;
|
|
657
657
|
const commands = await this.#readRecord(OUTBOX_KEY);
|
|
658
658
|
return Object.values(commands)
|
|
659
|
-
.filter((command) => command.userId === scope.userId && command.
|
|
659
|
+
.filter((command) => command.userId === scope.userId && command.scopeId === scope.scopeId)
|
|
660
660
|
.sort(compareOfflineCommands$1);
|
|
661
661
|
}
|
|
662
662
|
async getCommandsForUser(userId) {
|
|
@@ -701,9 +701,9 @@ class IonicOfflineRepository {
|
|
|
701
701
|
await this.#storage.set(METADATA_KEY, { ...metadata, lastUserId: null });
|
|
702
702
|
}
|
|
703
703
|
}
|
|
704
|
-
async
|
|
704
|
+
async clearScope(scope) {
|
|
705
705
|
await this.initialize();
|
|
706
|
-
const belongsToGroup = (value) => value.userId === scope.userId && value.
|
|
706
|
+
const belongsToGroup = (value) => value.userId === scope.userId && value.scopeId === scope.scopeId;
|
|
707
707
|
await Promise.all([
|
|
708
708
|
this.#filterRecord(ROWS_KEY, (value) => {
|
|
709
709
|
const schema = this.#resolveReplicaEntitySchema(value.sourceKey);
|
|
@@ -888,7 +888,7 @@ class IonicOfflineRepository {
|
|
|
888
888
|
const schema = this.#resolveReplicaEntitySchema(row.sourceKey);
|
|
889
889
|
rows[this.#rowKey(row, row.sourceKey, row.localId)] = {
|
|
890
890
|
...row,
|
|
891
|
-
|
|
891
|
+
scopeId: schema.scope === 'user' ? '' : row.scopeId,
|
|
892
892
|
values: projectOfflineReplicaValues(schema, row.values),
|
|
893
893
|
confirmedValues: row.confirmedValues === null ? null : projectOfflineReplicaValues(schema, row.confirmedValues),
|
|
894
894
|
};
|
|
@@ -935,14 +935,14 @@ class IonicOfflineRepository {
|
|
|
935
935
|
}
|
|
936
936
|
#rowKey(scope, sourceKey, localId) {
|
|
937
937
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
938
|
-
const partition = schema.scope === 'user' ? 'user' : String(scope.
|
|
938
|
+
const partition = schema.scope === 'user' ? 'user' : String(scope.scopeId);
|
|
939
939
|
return `${scope.userId}:${partition}:${sourceKey}:${localId}`;
|
|
940
940
|
}
|
|
941
941
|
#rowForScope(row, schema, scope) {
|
|
942
|
-
return schema.scope === 'user' ? { ...row,
|
|
942
|
+
return schema.scope === 'user' ? { ...row, scopeId: scope.scopeId } : row;
|
|
943
943
|
}
|
|
944
944
|
#cursorKey(scope) {
|
|
945
|
-
return `${scope.userId}:${scope.
|
|
945
|
+
return `${scope.userId}:${scope.scopeId}`;
|
|
946
946
|
}
|
|
947
947
|
#schemaHasServerId(schema) {
|
|
948
948
|
return schema.fields.some((field) => field.policy === 'serverId');
|
|
@@ -965,7 +965,7 @@ class IonicOfflineRepository {
|
|
|
965
965
|
if (row.userId !== incoming.userId || row.sourceKey !== incoming.sourceKey || row.serverId !== incoming.serverId) {
|
|
966
966
|
return false;
|
|
967
967
|
}
|
|
968
|
-
return schema.scope === 'user' || row.
|
|
968
|
+
return schema.scope === 'user' || row.scopeId === incoming.scopeId;
|
|
969
969
|
});
|
|
970
970
|
if (collision) {
|
|
971
971
|
throw new Error(`Offline replica serverId ${String(incoming.serverId)} is already mapped to localId ${collision[1].localId}.`);
|
|
@@ -1006,7 +1006,7 @@ class OfflineReplicaPullService {
|
|
|
1006
1006
|
this.#assertPullPage(page);
|
|
1007
1007
|
this.#assertHandshake(page.schemaVersion, page.schemaHash, schemaHash);
|
|
1008
1008
|
if (page.hasMore && page.nextCursor === cursor) {
|
|
1009
|
-
throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.
|
|
1009
|
+
throw new Error(`Offline replica pull cursor did not advance for scope ${scope.userId}:${scope.scopeId}.`);
|
|
1010
1010
|
}
|
|
1011
1011
|
const scopeCommands = await this.#repository.getCommands(scope);
|
|
1012
1012
|
const userCommands = this.#repository.getCommandsForUser ? await this.#repository.getCommandsForUser(scope.userId) : scopeCommands;
|
|
@@ -1035,7 +1035,7 @@ class OfflineReplicaPullService {
|
|
|
1035
1035
|
}
|
|
1036
1036
|
const acknowledgedCommand = acknowledged[0];
|
|
1037
1037
|
const acknowledgedScope = acknowledgedCommand
|
|
1038
|
-
? { userId: acknowledgedCommand.userId,
|
|
1038
|
+
? { userId: acknowledgedCommand.userId, scopeId: acknowledgedCommand.scopeId }
|
|
1039
1039
|
: scope;
|
|
1040
1040
|
const acknowledgedRow = acknowledgedCommand
|
|
1041
1041
|
? await this.#repository.getReplicaRow(acknowledgedScope, change.sourceKey, acknowledgedCommand.aggregateLocalId)
|
|
@@ -1347,7 +1347,7 @@ class OfflineSessionService {
|
|
|
1347
1347
|
await this.initialize();
|
|
1348
1348
|
if (lease && !lease.isCurrent())
|
|
1349
1349
|
return false;
|
|
1350
|
-
const normalizedScopeIds = [...new Set(scopeIds)].sort((a, b) => a
|
|
1350
|
+
const normalizedScopeIds = [...new Set(scopeIds)].sort((a, b) => a.localeCompare(b));
|
|
1351
1351
|
const previousUserId = await this.#repository.getLastUserId();
|
|
1352
1352
|
if (lease && !lease.isCurrent())
|
|
1353
1353
|
return false;
|
|
@@ -1364,8 +1364,8 @@ class OfflineSessionService {
|
|
|
1364
1364
|
}
|
|
1365
1365
|
const active = new Set(normalizedScopeIds);
|
|
1366
1366
|
await Promise.all((previous?.scopeIds ?? [])
|
|
1367
|
-
.filter((
|
|
1368
|
-
.map((
|
|
1367
|
+
.filter((scopeId) => !active.has(scopeId))
|
|
1368
|
+
.map((scopeId) => this.#repository.clearScope({ userId, scopeId })));
|
|
1369
1369
|
if (lease && !lease.isCurrent())
|
|
1370
1370
|
return false;
|
|
1371
1371
|
const manifest = {
|
|
@@ -1454,7 +1454,7 @@ class OfflineSessionService {
|
|
|
1454
1454
|
#sessionFromManifest() {
|
|
1455
1455
|
const manifest = this.#activeManifest();
|
|
1456
1456
|
return manifest
|
|
1457
|
-
? { userId: manifest.userId, scopes: manifest.scopeIds.map((
|
|
1457
|
+
? { userId: manifest.userId, scopes: manifest.scopeIds.map((scopeId) => ({ userId: manifest.userId, scopeId })) }
|
|
1458
1458
|
: null;
|
|
1459
1459
|
}
|
|
1460
1460
|
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSessionService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
@@ -1472,8 +1472,22 @@ class OfflinePayloadValidationError extends Error {
|
|
|
1472
1472
|
this.name = 'OfflinePayloadValidationError';
|
|
1473
1473
|
}
|
|
1474
1474
|
}
|
|
1475
|
+
/** Raised before persistence when retaining another command would exceed the configured durable Outbox capacity. */
|
|
1476
|
+
class OfflineOutboxCapacityError extends Error {
|
|
1477
|
+
constructor(reason, currentCommands, currentBytes) {
|
|
1478
|
+
super(reason === 'command_count'
|
|
1479
|
+
? 'Offline Outbox command limit reached; synchronize or discard a pending command before continuing'
|
|
1480
|
+
: 'Offline Outbox storage limit reached; synchronize or discard a pending command before continuing');
|
|
1481
|
+
this.reason = reason;
|
|
1482
|
+
this.currentCommands = currentCommands;
|
|
1483
|
+
this.currentBytes = currentBytes;
|
|
1484
|
+
this.name = 'OfflineOutboxCapacityError';
|
|
1485
|
+
}
|
|
1486
|
+
}
|
|
1475
1487
|
const MAX_PARALLEL_AGGREGATES = 3;
|
|
1476
1488
|
const MAX_BACKOFF_MS = 60 * 60 * 1000;
|
|
1489
|
+
const DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER = 1_000;
|
|
1490
|
+
const DEFAULT_MAX_OUTBOX_BYTES_PER_USER = 10 * 1024 * 1024;
|
|
1477
1491
|
/** Maintains the optimistic local replica and synchronizes its durable outbox. */
|
|
1478
1492
|
class OfflineSyncService {
|
|
1479
1493
|
#network;
|
|
@@ -1595,7 +1609,7 @@ class OfflineSyncService {
|
|
|
1595
1609
|
throw new Error('Cannot enqueue an offline command without an authenticated user');
|
|
1596
1610
|
const userId = session.userId;
|
|
1597
1611
|
this.#setActiveUser(userId);
|
|
1598
|
-
const scope = { userId,
|
|
1612
|
+
const scope = { userId, scopeId: request.scopeId };
|
|
1599
1613
|
this.noteScope(scope);
|
|
1600
1614
|
const aggregateLocalId = request.aggregateLocalId;
|
|
1601
1615
|
const normalized = await this.#normalizeEnqueueRequest(scope, request);
|
|
@@ -1617,6 +1631,7 @@ class OfflineSyncService {
|
|
|
1617
1631
|
createdAt: await this.#nextCommandCreatedAt(userId),
|
|
1618
1632
|
lastErrorCode: null,
|
|
1619
1633
|
};
|
|
1634
|
+
await this.#assertOutboxCapacity(userId, command);
|
|
1620
1635
|
const entityType = this.#entityType(command);
|
|
1621
1636
|
const existing = await this.#repository.getReplicaRow(scope, entityType, aggregateLocalId);
|
|
1622
1637
|
const initialServerId = this.#initialServerId(existing?.serverId ?? null, request.serverId);
|
|
@@ -1646,6 +1661,24 @@ class OfflineSyncService {
|
|
|
1646
1661
|
this.#flushInBackground();
|
|
1647
1662
|
return commandId;
|
|
1648
1663
|
}
|
|
1664
|
+
async #assertOutboxCapacity(userId, command) {
|
|
1665
|
+
const commands = this.#repository.getCommandsForUser
|
|
1666
|
+
? await this.#repository.getCommandsForUser(userId)
|
|
1667
|
+
: (await Promise.all([...this.#knownScopes.values()].filter((scope) => scope.userId === userId).map((scope) => this.#repository.getCommands(scope)))).flat();
|
|
1668
|
+
const maxCommands = this.#options.outboxLimits?.maxCommandsPerUser ?? DEFAULT_MAX_OUTBOX_COMMANDS_PER_USER;
|
|
1669
|
+
const maxBytes = this.#options.outboxLimits?.maxBytesPerUser ?? DEFAULT_MAX_OUTBOX_BYTES_PER_USER;
|
|
1670
|
+
const currentBytes = this.#serializedOutboxBytes(commands);
|
|
1671
|
+
if (commands.length >= maxCommands) {
|
|
1672
|
+
throw new OfflineOutboxCapacityError('command_count', commands.length, currentBytes);
|
|
1673
|
+
}
|
|
1674
|
+
const nextBytes = currentBytes + this.#serializedOutboxBytes([command]);
|
|
1675
|
+
if (nextBytes > maxBytes) {
|
|
1676
|
+
throw new OfflineOutboxCapacityError('serialized_bytes', commands.length, currentBytes);
|
|
1677
|
+
}
|
|
1678
|
+
}
|
|
1679
|
+
#serializedOutboxBytes(commands) {
|
|
1680
|
+
return new TextEncoder().encode(JSON.stringify(commands)).byteLength;
|
|
1681
|
+
}
|
|
1649
1682
|
async discard(commandId, options = {}) {
|
|
1650
1683
|
await this.initialize();
|
|
1651
1684
|
const command = (await this.#readKnownCommands()).find((item) => item.commandId === commandId);
|
|
@@ -1825,7 +1858,7 @@ class OfflineSyncService {
|
|
|
1825
1858
|
});
|
|
1826
1859
|
}
|
|
1827
1860
|
async #rowForCommand(command) {
|
|
1828
|
-
const scope = { userId: command.userId,
|
|
1861
|
+
const scope = { userId: command.userId, scopeId: command.scopeId };
|
|
1829
1862
|
const entityType = this.#entityType(command);
|
|
1830
1863
|
return this.#repository.getReplicaRow(scope, entityType, command.aggregateLocalId);
|
|
1831
1864
|
}
|
|
@@ -1872,7 +1905,7 @@ class OfflineSyncService {
|
|
|
1872
1905
|
const schema = this.#options.replicaSchema.entities.find((entity) => entity.sourceKey === sourceKey);
|
|
1873
1906
|
if (!schema)
|
|
1874
1907
|
throw new Error(`Unknown offline replica source key "${sourceKey}".`);
|
|
1875
|
-
const partition = schema.scope === 'user' ? 'user' : `
|
|
1908
|
+
const partition = schema.scope === 'user' ? 'user' : `partition:${command.scopeId}`;
|
|
1876
1909
|
return `${command.userId}:${partition}:${sourceKey}:${command.aggregateLocalId}`;
|
|
1877
1910
|
}
|
|
1878
1911
|
#failedCommand(command, error) {
|
|
@@ -2047,7 +2080,7 @@ class OfflineSyncService {
|
|
|
2047
2080
|
return serialized;
|
|
2048
2081
|
}
|
|
2049
2082
|
#scopeKey(scope) {
|
|
2050
|
-
return `${scope.userId}:${scope.
|
|
2083
|
+
return `${scope.userId}:${scope.scopeId}`;
|
|
2051
2084
|
}
|
|
2052
2085
|
static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
|
|
2053
2086
|
static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "21.2.17", ngImport: i0, type: OfflineSyncService, providedIn: 'root' }); }
|
|
@@ -2256,8 +2289,8 @@ function assertOfflineRemoteIdentity(identity) {
|
|
|
2256
2289
|
if (!Number.isSafeInteger(identity.userId) || identity.userId <= 0) {
|
|
2257
2290
|
throw new Error('Offline remote identity userId must be a positive safe integer.');
|
|
2258
2291
|
}
|
|
2259
|
-
if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) =>
|
|
2260
|
-
throw new Error('Offline remote identity scopeIds must contain only non-
|
|
2292
|
+
if (!Array.isArray(identity.scopeIds) || identity.scopeIds.some((scopeId) => typeof scopeId !== 'string' || scopeId.length === 0)) {
|
|
2293
|
+
throw new Error('Offline remote identity scopeIds must contain only non-empty strings.');
|
|
2261
2294
|
}
|
|
2262
2295
|
if (typeof identity.authSubject !== 'string' || identity.authSubject.length === 0) {
|
|
2263
2296
|
throw new Error('Offline remote identity authSubject must be a non-empty string.');
|
|
@@ -2353,7 +2386,7 @@ const SCHEMA = [
|
|
|
2353
2386
|
`CREATE TABLE IF NOT EXISTS offline_sync_commands (
|
|
2354
2387
|
command_id TEXT PRIMARY KEY,
|
|
2355
2388
|
user_id INTEGER NOT NULL,
|
|
2356
|
-
|
|
2389
|
+
scope_id TEXT NOT NULL,
|
|
2357
2390
|
aggregate_type TEXT NOT NULL,
|
|
2358
2391
|
aggregate_local_id TEXT NOT NULL,
|
|
2359
2392
|
operation TEXT NOT NULL,
|
|
@@ -2368,7 +2401,7 @@ const SCHEMA = [
|
|
|
2368
2401
|
last_error_code TEXT
|
|
2369
2402
|
)`,
|
|
2370
2403
|
`CREATE INDEX IF NOT EXISTS offline_sync_commands_scope_created
|
|
2371
|
-
ON offline_sync_commands (user_id,
|
|
2404
|
+
ON offline_sync_commands (user_id, scope_id, created_at)`,
|
|
2372
2405
|
`CREATE TABLE IF NOT EXISTS offline_replica_schema_metadata (
|
|
2373
2406
|
id INTEGER PRIMARY KEY CHECK (id = 1),
|
|
2374
2407
|
version INTEGER NOT NULL,
|
|
@@ -2376,9 +2409,9 @@ const SCHEMA = [
|
|
|
2376
2409
|
)`,
|
|
2377
2410
|
`CREATE TABLE IF NOT EXISTS offline_replica_cursors (
|
|
2378
2411
|
user_id INTEGER NOT NULL,
|
|
2379
|
-
|
|
2412
|
+
scope_id TEXT NOT NULL,
|
|
2380
2413
|
cursor TEXT NOT NULL,
|
|
2381
|
-
PRIMARY KEY (user_id,
|
|
2414
|
+
PRIMARY KEY (user_id, scope_id)
|
|
2382
2415
|
)`,
|
|
2383
2416
|
];
|
|
2384
2417
|
/** Native iOS/Android repository backed by encrypted `@capacitor-community/sqlite`. */
|
|
@@ -2413,9 +2446,9 @@ class SqliteOfflineRepository {
|
|
|
2413
2446
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2414
2447
|
const predicates = ['local_id = ?', '_offline_user_id = ?'];
|
|
2415
2448
|
const values = [localId, scope.userId];
|
|
2416
|
-
if (schema.scope === '
|
|
2417
|
-
predicates.push('
|
|
2418
|
-
values.push(scope.
|
|
2449
|
+
if (schema.scope === 'partition') {
|
|
2450
|
+
predicates.push('_offline_scope_id = ?');
|
|
2451
|
+
values.push(scope.scopeId);
|
|
2419
2452
|
}
|
|
2420
2453
|
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2421
2454
|
const row = rows[0];
|
|
@@ -2427,9 +2460,9 @@ class SqliteOfflineRepository {
|
|
|
2427
2460
|
const schema = this.#resolveReplicaEntitySchema(sourceKey);
|
|
2428
2461
|
const predicates = ['_offline_user_id = ?'];
|
|
2429
2462
|
const values = [scope.userId];
|
|
2430
|
-
if (schema.scope === '
|
|
2431
|
-
predicates.push('
|
|
2432
|
-
values.push(scope.
|
|
2463
|
+
if (schema.scope === 'partition') {
|
|
2464
|
+
predicates.push('_offline_scope_id = ?');
|
|
2465
|
+
values.push(scope.scopeId);
|
|
2433
2466
|
}
|
|
2434
2467
|
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')} ORDER BY local_id ASC`, values);
|
|
2435
2468
|
return rows.map((row) => this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row));
|
|
@@ -2440,9 +2473,9 @@ class SqliteOfflineRepository {
|
|
|
2440
2473
|
return null;
|
|
2441
2474
|
const predicates = ['server_id = ?', '_offline_user_id = ?'];
|
|
2442
2475
|
const values = [serverId, scope.userId];
|
|
2443
|
-
if (schema.scope === '
|
|
2444
|
-
predicates.push('
|
|
2445
|
-
values.push(scope.
|
|
2476
|
+
if (schema.scope === 'partition') {
|
|
2477
|
+
predicates.push('_offline_scope_id = ?');
|
|
2478
|
+
values.push(scope.scopeId);
|
|
2446
2479
|
}
|
|
2447
2480
|
const rows = await this.#query(`SELECT * FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2448
2481
|
const row = rows[0];
|
|
@@ -2451,9 +2484,9 @@ class SqliteOfflineRepository {
|
|
|
2451
2484
|
return this.#replicaRowFromSqliteRow(schema, scope, sourceKey, this.#string(row['local_id']), row);
|
|
2452
2485
|
}
|
|
2453
2486
|
async getReplicaCursor(scope) {
|
|
2454
|
-
const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND
|
|
2487
|
+
const rows = await this.#query('SELECT cursor FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', [
|
|
2455
2488
|
scope.userId,
|
|
2456
|
-
scope.
|
|
2489
|
+
scope.scopeId,
|
|
2457
2490
|
]);
|
|
2458
2491
|
const row = rows[0];
|
|
2459
2492
|
if (!row)
|
|
@@ -2461,7 +2494,7 @@ class SqliteOfflineRepository {
|
|
|
2461
2494
|
return { ...scope, cursor: this.#string(row['cursor']) };
|
|
2462
2495
|
}
|
|
2463
2496
|
async getCommands(scope) {
|
|
2464
|
-
const rows = await this.#query('SELECT * FROM offline_sync_commands WHERE user_id = ? AND
|
|
2497
|
+
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]);
|
|
2465
2498
|
return rows.map((row) => this.#command(row));
|
|
2466
2499
|
}
|
|
2467
2500
|
async getCommandsForUser(userId) {
|
|
@@ -2490,15 +2523,15 @@ class SqliteOfflineRepository {
|
|
|
2490
2523
|
await this.#execute(database, 'UPDATE offline_metadata SET last_user_id = NULL WHERE id = 1 AND last_user_id = ?', [userId]);
|
|
2491
2524
|
});
|
|
2492
2525
|
}
|
|
2493
|
-
async
|
|
2526
|
+
async clearScope(scope) {
|
|
2494
2527
|
await this.#transaction(async (database) => {
|
|
2495
|
-
const values = [scope.userId, scope.
|
|
2496
|
-
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ? AND
|
|
2497
|
-
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND
|
|
2528
|
+
const values = [scope.userId, scope.scopeId];
|
|
2529
|
+
await this.#execute(database, 'DELETE FROM offline_sync_commands WHERE user_id = ? AND scope_id = ?', values);
|
|
2530
|
+
await this.#execute(database, 'DELETE FROM offline_replica_cursors WHERE user_id = ? AND scope_id = ?', values);
|
|
2498
2531
|
for (const entity of this.#options.replicaSchema.entities) {
|
|
2499
|
-
if (entity.scope !== '
|
|
2532
|
+
if (entity.scope !== 'partition')
|
|
2500
2533
|
continue;
|
|
2501
|
-
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND
|
|
2534
|
+
await this.#execute(database, `DELETE FROM ${entity.tableName} WHERE _offline_user_id = ? AND _offline_scope_id = ?`, values);
|
|
2502
2535
|
}
|
|
2503
2536
|
});
|
|
2504
2537
|
}
|
|
@@ -2638,7 +2671,7 @@ class SqliteOfflineRepository {
|
|
|
2638
2671
|
return {
|
|
2639
2672
|
commandId: this.#string(row['command_id']),
|
|
2640
2673
|
userId: this.#number(row['user_id']),
|
|
2641
|
-
|
|
2674
|
+
scopeId: this.#string(row['scope_id']),
|
|
2642
2675
|
aggregateType: this.#string(row['aggregate_type']),
|
|
2643
2676
|
aggregateLocalId: this.#string(row['aggregate_local_id']),
|
|
2644
2677
|
operation: this.#string(row['operation']),
|
|
@@ -2655,18 +2688,18 @@ class SqliteOfflineRepository {
|
|
|
2655
2688
|
}
|
|
2656
2689
|
#putCommand(databaseId, command) {
|
|
2657
2690
|
return this.#execute(databaseId, `INSERT INTO offline_sync_commands
|
|
2658
|
-
(command_id, user_id,
|
|
2691
|
+
(command_id, user_id, scope_id, aggregate_type, aggregate_local_id, operation, payload_json, optimistic_value_json,
|
|
2659
2692
|
payload_hash, base_revision_json, state, attempts, retry_at, created_at, last_error_code)
|
|
2660
2693
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
2661
2694
|
ON CONFLICT(command_id) DO UPDATE SET
|
|
2662
|
-
user_id = excluded.user_id,
|
|
2695
|
+
user_id = excluded.user_id, scope_id = excluded.scope_id, aggregate_type = excluded.aggregate_type,
|
|
2663
2696
|
aggregate_local_id = excluded.aggregate_local_id, operation = excluded.operation, payload_json = excluded.payload_json,
|
|
2664
2697
|
optimistic_value_json = excluded.optimistic_value_json, payload_hash = excluded.payload_hash,
|
|
2665
2698
|
base_revision_json = excluded.base_revision_json, state = excluded.state, attempts = excluded.attempts,
|
|
2666
2699
|
retry_at = excluded.retry_at, created_at = excluded.created_at, last_error_code = excluded.last_error_code`, [
|
|
2667
2700
|
command.commandId,
|
|
2668
2701
|
command.userId,
|
|
2669
|
-
command.
|
|
2702
|
+
command.scopeId,
|
|
2670
2703
|
command.aggregateType,
|
|
2671
2704
|
command.aggregateLocalId,
|
|
2672
2705
|
command.operation,
|
|
@@ -2690,7 +2723,7 @@ class SqliteOfflineRepository {
|
|
|
2690
2723
|
const values = [
|
|
2691
2724
|
row.localId,
|
|
2692
2725
|
row.userId,
|
|
2693
|
-
...(schema.scope === '
|
|
2726
|
+
...(schema.scope === 'partition' ? [row.scopeId] : []),
|
|
2694
2727
|
...(this.#schemaHasServerId(schema) ? [row.serverId] : []),
|
|
2695
2728
|
confirmedValues === null ? null : JSON.stringify(confirmedValues),
|
|
2696
2729
|
row.serverRevision == null ? null : JSON.stringify(row.serverRevision),
|
|
@@ -2704,22 +2737,22 @@ class SqliteOfflineRepository {
|
|
|
2704
2737
|
const schema = this.#resolveReplicaEntitySchema(key.sourceKey);
|
|
2705
2738
|
const predicates = ['local_id = ?', '_offline_user_id = ?'];
|
|
2706
2739
|
const values = [key.localId, key.userId];
|
|
2707
|
-
if (schema.scope === '
|
|
2708
|
-
predicates.push('
|
|
2709
|
-
values.push(key.
|
|
2740
|
+
if (schema.scope === 'partition') {
|
|
2741
|
+
predicates.push('_offline_scope_id = ?');
|
|
2742
|
+
values.push(key.scopeId);
|
|
2710
2743
|
}
|
|
2711
2744
|
return this.#execute(databaseId, `DELETE FROM ${schema.tableName} WHERE ${predicates.join(' AND ')}`, values);
|
|
2712
2745
|
}
|
|
2713
2746
|
#putReplicaCursor(databaseId, cursor) {
|
|
2714
|
-
return this.#execute(databaseId, `INSERT INTO offline_replica_cursors (user_id,
|
|
2715
|
-
ON CONFLICT(user_id,
|
|
2747
|
+
return this.#execute(databaseId, `INSERT INTO offline_replica_cursors (user_id, scope_id, cursor) VALUES (?, ?, ?)
|
|
2748
|
+
ON CONFLICT(user_id, scope_id) DO UPDATE SET cursor = excluded.cursor`, [cursor.userId, cursor.scopeId, cursor.cursor]);
|
|
2716
2749
|
}
|
|
2717
2750
|
#buildReplicaUpsertStatement(schema) {
|
|
2718
2751
|
const insertColumns = ['local_id', '_offline_user_id'];
|
|
2719
2752
|
const updateSets = ['_offline_user_id = excluded._offline_user_id'];
|
|
2720
|
-
if (schema.scope === '
|
|
2721
|
-
insertColumns.push('
|
|
2722
|
-
updateSets.push('
|
|
2753
|
+
if (schema.scope === 'partition') {
|
|
2754
|
+
insertColumns.push('_offline_scope_id');
|
|
2755
|
+
updateSets.push('_offline_scope_id = excluded._offline_scope_id');
|
|
2723
2756
|
}
|
|
2724
2757
|
if (this.#schemaHasServerId(schema)) {
|
|
2725
2758
|
insertColumns.push('server_id');
|
|
@@ -2829,6 +2862,7 @@ function provideOffline(options) {
|
|
|
2829
2862
|
databaseName: options.databaseName,
|
|
2830
2863
|
createEncryptionKey: options.createEncryptionKey,
|
|
2831
2864
|
replicaSchema: options.replicaSchema,
|
|
2865
|
+
outboxLimits: options.outboxLimits,
|
|
2832
2866
|
},
|
|
2833
2867
|
},
|
|
2834
2868
|
{
|
|
@@ -2910,5 +2944,5 @@ i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "21.2.17", ngImpo
|
|
|
2910
2944
|
* Generated bundle index. Do not edit.
|
|
2911
2945
|
*/
|
|
2912
2946
|
|
|
2913
|
-
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, 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 };
|
|
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 };
|
|
2914
2948
|
//# sourceMappingURL=rdlabo-ionic-angular-kit-offline.mjs.map
|